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
refactor: add validation toolchain and normalize project formatting (#39)
Sergey Eroshenkovbc97b38e1477
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 4f250da0..b76b2c6a 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -14,14 +14,7 @@"source": "./","description": "Plugin-first second brain for AI agents and humans (Obsidian-compatible Markdown vaults).","category": "knowledge",- "tags": [- "second-brain",- "obsidian",- "agents",- "skills",- "event-log",- "mcp"- ]+ "tags": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"]}]}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 2eae7f7f..a5d2727c 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -8,12 +8,5 @@"license": "MIT","homepage": "https://github.com/itechmeat/open-second-brain","repository": "https://github.com/itechmeat/open-second-brain",- "keywords": [- "second-brain",- "obsidian",- "agents",- "skills",- "event-log",- "mcp"- ]+ "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"]}diff --git a/.oxfmtrc.json b/.oxfmtrc.jsonnew file mode 100644index 00000000..de753c53--- /dev/null+++ b/.oxfmtrc.json@@ -0,0 +1,3 @@+{+ "printWidth": 100+}diff --git a/bun.lock b/bun.lockindex 4f7c5812..18f3f7d1 100644--- a/bun.lock+++ b/bun.lock@@ -11,6 +11,8 @@"@types/bun": "^1.1.0","@types/node": "^22.0.0","@types/proper-lockfile": "^4.1.4",+ "oxfmt": "0.47.0",+ "oxlint": "1.62.0","typescript": "^5.5.0",},"optionalDependencies": {@@ -19,6 +21,82 @@},},"packages": {+ "@oxfmt/binding-android-arm-eabi": ["@oxfmt/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-KrMQRdMi/upr81qT4ijK6X6BNp6jqpMY7FwILQnwIy9QLc3qpnhUx5rsCLGzn4ewsCQ0CNAspN2ogmP1GXLyLw=="],++ "@oxfmt/binding-android-arm64": ["@oxfmt/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-r4ixS/PeUpAFKgrpDoZ5pSkthjZzVzKd95525Aazj+aOv9H4ulK5zYHGb7wFY5n5kZxHK8TbOJUZgoEb1ohddQ=="],++ "@oxfmt/binding-darwin-arm64": ["@oxfmt/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-CLWxiKpMl+195cm09CuaWEhJK0CirRkoMa07aR9+9AFPat2LfIKtwx1JqxZM0MTvcMe6+adlJNdVL6jdInvq3g=="],++ "@oxfmt/binding-darwin-x64": ["@oxfmt/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Xq5fjTYDC50faUeLSm0rZdBqoTgleXEdD7NpJdARtQIczkCJn3xNjMUSQQkUmh4CtxkKTNL68lytcOK3e/osgg=="],++ "@oxfmt/binding-freebsd-x64": ["@oxfmt/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QOU9ZIJ52p5askcEC0QJvvr8trHAWoonul8bgISo6gYUL3s50zkqafBYcNAr9LJZQbsZtPfIWHk9+5+nUp1qJQ=="],++ "@oxfmt/binding-linux-arm-gnueabihf": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-oJxDM1aBhPvz9gmElBv8UpxyiqhwfjcbrSxT5F0xtuUzY6dQI27/AQPIt3eu3Z5Yvn0kQl5R7MA3Z+MbnRvCBw=="],++ "@oxfmt/binding-linux-arm-musleabihf": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-g8Lh50VS4ibGz2q6v7r9UZY4D0dM16SdrFYOMzhqIoCwGcai8VMIRUAcqn1/jlCsOOzUXJ741+kCeJt0cofakQ=="],++ "@oxfmt/binding-linux-arm64-gnu": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-YrNT1vQ0asaXoRbrvYENPqmBfOQ9Xr8enPNOULeYfg44VjCcrUowFy5QZr+WawE0zyP8cH9e9Gxxg0fDEFzhcg=="],++ "@oxfmt/binding-linux-arm64-musl": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-IxtQC/sbBi4ubbY+MdwdanRWrG9InQJVZqyMsBa5IUaQcnSg86gQme574HxXMC1p4bo4YhV99zQ+wNnGCvEgzw=="],++ "@oxfmt/binding-linux-ppc64-gnu": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-EWXEhOMbWO0q6eJSbu0QLkU8cKi0ljlYLngeDs2Ocu/pm1rrLwyQiYzlFbdnMRURI4w9ndr1sI9rSbhlJ5o23Q=="],++ "@oxfmt/binding-linux-riscv64-gnu": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-tZrjS11TUiDuEpRaqdk8K9F9xETRyKXfuZKmdeW+Gj7coBnm7+8sBEfyt033EAFEQSlkniAXvBLh+Qja2ioGBQ=="],++ "@oxfmt/binding-linux-riscv64-musl": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-KBFy+2CFKUCZzYwX2ZOPQKck1vjQbz+hextuc19G4r0WRJwadfAeuQMQRQvB+Ivc8brlbOVg7et8K7E467440g=="],++ "@oxfmt/binding-linux-s390x-gnu": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-REUPFKVGSiK99B+9eaPhluEVglzaoj/SMykNC5SUiV2RSsBfV5lWN7Y0iCIc251Wz3GaeAGZsJ/zj3gjarxdFg=="],++ "@oxfmt/binding-linux-x64-gnu": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-KVftVSVEDeIfRW3TIeLe3aNI/iY4m1fu5mDwHcisKMZSCMKLkrhFsjowC7o9RoqNPxbbglm2+/6KAKBIts2t0Q=="],++ "@oxfmt/binding-linux-x64-musl": ["@oxfmt/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-DTsmGEaA2860Aq5VUyDO8/MT9NFxwVL93RnRYmpMwK6DsSkThmvEpqoUDDljziEpAedMRG19SCogrNbINSbLUQ=="],++ "@oxfmt/binding-openharmony-arm64": ["@oxfmt/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-8r5BDro7fLOBoq1JXHLVSs55OlrxQhEso4HVo0TcY7OXJUPYfjPoOaYL5us+yIwqyP9rQwN+rxuiNFSmaxSuOQ=="],++ "@oxfmt/binding-win32-arm64-msvc": ["@oxfmt/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-qtz/gzm8IjSPUlseZ0ofW8zyHLoZsuP5HTfcGGkWkUblB89JT8GNYH3ICqjbDsqsGqXum0/ZndXTFplSdXFIcg=="],++ "@oxfmt/binding-win32-ia32-msvc": ["@oxfmt/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-5vIcdcIDE7nCx+MXN6sm8kbC4zajDB31E86rez4i45iHNH/2NjdKlJ720xcHTr3eeiMcttCGPHPhE1TjtBDGZw=="],++ "@oxfmt/binding-win32-x64-msvc": ["@oxfmt/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-Sr59Y5ms54ONBjxFeWhVlGyQcHXxcl9DxC23f6yXlRkcos7LXBLoO+KDfxexjHIOZh7cWqrWduzvUjJ+pHp8cQ=="],++ "@oxlint/binding-android-arm-eabi": ["@oxlint/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-pKsthNECyvJh8lPTICz6VcwVy2jOqdhhsp1rlxCkhgZR47aKvXPmaRWQDv+zlXpRae4qm1MaaTnutkaOk5aofg=="],++ "@oxlint/binding-android-arm64": ["@oxlint/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-b1AUNViByvgmR2xJDubvLIr+dSuu3uraG7bsAoKo+xrpspPvu6RIn6Fhr2JUhobfep3jwUTy18Huco6GkwdvGQ=="],++ "@oxlint/binding-darwin-arm64": ["@oxlint/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-iG+Tvf70UJ6otfwFYIHk36Sjq9cpPP5YLxkoggANNRtzgi3Tj3g8q6Ybqi6AtkU3+yg9QwF7bDCkCS6bbL4PCg=="],++ "@oxlint/binding-darwin-x64": ["@oxlint/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-oOWI6YPPr5AJUx+yIDlxmuUbQjS5gZX3OH3QisawYvsZgLiQVvZtR0rPBcJTxLWqt2ClrWg0DlSrlUiG5SQNHg=="],++ "@oxlint/binding-freebsd-x64": ["@oxlint/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-dLP33T7VLCmLVv4cvjkVX+rmkcwNk2UfxmsZPNur/7BQHoQR60zJ7XLiRvNUawlzn0u8ngCa3itjEG73MAMa/w=="],++ "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-fl//LWNks6qo9chNY60UDYyIwtp7a5cEx4Y/rHPjaarhuwqx6jtbzEpD5V5AqmdL4a6Y5D8zeXg5HF2Cr0QmSQ=="],++ "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-i5vkAuxvueTODV3J2dL61/TXewDHhMFKvtD156cIsk7GsdfiAu7zW7kY0NJXhKeFHeiMZIh7eFNjkPYH6J47HQ=="],++ "@oxlint/binding-linux-arm64-gnu": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-QwN19LLuIGuOjEflSeJkZmOTfBdBMlTmW8xbMf8TZhjd//cxVNYQPq75q7oKZBJc6hRx3gY7sX0Egc8cEIFZYg=="],++ "@oxlint/binding-linux-arm64-musl": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-8eCy3FCDuWUM5hWujAv6heMvfZPbcCOU3SdQUAkixZLu5bSzOkNfirJiLGoQFO943xceOKkiQRMQNzH++jM3WA=="],++ "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-NjQ7K7tpTPDe9J+yq8p/s/J0E7lRCkK2uDBDqvT4XIT6f4Z0tlnr59OBg/WcrmVHER1AbrcfyxhGTXgcG8ytWg=="],++ "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-oKZed9gmSwze29dEt3/Wnsv6l/Ygw/FUst+8Kfpv2SGeS/glEoTGZAMQw37SVyzFV76UTHJN2snGgxK2t2+8ow=="],++ "@oxlint/binding-linux-riscv64-musl": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-gBjBxQ+9lGpAYq+ELqw0w8QXsBnkZclFc7GRX2r0LnEVn3ZTEqeIKpKcGjucmp76Q53bvJD0i4qBWBhcfhSfGA=="],++ "@oxlint/binding-linux-s390x-gnu": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-Ew2Kxs9EQ9/mbAIJ2hvocMC0wsOu6YKzStI2eFBDt+Td5O8seVC/oxgRIHqCcl5sf5ratA1nozQBAuv7tphkHg=="],++ "@oxlint/binding-linux-x64-gnu": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-5z25jcAA0gfKyVwz71A0VXgaPlocPoTAxhlv/hgoK6tlCrfoNuw7haWbDHvGMfjXhdic4EqVXGRv5XsTqFnbRQ=="],++ "@oxlint/binding-linux-x64-musl": ["@oxlint/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-IWpHmMB6ZDllPvqWDkG6AmXrN7JF5e/c4g/0PuURsmlK+vHoYZPB70rr4u1bn3I4LsKCSpqqfveyx6UCOC8wdg=="],++ "@oxlint/binding-openharmony-arm64": ["@oxlint/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-fjlSxxrD5pA594vkyikCS9MnPRjQawW6/BLgyTYkO+73wwPlYjkcZ7LSd974l0Q2zkHQmu4DPvJFLYA7o8xrxQ=="],++ "@oxlint/binding-win32-arm64-msvc": ["@oxlint/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-EiFXr8loNS0Ul3Gu80+9nr1T8jRmnKocqmHHg16tj5ZqTgUXyb97l2rrspVHdDluyFn9JfR4PoJFdNzw4paHww=="],++ "@oxlint/binding-win32-ia32-msvc": ["@oxlint/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-IgOFvL73li1bFgab+hThXYA0N2Xms2kV2MvZN95cebV+fmrZ9AVui1JSxfeeqRLo3CpPxKZlzhyq4G0cnaAvIw=="],++ "@oxlint/binding-win32-x64-msvc": ["@oxlint/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-6hMpyDWQ2zGA1OXFKBrdYMUveUCO8UJhkO6JdwZPd78xIdHZNhjx+pib+4fC2Cljuhjyl0QwA2F3df/bs4Bp6A=="],+"@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.13" } }, "sha512-9fqXWk5YIHGGnUau9TEi+qdlTYDAnOj+xLCmSTwXfAIqXr2x4tytJb43E9uCvt09zJURKXwAtkoH4nLQfzeTXw=="],"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-9v00a+dn2yWVsYDEunWC4g/TcRKVq3r8N5FuZp7u0SGrPvdN9c2yXI9bBuf5Fl0hNCb+QTIePTn5pJs2pwBOQQ=="],@@ -31,6 +109,10 @@"graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],+ "oxfmt": ["[email protected]", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.47.0", "@oxfmt/binding-android-arm64": "0.47.0", "@oxfmt/binding-darwin-arm64": "0.47.0", "@oxfmt/binding-darwin-x64": "0.47.0", "@oxfmt/binding-freebsd-x64": "0.47.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.47.0", "@oxfmt/binding-linux-arm-musleabihf": "0.47.0", "@oxfmt/binding-linux-arm64-gnu": "0.47.0", "@oxfmt/binding-linux-arm64-musl": "0.47.0", "@oxfmt/binding-linux-ppc64-gnu": "0.47.0", "@oxfmt/binding-linux-riscv64-gnu": "0.47.0", "@oxfmt/binding-linux-riscv64-musl": "0.47.0", "@oxfmt/binding-linux-s390x-gnu": "0.47.0", "@oxfmt/binding-linux-x64-gnu": "0.47.0", "@oxfmt/binding-linux-x64-musl": "0.47.0", "@oxfmt/binding-openharmony-arm64": "0.47.0", "@oxfmt/binding-win32-arm64-msvc": "0.47.0", "@oxfmt/binding-win32-ia32-msvc": "0.47.0", "@oxfmt/binding-win32-x64-msvc": "0.47.0" }, "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-OFbkbzxKCpooQEnRmpTDnuwTX8KHXzZTQ4Df/hz85fpS67Pl+lxPEFvUtin56HIIS0B1k4X8oIzTXRZPufA2CA=="],++ "oxlint": ["[email protected]", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.62.0", "@oxlint/binding-android-arm64": "1.62.0", "@oxlint/binding-darwin-arm64": "1.62.0", "@oxlint/binding-darwin-x64": "1.62.0", "@oxlint/binding-freebsd-x64": "1.62.0", "@oxlint/binding-linux-arm-gnueabihf": "1.62.0", "@oxlint/binding-linux-arm-musleabihf": "1.62.0", "@oxlint/binding-linux-arm64-gnu": "1.62.0", "@oxlint/binding-linux-arm64-musl": "1.62.0", "@oxlint/binding-linux-ppc64-gnu": "1.62.0", "@oxlint/binding-linux-riscv64-gnu": "1.62.0", "@oxlint/binding-linux-riscv64-musl": "1.62.0", "@oxlint/binding-linux-s390x-gnu": "1.62.0", "@oxlint/binding-linux-x64-gnu": "1.62.0", "@oxlint/binding-linux-x64-musl": "1.62.0", "@oxlint/binding-openharmony-arm64": "1.62.0", "@oxlint/binding-win32-arm64-msvc": "1.62.0", "@oxlint/binding-win32-ia32-msvc": "1.62.0", "@oxlint/binding-win32-x64-msvc": "1.62.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.18.0" }, "optionalPeers": ["oxlint-tsgolint"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-1uFkg6HakjsGIpW9wNdeW4/2LOHW9MEkoWjZUTUfQtIHyLIZPYt00w3Sg+H3lH+206FgBPHBbW5dVE5l2ExECQ=="],+"proper-lockfile": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "retry": "^0.12.0", "signal-exit": "^3.0.2" } }, "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA=="],"retry": ["[email protected]", "", {}, "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow=="],@@ -49,6 +131,8 @@"sqlite-vec-windows-x64": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-y3gEIyy/17bq2QFPQOWLE68TYWcRZkBQVA2XLrTPHNTOp55xJi/BBBmOm40tVMDMjtP+Elpk6UBUXdaq+46b0Q=="],+ "tinypool": ["[email protected]", "", {}, "sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw=="],+"typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],"undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],diff --git a/hooks/lib/detect.ts b/hooks/lib/detect.tsindex 4d44747c..3e0214a3 100644--- a/hooks/lib/detect.ts+++ b/hooks/lib/detect.ts@@ -23,12 +23,7 @@ import type { ToolCall } from "./transcript.ts";// `name` field in the transcript is always `apply_patch` for file// edits done through it; we still accept Edit/Write to defend against// a future runtime that mirrors the matcher alias into the call name.-const NATIVE_ARTIFACT_NAMES = new Set<string>([- "Write",- "Edit",- "MultiEdit",- "apply_patch",-]);+const NATIVE_ARTIFACT_NAMES = new Set<string>(["Write", "Edit", "MultiEdit", "apply_patch"]);// Tool-name suffixes that count as "the agent logged this turn",// regardless of any runtime-injected MCP prefix.@@ -45,8 +40,7 @@ const NATIVE_ARTIFACT_NAMES = new Set<string>([// in Claude Code transcripts. The regex anchors on either string// start or a `__` separator so a future prefix change keeps working// without an emergency patch.-const BRAIN_EVENT_NAME_SUFFIX =- /(?:^|__)(brain_feedback|brain_apply_evidence|brain_note)$/;+const BRAIN_EVENT_NAME_SUFFIX = /(?:^|__)(brain_feedback|brain_apply_evidence|brain_note)$/;// Bash command shape that counts as a brain-event call from the CLI.// Keep this anchored to command boundaries rather than raw substrings:@@ -170,10 +164,7 @@ export function summarizeTurn(*/export type HookRuntime = "claudecode" | "codex" | "unknown";-const CLAUDE_TRANSCRIPT_NEEDLES = [- "/.claude/projects/",- "/.claude/sessions/",-] as const;+const CLAUDE_TRANSCRIPT_NEEDLES = ["/.claude/projects/", "/.claude/sessions/"] as const;const CODEX_TRANSCRIPT_NEEDLE = "/.codex/sessions/";/**@@ -204,9 +195,9 @@ export function detectHookRuntime(payload: unknown): HookRuntime {}if (- typeof p["session_id"] === "string"- && typeof p["cwd"] === "string"- && typeof p["tool_use_id"] === "string"+ typeof p["session_id"] === "string" &&+ typeof p["cwd"] === "string" &&+ typeof p["tool_use_id"] === "string") {return "claudecode";}diff --git a/hooks/lib/messages.ts b/hooks/lib/messages.tsindex e7d54210..9b4df21b 100644--- a/hooks/lib/messages.ts+++ b/hooks/lib/messages.ts@@ -47,11 +47,7 @@ function postWriteCadenceLine(runtime: HookRuntime): string {}}-export function postWriteReminder({- toolName,- filePath,- runtime,-}: PostWriteReminderInput): string {+export function postWriteReminder({ toolName, filePath, runtime }: PostWriteReminderInput): string {const target = filePath ? `\`${filePath}\`` : "a file";const cadence = postWriteCadenceLine(runtime);const parts: string[] = [@@ -61,8 +57,8 @@ export function postWriteReminder({if (cadence !== "") parts.push(cadence, "");parts.push("If this turn contained a user preference, correction, or rule that",- "should outlast the current task (\"don't do X\", \"prefer Y\", \"use",- "A instead of B\"), call `brain_feedback` once per signal to record",+ 'should outlast the current task ("don\'t do X", "prefer Y", "use',+ 'A instead of B"), call `brain_feedback` once per signal to record',"it into `Brain/inbox/`.","","If a confirmed or unconfirmed preference in `Brain/preferences/`",@@ -78,7 +74,7 @@ export function postWriteReminder({"","Trivial edits (typo fix, pure formatting) don't need any of the","three calls. When a preference plausibly applies but you are",- "unsure, record the event with `note: \"speculative; <reason>\"`",+ 'unsure, record the event with `note: "speculative; <reason>"`',"instead of skipping — the dream pass discards single-event","speculative entries that do not recur.",);diff --git a/hooks/lib/transcript.ts b/hooks/lib/transcript.tsindex 812a266d..64079fb2 100644--- a/hooks/lib/transcript.ts+++ b/hooks/lib/transcript.ts@@ -260,11 +260,6 @@ function extractCodexShellCommand(serialized: string | undefined): string | nullfunction isCodexEnvelope(p: NonNullable<CodexRecord["payload"]>): boolean {const content = p.content;if (!Array.isArray(content)) return false;- const text = content- .map((c) => (typeof c?.text === "string" ? c.text : ""))- .join("");- return (- text.startsWith("<environment_context>") ||- text.startsWith("<user_instructions>")- );+ const text = content.map((c) => (typeof c?.text === "string" ? c.text : "")).join("");+ return text.startsWith("<environment_context>") || text.startsWith("<user_instructions>");}diff --git a/openclaw/index.js b/openclaw/index.jsindex 05ca41fa..259d4f91 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -1691,6 +1691,14 @@ function discoverConfig(path) {return { path: resolved, exists: false, data: {} };}}+function validateTimezoneName(name) {+ try {+ new Intl.DateTimeFormat("en-US", { timeZone: name });+ return { ok: true, error: null };+ } catch (exc) {+ return { ok: false, error: exc.message ?? String(exc) };+ }+}function resolveTimezone(configPath) {let name = process.env["VAULT_TIMEZONE"];if (!name) {@@ -1698,12 +1706,7 @@ function resolveTimezone(configPath) {}if (!name)return null;- try {- new Intl.DateTimeFormat("en-US", { timeZone: name });- return name;- } catch {- return null;- }+ return validateTimezoneName(name).ok ? name : null;}function resolveAgentName(configPath) {const env = process.env["VAULT_AGENT_NAME"];@@ -3600,6 +3603,27 @@ function normalizeAgentArgument(value) {return cleaned;}+// src/core/validate.ts+function parseOptionalFiniteNumberInput(raw) {+ if (raw === undefined || raw === null)+ return { value: null, error: null };+ if (typeof raw === "number") {+ if (!Number.isFinite(raw))+ return { value: null, error: "finite-number" };+ return { value: raw, error: null };+ }+ if (typeof raw === "string") {+ const trimmed = raw.trim();+ if (trimmed === "")+ return { value: null, error: null };+ const parsed = Number(trimmed);+ if (!Number.isFinite(parsed))+ return { value: null, error: "number-or-numeric-string" };+ return { value: parsed, error: null };+ }+ return { value: null, error: "number-or-numeric-string" };+}+// src/openclaw/index.tsfunction resolveVaultPath(api) {const cfg = api.pluginConfig ?? {};@@ -3610,12 +3634,7 @@ function resolveOpenclawTimezone(api) {const candidate = cfg.timezone || process.env["VAULT_TIMEZONE"] || null;if (!candidate)return null;- try {- new Intl.DateTimeFormat("en-US", { timeZone: candidate });- return candidate;- } catch {- return null;- }+ return validateTimezoneName(candidate).ok ? candidate : null;}function resolveOpenclawAgent(api, argAgent) {const normalized = normalizeAgentArgument(argAgent);@@ -3625,25 +3644,14 @@ function resolveOpenclawAgent(api, argAgent) {return cfg.agentName ?? process.env["VAULT_AGENT_NAME"] ?? resolveAgentName();}function coerceExpectedAmount(value) {- if (value === undefined || value === null)- return null;- if (typeof value === "number") {- if (!Number.isFinite(value)) {- throw new Error("expected_amount must be a finite number");- }- return value;+ const parsed = parseOptionalFiniteNumberInput(value);+ if (parsed.error === "finite-number") {+ throw new Error("expected_amount must be a finite number");}- if (typeof value === "string") {- const trimmed = value.trim();- if (trimmed === "")- return null;- const parsed = Number(trimmed);- if (!Number.isFinite(parsed)) {- throw new Error("expected_amount must be a number or numeric string");- }- return parsed;+ if (parsed.error === "number-or-numeric-string") {+ throw new Error("expected_amount must be a number or numeric string");}- throw new Error("expected_amount must be a number or numeric string");+ return parsed.value;}function strOrNull(value) {if (value === undefined || value === null)diff --git a/oxlint.json b/oxlint.jsonnew file mode 100644index 00000000..08aad051--- /dev/null+++ b/oxlint.json@@ -0,0 +1,19 @@+{+ "$schema": "./node_modules/oxlint/configuration_schema.json",+ "plugins": ["typescript", "unicorn"],+ "categories": {+ "correctness": "error",+ "perf": "warn",+ "suspicious": "warn"+ },+ "rules": {+ "no-console": "off",+ "no-control-regex": "warn",+ "no-unused-vars": "warn",+ "require-yield": "warn",+ "unicorn/no-new-array": "warn",+ "unicorn/no-useless-fallback-in-spread": "warn",+ "unicorn/no-useless-spread": "warn"+ },+ "ignorePatterns": [".codegraph", "node_modules", "openclaw/**", "dist", "coverage"]+}diff --git a/package.json b/package.jsonindex d15fbb9c..6b08bb63 100644--- a/package.json+++ b/package.json@@ -1,30 +1,25 @@{"name": "open-second-brain","version": "0.14.0",- "type": "module","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",- "license": "MIT",+ "keywords": [+ "agents",+ "mcp",+ "obsidian",+ "openclaw-plugin",+ "second-brain"+ ],"homepage": "https://github.com/itechmeat/open-second-brain",+ "license": "MIT","repository": {"type": "git","url": "https://github.com/itechmeat/open-second-brain.git"},- "keywords": ["second-brain", "obsidian", "agents", "openclaw-plugin", "mcp"],- "engines": {- "bun": ">=1.1.0"- },"bin": {"o2b": "./scripts/o2b","vault-log": "./scripts/vault-log"},- "scripts": {- "build:openclaw": "bun build src/openclaw/index.ts --outfile openclaw/index.js --target=node --format=esm --external openclaw/plugin-sdk/plugin-entry",- "test": "bun test",- "typecheck": "tsc --noEmit",- "sync-version": "bun run scripts/sync-version.ts",- "sync-version:check": "bun run scripts/sync-version.ts --check"- },"files": ["bin/","openclaw/",@@ -37,6 +32,20 @@"LICENSE","pyproject.toml"],+ "type": "module",+ "scripts": {+ "build:openclaw": "bun build src/openclaw/index.ts --outfile openclaw/index.js --target=node --format=esm --external openclaw/plugin-sdk/plugin-entry",+ "test": "bash scripts/test",+ "lint": "oxlint -c oxlint.json",+ "lint:fix": "oxlint -c oxlint.json --fix",+ "fmt": "oxfmt --write '**/*.{ts,js,json}' '.oxfmtrc.json' '!openclaw/index.js' --no-error-on-unmatched-pattern",+ "fmt:check": "oxfmt --check '**/*.{ts,js,json}' '.oxfmtrc.json' '!openclaw/index.js' --no-error-on-unmatched-pattern",+ "typecheck": "tsc --noEmit",+ "validate": "bun run typecheck && bun run lint && bun run test",+ "validate:fix": "bun run lint:fix && bun run fmt",+ "sync-version": "bun run scripts/sync-version.ts",+ "sync-version:check": "bun run scripts/sync-version.ts --check"+ },"dependencies": {"proper-lockfile": "^4.1.2"},@@ -44,12 +53,19 @@"@types/bun": "^1.1.0","@types/node": "^22.0.0","@types/proper-lockfile": "^4.1.4",+ "oxfmt": "0.47.0",+ "oxlint": "1.62.0","typescript": "^5.5.0"},- "openclaw": {- "extensions": ["./openclaw/index.js"]- },"optionalDependencies": {"sqlite-vec": "^0.1.9"+ },+ "engines": {+ "bun": ">=1.1.0"+ },+ "openclaw": {+ "extensions": [+ "./openclaw/index.js"+ ]}}diff --git a/scripts/discipline-report.ts b/scripts/discipline-report.tsindex e79aa985..72c34eb4 100644--- a/scripts/discipline-report.ts+++ b/scripts/discipline-report.ts@@ -43,7 +43,9 @@ if (window) {} else {const res = runDisciplineReport({ vault });if (res.status === "disabled") {- process.stderr.write("o2b-discipline-report: discipline_report disabled in Brain/_brain.yaml\n");+ process.stderr.write(+ "o2b-discipline-report: discipline_report disabled in Brain/_brain.yaml\n",+ );process.exit(0);}process.stdout.write(res.text + "\n");diff --git a/scripts/test b/scripts/testnew file mode 100644index 00000000..4c49e925--- /dev/null+++ b/scripts/test@@ -0,0 +1,13 @@+#!/usr/bin/env bash+set -euo pipefail++SELF=$(realpath -- "${BASH_SOURCE[0]}")+SCRIPT_DIR=$(cd -- "$(dirname -- "$SELF")" && pwd)++# shellcheck source=./_bun-precheck.sh+. "$SCRIPT_DIR/_bun-precheck.sh"++# shellcheck source=./_macos-sqlite.sh+. "$SCRIPT_DIR/_macos-sqlite.sh"++exec bun test "$@"\ No newline at end of filediff --git a/src/cli/brain.ts b/src/cli/brain.tsindex cf795508..2022267f 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -61,60 +61,106 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisif (rest.length === 1 && (rest[0] === "-h" || rest[0] === "--help")) {const text = VERB_HELP[verb];- if (text) { process.stdout.write(text); return 0; }+ 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 "note": return await cmdBrainNote(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 "health": return await cmdBrainHealth(rest);- case "history": return await cmdBrainHistory(rest);- case "backlinks": return await cmdBrainBacklinks(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 "page-dedup": return await cmdBrainPageDedup(rest);- case "token-footprint": return await cmdBrainTokenFootprint(rest);- case "context-pack": return await cmdBrainContextPack(rest);- case "lint": return await cmdBrainLint(rest);- case "actions": return await cmdBrainActions(rest);- case "summary": return await cmdBrainSummary(rest);- case "unlinked": return await cmdBrainUnlinked(rest);- case "synthesise": return await cmdBrainSynthesise(rest);- case "moc-audit": return await cmdBrainMocAudit(rest);- case "timeline": return await cmdBrainTimeline(rest);- case "evolution": return await cmdBrainEvolution(rest);- case "stale": return await cmdBrainStale(rest);- case "daily": return await cmdBrainDaily(rest);- case "weekly": return await cmdBrainWeekly(rest);+ case "init":+ return await cmdBrainInit(rest);+ case "feedback":+ return await cmdBrainFeedback(rest);+ case "note":+ return await cmdBrainNote(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 "health":+ return await cmdBrainHealth(rest);+ case "history":+ return await cmdBrainHistory(rest);+ case "backlinks":+ return await cmdBrainBacklinks(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 "page-dedup":+ return await cmdBrainPageDedup(rest);+ case "token-footprint":+ return await cmdBrainTokenFootprint(rest);+ case "context-pack":+ return await cmdBrainContextPack(rest);+ case "lint":+ return await cmdBrainLint(rest);+ case "actions":+ return await cmdBrainActions(rest);+ case "summary":+ return await cmdBrainSummary(rest);+ case "unlinked":+ return await cmdBrainUnlinked(rest);+ case "synthesise":+ return await cmdBrainSynthesise(rest);+ case "moc-audit":+ return await cmdBrainMocAudit(rest);+ case "timeline":+ return await cmdBrainTimeline(rest);+ case "evolution":+ return await cmdBrainEvolution(rest);+ case "stale":+ return await cmdBrainStale(rest);+ case "daily":+ return await cmdBrainDaily(rest);+ case "weekly":+ return await cmdBrainWeekly(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;}}diff --git a/src/cli/brain/helpers.ts b/src/cli/brain/helpers.tsindex 9591cc3c..6ebf7d7f 100644--- a/src/cli/brain/helpers.ts+++ b/src/cli/brain/helpers.ts@@ -30,10 +30,7 @@ import { NO_VAULT_ERROR, normalizeFlagString } from "../helpers.ts";// ── Vault resolution ────────────────────────────────────────────────────────-export function resolveBrainVault(- flagVal: string | undefined,- configPath: string | null,-): string {+export function resolveBrainVault(flagVal: string | undefined, configPath: string | null): string {// Mirror `requireVault` in `../helpers.ts`: explicit `--vault ""`// is a user error, not an excuse to fall through to `resolveVault`.const explicit = normalizeFlagString(flagVal);diff --git a/src/cli/brain/query-render.ts b/src/cli/brain/query-render.tsindex 0803dea0..d84480d9 100644--- a/src/cli/brain/query-render.ts+++ b/src/cli/brain/query-render.ts@@ -7,15 +7,10 @@*/import type { BrainLogEntry } from "../../core/brain/log.ts";-import {- queryByPreference,- queryByTopic,-} from "../../core/brain/query.ts";+import { queryByPreference, queryByTopic } from "../../core/brain/query.ts";import { info, ok } from "../output.ts";-export function renderQueryPreferenceText(- out: ReturnType<typeof queryByPreference>,-): void {+export function renderQueryPreferenceText(out: ReturnType<typeof queryByPreference>): void {const p = out.preference;ok(`id: ${p.id}`);ok(`topic: ${p.topic}`);@@ -34,10 +29,7 @@ export function renderQueryPreferenceText(}}-export function renderQueryTopicText(- out: ReturnType<typeof queryByTopic>,- topic: string,-): void {+export function renderQueryTopicText(out: ReturnType<typeof queryByTopic>, topic: string): void {ok(`topic: ${topic}`);if (out.preference) {ok(`preference: ${out.preference.id}`);diff --git a/src/cli/brain/upgrade-render.ts b/src/cli/brain/upgrade-render.tsindex 602756e1..9554f94f 100644--- a/src/cli/brain/upgrade-render.ts+++ b/src/cli/brain/upgrade-render.ts@@ -49,10 +49,7 @@ export function printUpgradePlanText(plan: UpgradePlan): void {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.`,- );+ ok(`upgrade: ${plan.pending} pending update(s); ` + `re-run with --apply --yes when ready.`);}}@@ -72,11 +69,7 @@ export function renderUnifiedDiff(before: string, after: string, label: string):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]- ) {+ while (tailA > head && tailB > head && a[tailA - 1] === b[tailB - 1]) {tailA--;tailB--;}diff --git a/src/cli/brain/verbs/actions.ts b/src/cli/brain/verbs/actions.tsindex 90ef6944..91ec1cd0 100644--- a/src/cli/brain/verbs/actions.ts+++ b/src/cli/brain/verbs/actions.ts@@ -10,10 +10,7 @@ import { defaultConfigPath } from "../../../core/config.ts";import { findDuplicateCandidates } from "../../../core/brain/page-dedup.ts";import { lintConsolidate } from "../../../core/brain/lint-consolidate.ts";import { computeTokenFootprint } from "../../../core/brain/token-footprint.ts";-import {- scoreActions,- type ActionInputs,-} from "../../../core/brain/maintenance/action-scorer.ts";+import { scoreActions, type ActionInputs } from "../../../core/brain/maintenance/action-scorer.ts";import { parse, fail, okJson, resolveBrainVault } from "../helpers.ts";export async function cmdBrainActions(argv: string[]): Promise<number> {@@ -29,9 +26,7 @@ export async function cmdBrainActions(argv: string[]): Promise<number> {if (topNRaw !== undefined) {const parsed = Number(topNRaw);if (!Number.isInteger(parsed) || parsed <= 0) {- return fail(- `brain actions: --top-n must be a positive integer; got ${topNRaw}`,- );+ return fail(`brain actions: --top-n must be a positive integer; got ${topNRaw}`);}topN = parsed;}diff --git a/src/cli/brain/verbs/apply-evidence.ts b/src/cli/brain/verbs/apply-evidence.tsindex e4b947ea..ac890953 100644--- a/src/cli/brain/verbs/apply-evidence.ts+++ b/src/cli/brain/verbs/apply-evidence.ts@@ -1,5 +1,8 @@import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";-import { appendApplyEvidence, BrainPreferenceNotFoundError } from "../../../core/brain/apply-evidence.ts";+import {+ appendApplyEvidence,+ BrainPreferenceNotFoundError,+} from "../../../core/brain/apply-evidence.ts";import { parse, fail, normalizeFlagString, ok, okJson, resolveBrainVault } from "../helpers.ts";export async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {diff --git a/src/cli/brain/verbs/digest.ts b/src/cli/brain/verbs/digest.tsindex cae5f15f..01fc3d0c 100644--- a/src/cli/brain/verbs/digest.ts+++ b/src/cli/brain/verbs/digest.ts@@ -1,6 +1,6 @@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";+import { parse, fail, resolveBrainVault, parseOptionalIsoDate } from "../helpers.ts";export function parseWindow(raw: string): number {const m = /^(\d+)(?:d)?$/.exec(raw);@@ -22,22 +22,11 @@ export async function cmdBrainDigest(argv: string[]): Promise<number> {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 { value: parsedSinceDate, error: sinceErr } = parseOptionalIsoDate(flags, "since");+ if (sinceErr) return fail(sinceErr);+ let sinceDate = parsedSinceDate;+ const { value: untilDate, error: untilErr } = parseOptionalIsoDate(flags, "until");+ if (untilErr) return fail(untilErr);if (flags["window"]) {if (flags["since"]) {return fail("--since and --window are mutually exclusive");diff --git a/src/cli/brain/verbs/doctor.ts b/src/cli/brain/verbs/doctor.tsindex 3da92edf..b0e51f7d 100644--- a/src/cli/brain/verbs/doctor.ts+++ b/src/cli/brain/verbs/doctor.ts@@ -20,8 +20,11 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {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}`); }+ try {+ result = runDoctor(vault, { strict: Boolean(flags["strict"]) });+ } catch (exc) {+ return fail(`doctor failed: ${(exc as Error).message ?? exc}`);+ }if (flags["remediate"]) {// Never auto-repair a vault that has structural errors - those need@@ -40,10 +43,14 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {}if (flags["json"]) {- process.stdout.write(JSON.stringify({ warnings: result.warnings, errors: result.errors }, null, 2) + "\n");+ 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`);+ 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");}@@ -67,7 +74,9 @@ function runRemediate(let stepCap = 20;try {stepCap = resolveHealth(loadBrainConfigDetailed(vault).config).remediation_step_cap;- } catch { /* fall back to default cap */ }+ } catch {+ /* fall back to default cap */+ }const sh = result.semantic_health;const plan = planRemediation(diff --git a/src/cli/brain/verbs/dream.ts b/src/cli/brain/verbs/dream.tsindex 5dc54dda..531a8193 100644--- a/src/cli/brain/verbs/dream.ts+++ b/src/cli/brain/verbs/dream.ts@@ -1,6 +1,6 @@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";+import { parse, fail, ok, resolveBrainVault, parseOptionalIsoDate } from "../helpers.ts";export async function cmdBrainDream(argv: string[]): Promise<number> {const { flags } = parse(argv, {@@ -25,23 +25,13 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {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;- }+ const { value: now, error: nowErr } = parseOptionalIsoDate(flags, "now");+ if (nowErr) return fail(nowErr);let summary;try {summary = dream(vault, {- ...(now !== undefined ? { now } : {}),+ ...(now !== null ? { now } : {}),dryRun: Boolean(flags["dry-run"]),...(agent ? { agentName: agent } : {}),});@@ -59,10 +49,13 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {}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.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.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}`);+ 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.tsindex 77751126..579b3ba0 100644--- a/src/cli/brain/verbs/explorer.ts+++ b/src/cli/brain/verbs/explorer.ts@@ -1,7 +1,12 @@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 {+ 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> {@@ -17,24 +22,31 @@ export async function cmdBrainExplorer(argv: string[]): Promise<number> {const force = flags["force"] === true;if (exportPath !== undefined) {- if (existsSync(exportPath) && !force) return fail(`${exportPath} exists; pass --force to overwrite`);+ 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}`); }+ 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}`);+ 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) {+ 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>`);+ 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}`);}@@ -45,7 +57,10 @@ export async function cmdBrainExplorer(argv: string[]): Promise<number> {// always settles — without the catch, a rejected `server.close()`// leaves the outer await pending and Ctrl+C hangs the process.const stop = (): void => {- void server.close().catch(() => undefined).finally(() => resolveStop());+ void server+ .close()+ .catch(() => undefined)+ .finally(() => resolveStop());};process.once("SIGINT", stop);process.once("SIGTERM", stop);diff --git a/src/cli/brain/verbs/export.ts b/src/cli/brain/verbs/export.tsindex 9b42c315..b7f26aa9 100644--- a/src/cli/brain/verbs/export.ts+++ b/src/cli/brain/verbs/export.ts@@ -21,14 +21,26 @@ export async function cmdBrainExport(argv: string[]): Promise<number> {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}`); }+ 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}`); }+ 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.tsindex 63860859..de6b613a 100644--- a/src/cli/brain/verbs/feedback.ts+++ b/src/cli/brain/verbs/feedback.ts@@ -4,7 +4,11 @@ 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 {+ 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";@@ -78,7 +82,12 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {appendLogEvent(vault, {timestamp: isoSecond(now),eventType: BRAIN_LOG_EVENT_KIND.feedback,- body: { signal: `[[${sigResult.id}]]`, topic: String(flags["topic"]), sign: signalSign, agent },+ 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`);@@ -87,17 +96,21 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {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 });+ 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}`);}@@ -105,10 +118,15 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {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 },+ 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`);+ process.stderr.write(+ `warning: append force-confirmed log failed: ${(err as Error).message}\n`,+ );}}diff --git a/src/cli/brain/verbs/history.ts b/src/cli/brain/verbs/history.tsindex 3f04a539..b4594c82 100644--- a/src/cli/brain/verbs/history.ts+++ b/src/cli/brain/verbs/history.ts@@ -1,8 +1,5 @@import { defaultConfigPath } from "../../../core/config.ts";-import {- readEditHistory,- renderEditHistory,-} from "../../../core/brain/health/edit-history.ts";+import { readEditHistory, renderEditHistory } from "../../../core/brain/health/edit-history.ts";import { fail, parse, resolveBrainVault } from "../helpers.ts";/**diff --git a/src/cli/brain/verbs/import-claude-memory.ts b/src/cli/brain/verbs/import-claude-memory.tsindex 5c5b28b4..88235578 100644--- a/src/cli/brain/verbs/import-claude-memory.ts+++ b/src/cli/brain/verbs/import-claude-memory.ts@@ -24,19 +24,60 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<numberfor (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; }+ 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");+ process.stderr.write(+ "o2b brain import-claude-memory: --apply requires --yes in non-interactive mode\n",+ );return 2;}@@ -44,22 +85,36 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<numberconst 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; }+ 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 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`);+ 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`);+ 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`);diff --git a/src/cli/brain/verbs/import-session.ts b/src/cli/brain/verbs/import-session.tsindex 268ab6df..62a59aad 100644--- a/src/cli/brain/verbs/import-session.ts+++ b/src/cli/brain/verbs/import-session.ts@@ -5,7 +5,16 @@ 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, info, normalizeFlagString, ok, okJson, resolveBrainVault, ISO_8601_RE } from "../helpers.ts";+import {+ parse,+ fail,+ info,+ normalizeFlagString,+ ok,+ okJson,+ resolveBrainVault,+ parseOptionalIsoDate,+} from "../helpers.ts";export async function cmdBrainImportSession(argv: string[]): Promise<number> {const { flags, positional } = parse(argv, {@@ -29,42 +38,78 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {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}`);+ 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;- }+ const { value: since, error: sinceErr } = parseOptionalIsoDate(flags, "since");+ if (sinceErr) return fail(sinceErr);let stat;- try { stat = statSync(sessionPath); }- catch (err) { return fail(`cannot stat ${sessionPath}: ${(err as Error).message ?? err}`); }+ 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: [] };+ ? 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) },+ 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`); }+ } 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 })),+ 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 {diff --git a/src/cli/brain/verbs/init.ts b/src/cli/brain/verbs/init.tsindex d8e3cf51..a24ad3fe 100644--- a/src/cli/brain/verbs/init.ts+++ b/src/cli/brain/verbs/init.ts@@ -48,7 +48,12 @@ export async function cmdBrainInit(argv: string[]): Promise<number> {}if (flags["json"]) {- okJson({ vault, created: result.created, overwritten: result.overwritten, skipped: result.skipped });+ okJson({+ vault,+ created: result.created,+ overwritten: result.overwritten,+ skipped: result.skipped,+ });return 0;}ok(`brain initialized: ${vault}`);diff --git a/src/cli/brain/verbs/merge.ts b/src/cli/brain/verbs/merge.tsindex 1957f974..d7457a0f 100644--- a/src/cli/brain/verbs/merge.ts+++ b/src/cli/brain/verbs/merge.ts@@ -10,7 +10,8 @@ export async function cmdBrainMerge(argv: string[]): Promise<number> {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>");+ 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);@@ -21,7 +22,11 @@ export async function cmdBrainMerge(argv: string[]): Promise<number> {let plan;try {- plan = mergePreferences(vault, keepId, dropId, { now: new Date(), agentName: agent, dryRun: true });+ 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}`);@@ -39,27 +44,44 @@ export async function cmdBrainMerge(argv: string[]): Promise<number> {];if (dryRun) {- if (wantJson) { okJson({ dry_run: true, plan }); }- else { for (const line of planLines) ok(line); ok("dry-run; no changes written"); }+ 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)");+ 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; }+ if (ans !== "y" && ans !== "yes") {+ ok("merge cancelled");+ return 0;+ }}- try { mergePreferences(vault, keepId, dropId, { now: new Date(), agentName: agent }); }- catch (exc) {+ 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)`); }+ 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/moc-audit.ts b/src/cli/brain/verbs/moc-audit.tsindex a71606c6..d02b10c4 100644--- a/src/cli/brain/verbs/moc-audit.ts+++ b/src/cli/brain/verbs/moc-audit.ts@@ -1,8 +1,5 @@import { defaultConfigPath } from "../../../core/config.ts";-import {- auditMoc,- MocAuditError,-} from "../../../core/brain/link-graph/moc-audit.ts";+import { auditMoc, MocAuditError } from "../../../core/brain/link-graph/moc-audit.ts";import { normaliseWikilinkTarget } from "../../../core/brain/wikilink.ts";import { parse, fail, resolveBrainVault } from "../helpers.ts";@@ -42,9 +39,7 @@ export async function cmdBrainMocAudit(argv: string[]): Promise<number> {well_covered: report.wellCovered,fragile: report.fragile,candidate_missing: report.candidateMissing,- ...(report.suggestedNext- ? { suggested_next: report.suggestedNext }- : {}),+ ...(report.suggestedNext ? { suggested_next: report.suggestedNext } : {}),},null,2,@@ -53,9 +48,7 @@ export async function cmdBrainMocAudit(argv: string[]): Promise<number> {return 0;}- process.stdout.write(- `MOC audit for ${report.hubId} (${report.outboundCount} outbound):\n`,- );+ process.stdout.write(`MOC audit for ${report.hubId} (${report.outboundCount} outbound):\n`);process.stdout.write(` well-covered: ${report.wellCovered.length}\n`);for (const m of report.wellCovered) {process.stdout.write(` ${m.id} (backlinks=${m.backlinkCount}, body=${m.bodyChars})\n`);diff --git a/src/cli/brain/verbs/note.ts b/src/cli/brain/verbs/note.tsindex 8f153c28..a0ae51f3 100644--- a/src/cli/brain/verbs/note.ts+++ b/src/cli/brain/verbs/note.ts@@ -7,13 +7,7 @@import { defaultConfigPath } from "../../../core/config.ts";import { appendBrainNote } from "../../../core/brain/note.ts";-import {- normalizeFlagString,- ok,- okJson,- parse,- resolveBrainVault,-} from "../helpers.ts";+import { normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";const USAGE_ERROR_EXIT = 2;@@ -31,14 +25,10 @@ export async function cmdBrainNote(argv: string[]): Promise<number> {});if (positional.length === 0) {- return usageError(- 'brain note requires a text argument: o2b brain note "<text>"',- );+ return usageError('brain note requires a text argument: o2b brain note "<text>"');}if (positional.length > 1) {- return usageError(- "brain note takes exactly one positional argument — quote multi-word text",- );+ return usageError("brain note takes exactly one positional argument — quote multi-word text");}const text = positional[0]!;// Pre-validate empty / whitespace-only text at the CLI surface so a@@ -47,9 +37,7 @@ export async function cmdBrainNote(argv: string[]): Promise<number> {// the catch arm below maps to exit 1 — that drift is on the spec// (design §7.2: "Empty / whitespace only → exit 2").if (text.trim().length === 0) {- return usageError(- 'brain note requires non-empty text: o2b brain note "<text>"',- );+ return usageError('brain note requires non-empty text: o2b brain note "<text>"');}const config = (flags["config"] as string | undefined) ?? defaultConfigPath();diff --git a/src/cli/brain/verbs/page-dedup.ts b/src/cli/brain/verbs/page-dedup.tsindex 3a76d11a..5817de5f 100644--- a/src/cli/brain/verbs/page-dedup.ts+++ b/src/cli/brain/verbs/page-dedup.ts@@ -9,10 +9,7 @@*/import { defaultConfigPath } from "../../../core/config.ts";-import {- findDuplicateCandidates,- mergePage,-} from "../../../core/brain/page-dedup.ts";+import { findDuplicateCandidates, mergePage } from "../../../core/brain/page-dedup.ts";import { parse, fail, okJson, resolveBrainVault } from "../helpers.ts";export async function cmdBrainPageDedup(argv: string[]): Promise<number> {@@ -27,9 +24,7 @@ export async function cmdBrainPageDedup(argv: string[]): Promise<number> {const apply = Boolean(flags["apply"]);if (apply && !flags["yes"] && (flags["json"] || !process.stdin.isTTY)) {- return fail(- "brain page-dedup --apply requires --yes in non-interactive mode",- );+ return fail("brain page-dedup --apply requires --yes in non-interactive mode");}const report = findDuplicateCandidates(vault);@@ -49,9 +44,7 @@ export async function cmdBrainPageDedup(argv: string[]): Promise<number> {process.stdout.write(`pages scanned: ${report.scanned}\n`);process.stdout.write(`duplicate clusters: ${report.candidates.length}\n`);for (const c of report.candidates) {- process.stdout.write(- `\ncanonical: ${c.canonical.id} (topic: ${c.canonical.topic})\n`,- );+ process.stdout.write(`\ncanonical: ${c.canonical.id} (topic: ${c.canonical.topic})\n`);for (const s of c.secondaries) {process.stdout.write(` -> ${s.id}\n`);}diff --git a/src/cli/brain/verbs/pin.ts b/src/cli/brain/verbs/pin.tsindex f5673faa..5b6bc0ce 100644--- a/src/cli/brain/verbs/pin.ts+++ b/src/cli/brain/verbs/pin.ts@@ -25,15 +25,26 @@ async function pinOrUnpin(argv: string[], value: boolean): Promise<number> {const slug = id.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}`); }+ 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; }+ 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); }+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.tsindex f59bd71d..15961744 100644--- a/src/cli/brain/verbs/protect.ts+++ b/src/cli/brain/verbs/protect.ts@@ -1,5 +1,12 @@import { defaultConfigPath } from "../../../core/config.ts";-import { applyProtect, BrainProtectError, isProtectTarget, printSnippet, PROTECT_TARGETS, unprotect } from "../../../core/brain/protect.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> {@@ -11,7 +18,9 @@ export async function cmdBrainProtect(argv: string[]): Promise<number> {});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(", ")}`);+ 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());@@ -19,14 +28,27 @@ export async function cmdBrainProtect(argv: string[]): Promise<number> {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)`;+ 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; }+ 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`);@@ -46,15 +68,24 @@ export async function cmdBrainUnprotect(argv: string[]): Promise<number> {});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(", ")}`);+ 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; }+ 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}`); }+ 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.tsindex 27326486..95482f40 100644--- a/src/cli/brain/verbs/query.ts+++ b/src/cli/brain/verbs/query.ts@@ -1,6 +1,19 @@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";+import {+ queryByLogSince,+ queryByPreference,+ queryByTopic,+ BrainNotFoundError,+} from "../../../core/brain/query.ts";+import {+ parse,+ fail,+ resolveBrainVault,+ parseOptionalIsoDate,+ renderQueryPreferenceText,+ renderQueryTopicText,+ renderQueryLogText,+} from "../helpers.ts";export async function cmdBrainQuery(argv: string[]): Promise<number> {const { flags } = parse(argv, {@@ -16,34 +29,48 @@ export async function cmdBrainQuery(argv: string[]): Promise<number> {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(", ")})`);+ 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); }+ 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"])); }+ 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); }+ const { value: sinceDate, error: sinceErr } = parseOptionalIsoDate(flags, "since");+ if (sinceErr) return fail(sinceErr);+ const entries = queryByLogSince(vault, sinceDate!);+ 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; }+ 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.tsindex d742f7c7..3aae85c8 100644--- a/src/cli/brain/verbs/reject.ts+++ b/src/cli/brain/verbs/reject.ts@@ -20,7 +20,9 @@ export async function cmdBrainReject(argv: string[]): Promise<number> {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)");+ 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);@@ -34,8 +36,11 @@ export async function cmdBrainReject(argv: string[]): Promise<number> {return 2;}let pref;- try { pref = parsePreference(path); }- catch (exc) { return fail(`failed to parse preference: ${(exc as Error).message ?? exc}`); }+ 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`);@@ -48,7 +53,11 @@ export async function cmdBrainReject(argv: string[]): Promise<number> {const reasonText = String(flags["reason"]).trim();try {- moveToRetired(vault, path, "user-rejected", { now, retired_by: retiredBy, user_rejected_reason: reasonText });+ 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}`);}@@ -60,12 +69,19 @@ export async function cmdBrainReject(argv: string[]): Promise<number> {};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 });+ 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)`); }+ 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.tsindex 4c668381..bde18f17 100644--- a/src/cli/brain/verbs/rollback.ts+++ b/src/cli/brain/verbs/rollback.ts@@ -1,13 +1,33 @@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 {+ 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";+import {+ parse,+ fail,+ ok,+ okJson,+ resolveBrainVault,+ diffSummary,+ readSingleLine,+} from "../helpers.ts";export async function cmdBrainRollback(argv: string[]): Promise<number> {const { flags, positional } = parse(argv, {@@ -24,34 +44,52 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {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; }+ 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)");+ 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`);+ 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 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; }+ 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;}@@ -59,19 +97,27 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {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 {+ 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 });+ 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(); }+ } 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)");+ 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` +@@ -79,20 +125,38 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {`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; }+ 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 {+ 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) };+ 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`); }+ 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)`); }+ 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.tsindex a4d83216..ec28961c 100644--- a/src/cli/brain/verbs/scan-inline.ts+++ b/src/cli/brain/verbs/scan-inline.ts@@ -22,26 +22,47 @@ export async function cmdBrainScanInline(argv: string[]): Promise<number> {let result;try {result = await scanInline(vault, {- agent, dryRun: Boolean(flags["dry-run"]),+ 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}`); }+ } 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) },+ 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`); }+ } 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,+ 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 })),+ files_with_markers: result.filesWithMarkers.map((f) => ({+ path: f.path,+ markers: f.markers,+ })),});} else {ok(`scanned: ${result.scanned}`);diff --git a/src/cli/brain/verbs/set-primary.ts b/src/cli/brain/verbs/set-primary.tsindex 779e1406..e34aa11c 100644--- a/src/cli/brain/verbs/set-primary.ts+++ b/src/cli/brain/verbs/set-primary.ts@@ -13,10 +13,12 @@ export async function cmdBrainSetPrimary(argv: string[]): Promise<number> {let name: string | null;if (flags["clear"]) {- if (positional.length > 0) return fail("brain set-primary --clear takes no positional argument");+ 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 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");@@ -24,13 +26,22 @@ export async function cmdBrainSetPrimary(argv: string[]): Promise<number> {}let result;- try { result = setPrimaryAgent(vault, name); }- catch (exc) { return fail(`set-primary failed: ${(exc as Error).message ?? exc}`); }+ 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; }+ 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)}`); }+ 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.tsindex 55c88e8c..a992e9a0 100644--- a/src/cli/brain/verbs/snapshot.ts+++ b/src/cli/brain/verbs/snapshot.ts@@ -1,4 +1,8 @@-import { listSnapshots, extractSnapshotToTemp, type ExtractSnapshotResult } from "../../../core/brain/snapshot.ts";+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";@@ -14,16 +18,22 @@ export async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {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)");+ 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`);+ 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`);+ process.stderr.write(+ `snapshot not found: ${b}; run \`o2b brain rollback --list\` to enumerate.\n`,+ );return 2;}@@ -31,9 +41,12 @@ export async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {let extB: ExtractSnapshotResult | null = null;try {extA = extractSnapshotToTemp(vault, a!);- const bRoot = b !== undefined ? (extB = extractSnapshotToTemp(vault, b)).brainRoot : brainDirs(vault).brain;+ 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" });+ 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) {@@ -57,7 +70,8 @@ export async function handleBrainSnapshotSubcommand(argv: ReadonlyArray<string>)const sub = argv[0]!;const rest = argv.slice(1);switch (sub) {- case "diff": return await cmdBrainSnapshotDiff([...rest]);+ 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/summary.ts b/src/cli/brain/verbs/summary.tsindex 0a3a702e..56a2dc79 100644--- a/src/cli/brain/verbs/summary.ts+++ b/src/cli/brain/verbs/summary.ts@@ -30,9 +30,7 @@ export async function cmdBrainSummary(argv: string[]): Promise<number> {if (topRaw !== undefined) {const n = Number(topRaw);if (!Number.isInteger(n) || n < 0) {- return fail(- `brain summary: --top-actions must be a non-negative integer; got ${topRaw}`,- );+ return fail(`brain summary: --top-actions must be a non-negative integer; got ${topRaw}`);}topActionsN = n;}diff --git a/src/cli/brain/verbs/synthesise.ts b/src/cli/brain/verbs/synthesise.tsindex 7086e38a..313caba4 100644--- a/src/cli/brain/verbs/synthesise.ts+++ b/src/cli/brain/verbs/synthesise.ts@@ -45,9 +45,7 @@ export async function cmdBrainSynthesise(argv: string[]): Promise<number> {return 0;}- process.stdout.write(- `Concept cluster for ${cluster.targetId} (${cluster.targetTitle}):\n`,- );+ process.stdout.write(`Concept cluster for ${cluster.targetId} (${cluster.targetTitle}):\n`);process.stdout.write(` Linkers: ${cluster.linkers.length}\n`);for (const l of cluster.linkers) {const anchor = l.targetAnchor ? `#${l.targetAnchor}` : "";@@ -58,9 +56,7 @@ export async function cmdBrainSynthesise(argv: string[]): Promise<number> {);}if (cluster.unlinkedMentions.length > 0) {- process.stdout.write(- ` Unlinked mentions: ${cluster.unlinkedMentions.length}\n`,- );+ process.stdout.write(` Unlinked mentions: ${cluster.unlinkedMentions.length}\n`);for (const m of cluster.unlinkedMentions) {process.stdout.write(` ${m.source}:${m.line} (${m.term})\n`);}diff --git a/src/cli/brain/verbs/temporal-daily.ts b/src/cli/brain/verbs/temporal-daily.tsindex 9215c681..19c46190 100644--- a/src/cli/brain/verbs/temporal-daily.ts+++ b/src/cli/brain/verbs/temporal-daily.ts@@ -39,9 +39,7 @@ export async function cmdBrainDaily(argv: string[]): Promise<number> {}process.stdout.write(`Daily brief ${brief.date}\n`);- process.stdout.write(- ` window: ${brief.window.since} .. ${brief.window.until}\n`,- );+ process.stdout.write(` window: ${brief.window.since} .. ${brief.window.until}\n`);process.stdout.write(` events by kind:\n`);for (const [kind, count] of Object.entries(brief.eventsByKind)) {process.stdout.write(` ${kind}: ${count}\n`);diff --git a/src/cli/brain/verbs/temporal-evolution.ts b/src/cli/brain/verbs/temporal-evolution.tsindex 6aa69676..d5d30548 100644--- a/src/cli/brain/verbs/temporal-evolution.ts+++ b/src/cli/brain/verbs/temporal-evolution.ts@@ -56,9 +56,7 @@ export async function cmdBrainEvolution(argv: string[]): Promise<number> {return 0;}-function trimOrUndefined(- v: string | boolean | string[] | undefined,-): string | undefined {+function trimOrUndefined(v: string | boolean | string[] | undefined): string | undefined {if (typeof v !== "string") return undefined;const t = v.trim();return t.length > 0 ? t : undefined;@@ -75,13 +73,9 @@ function buildEvolutionTarget(topic: string | undefined,): BeliefEvolutionTarget {if (prefId !== undefined && topic !== undefined) {- throw new CliError(- "brain evolution: pass exactly one of --pref-id or --topic",- );+ throw new CliError("brain evolution: pass exactly one of --pref-id or --topic");}if (prefId !== undefined) return { prefId };if (topic !== undefined) return { topic };- throw new CliError(- "brain evolution: pass exactly one of --pref-id or --topic",- );+ throw new CliError("brain evolution: pass exactly one of --pref-id or --topic");}diff --git a/src/cli/brain/verbs/temporal-timeline.ts b/src/cli/brain/verbs/temporal-timeline.tsindex 70901d84..15ba83ac 100644--- a/src/cli/brain/verbs/temporal-timeline.ts+++ b/src/cli/brain/verbs/temporal-timeline.ts@@ -1,8 +1,5 @@import { defaultConfigPath } from "../../../core/config.ts";-import {- isBrainLogEventKind,- type BrainLogEventKind,-} from "../../../core/brain/types.ts";+import { isBrainLogEventKind, type BrainLogEventKind } from "../../../core/brain/types.ts";import { buildTimelineIndex } from "../../../core/brain/temporal/build-index.ts";import { selectEvents } from "../../../core/brain/temporal/select-events.ts";import { CliError, parse, resolveBrainVault } from "../helpers.ts";@@ -72,31 +69,22 @@ export async function cmdBrainTimeline(argv: string[]): Promise<number> {if (flags["json"]) {process.stdout.write(- JSON.stringify(- { window: index.window, total: events.length, events: sliced },- null,- 2,- ) + "\n",+ JSON.stringify({ window: index.window, total: events.length, events: sliced }, null, 2) ++ "\n",);return 0;}- process.stdout.write(- `Timeline window ${index.window.since} .. ${index.window.until}\n`,- );+ process.stdout.write(`Timeline window ${index.window.since} .. ${index.window.until}\n`);process.stdout.write(`${sliced.length} of ${events.length} event(s):\n`);for (const ev of sliced) {const slug = ev.prefId ?? ev.topic ?? "-";- process.stdout.write(- ` ${ev.at} ${ev.kind} ${slug}${ev.result ? ` [${ev.result}]` : ""}\n`,- );+ process.stdout.write(` ${ev.at} ${ev.kind} ${slug}${ev.result ? ` [${ev.result}]` : ""}\n`);}return 0;}-function trimOrUndefined(- v: string | boolean | string[] | undefined,-): string | undefined {+function trimOrUndefined(v: string | boolean | string[] | undefined): string | undefined {if (typeof v !== "string") return undefined;const t = v.trim();return t.length > 0 ? t : undefined;diff --git a/src/cli/brain/verbs/temporal-weekly.ts b/src/cli/brain/verbs/temporal-weekly.tsindex 282cdc05..b51442dc 100644--- a/src/cli/brain/verbs/temporal-weekly.ts+++ b/src/cli/brain/verbs/temporal-weekly.ts@@ -60,9 +60,7 @@ export async function cmdBrainWeekly(argv: string[]): Promise<number> {* (`YYYY-MM-DD`); rejects whitespace-only / malformed input as a CLI* error so the underlying helper does not see garbage.*/-function resolveWeekEndArg(- raw: string | boolean | string[] | undefined,-): string {+function resolveWeekEndArg(raw: string | boolean | string[] | undefined): string {if (typeof raw !== "string" || raw.trim().length === 0) {return new Date().toISOString().slice(0, 10);}diff --git a/src/cli/brain/verbs/token-footprint.ts b/src/cli/brain/verbs/token-footprint.tsindex a2d309a3..88a0c9cd 100644--- a/src/cli/brain/verbs/token-footprint.ts+++ b/src/cli/brain/verbs/token-footprint.ts@@ -49,9 +49,7 @@ export async function cmdBrainTokenFootprint(argv: string[]): Promise<number> {return 0;}- process.stdout.write(- `total tokens: ${report.total} (across ${report.files} file(s))\n`,- );+ process.stdout.write(`total tokens: ${report.total} (across ${report.files} file(s))\n`);process.stdout.write(`warn threshold: ${report.warnThreshold}\n`);if (report.exceeded) {process.stdout.write(`WARN: vault exceeds ${report.warnThreshold} tokens\n`);diff --git a/src/cli/brain/verbs/unlinked.ts b/src/cli/brain/verbs/unlinked.tsindex 7813bb64..971ae5f0 100644--- a/src/cli/brain/verbs/unlinked.ts+++ b/src/cli/brain/verbs/unlinked.ts@@ -39,9 +39,7 @@ export async function cmdBrainUnlinked(argv: string[]): Promise<number> {limit = parsed;}- const mentions = findUnlinkedMentions(vault, target, {- ...(limit !== undefined ? { limit } : {}),- });+ const mentions = findUnlinkedMentions(vault, target, limit !== undefined ? { limit } : {});if (flags["json"]) {process.stdout.write(@@ -63,13 +61,9 @@ export async function cmdBrainUnlinked(argv: string[]): Promise<number> {return 0;}- process.stdout.write(- `Unlinked mentions of ${target}: ${mentions.length}\n`,- );+ process.stdout.write(`Unlinked mentions of ${target}: ${mentions.length}\n`);for (const m of mentions) {- process.stdout.write(- ` ${m.source}:${m.line} (${m.term}) ${m.contextSnippet.trim()}\n`,- );+ process.stdout.write(` ${m.source}:${m.line} (${m.term}) ${m.contextSnippet.trim()}\n`);}return 0;}diff --git a/src/cli/brain/verbs/upgrade.ts b/src/cli/brain/verbs/upgrade.tsindex 822637be..6573ffe3 100644--- a/src/cli/brain/verbs/upgrade.ts+++ b/src/cli/brain/verbs/upgrade.ts@@ -1,6 +1,20 @@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";+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, {@@ -14,51 +28,86 @@ export async function cmdBrainUpgrade(argv: string[]): Promise<number> {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");+ 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}`); }+ 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); }+ 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); }+ 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.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."); }+ 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)");+ 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("") ++ 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; }+ 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; }+ 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 {+ 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}`);diff --git a/src/cli/coerce.ts b/src/cli/coerce.tsindex e39b0a91..b01c9ec4 100644--- a/src/cli/coerce.ts+++ b/src/cli/coerce.ts@@ -5,6 +5,8 @@* `{ value, error }` tuple so the caller can decide the exit code.*/+import { parseOptionalFiniteNumberInput } from "../core/validate.ts";+/*** Parse an optional `--<name>` flag whose value should be a finite number.* Returns `{ value: number | null, error: string | null }`.@@ -21,15 +23,16 @@ export function parseOptionalNumberFlag(// flag schema — surface it as a clean validation error instead of// throwing at the `.trim()` call below.if (typeof raw !== "string") {- return { value: null, error: `--${name} must be provided as a single string value` };+ return {+ value: null,+ error: `--${name} must be provided as a single string value`,+ };}- const trimmed = raw.trim();- if (trimmed === "") return { value: null, error: null };- const parsed = Number(trimmed);- if (!Number.isFinite(parsed)) {+ const parsed = parseOptionalFiniteNumberInput(raw);+ if (parsed.error !== null) {return { value: null, error: `--${name} must be a number, got: ${raw}` };}- return { value: parsed, error: null };+ return { value: parsed.value, error: null };}/**@@ -45,8 +48,7 @@ export function parseOptionalNumberFlag(* `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})$/;+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.@@ -59,16 +61,25 @@ export function parseOptionalIsoDate(const raw = flags[name];if (raw === undefined) return { value: null, error: null };if (typeof raw !== "string") {- return { value: null, error: `--${name} must be provided as a single string value` };+ return {+ value: null,+ error: `--${name} must be provided as a single string value`,+ };}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}` };+ 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: null,+ error: `--${name} must be a valid ISO-8601 timestamp; got ${raw}`,+ };}return { value: d, error: null };}diff --git a/src/cli/discipline-install.ts b/src/cli/discipline-install.tsindex 6e533024..e012aefe 100644--- a/src/cli/discipline-install.ts+++ b/src/cli/discipline-install.ts@@ -33,10 +33,7 @@ function scriptPath(): string {}function jobId(vault: string): string {- const slug = createHash("sha256")- .update(resolve(vault))- .digest("hex")- .slice(0, 12);+ const slug = createHash("sha256").update(resolve(vault)).digest("hex").slice(0, 12);return `osb-discipline-report-${slug}`;}@@ -72,8 +69,9 @@ function loadJobs(file: string): JobsFile {} catch (e) {throw new Error(`o2b discipline: jobs file is corrupted JSON: ${file}\n` +- `Original error: ${(e as Error).message}\n` +- `Resolve manually before re-running install/uninstall.`,+ `Original error: ${(e as Error).message}\n` ++ `Resolve manually before re-running install/uninstall.`,+ { cause: e },);}if (@@ -81,9 +79,7 @@ function loadJobs(file: string): JobsFile {typeof parsed !== "object" ||!Array.isArray((parsed as { jobs?: unknown }).jobs)) {- throw new Error(- `o2b discipline: jobs file is missing the jobs[] array: ${file}`,- );+ throw new Error(`o2b discipline: jobs file is missing the jobs[] array: ${file}`);}return parsed as JobsFile;}@@ -99,10 +95,7 @@ function pickVault(args: ReadonlyArray<string>, defaultVault: string): string {return defaultVault;}-export async function disciplineInstallVerb(- args: string[],- defaultVault: string,-): Promise<number> {+export async function disciplineInstallVerb(args: string[], defaultVault: string): Promise<number> {let vault = pickVault(args, defaultVault);let telegramTarget = "";let at = "59 4 * * *";@@ -189,9 +182,7 @@ export async function disciplineUninstallVerb(}vault = vault ?? defaultVault;if (!vault) {- process.stderr.write(- "o2b discipline uninstall: --vault is required\n",- );+ process.stderr.write("o2b discipline uninstall: --vault is required\n");return 2;}const file = jobsFilePath();diff --git a/src/cli/discipline.ts b/src/cli/discipline.tsindex 9a457d6c..4a0a4f0a 100644--- a/src/cli/discipline.ts+++ b/src/cli/discipline.ts@@ -7,20 +7,14 @@import { defaultConfigPath, resolveVault } from "../core/config.ts";import { runDisciplineReport } from "../core/discipline/report.ts";-import {- disciplineInstallVerb,- disciplineUninstallVerb,-} from "./discipline-install.ts";+import { disciplineInstallVerb, disciplineUninstallVerb } from "./discipline-install.ts";const NO_VAULT_ERROR ="error: no vault configured. Pass --vault <path> explicitly, " +"set VAULT_DIR in the environment, or run " +"`o2b init --vault <path> ...` first to persist a default.";-function resolveDisciplineVault(- flagVal: string | undefined,- configPath: string | null,-): string {+function resolveDisciplineVault(flagVal: string | undefined, configPath: string | null): string {const vault = flagVal ?? resolveVault(configPath ?? undefined);if (vault === null || vault === undefined) {process.stderr.write(NO_VAULT_ERROR + "\n");@@ -29,10 +23,7 @@ function resolveDisciplineVault(return vault;}-export async function disciplineReportVerb(- args: string[],- defaultVault: string,-): Promise<number> {+export async function disciplineReportVerb(args: string[], defaultVault: string): Promise<number> {let vault = defaultVault;for (let i = 0; i < args.length; i++) {if (args[i] === "--vault" && args[i + 1]) {@@ -51,9 +42,7 @@ export async function disciplineReportVerb(return 0;}-export async function handleDisciplineSubcommand(- argv: ReadonlyArray<string>,-): Promise<number> {+export async function handleDisciplineSubcommand(argv: ReadonlyArray<string>): Promise<number> {const verb = argv[0];const rest = argv.slice(1) as string[];@@ -86,9 +75,7 @@ export async function handleDisciplineSubcommand(return await disciplineUninstallVerb(rest, vault);}default:- process.stderr.write(- `error: unknown discipline subcommand: ${verb ?? "(none)"}\n`,- );+ process.stderr.write(`error: unknown discipline subcommand: ${verb ?? "(none)"}\n`);return 2;}}diff --git a/src/cli/helpers.ts b/src/cli/helpers.tsindex 67f51cbf..11111c2e 100644--- a/src/cli/helpers.ts+++ b/src/cli/helpers.ts@@ -56,7 +56,7 @@ export function requireVault(flagVal: string | undefined, configPath: string | nexport 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 Object.fromEntries(Object.entries(value).toSorted(([a], [b]) => a.localeCompare(b)));}return value;}diff --git a/src/cli/install/init-interactive.ts b/src/cli/install/init-interactive.tsindex f575a03e..a028f682 100644--- a/src/cli/install/init-interactive.ts+++ b/src/cli/install/init-interactive.ts@@ -12,6 +12,7 @@ import { existsSync, readdirSync, statSync } from "node:fs";import { homedir } from "node:os";import { dirname, join } from "node:path";+import { validateTimezoneName } from "../../core/config.ts";import { defaultRegistry } from "../../core/install/registry.ts";import "../../core/install/adapters/aider.ts";import "../../core/install/adapters/copilot-cli.ts";@@ -84,12 +85,7 @@ function hostName(): string {function tryNormaliseTz(input: string): string | null {if (!input || input.trim().length === 0) return null;const trimmed = input.trim();- try {- new Intl.DateTimeFormat("en-US", { timeZone: trimmed });- return trimmed;- } catch {- return null;- }+ return validateTimezoneName(trimmed).ok ? trimmed : null;}// ---------- Default reader & runner ----------@@ -153,9 +149,7 @@ export function defaultRunner(): WizardRunner {// ---------- Wizard ----------async function ask(opts: WizardOpts, label: string, defaultValue?: string): Promise<string> {- const suffix = defaultValue !== undefined && defaultValue !== ""- ? ` [${defaultValue}]: `- : ": ";+ const suffix = defaultValue !== undefined && defaultValue !== "" ? ` [${defaultValue}]: ` : ": ";opts.stdout.write(`${label}${suffix}`);const line = await opts.reader.read();if (line === null || line.trim().length === 0) {@@ -211,7 +205,11 @@ export async function runWizard(opts: WizardOpts): Promise<WizardResult> {vault,home: homedir(),cwd: process.cwd(),- env: { ...process.env, VAULT_AGENT_NAME: agentName, VAULT_TIMEZONE: tz } as Record<string, string>,+ env: {+ ...process.env,+ VAULT_AGENT_NAME: agentName,+ VAULT_TIMEZONE: tz,+ } as Record<string, string>,now: new Date(),};const detected = defaultRegistry.detectAll(env);@@ -227,7 +225,10 @@ export async function runWizard(opts: WizardOpts): Promise<WizardResult> {);const selected: string[] = [];if (sel.toLowerCase() !== "none" && sel.length > 0) {- for (const tok of sel.split(",").map((s) => s.trim()).filter((s) => s.length > 0)) {+ for (const tok of sel+ .split(",")+ .map((s) => s.trim())+ .filter((s) => s.length > 0)) {const idx = parseInt(tok, 10) - 1;if (idx >= 0 && idx < detected.length) selected.push(detected[idx]!.target);}diff --git a/src/cli/install/install.ts b/src/cli/install/install.tsindex 6a9f5979..ecbfd460 100644--- a/src/cli/install/install.ts+++ b/src/cli/install/install.ts@@ -37,11 +37,7 @@ import "../../core/install/adapters/pi.ts";import { buildPayload, PayloadError } from "../../core/install/payload.ts";import { InstallError } from "../../core/install/types.ts";-import type {- ApplyOpts,- InstallEnv,- VerifyResult,-} from "../../core/install/types.ts";+import type { ApplyOpts, InstallEnv, VerifyResult } from "../../core/install/types.ts";import {renderApplyJson,renderApplyResult,diff --git a/src/cli/install/render.ts b/src/cli/install/render.tsindex d8caa08a..d25ee655 100644--- a/src/cli/install/render.ts+++ b/src/cli/install/render.ts@@ -22,10 +22,7 @@ export interface DetectTableRow {export function renderDetectTable(rows: ReadonlyArray<DetectResult>): string {if (rows.length === 0) return "o2b install — no adapters registered\n";- const lines: string[] = [- "o2b install — detected runtimes",- "-".repeat(35),- ];+ const lines: string[] = ["o2b install — detected runtimes", "-".repeat(35)];let installed = 0;let drift = 0;let notInstalled = 0;@@ -42,8 +39,7 @@ export function renderDetectTable(rows: ReadonlyArray<DetectResult>): string {else if (r.status === "not-installed") notInstalled += 1;}lines.push("");- const summary =- `${rows.length} runtime(s) in registry; ${installed} installed, ${drift} drift, ${notInstalled} not-installed.`;+ const summary = `${rows.length} runtime(s) in registry; ${installed} installed, ${drift} drift, ${notInstalled} not-installed.`;lines.push(summary);if (drift > 0 || notInstalled > 0) {lines.push("");@@ -114,10 +110,7 @@ export function renderApplyJson(result: ApplyResult): string {export function renderVerifyTable(rows: ReadonlyArray<VerifyResult>): string {if (rows.length === 0) return "o2b install --check — no targets verified\n";- const lines: string[] = [- "o2b install --check",- "-".repeat(20),- ];+ const lines: string[] = ["o2b install --check", "-".repeat(20)];for (const v of rows) {const status = v.status.padEnd(18);lines.push(` ${v.target.padEnd(14)}${status}${v.details.join("; ")}`);diff --git a/src/cli/install/uninstall-target.ts b/src/cli/install/uninstall-target.tsindex 9e22b3fa..3a744b84 100644--- a/src/cli/install/uninstall-target.ts+++ b/src/cli/install/uninstall-target.ts@@ -77,9 +77,7 @@ export async function cmdUninstallTarget(argv: string[]): Promise<number> {return 0;}const lines: string[] = [];- lines.push(- `o2b uninstall --target ${target}` + (dryRun ? " (dry-run)" : " --apply"),- );+ lines.push(`o2b uninstall --target ${target}` + (dryRun ? " (dry-run)" : " --apply"));if (result.removed_keys.length > 0) {lines.push(" removed keys:");for (const k of result.removed_keys) lines.push(` - ${k}`);diff --git a/src/cli/main.ts b/src/cli/main.tsindex 09da2b65..22791752 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -16,6 +16,7 @@ import {discoverConfig,redactMapping,setConfigValue,+ validateTimezoneName,} from "../core/config.ts";import { BRAIN_INDEX_REL } from "../core/brain/paths.ts";import { doctor } from "../core/doctor.ts";@@ -82,7 +83,7 @@ async function cmdStatus(argv: string[]): Promise<number> {semantic_hint: semantic.hint,};if (Object.keys(result.data).length > 0) {- output["config_keys"] = Object.keys(result.data).sort();+ output["config_keys"] = Object.keys(result.data).toSorted();}if (flags["vault"]) output["vault"] = String(flags["vault"]);process.stdout.write(JSON.stringify(output, sortedReplacer, 2) + "\n");@@ -91,7 +92,7 @@ async function cmdStatus(argv: string[]): Promise<number> {process.stdout.write(`config_exists: ${result.exists ? "true" : "false"}\n`);if (Object.keys(result.data).length > 0) {process.stdout.write("config_keys:\n");- for (const key of Object.keys(result.data).sort()) {+ for (const key of Object.keys(result.data).toSorted()) {process.stdout.write(`- ${key}\n`);}}@@ -120,12 +121,11 @@ async function cmdInit(argv: string[]): Promise<number> {const timezone = (flags["timezone"] as string | undefined) ?? null;if (timezone) {- try {- new Intl.DateTimeFormat("en-US", { timeZone: timezone });- } catch (exc) {+ const timezoneValidation = validateTimezoneName(timezone);+ if (!timezoneValidation.ok) {process.stderr.write(`error: --timezone ${JSON.stringify(timezone)} is not a valid IANA name ` +- `(${(exc as Error).message ?? exc}). ` ++ `(${timezoneValidation.error}). ` +"Examples: Europe/Belgrade, America/New_York, UTC.\n",);return 1;@@ -186,11 +186,7 @@ function writeSearchInitBlock(configPath: string): void {// Skip the embedding-key prompt when search is explicitly disabled// (no point onboarding semantic when the whole layer is off), the// semantic flag is off, or the key is already present.- if (- semantic.search_disabled ||- !semantic.semantic_enabled ||- semantic.embedding_key_present- ) {+ if (semantic.search_disabled || !semantic.semantic_enabled || semantic.embedding_key_present) {return;}@@ -231,7 +227,11 @@ async function cmdDoctor(argv: string[]): Promise<number> {let results;try {- results = doctor({ vault, config, repoRoot: (flags["repo"] as string | undefined) ?? null });+ results = doctor({+ vault,+ config,+ repoRoot: (flags["repo"] as string | undefined) ?? null,+ });} catch (exc) {process.stderr.write(`error: doctor failed: ${(exc as Error).message ?? exc}\n`);return 1;@@ -326,14 +326,11 @@ async function cmdMcp(argv: string[]): Promise<number> {return 2;}if (writerOnly && rawScope !== "writer") {- process.stderr.write(- `o2b mcp: --writer-only conflicts with --scope ${rawScope}\n`,- );+ process.stderr.write(`o2b mcp: --writer-only conflicts with --scope ${rawScope}\n`);return 2;}const scope = rawScope;- const serverName =- scope === "writer" ? "open-second-brain-writer" : "open-second-brain";+ const serverName = scope === "writer" ? "open-second-brain-writer" : "open-second-brain";const config = (flags["config"] as string | undefined) ?? defaultConfigPath();@@ -368,9 +365,7 @@ async function runMcpProbe(args: {try {vault = requireVault(args.vault, args.config);} catch (e) {- process.stdout.write(- `mcp probe FAIL: vault not configured (${(e as Error).message})\n`,- );+ process.stdout.write(`mcp probe FAIL: vault not configured (${(e as Error).message})\n`);return 1;}try {@@ -405,7 +400,10 @@ async function cmdUninstall(argv: string[]): Promise<number> {"remove-cli": { type: "boolean" },});const config = (flags["config"] as string | undefined) ?? defaultConfigPath();- const plan = planUninstall({ configPath: config, applyLocal: Boolean(flags["apply-local"]) });+ const plan = planUninstall({+ configPath: config,+ applyLocal: Boolean(flags["apply-local"]),+ });process.stdout.write(renderPlan(plan));let returnCode = 0;if (flags["remove-cli"]) {diff --git a/src/cli/pay-memory/verbs/append-receipt.ts b/src/cli/pay-memory/verbs/append-receipt.tsindex 4695e182..081700a7 100644--- a/src/cli/pay-memory/verbs/append-receipt.ts+++ b/src/cli/pay-memory/verbs/append-receipt.ts@@ -37,8 +37,7 @@ export async function cmdAppendPaymentReceipt(argv: string[]): Promise<number> {});const config = defaultConfigPath();const vault = requireVault(flags["vault"] as string | undefined, config);- const agent =- (flags["agent"] as string | undefined) ?? resolveAgentName(config);+ const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);const tz = resolveTimezone(config);let rawOutput: string | undefined;@@ -57,8 +56,7 @@ export async function cmdAppendPaymentReceipt(argv: string[]): Promise<number> {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 policyCheckedAt = (flags["policy-checked-at"] as string | undefined) ?? null;let approvalStatus: string | null = null;let approvedBy: string | null = null;let approvedAt: string | null = null;@@ -89,9 +87,7 @@ export async function cmdAppendPaymentReceipt(argv: string[]): Promise<number> {"not_checked",];if (!allowed.includes(policyStatus as ReceiptPolicyStatus)) {- process.stderr.write(- `error: --policy-status must be one of: ${allowed.join(", ")}\n`,- );+ process.stderr.write(`error: --policy-status must be one of: ${allowed.join(", ")}\n`);return 2;}}@@ -124,19 +120,12 @@ export async function cmdAppendPaymentReceipt(argv: string[]): Promise<number> {policyReasons,policyCheckedAt,approvalRequestId: fromRequest,- approvalStatus: approvalStatus as- | "pending"- | "approved"- | "rejected"- | "consumed"- | null,+ 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`,- );+ process.stderr.write(`error: failed to write receipt: ${(exc as Error).message ?? exc}\n`);return 1;}diff --git a/src/cli/pay-memory/verbs/approve.ts b/src/cli/pay-memory/verbs/approve.tsindex af587390..4a1ad261 100644--- a/src/cli/pay-memory/verbs/approve.ts+++ b/src/cli/pay-memory/verbs/approve.ts@@ -21,9 +21,7 @@ export async function cmdApprovePaymentRequest(argv: string[]): Promise<number>note: (flags["note"] as string | undefined) ?? null,});} catch (exc) {- process.stderr.write(- `error: failed to approve request: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: failed to approve request: ${(exc as Error).message ?? exc}\n`);return 1;}if (flags["json"]) {diff --git a/src/cli/pay-memory/verbs/capture-asset.ts b/src/cli/pay-memory/verbs/capture-asset.tsindex 245312fa..31248a47 100644--- a/src/cli/pay-memory/verbs/capture-asset.ts+++ b/src/cli/pay-memory/verbs/capture-asset.ts@@ -27,9 +27,7 @@ export async function cmdCaptureAsset(argv: string[]): Promise<number> {try {prompt = readFileSync(promptFile, "utf8");} catch (exc) {- process.stderr.write(- `error: cannot read prompt-file: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: cannot read prompt-file: ${(exc as Error).message ?? exc}\n`);return 1;}}@@ -47,9 +45,7 @@ export async function cmdCaptureAsset(argv: string[]): Promise<number> {overwrite: Boolean(flags["overwrite"]),});} catch (exc) {- process.stderr.write(- `error: failed to write asset: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: failed to write asset: ${(exc as Error).message ?? exc}\n`);return 1;}diff --git a/src/cli/pay-memory/verbs/check-policy.ts b/src/cli/pay-memory/verbs/check-policy.tsindex 718e196a..ed847787 100644--- a/src/cli/pay-memory/verbs/check-policy.ts+++ b/src/cli/pay-memory/verbs/check-policy.ts@@ -38,9 +38,7 @@ export async function cmdCheckPaymentPolicy(argv: string[]): Promise<number> {tz,});} catch (exc) {- process.stderr.write(- `error: failed to evaluate policy: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: failed to evaluate policy: ${(exc as Error).message ?? exc}\n`);return 1;}diff --git a/src/cli/pay-memory/verbs/consume.ts b/src/cli/pay-memory/verbs/consume.tsindex 49498b60..b5c7e895 100644--- a/src/cli/pay-memory/verbs/consume.ts+++ b/src/cli/pay-memory/verbs/consume.ts@@ -19,9 +19,7 @@ export async function cmdConsumePaymentRequest(argv: string[]): Promise<number>receiptPath: String(flags["receipt"]),});} catch (exc) {- process.stderr.write(- `error: failed to consume request: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: failed to consume request: ${(exc as Error).message ?? exc}\n`);return 1;}if (flags["json"]) {diff --git a/src/cli/pay-memory/verbs/digest.ts b/src/cli/pay-memory/verbs/digest.tsindex 64342374..a894c901 100644--- a/src/cli/pay-memory/verbs/digest.ts+++ b/src/cli/pay-memory/verbs/digest.ts@@ -27,9 +27,7 @@ export async function cmdPaymentDigest(argv: string[]): Promise<number> {tz,});} catch (exc) {- process.stderr.write(- `error: failed to build digest: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: failed to build digest: ${(exc as Error).message ?? exc}\n`);return 1;}diff --git a/src/cli/pay-memory/verbs/init.ts b/src/cli/pay-memory/verbs/init.tsindex 5ef4d603..b96bbc01 100644--- a/src/cli/pay-memory/verbs/init.ts+++ b/src/cli/pay-memory/verbs/init.ts@@ -5,7 +5,11 @@import { existsSync, mkdirSync } from "node:fs";import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";-import { payMemoryDirs, vaultRelativePath, writePolicyIfMissing } from "../../../core/pay-memory/index.ts";+import {+ payMemoryDirs,+ vaultRelativePath,+ writePolicyIfMissing,+} from "../../../core/pay-memory/index.ts";import { requireVault, sortedReplacer } from "../../helpers.ts";import { parseFlags } from "../../argparse.ts";@@ -18,8 +22,7 @@ export async function cmdInitPayMemory(argv: string[]): Promise<number> {});const config = defaultConfigPath();const vault = requireVault(flags["vault"] as string | undefined, config);- const agent =- (flags["agent"] as string | undefined) ?? resolveAgentName(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];@@ -30,9 +33,7 @@ export async function cmdInitPayMemory(argv: string[]): Promise<number> {try {mkdirSync(dir, { recursive: true });} catch (exc) {- process.stderr.write(- `error: failed to create ${dir}: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: failed to create ${dir}: ${(exc as Error).message ?? exc}\n`);return 1;}(existed ? skipped : created).push(vaultRelativePath(dir, vault));@@ -42,9 +43,7 @@ export async function cmdInitPayMemory(argv: string[]): Promise<number> {try {policy = writePolicyIfMissing(vault, { overwrite: Boolean(flags["overwrite"]) });} catch (exc) {- process.stderr.write(- `error: failed to write policy: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: failed to write policy: ${(exc as Error).message ?? exc}\n`);return 1;}const policyRel = vaultRelativePath(policy.path, vault);diff --git a/src/cli/pay-memory/verbs/list.ts b/src/cli/pay-memory/verbs/list.tsindex 347aa4bc..40db3782 100644--- a/src/cli/pay-memory/verbs/list.ts+++ b/src/cli/pay-memory/verbs/list.ts@@ -14,9 +14,7 @@ export async function cmdListPendingPayments(argv: string[]): Promise<number> {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`,- );+ process.stderr.write(`error: --status must be one of: ${valid.join(", ")}\n`);return 2;}@@ -26,9 +24,7 @@ export async function cmdListPendingPayments(argv: string[]): Promise<number> {status: status as "pending" | "approved" | "rejected" | "consumed" | "all",});} catch (exc) {- process.stderr.write(- `error: failed to list requests: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: failed to list requests: ${(exc as Error).message ?? exc}\n`);return 1;}diff --git a/src/cli/pay-memory/verbs/reject.ts b/src/cli/pay-memory/verbs/reject.tsindex c07d3b70..0e1fc09a 100644--- a/src/cli/pay-memory/verbs/reject.ts+++ b/src/cli/pay-memory/verbs/reject.ts@@ -21,9 +21,7 @@ export async function cmdRejectPaymentRequest(argv: string[]): Promise<number> {reason: (flags["reason"] as string | undefined) ?? null,});} catch (exc) {- process.stderr.write(- `error: failed to reject request: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: failed to reject request: ${(exc as Error).message ?? exc}\n`);return 1;}if (flags["json"]) {diff --git a/src/cli/pay-memory/verbs/report.ts b/src/cli/pay-memory/verbs/report.tsindex daaf0a48..2db7c9c3 100644--- a/src/cli/pay-memory/verbs/report.ts+++ b/src/cli/pay-memory/verbs/report.ts@@ -26,9 +26,7 @@ export async function cmdPaymentReport(argv: string[]): Promise<number> {overwrite: Boolean(flags["overwrite"]),});} catch (exc) {- process.stderr.write(- `error: failed to write report: ${(exc as Error).message ?? exc}\n`,- );+ process.stderr.write(`error: failed to write report: ${(exc as Error).message ?? exc}\n`);return 1;}diff --git a/src/cli/search-cron-template.ts b/src/cli/search-cron-template.tsindex f5ce60a3..728da213 100644--- a/src/cli/search-cron-template.ts+++ b/src/cli/search-cron-template.ts@@ -38,16 +38,13 @@ export function parseInterval(raw: string): ParsedInterval {const m = /^(\d+)\s*(s|m|h|d)$/.exec(trimmed);if (!m) {throw new CronTemplateError(- "cannot parse interval " + JSON.stringify(raw) +- ": expected <N>s|m|h|d (e.g. 30m, 6h, 1d)",+ "cannot parse interval " + JSON.stringify(raw) + ": expected <N>s|m|h|d (e.g. 30m, 6h, 1d)",);}const n = parseInt(m[1]!, 10);const unit = m[2]!;if (n <= 0) {- throw new CronTemplateError(- "interval must be positive; got " + JSON.stringify(raw),- );+ throw new CronTemplateError("interval must be positive; got " + JSON.stringify(raw));}if (unit === "s") {throw new CronTemplateError(@@ -58,8 +55,7 @@ export function parseInterval(raw: string): ParsedInterval {if (n >= 60) {const hours = Math.round(n / 60);throw new CronTemplateError(- "intervals of 60 minutes or more must use the h unit (e.g. " +- hours + "h)",+ "intervals of 60 minutes or more must use the h unit (e.g. " + hours + "h)",);}const cron = "*/" + n + " * * * *";@@ -69,8 +65,7 @@ export function parseInterval(raw: string): ParsedInterval {if (n >= 24) {const days = Math.round(n / 24);throw new CronTemplateError(- "intervals of 24 hours or more must use the d unit (e.g. " +- days + "d)",+ "intervals of 24 hours or more must use the d unit (e.g. " + days + "d)",);}const cron = "0 */" + n + " * * *";@@ -86,17 +81,16 @@ export interface RenderCronTemplateOptions {readonly o2bBin?: string;}-export function renderCronTemplate(- interval: string,- opts: RenderCronTemplateOptions = {},-): string {+export function renderCronTemplate(interval: string, opts: RenderCronTemplateOptions = {}): string {const parsed = parseInterval(interval);const o2bBin = opts.o2bBin ?? "o2b";const watchdogBody = renderWatchdogBody(o2bBin);const header ="# ----------------------------------------------------------------------\n" +"# Open Second Brain - periodic reindex template\n" +- "# interval: " + parsed.human + "\n" ++ "# interval: " ++ parsed.human ++ "\n" +"#\n" +"# Pick ONE of the three paths below. The watchdog script is the\n" +"# common piece; both crontab and Hermes-cron rely on it.\n" +@@ -113,21 +107,25 @@ export function renderCronTemplate(const nativeCron ="## 2. Native crontab - open 'crontab -e' and append:\n" +"\n" +- parsed.cron + " ~/.local/bin/osb-reindex.sh\n";+ parsed.cron ++ " ~/.local/bin/osb-reindex.sh\n";const hermesCron ="## 3. Hermes cron (preferred when Hermes is the embedding owner):\n" +"\n" +"hermes cron create \\\n" +" --name osb-reindex \\\n" +- " --schedule '" + parsed.hermesSchedule + "' \\\n" ++ " --schedule '" ++ parsed.hermesSchedule ++ "' \\\n" +' --command "$HOME/.local/bin/osb-reindex.sh" \\\n' +" --no-agent\n";const footer ="# ----------------------------------------------------------------------\n" +- "# After install, verify with: " + o2bBin + " search status\n" ++ "# After install, verify with: " ++ o2bBin ++ " search status\n" +"# ----------------------------------------------------------------------\n";- return [header, "", watchdog, "", nativeCron, "", hermesCron, "", footer]- .join("\n");+ return [header, "", watchdog, "", nativeCron, "", hermesCron, "", footer].join("\n");}function renderWatchdogBody(o2bBin: string): string {diff --git a/src/cli/search.ts b/src/cli/search.tsindex 8fc53ab6..1f29817a 100644--- a/src/cli/search.ts+++ b/src/cli/search.ts@@ -32,10 +32,7 @@ import type {SearchOutcome,} from "../core/search/index.ts";import { CliError, parseFlags } from "./argparse.ts";-import {- CronTemplateError,- renderCronTemplate,-} from "./search-cron-template.ts";+import { CronTemplateError, renderCronTemplate } from "./search-cron-template.ts";const KNOWN_VERBS = new Set(["query", "index", "reindex", "status", "check"]);@@ -92,8 +89,10 @@ function resolveConfig();}const dbFlag = typeof flags["db"] === "string" ? (flags["db"] as string) : undefined;- const kwFlag = typeof flags["keyword-weight"] === "string" ? Number(flags["keyword-weight"]) : undefined;- const semFlag = typeof flags["semantic-weight"] === "string" ? Number(flags["semantic-weight"]) : undefined;+ const kwFlag =+ typeof flags["keyword-weight"] === "string" ? Number(flags["keyword-weight"]) : undefined;+ const semFlag =+ typeof flags["semantic-weight"] === "string" ? Number(flags["semantic-weight"]) : undefined;const concurrencyFlag =typeof flags["concurrency"] === "string" ? Number(flags["concurrency"]) : undefined;const overrides = {@@ -355,9 +354,7 @@ async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<number> {const cfg = resolveConfig(flags);const stats = await reindexVault(cfg, {embeddings: flags["embeddings"] === true,- onFile: flags["verbose"]- ? (e) => process.stderr.write(`${e.kind}\t${e.path}\n`)- : undefined,+ onFile: flags["verbose"] ? (e) => process.stderr.write(`${e.kind}\t${e.path}\n`) : undefined,});if (flags["json"]) {process.stdout.write(JSON.stringify(jsonForStats(stats, cfg)) + "\n");diff --git a/src/cli/uninstall.ts b/src/cli/uninstall.tsindex ceca5bd8..17aa89cb 100644--- a/src/cli/uninstall.ts+++ b/src/cli/uninstall.ts@@ -29,8 +29,8 @@ function isSafeLocalConfigDir(target: string): readonly [boolean, string] {`directory name '${name}' is not a recognized Open Second Brain config directory; refusing to remove`,];}- const partsLower = target.split(sep).map((p) => p.toLowerCase());- if (partsLower.includes(".hermes") || partsLower.includes("hermes")) {+ const partsLower = new Set(target.split(sep).map((p) => p.toLowerCase()));+ if (partsLower.has(".hermes") || partsLower.has("hermes")) {return [false, "config directory is inside a Hermes-owned path; refusing to remove"];}if (existsSync(join(target, ".git"))) {@@ -51,7 +51,7 @@ function listEntries(dir: string): string[] {if (!existsSync(dir)) return [];try {if (!statSync(dir).isDirectory()) return [];- return readdirSync(dir).sort();+ return readdirSync(dir).toSorted();} catch {return [];}@@ -165,7 +165,11 @@ export function renderPlan(plan: UninstallPlan): string {if (plan.errors.length > 0) {for (const [p, reason] of plan.errors) lines.push(` error: ${p} — ${reason}`);}- if (plan.removedPaths.length === 0 && plan.skippedPaths.length === 0 && plan.errors.length === 0) {+ if (+ plan.removedPaths.length === 0 &&+ plan.skippedPaths.length === 0 &&+ plan.errors.length === 0+ ) {lines.push(" (nothing to do)");}lines.push("");@@ -173,7 +177,9 @@ export function renderPlan(plan: UninstallPlan): string {lines.push("Next steps:");lines.push(" 1. Run the Hermes commands above to deregister the MCP server and plugin.");lines.push(" 2. Re-run with --apply-local to remove the machine-local config directory.");- lines.push(" 3. Add --remove-cli to also remove the o2b/vault-log symlinks from ~/.local/bin.");+ lines.push(+ " 3. Add --remove-cli to also remove the o2b/vault-log symlinks from ~/.local/bin.",+ );lines.push(" 4. Delete the vault yourself if and only if you really want to lose your notes.");lines.push("");}diff --git a/src/cli/update.ts b/src/cli/update.tsindex 456805b4..992d1f4b 100644--- a/src/cli/update.ts+++ b/src/cli/update.ts@@ -150,9 +150,7 @@ export async function cmdUpdate(argv: string[]): Promise<number> {const hasError = result.targets.some((t) => t.status === "error");if (hasError) {- const hasUserModifiedBlock = result.targets.some(- (t) => t.kind === "user-modified-block",- );+ const hasUserModifiedBlock = result.targets.some((t) => t.kind === "user-modified-block");return hasUserModifiedBlock ? 4 : 1;}return 0;diff --git a/src/cli/vault.ts b/src/cli/vault.tsindex ecee227c..89aadee4 100644--- a/src/cli/vault.ts+++ b/src/cli/vault.ts@@ -10,9 +10,7 @@ import { VAULT_HELP, VAULT_VERB_HELP } from "./vault/help-text.ts";import { cmdVaultStatus } from "./vault/verbs/status.ts";import { cmdVaultInspect } from "./vault/verbs/inspect.ts";-export async function handleVaultSubcommand(- argv: ReadonlyArray<string>,-): Promise<number> {+export async function handleVaultSubcommand(argv: ReadonlyArray<string>): Promise<number> {if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {process.stdout.write(VAULT_HELP);return argv.length === 0 ? 2 : 0;diff --git a/src/cli/vault/verbs/inspect.ts b/src/cli/vault/verbs/inspect.tsindex cb33f023..c27c18af 100644--- a/src/cli/vault/verbs/inspect.ts+++ b/src/cli/vault/verbs/inspect.ts@@ -5,10 +5,7 @@*/import { defaultConfigPath } from "../../../core/config.ts";-import {- inspectPath,- resolveVaultScope,-} from "../../../core/vault-scope/index.ts";+import { inspectPath, resolveVaultScope } from "../../../core/vault-scope/index.ts";import { CliError, parseFlags } from "../../argparse.ts";import { resolveBrainVault } from "../../brain/helpers.ts";import { fail, info, writeJson } from "../../output.ts";@@ -20,9 +17,7 @@ export async function cmdVaultInspect(argv: ReadonlyArray<string>): Promise<numb});const relpath = positional[0];if (!relpath) {- process.stderr.write(- "error: usage: o2b vault inspect <relpath> [--vault <path>] [--json]\n",- );+ process.stderr.write("error: usage: o2b vault inspect <relpath> [--vault <path>] [--json]\n");return 2;}const config = defaultConfigPath();@@ -51,9 +46,7 @@ export async function cmdVaultInspect(argv: ReadonlyArray<string>): Promise<numbrelpath: result.relPath,status: result.excluded ? "excluded" : "included",exists_on_disk: result.existsOnDisk,- matched_rule: result.rule- ? { raw: result.rule.raw, kind: result.rule.kind }- : null,+ matched_rule: result.rule ? { raw: result.rule.raw, kind: result.rule.kind } : null,matched_at: result.matchedAt,source: result.source,});diff --git a/src/cli/vault/verbs/status.ts b/src/cli/vault/verbs/status.tsindex 285f3af6..57df107a 100644--- a/src/cli/vault/verbs/status.ts+++ b/src/cli/vault/verbs/status.ts@@ -7,10 +7,7 @@*/import { defaultConfigPath } from "../../../core/config.ts";-import {- resolveVaultScope,- walkVaultScope,-} from "../../../core/vault-scope/index.ts";+import { resolveVaultScope, walkVaultScope } from "../../../core/vault-scope/index.ts";import { CliError, parseFlags } from "../../argparse.ts";import { resolveBrainVault } from "../../brain/helpers.ts";import { fail, info, writeJson } from "../../output.ts";@@ -63,9 +60,7 @@ export async function cmdVaultStatus(argv: ReadonlyArray<string>): Promise<numbeinfo(`ignore source: ${scope.source}`);info("");info(`included: ${walk.includedFiles} files, ${walk.includedDirs} directories`);- info(- `excluded: ${walk.excludedDirs.length} directories, ${walk.excludedFiles.length} files`,- );+ info(`excluded: ${walk.excludedDirs.length} directories, ${walk.excludedFiles.length} files`);if (walk.excludedDirs.length > 0) {info("");info("excluded directories:");diff --git a/src/core/brain/active.ts b/src/core/brain/active.tsindex 11260f1b..c8274b27 100644--- a/src/core/brain/active.ts+++ b/src/core/brain/active.ts@@ -45,11 +45,7 @@ import {import { parsePreference, parseRetired } from "./preference.ts";import { brainActivePath, brainDirs } from "./paths.ts";import { isoSecond } from "./time.ts";-import {- BRAIN_PREFERENCE_STATUS,- type BrainPreference,- type BrainRetired,-} from "./types.ts";+import { BRAIN_PREFERENCE_STATUS, type BrainPreference, type BrainRetired } from "./types.ts";const RECENTLY_RETIRED_COUNT = 3;@@ -105,10 +101,10 @@ export function regenerateActive(const confirmed = preferences.filter((p) => p.status === BRAIN_PREFERENCE_STATUS.confirmed)- .sort(sortByConfidenceThenId);+ .toSorted(sortByConfidenceThenId);const quarantine = preferences.filter((p) => p.status === BRAIN_PREFERENCE_STATUS.quarantine)- .sort(sortByIdAscending);+ .toSorted(sortByIdAscending);// Read window/limit from `_brain.yaml:active.most_applied_*`. The// loader throws on a malformed `_brain.yaml`; we fall back to@@ -175,16 +171,11 @@ export function regenerateActive(* Exported as the single source of truth for fire-and-warn semantics* so the same swallow shape isn't copy-pasted at each call site.*/-export function regenerateActiveQuiet(- vault: string,- opts: RegenerateActiveOptions = {},-): void {+export function regenerateActiveQuiet(vault: string, opts: RegenerateActiveOptions = {}): void {try {regenerateActive(vault, opts);} catch (err) {- process.stderr.write(- `warning: regenerate active.md failed: ${(err as Error).message}\n`,- );+ process.stderr.write(`warning: regenerate active.md failed: ${(err as Error).message}\n`);}}diff --git a/src/core/brain/apply-evidence.ts b/src/core/brain/apply-evidence.tsindex 9b419557..ea0c29e3 100644--- a/src/core/brain/apply-evidence.ts+++ b/src/core/brain/apply-evidence.ts@@ -39,11 +39,7 @@ import { isoSecond } from "./time.ts";import { checkRolePermission } from "./trust/check-role-permission.ts";import { BRAIN_OPERATIONS, type BrainRole } from "./trust/role.ts";import { renderPrefLink } from "./wikilink.ts";-import {- BRAIN_APPLY_RESULT,- BRAIN_LOG_EVENT_KIND,- type BrainApplyResult,-} from "./types.ts";+import { BRAIN_APPLY_RESULT, BRAIN_LOG_EVENT_KIND, type BrainApplyResult } from "./types.ts";const ARTIFACT_MAX_LEN = 512;const NOTE_MAX_LEN = 4096;@@ -155,9 +151,7 @@ export function appendApplyEvidence(singleLine: true,});const note =- input.note !== undefined- ? sanitiseTextField(input.note, { maxLen: NOTE_MAX_LEN })- : undefined;+ input.note !== undefined ? sanitiseTextField(input.note, { maxLen: NOTE_MAX_LEN }) : undefined;if (!artifact || !artifact.trim()) {throw new Error("apply-evidence missing field: artifact");}@@ -218,4 +212,3 @@ export function appendApplyEvidence(const result: AppendLogEventResult = appendLogEvent(vault, entry);return { logged_at: timestamp, log_path: result.logPath };}-diff --git a/src/core/brain/backlinks.ts b/src/core/brain/backlinks.tsindex 1143789e..6b45910c 100644--- a/src/core/brain/backlinks.ts+++ b/src/core/brain/backlinks.ts@@ -30,10 +30,7 @@ import { join } from "node:path";import { parseFrontmatter } from "../vault.ts";import { buildAliasIndex } from "./link-graph/alias-index.ts";-import {- extractWikilinkRichBodies,- parseWikilinkRich,-} from "./link-graph/parse-wikilink.ts";+import { extractWikilinkRichBodies, parseWikilinkRich } from "./link-graph/parse-wikilink.ts";import { parseLogDay } from "./log.ts";import { brainDirs } from "./paths.ts";import { normalizeDerivedKeys } from "./preference.ts";@@ -41,11 +38,7 @@ import { normaliseWikilinkTarget } from "./wikilink.ts";// ----- Public types ---------------------------------------------------------export type BacklinkSourceKind =- | "preference"- | "retired"- | "signal"- | `log-${string}`;+export type BacklinkSourceKind = "preference" | "retired" | "signal" | `log-${string}`;export interface BacklinkRef {/** Source id (basename without `.md`, e.g. `pref-foo`, `ret-bar`, `sig-2026-05-14-baz`). */@@ -218,10 +211,7 @@ function collectPreferences(}}-function collectSignals(- dir: string,- push: (target: string, ref: BacklinkRef) => void,-): void {+function collectSignals(dir: string, push: (target: string, ref: BacklinkRef) => void): void {if (!existsSync(dir)) return;for (const name of readdirSync(dir)) {if (!name.endsWith(".md")) continue;diff --git a/src/core/brain/claude-memory-parser.ts b/src/core/brain/claude-memory-parser.tsindex 2b1aa5a6..d16b806c 100644--- a/src/core/brain/claude-memory-parser.ts+++ b/src/core/brain/claude-memory-parser.ts@@ -94,10 +94,7 @@ function detectIndent(lines: string[], from: number): number {}function stripYamlQuotes(val: string): string {- if (- (val.startsWith('"') && val.endsWith('"')) ||- (val.startsWith("'") && val.endsWith("'"))- ) {+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {return val.slice(1, -1);}return val;diff --git a/src/core/brain/claude-memory-paths.ts b/src/core/brain/claude-memory-paths.tsindex 35b3652a..507b1184 100644--- a/src/core/brain/claude-memory-paths.ts+++ b/src/core/brain/claude-memory-paths.ts@@ -29,7 +29,7 @@ export function assertSafeMemoryPath(path: string, override: boolean): void {if (!norm.startsWith(root)) {throw new Error(`refusing to import from ${path}: it is not under ~/.claude/projects/.\n` +- `Pass --allow-arbitrary-memory-path to override.`,+ `Pass --allow-arbitrary-memory-path to override.`,);}}diff --git a/src/core/brain/claude-memory-plan.ts b/src/core/brain/claude-memory-plan.tsindex d400bddf..7bf99ce8 100644--- a/src/core/brain/claude-memory-plan.ts+++ b/src/core/brain/claude-memory-plan.ts@@ -1,9 +1,4 @@-export type PlanAction =- | "CREATE"- | "UPDATE"- | "RECREATE"- | "SKIP_UNCHANGED"- | "CONFLICT";+export type PlanAction = "CREATE" | "UPDATE" | "RECREATE" | "SKIP_UNCHANGED" | "CONFLICT";export interface PlanActionInput {readonly basename: string;diff --git a/src/core/brain/claude-memory-render.ts b/src/core/brain/claude-memory-render.tsindex 5a00313e..cacb6bf0 100644--- a/src/core/brain/claude-memory-render.ts+++ b/src/core/brain/claude-memory-render.ts@@ -3,7 +3,7 @@ export interface RenderMemoryInput {readonly description: string;readonly body: string;readonly memoryPath: string;- readonly importedAt: string; // ISO Z+ readonly importedAt: string; // ISO Zreadonly bodySha256: string;}diff --git a/src/core/brain/content-hash.ts b/src/core/brain/content-hash.tsindex 17937cfd..a68ed232 100644--- a/src/core/brain/content-hash.ts+++ b/src/core/brain/content-hash.ts@@ -68,9 +68,7 @@ export interface ContentHashVerification {* the result is neutral (`ok: true`, no expected/observed) - the* caller MUST NOT log a drift event in that case.*/-export function verifyContentHash(- input: ContentHashInput,-): ContentHashVerification {+export function verifyContentHash(input: ContentHashInput): ContentHashVerification {if (!input.content_hash) {return { ok: true };}diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.tsindex 11ec24dc..8d4df590 100644--- a/src/core/brain/context-pack.ts+++ b/src/core/brain/context-pack.ts@@ -13,11 +13,7 @@* are reported in `pagesSkipped` with their estimated cost.*/-import {- existsSync,- readdirSync,- statSync,-} from "node:fs";+import { existsSync, readdirSync, statSync } from "node:fs";import { join } from "node:path";import { parseFrontmatter } from "../vault.ts";@@ -118,10 +114,7 @@ function collectCandidates(vault: string): Candidate[] {return out;}-export function packContext(- vault: string,- opts: ContextPackOptions,-): ContextPackReport {+export function packContext(vault: string, opts: ContextPackOptions): ContextPackReport {if (!Number.isFinite(opts.maxTokens) || opts.maxTokens <= 0) {return Object.freeze({maxTokens: 0,@@ -130,9 +123,7 @@ export function packContext(skipped: Object.freeze([]),});}- const query = opts.query- ? normalizeForDedup(opts.query)- : null;+ const query = opts.query ? normalizeForDedup(opts.query) : null;const candidates = collectCandidates(vault);candidates.sort((a, b) => {diff --git a/src/core/brain/dedup-hash.ts b/src/core/brain/dedup-hash.tsindex 7bf99206..c9eefcca 100644--- a/src/core/brain/dedup-hash.ts+++ b/src/core/brain/dedup-hash.ts@@ -76,10 +76,7 @@ export function buildDedupIndex(out.set(hash, { id, path });}} catch (err) {- opts.onError?.(- path,- `dedup-index parse failed: ${(err as Error).message ?? String(err)}`,- );+ opts.onError?.(path, `dedup-index parse failed: ${(err as Error).message ?? String(err)}`);}}}diff --git a/src/core/brain/digest-agent-summary.ts b/src/core/brain/digest-agent-summary.tsindex b4f68292..6468a70b 100644--- a/src/core/brain/digest-agent-summary.ts+++ b/src/core/brain/digest-agent-summary.ts@@ -114,17 +114,13 @@ export function computeAgentSummary(}}- return [...byAgent.values()].sort((a, b) => {+ return [...byAgent.values()].toSorted((a, b) => {const diff = b.total_events - a.total_events;return diff !== 0 ? diff : a.agent.localeCompare(b.agent);});}-function readLogsInWindow(- vault: string,- since: Date,- until: Date,-): BrainLogEntry[] {+function readLogsInWindow(vault: string, since: Date, until: Date): BrainLogEntry[] {const dirs = brainDirs(vault);if (!existsSync(dirs.log)) return [];const sinceIso = since.toISOString();@@ -136,7 +132,7 @@ function readLogsInWindow(.filter((d) => d.isFile() && d.name.endsWith(".md")).map((d) => d.name.slice(0, -3)).filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n))- .sort();+ .toSorted();for (const date of dates) {if (date < addDays(sinceDay, -1)) continue;if (date > addDays(untilDay, 1)) continue;diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.tsindex 9e356b44..f7f16bcb 100644--- a/src/core/brain/digest.ts+++ b/src/core/brain/digest.ts@@ -60,11 +60,7 @@ import {BRAIN_PREFERENCE_STATUS,BRAIN_RETIRED_REASON,} from "./types.ts";-import type {- BrainConfidence,- BrainPreference,- BrainRetired,-} from "./types.ts";+import type { BrainConfidence, BrainPreference, BrainRetired } from "./types.ts";// ----- Public types ---------------------------------------------------------@@ -315,10 +311,7 @@ const HOT_SECTION_LIMIT = 5;const ONE_DAY_MS = 24 * 60 * 60 * 1000;-export function renderDigest(- vault: string,- opts: RenderDigestOptions = {},-): RenderDigestResult {+export function renderDigest(vault: string, opts: RenderDigestOptions = {}): RenderDigestResult {const format = opts.format ?? "markdown";const now = opts.now ?? new Date();const until = opts.until ?? now;@@ -376,9 +369,7 @@ export function renderDigest(}// Markdown.- const baseMd = empty- ? renderEmptyMarkdown(until)- : renderMarkdown(data, since, until);+ const baseMd = empty ? renderEmptyMarkdown(until) : renderMarkdown(data, since, until);const trustSection = renderTrustSection(opts.doctorResult, opts.dreamSummary);const content = trustSection ? `${baseMd}\n${trustSection}` : baseMd;return Object.freeze({ content, empty });@@ -423,11 +414,7 @@ interface DigestData {readonly actions: ReadonlyArray<ActionItem>;}-function collectDigestData(- vault: string,- since: Date,- until: Date,-): DigestData {+function collectDigestData(vault: string, since: Date, until: Date): DigestData {const sinceMs = since.getTime();const untilMs = until.getTime();const inWindow = (iso: string | null): boolean => {@@ -665,15 +652,12 @@ function computeConnectionHealth(if (totalNodes > 0) {const sum = counts.reduce((a, b) => a + b, 0);meanBacklinks = Math.round((sum / totalNodes) * 100) / 100;- const sorted = [...counts].sort((a, b) => a - b);+ const sorted = [...counts].toSorted((a, b) => a - b);const mid = Math.floor(sorted.length / 2);- medianBacklinks = sorted.length % 2 === 0- ? (sorted[mid - 1]! + sorted[mid]!) / 2- : sorted[mid]!;+ medianBacklinks =+ sorted.length % 2 === 0 ? (sorted[mid - 1]! + sorted[mid]!) / 2 : sorted[mid]!;}- const linkDensity = totalNodes > 0- ? Math.round((linkedNodes / totalNodes) * 1000) / 1000- : 0;+ const linkDensity = totalNodes > 0 ? Math.round((linkedNodes / totalNodes) * 1000) / 1000 : 0;return Object.freeze({total_nodes: totalNodes,@@ -743,11 +727,7 @@ function readAllRetired(vault: string): ReadonlyArray<RetiredWithPath> {return out;}-function readLogsInWindow(- vault: string,- since: Date,- until: Date,-): ReadonlyArray<BrainLogEntry> {+function readLogsInWindow(vault: string, since: Date, until: Date): ReadonlyArray<BrainLogEntry> {const dirs = brainDirs(vault);if (!existsSync(dirs.log)) return [];const sinceIso = since.toISOString();@@ -761,7 +741,7 @@ function readLogsInWindow(.filter((d) => d.isFile() && d.name.endsWith(".md")).map((d) => d.name.slice(0, -".md".length)).filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n))- .sort();+ .toSorted();for (const date of dates) {if (date < addDays(sinceDay, -1)) continue;if (date > addDays(untilDay, 1)) continue;@@ -788,17 +768,14 @@ function addDays(day: string, delta: number): string {* applied evidence is found — e.g. a preference that was force-confirmed* without ever being applied. This matches design doc §8.2 example.*/-function findFirstAppliedArtifact(- vault: string,- prefId: string,-): string | null {+function findFirstAppliedArtifact(vault: string, prefId: string): string | null {const dirs = brainDirs(vault);if (!existsSync(dirs.log)) return null;const dates = readdirSync(dirs.log, { withFileTypes: true }).filter((d) => d.isFile() && d.name.endsWith(".md")).map((d) => d.name.slice(0, -".md".length)).filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n))- .sort();+ .toSorted();for (const date of dates) {const { entries } = parseLogDay(vault, date);for (const e of entries) {@@ -948,16 +925,10 @@ function renderEmptyMarkdown(until: Date): string {return `Brain digest — ${ymd}: no changes\n`;}-function renderMarkdown(- data: DigestData,- since: Date,- until: Date,-): string {+function renderMarkdown(data: DigestData, since: Date, until: Date): string {const sinceIso = since.toISOString();const untilIso = until.toISOString();- const windowHours = Math.round(- (until.getTime() - since.getTime()) / (60 * 60 * 1000),- );+ const windowHours = Math.round((until.getTime() - since.getTime()) / (60 * 60 * 1000));const lines: string[] = [];lines.push(`# Brain digest — ${untilIso.slice(0, 16)}Z (${windowHours}h)`,@@ -1083,9 +1054,9 @@ function renderMarkdown(for (const item of data.merge_suggestions) {const scope = item.scope ?? "—";lines.push(- `- ${renderPrefLink({ id: item.a, principle: item.principle_a })}`- + ` ≈ ${renderPrefLink({ id: item.b, principle: item.principle_b })}`- + ` — topic '${item.topic}', scope ${scope}, jaccard ${item.jaccard.toFixed(2)}`,+ `- ${renderPrefLink({ id: item.a, principle: item.principle_a })}` ++ ` ≈ ${renderPrefLink({ id: item.b, principle: item.principle_b })}` ++ ` — topic '${item.topic}', scope ${scope}, jaccard ${item.jaccard.toFixed(2)}`,);}lines.push("");diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex 88190d1f..eebfefe4 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -60,11 +60,7 @@ import {} from "./trust/compute-verification-delta.ts";import { checkInstructionFileCeiling } from "./trust/instruction-file-ceiling.ts";import { brainConfigPath, brainDirs } from "./paths.ts";-import {- BrainStatusFolderMismatchError,- parsePreference,- parseRetired,-} from "./preference.ts";+import { BrainStatusFolderMismatchError, parsePreference, parseRetired } from "./preference.ts";import {reconcileSemanticHealth,type PreferenceForHealth,@@ -211,10 +207,7 @@ export interface RunDoctorResult {// ----- Entry point -----------------------------------------------------------export function runDoctor(- vault: string,- opts: RunDoctorOptions = {},-): RunDoctorResult {+export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctorResult {const issues: DoctorIssue[] = [];const dirs = brainDirs(vault);@@ -291,13 +284,19 @@ export function runDoctor(if (cfg) {try {checkDuplicatePreferences(prefRecords, issues);- } catch { /* doctor never throws */ }+ } catch {+ /* doctor never throws */+ }try {checkLowEvidenceConfirmed(prefRecords, issues, cfg, now);- } catch { /* doctor never throws */ }+ } catch {+ /* doctor never throws */+ }try {checkPinnedWithoutRecentEvidence(prefRecords, issues, cfg, now);- } catch { /* doctor never throws */ }+ } catch {+ /* doctor never throws */+ }}// v0.12.0 Brain Integrity Suite: surface preferences whose live// (principle, scope) does not hash to the value stored in@@ -305,7 +304,9 @@ export function runDoctor(// observable.try {checkContentHashDrift(prefRecords, issues);- } catch { /* doctor never throws */ }+ } catch {+ /* doctor never throws */+ }// v0.12.0 Brain Integrity Suite: surface every dream workrun file// whose last phase is neither `finalized` nor `interrupted`. A// dangling workrun is forensic evidence that a previous dream@@ -313,13 +314,19 @@ export function runDoctor(// how far the run got.try {checkDanglingWorkruns(vault, issues);- } catch { /* doctor never throws */ }+ } catch {+ /* doctor never throws */+ }try {checkMalformedEvidenceRange(logRecords, issues);- } catch { /* doctor never throws */ }+ } catch {+ /* doctor never throws */+ }try {checkOrphanEvidence(vault, logRecords, issues);- } catch { /* doctor never throws */ }+ } catch {+ /* doctor never throws */+ }// v0.14.0 semantic-health pass. Best-effort like every other lint:// a failure here must not poison the structural warning / error@@ -330,7 +337,9 @@ export function runDoctor(try {const health = cfg ? resolveHealth(cfg) : BRAIN_HEALTH_DEFAULTS;semanticReport = checkSemanticHealth(vault, prefRecords, issues, health, now);- } catch { /* doctor never throws */ }+ } catch {+ /* doctor never throws */+ }// Partition by severity. Stable sort preserves discovery order which// is convenient for tests asserting on `path`+`code`.@@ -345,14 +354,18 @@ export function runDoctor(instructionWarnings = checkInstructionFileCeiling(vault, {maxLines: guardrails.instruction_file_max_lines,});- } catch { /* doctor never throws */ }+ } catch {+ /* doctor never throws */+ }let verificationCounts: VerificationDeltaSummaryCounts | undefined;if (opts.dreamSummary !== undefined) {try {const delta = computeVerificationDelta(vault, opts.dreamSummary);verificationCounts = delta.summary;- } catch { /* doctor never throws */ }+ } catch {+ /* doctor never throws */+ }}const trustVerdict: TrustVerdict = computeTrustVerdict({@@ -371,9 +384,7 @@ export function runDoctor(warnings: Object.freeze(warnings),errors: Object.freeze(errors),trust_verdict: trustVerdict,- ...(verificationCounts !== undefined- ? { verification_delta_summary: verificationCounts }- : {}),+ ...(verificationCounts !== undefined ? { verification_delta_summary: verificationCounts } : {}),instruction_file_warnings: instructionWarnings,...(semanticReport !== undefined ? { semantic_health: semanticReport } : {}),});@@ -485,8 +496,7 @@ function checkConfig(vault: string, issues: DoctorIssue[]): void {severity: "error",code: "config-missing",path: cfgPath,- message:- "_brain.yaml is missing; run `o2b brain init` to bootstrap the Brain layer",+ message: "_brain.yaml is missing; run `o2b brain init` to bootstrap the Brain layer",});return;}@@ -558,19 +568,14 @@ function checkVaultIgnore(vault: string, issues: DoctorIssue[]): void {issues.push({severity: "warning",code: "vault-ignore-missing-path",- message:- `vault.ignore_paths entry '${rule.raw}' does not exist in this vault`,+ message: `vault.ignore_paths entry '${rule.raw}' does not exist in this vault`,});}}// ----- Signal check ----------------------------------------------------------function checkSignals(- vault: string,- issues: DoctorIssue[],- idIndex: Map<string, string[]>,-): void {+function checkSignals(vault: string, issues: DoctorIssue[], idIndex: Map<string, string[]>): void {const dirs = brainDirs(vault);for (const dir of [dirs.inbox, dirs.processed]) {if (!existsSync(dir)) continue;@@ -633,21 +638,9 @@ function checkPreferences(// values via the enum; a non-canonical value would have thrown// BrainStatusFolderMismatchError, caught below. Reaching here// means the status is valid; nothing more to check.- checkWikilinks(- path,- "evidenced_by",- pref.evidenced_by,- knownBasenames,- issues,- );+ checkWikilinks(path, "evidenced_by", pref.evidenced_by, knownBasenames, issues);if (pref.supersedes) {- checkWikilinks(- path,- "supersedes",- [pref.supersedes],- knownBasenames,- issues,- );+ checkWikilinks(path, "supersedes", [pref.supersedes], knownBasenames, issues);}} catch (err) {if (err instanceof BrainStatusFolderMismatchError) {@@ -700,28 +693,10 @@ function checkRetired(if (ret.last_evidence_at !== null) {checkIso(path, "last_evidence_at", ret.last_evidence_at, issues);}- checkWikilinks(- path,- "evidenced_by",- ret.evidenced_by,- knownBasenames,- issues,- );- checkWikilinks(- path,- "retired_by",- [ret.retired_by],- knownBasenames,- issues,- );+ checkWikilinks(path, "evidenced_by", ret.evidenced_by, knownBasenames, issues);+ checkWikilinks(path, "retired_by", [ret.retired_by], knownBasenames, issues);if (ret.superseded_by) {- checkWikilinks(- path,- "superseded_by",- [ret.superseded_by],- knownBasenames,- issues,- );+ checkWikilinks(path, "superseded_by", [ret.superseded_by], knownBasenames, issues);}} catch (err) {if (err instanceof BrainStatusFolderMismatchError) {@@ -774,11 +749,7 @@ function checkLogs(vault: string, issues: DoctorIssue[]): void {// ----- Helpers ---------------------------------------------------------------function registerId(- idIndex: Map<string, string[]>,- id: string,- path: string,-): void {+function registerId(idIndex: Map<string, string[]>, id: string, path: string): void {const list = idIndex.get(id);if (list) list.push(path);else idIndex.set(id, [path]);@@ -787,15 +758,9 @@ function registerId(// ISO-8601 UTC: YYYY-MM-DDTHH:MM:SS(.fff)?Z. Lenient — we accept the// shorter date-only form too (created_at is sometimes a date-only string// in hand-authored signals).-const ISO_RE =- /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?$/;+const ISO_RE = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?$/;-function checkIso(- path: string,- field: string,- value: string,- issues: DoctorIssue[],-): void {+function checkIso(path: string, field: string, value: string, issues: DoctorIssue[]): void {if (!ISO_RE.test(value)) {issues.push({severity: "error",@@ -872,7 +837,7 @@ function checkBrokenBacklinks(// outside the Brain layer are user prose and not our concern.if (!/^(pref|ret|sig)-/.test(target)) continue;if (knownBasenames.has(target)) continue;- const sources = Array.from(new Set(refs.map((r) => r.source))).sort();+ const sources = Array.from(new Set(refs.map((r) => r.source))).toSorted();issues.push({severity: "warning",code: "broken-backlinks",@@ -956,7 +921,8 @@ function checkDuplicatePreferences(if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed &&pref.status !== BRAIN_PREFERENCE_STATUS.quarantine- ) continue;+ )+ continue;entries.push({id: pref.id,// Same-scope-undefined falls in its own bucket. Mirrors the@@ -1097,10 +1063,7 @@ function checkContentHashDrift(* dream pass starts fresh - this check is purely observational so* the operator notices the failed run.*/-function checkDanglingWorkruns(- vault: string,- issues: DoctorIssue[],-): void {+function checkDanglingWorkruns(vault: string, issues: DoctorIssue[]): void {for (const path of scanDanglingWorkruns(vault)) {issues.push({severity: "warning",diff --git a/src/core/brain/dream-workrun.ts b/src/core/brain/dream-workrun.tsindex 2d289994..3b3f64ff 100644--- a/src/core/brain/dream-workrun.ts+++ b/src/core/brain/dream-workrun.ts@@ -32,10 +32,7 @@ import {} from "node:fs";import { dirname, join } from "node:path";-import {- dreamRunsDir,- dreamWorkrunPath,-} from "./paths.ts";+import { dreamRunsDir, dreamWorkrunPath } from "./paths.ts";/*** Canonical phase identifiers. Five forward-progress phases plus the@@ -51,8 +48,7 @@ export const WORKRUN_PHASE = Object.freeze({interrupted: "interrupted",} as const);-export type WorkrunPhase =- (typeof WORKRUN_PHASE)[keyof typeof WORKRUN_PHASE];+export type WorkrunPhase = (typeof WORKRUN_PHASE)[keyof typeof WORKRUN_PHASE];export interface WorkrunHandle {/** Path of the underlying JSONL file. */@@ -74,12 +70,13 @@ export function openWorkrun(vault: string, runId: string): WorkrunHandle {mkdirSync(dirname(path), { recursive: true });let closed = false;const append = (phase: WorkrunPhase, extra: Record<string, unknown> = {}): void => {- const line = JSON.stringify({- phase,- at: new Date().toISOString(),- run_id: runId,- ...extra,- }) + "\n";+ const line =+ JSON.stringify({+ phase,+ at: new Date().toISOString(),+ run_id: runId,+ ...extra,+ }) + "\n";appendFileSync(path, line, "utf8");};append(WORKRUN_PHASE.started);@@ -97,10 +94,7 @@ export function openWorkrun(vault: string, runId: string): WorkrunHandle {interrupt(reason?: string): void {if (closed) return;closed = true;- append(- WORKRUN_PHASE.interrupted,- reason !== undefined ? { reason } : {},- );+ append(WORKRUN_PHASE.interrupted, reason !== undefined ? { reason } : {});},};}@@ -141,10 +135,7 @@ export function scanDanglingWorkruns(vault: string): string[] {out.push(path);continue;}- if (- parsed.phase !== WORKRUN_PHASE.finalized &&- parsed.phase !== WORKRUN_PHASE.interrupted- ) {+ if (parsed.phase !== WORKRUN_PHASE.finalized && parsed.phase !== WORKRUN_PHASE.interrupted) {out.push(path);}} catch {diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.tsindex 5c4f9937..1c519371 100644--- a/src/core/brain/dream.ts+++ b/src/core/brain/dream.ts@@ -39,35 +39,22 @@ import { basename, join } from "node:path";import { parseFrontmatter } from "../vault.ts";import { regenerateActiveQuiet } from "./active.ts";-import {- openWorkrun,- WORKRUN_PHASE,- type WorkrunHandle,-} from "./dream-workrun.ts";+import { openWorkrun, WORKRUN_PHASE, type WorkrunHandle } from "./dream-workrun.ts";import { collectEvidenceForSlug } from "./evidence.ts";import { writePreferenceTxn } from "./preference-txn.ts";-import {- appendLogEvent,- parseLogDay,- type BrainLogEntry,-} from "./log.ts";-import {- moveToRetired,- parsePreference,- wouldRewritePreference,-} from "./preference.ts";+import { appendLogEvent, parseLogDay, type BrainLogEntry } from "./log.ts";+import { moveToRetired, parsePreference, wouldRewritePreference } from "./preference.ts";import { parseSignal } from "./signal.ts";import { isPinned } from "./pin.ts";-import {- createSnapshot,- pruneSnapshots,-} from "./snapshot.ts";+import { createSnapshot, pruneSnapshots } from "./snapshot.ts";import { loadBrainConfig, resolveGuardrails } from "./policy.ts";import { applySelfApprovalGuardrail } from "./trust/self-approval-guardrail.ts";import {brainDirs,+ dreamWorkrunPath,preferencePath,processedSignalPath,+ snapshotPath,vaultRelative,} from "./paths.ts";import { countSigns, dominantSignOf } from "./sign.ts";@@ -278,7 +265,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {const now = opts.now ?? new Date();const dryRun = opts.dryRun === true;const cfg = loadBrainConfig(vault);- const runId = formatRunId(now);+ let runId = formatRunId(now);const wikilinkToRun = `[[Brain/log/${isoDate(now)}]]`;// Collect non-fatal warnings raised during the run. The@@ -289,15 +276,13 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {const warnings: DreamWarning[] = [];const callerAgent = opts.agentName?.trim() ?? "";const isNonPrimary =- cfg.primary_agent !== null- && callerAgent.length > 0- && callerAgent !== cfg.primary_agent;+ cfg.primary_agent !== null && callerAgent.length > 0 && callerAgent !== cfg.primary_agent;if (isNonPrimary) {warnings.push({code: "non-primary-dream-run",message:- `dream run from agent '${callerAgent}', but primary is `- + `'${cfg.primary_agent}'. Convention violation, run proceeds.`,+ `dream run from agent '${callerAgent}', but primary is ` ++ `'${cfg.primary_agent}'. Convention violation, run proceeds.`,});}@@ -375,6 +360,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// function throws and nothing changes on disk.let snapshotPathStr: string | undefined;if (!dryRun) {+ runId = nextAvailableDreamRunId(vault, runId);const snap = createSnapshot(vault, runId);snapshotPathStr = snap.path;}@@ -427,9 +413,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {topic: np.topic,principle: np.principle,created_at: isoSecond(now),- unconfirmed_until: isoSecond(- addDays(now, cfg.dream.unconfirmed_window_days),- ),+ unconfirmed_until: isoSecond(addDays(now, cfg.dream.unconfirmed_window_days)),status: BRAIN_PREFERENCE_STATUS.unconfirmed,evidenced_by: np.evidencedBy,// No evidence yet → Wilson lower bound on (0, 0) is 0. Pre-@@ -564,9 +548,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// exclude retires the destructive-from-confirmed gate skipped, or// the next dream pass would parse a `pref-foo` log claiming the// pref was retired while the file is still in `preferences/`.- const gatedSlugs = new Set(- gatedRetires.map((g) => g.pref_id.replace(/^pref-/, "")),- );+ const gatedSlugs = new Set(gatedRetires.map((g) => g.pref_id.replace(/^pref-/, "")));// Emit log entries: skip-corrupted-frontmatter first (chronological// sense: corruption was detected during planning), then per-topic@@ -646,17 +628,13 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {const confirmedIds = Array.from(refresh.confirmed.values()).map((slug) =>renderPrefLink({id: `pref-${slug}`,- principle:- refresh.updated.get(slug)?.principle- ?? slugToPrefPrinciple.get(slug)- ?? "",+ principle: refresh.updated.get(slug)?.principle ?? slugToPrefPrinciple.get(slug) ?? "",}),);const retiredEntries = plan.retires.filter((r) => !gatedSlugs.has(r.slug)).map(- (r) =>- `${renderPrefLink({ id: `ret-${r.slug}`, principle: r.principle })} (${r.reason})`,+ (r) => `${renderPrefLink({ id: `ret-${r.slug}`, principle: r.principle })} (${r.reason})`,);const summaryBody: Record<string, string | ReadonlyArray<string>> = {run_id: runId,@@ -669,9 +647,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {summaryBody["contradictions"] = Array.from(plan.contradictionTopics);}if (plan.signalsSuppressed.length > 0) {- summaryBody["suppressed"] = plan.signalsSuppressed.map(- (s) => `${s.signal} ← ${s.retired}`,- );+ summaryBody["suppressed"] = plan.signalsSuppressed.map((s) => `${s.signal} ← ${s.retired}`);}if (refresh.bandDrops.length > 0) {// Format matches the digest's tolerant `parseShiftLine` parser:@@ -710,9 +686,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// successful dream run into an error. The next run will retry.// Surface so an operator can spot a recurring disk/permission// issue instead of wondering why retention stopped.- process.stderr.write(- `warning: prune snapshots failed: ${(err as Error).message}\n`,- );+ process.stderr.write(`warning: prune snapshots failed: ${(err as Error).message}\n`);}regenerateActiveQuiet(vault, { now });}@@ -766,8 +740,7 @@ export function shouldGateRetireFromConfirmed(if (reason === BRAIN_RETIRED_REASON.mergedInto) return false;if (existing.status !== BRAIN_PREFERENCE_STATUS.confirmed) return false;if (existing.pinned) return false;- const evidenceCount =- (existing.applied_count ?? 0) + (existing.violated_count ?? 0);+ const evidenceCount = (existing.applied_count ?? 0) + (existing.violated_count ?? 0);return evidenceCount < threshold;}@@ -829,8 +802,7 @@ function scanBrain(vault: string): ScanResult {const [meta] = parseFrontmatter(full);const topic = typeof meta["topic"] === "string" ? meta["topic"] : "";const id = typeof meta["id"] === "string" ? meta["id"] : "";- const principle =- typeof meta["principle"] === "string" ? meta["principle"] : "";+ const principle = typeof meta["principle"] === "string" ? meta["principle"] : "";const scope = typeof meta["scope"] === "string" ? meta["scope"] : undefined;const userReason =typeof meta["user_rejected_reason"] === "string"@@ -997,15 +969,7 @@ function planTopics(for (const [topic, sigs] of byTopic) {const active = prefByTopic.get(topic);if (active) {- handleSignalsOnActivePref(- active,- sigs,- plan,- cfg,- now,- scan.signals,- reservedSlugs,- );+ handleSignalsOnActivePref(active, sigs, plan, cfg, now, scan.signals, reservedSlugs);continue;}// v0.10.1 _summary §6: when a retired pref for this topic carries@@ -1022,9 +986,7 @@ function planTopics(// prefs on the same topic are tried in order — the first matching// suppressor wins. Non-matching signals fall through and remain// eligible for candidate-pref planning below.- const suppressors = (retiredByTopic.get(topic) ?? []).filter(- (r) => !!r.user_rejected_reason,- );+ const suppressors = (retiredByTopic.get(topic) ?? []).filter((r) => !!r.user_rejected_reason);let candidateSigs: SignalRecord[] = sigs;if (suppressors.length > 0) {const remaining: SignalRecord[] = [];@@ -1081,10 +1043,9 @@ function planTopics(const t = Date.parse(s.signal.created_at);if (Number.isFinite(t) && t < earliestSignalMs) earliestSignalMs = t;}- const ageDays =- Number.isFinite(earliestSignalMs)- ? Math.max(0, Math.floor((now.getTime() - earliestSignalMs) / (24 * 60 * 60 * 1000)))- : 0;+ const ageDays = Number.isFinite(earliestSignalMs)+ ? Math.max(0, Math.floor((now.getTime() - earliestSignalMs) / (24 * 60 * 60 * 1000)))+ : 0;const verdict = applySelfApprovalGuardrail({signal_count: dominantSize,@@ -1106,9 +1067,8 @@ function planTopics(// Decide supersede: if a retired pref for the same topic exists,// wire it through.const retiredForTopic = retiredByTopic.get(topic);- const supersedes = retiredForTopic && retiredForTopic.length > 0- ? retiredForTopic[0]!.id- : undefined;+ const supersedes =+ retiredForTopic && retiredForTopic.length > 0 ? retiredForTopic[0]!.id : undefined;const sign = dominant[0]!.signal.signal;// Slug from topic for the canonical filename, but reserve slugs// already present in retired/. Otherwise a superseding preference@@ -1205,8 +1165,7 @@ function handleSignalsOnActivePref(// Fallback: assume the active pref is OPPOSITE to the incoming// dominant sign. A unanimous flood thus reads as rebuttal.const c = signCounts(sigs);- activeSign =- c.pos > c.neg ? BRAIN_SIGNAL_SIGN.negative : BRAIN_SIGNAL_SIGN.positive;+ activeSign = c.pos > c.neg ? BRAIN_SIGNAL_SIGN.negative : BRAIN_SIGNAL_SIGN.positive;}const oppositeSign: BrainSignalSign =@@ -1297,9 +1256,7 @@ function collectReservedPreferenceSlugs(scan: ScanResult): Set<string> {}function preferenceSlugFromId(id: string, prefix: "pref-" | "ret-"): string | null {- return id.startsWith(prefix) && id.length > prefix.length- ? id.slice(prefix.length)- : null;+ return id.startsWith(prefix) && id.length > prefix.length ? id.slice(prefix.length) : null;}function allocatePreferencePlanSlug(base: string, reserved: Set<string>): string {@@ -1328,11 +1285,7 @@ function recordSignalMove(plan: PlanState, rec: SignalRecord): void {});}-function filterWithinWindow(- sigs: SignalRecord[],- windowDays: number,- now: Date,-): SignalRecord[] {+function filterWithinWindow(sigs: SignalRecord[], windowDays: number, now: Date): SignalRecord[] {const minTime = now.getTime() - windowDays * 24 * 3600 * 1000;return sigs.filter((s) => {const t = Date.parse(s.signal.created_at);@@ -1349,7 +1302,7 @@ interface RefreshUpdate {readonly principle: string;readonly created_at: string;readonly unconfirmed_until: string;- readonly status: typeof BRAIN_PREFERENCE_STATUS[keyof typeof BRAIN_PREFERENCE_STATUS];+ readonly status: (typeof BRAIN_PREFERENCE_STATUS)[keyof typeof BRAIN_PREFERENCE_STATUS];readonly evidenced_by: ReadonlyArray<string>;readonly confirmed_at: string | null;readonly applied_count: number;@@ -1392,7 +1345,7 @@ interface RefreshResult {interface ApplyEvidenceEntry {readonly pref_slug: string;readonly timestamp: string;- readonly result: typeof BRAIN_APPLY_RESULT[keyof typeof BRAIN_APPLY_RESULT];+ readonly result: (typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];}function scanApplyEvidence(vault: string): ApplyEvidenceEntry[] {@@ -1425,7 +1378,8 @@ function scanApplyEvidence(vault: string): ApplyEvidenceEntry[] {result !== BRAIN_APPLY_RESULT.applied &&result !== BRAIN_APPLY_RESULT.violated &&result !== BRAIN_APPLY_RESULT.outdated- ) continue;+ )+ continue;// Parse `[[pref-slug]]` → slug.const target = parseWikilink(prefRaw);if (!target || !target.startsWith("pref-")) continue;@@ -1450,10 +1404,7 @@ function parseWikilinkFromBodyValue(value: unknown): string | null {return typeof value === "string" ? parseWikilink(value) : null;}-function resolveMergeAlias(- slug: string,- aliases: ReadonlyMap<string, string>,-): string {+function resolveMergeAlias(slug: string, aliases: ReadonlyMap<string, string>): string {let current = slug;const seen = new Set<string>();while (!seen.has(current)) {@@ -1491,9 +1442,7 @@ function planRefresh(const retiringSlugs = new Set(plan.retires.map((r) => r.slug));for (const rec of scan.preferences) {- const slug = rec.pref.id.startsWith("pref-")- ? rec.pref.id.slice("pref-".length)- : rec.pref.id;+ const slug = rec.pref.id.startsWith("pref-") ? rec.pref.id.slice("pref-".length) : rec.pref.id;if (retiringSlugs.has(slug)) continue;const ev = bySlug.get(slug) ?? [];@@ -1567,13 +1516,7 @@ function planRefresh(}}- const confidence = computeConfidence(- applied,- violated,- lastEvidence,- cfg,- now,- );+ const confidence = computeConfidence(applied, violated, lastEvidence, cfg, now);// Idempotency on a no-op rerun: skip refresh for prefs where// counters AND status are unchanged AND the on-disk body already@@ -1588,8 +1531,7 @@ function planRefresh(// body-bytes check in `wouldRewritePreference` is what triggers// the write that populates the field.const valueDifferent =- previousValue !== null- && Math.abs(previousValue - confidence.value) > 1e-6;+ previousValue !== null && Math.abs(previousValue - confidence.value) > 1e-6;const countersChanged =applied !== rec.pref.applied_count ||violated !== rec.pref.violated_count ||@@ -1641,9 +1583,7 @@ function planRefresh(...(rec.pref.revision !== undefined && rec.pref.revision > 0? { revision: rec.pref.revision }: {}),- ...(rec.pref.content_hash !== undefined- ? { content_hash: rec.pref.content_hash }- : {}),+ ...(rec.pref.content_hash !== undefined ? { content_hash: rec.pref.content_hash } : {}),})) {// Counters and body both unchanged — true no-op for this pref.@@ -1719,8 +1659,7 @@ export function computeConfidence(const pHat = applied / n;const denom = 1 + z2 / n;const centre = (pHat + z2 / (2 * n)) / denom;- const margin =- (z * Math.sqrt((pHat * (1 - pHat)) / n + z2 / (4 * n * n))) / denom;+ const margin = (z * Math.sqrt((pHat * (1 - pHat)) / n + z2 / (4 * n * n))) / denom;wilsonLow = Math.max(0, centre - margin);}let freshness = 0;@@ -1757,9 +1696,7 @@ function planAutoRetires(refresh: RefreshResult,): void {for (const rec of scan.preferences) {- const slug = rec.pref.id.startsWith("pref-")- ? rec.pref.id.slice("pref-".length)- : rec.pref.id;+ const slug = rec.pref.id.startsWith("pref-") ? rec.pref.id.slice("pref-".length) : rec.pref.id;// Already planned to retire (rebutted)? Skip.if (plan.retires.some((r) => r.slug === slug)) continue;@@ -1812,9 +1749,7 @@ function planAutoRetires(// gate on the same staleness rule using `confirmed_at`. We// measure from confirmation in that case (cheaper than a// hand-crafted invariant check).- const confirmedAt = refreshed- ? refreshed.confirmed_at- : rec.pref.confirmed_at;+ const confirmedAt = refreshed ? refreshed.confirmed_at : rec.pref.confirmed_at;if (!confirmedAt) continue;const days = daysBetween(Date.parse(confirmedAt), now.getTime());if (days > cfg.retire.stale_evidence_days) {@@ -1901,5 +1836,17 @@ function formatRunId(d: Date): string {return `dream-${yyyy}-${mm}-${dd}-${hh}${mi}${ss}`;}+function nextAvailableDreamRunId(vault: string, baseRunId: string): string {+ let candidate = baseRunId;+ for (+ let n = 2;+ existsSync(snapshotPath(vault, candidate)) || existsSync(dreamWorkrunPath(vault, candidate));+ n+++ ) {+ candidate = `${baseRunId}-${n}`;+ }+ return candidate;+}+// Silence "unused" warnings for symbols exported only via barrel.void basename;diff --git a/src/core/brain/evidence.ts b/src/core/brain/evidence.tsindex 49e52e8d..4529454b 100644--- a/src/core/brain/evidence.ts+++ b/src/core/brain/evidence.ts@@ -119,10 +119,7 @@ export function collectEvidenceForSlug(});if (result === BRAIN_APPLY_RESULT.applied) {if (applied.length < maxApplied) applied.push(row);- } else if (- result === BRAIN_APPLY_RESULT.violated ||- result === BRAIN_APPLY_RESULT.outdated- ) {+ } else if (result === BRAIN_APPLY_RESULT.violated || result === BRAIN_APPLY_RESULT.outdated) {if (violated.length < maxViolated) violated.push(row);}if (applied.length >= maxApplied && violated.length >= maxViolated) {diff --git a/src/core/brain/explorer.ts b/src/core/brain/explorer.tsindex 0d081737..8e8b9c9c 100644--- a/src/core/brain/explorer.ts+++ b/src/core/brain/explorer.ts@@ -35,11 +35,7 @@ import {export const EXPLORER_SCHEMA_VERSION = 1 as const;export type ExplorerNodeKind = "preference" | "retired";-export type ExplorerNodeStatus =- | "unconfirmed"- | "confirmed"- | "quarantine"- | "retired";+export type ExplorerNodeStatus = "unconfirmed" | "confirmed" | "quarantine" | "retired";export type ExplorerEdgeKind = "supersedes" | "wikilink";export interface ExplorerNode {@@ -87,8 +83,7 @@ export function collectExplorerData(// final count in one pass — avoids the prior write-then-overwrite// shape that left a transient `backlink_count: 0` on every node.const backlinkIndex = buildBacklinkIndex(vault);- const countFor = (id: string): number =>- (backlinkIndex.get(id) ?? []).length;+ const countFor = (id: string): number => (backlinkIndex.get(id) ?? []).length;const nodes: ExplorerNode[] = [];const knownIds = new Set<string>();@@ -155,10 +150,7 @@ export function collectExplorerData(});}-function nodeFromPreference(- pref: BrainPreference,- backlinkCount: number,-): ExplorerNode {+function nodeFromPreference(pref: BrainPreference, backlinkCount: number): ExplorerNode {return {id: pref.id,kind: "preference",@@ -177,10 +169,7 @@ function nodeFromPreference(};}-function nodeFromRetired(- ret: BrainRetired,- backlinkCount: number,-): ExplorerNode {+function nodeFromRetired(ret: BrainRetired, backlinkCount: number): ExplorerNode {return {id: ret.id,kind: "retired",@@ -243,21 +232,19 @@ function loadTemplate(): string {raw = readFileSync(TEMPLATE_PATH, "utf8");} catch (err) {const msg = err instanceof Error ? err.message : String(err);- throw new Error(- `Failed to load brain-explorer template from ${TEMPLATE_PATH}: ${msg}`,- );+ throw new Error(`Failed to load brain-explorer template from ${TEMPLATE_PATH}: ${msg}`, {+ cause: err,+ });}const first = raw.indexOf(PLACEHOLDER);const last = raw.lastIndexOf(PLACEHOLDER);if (first === -1) {- throw new Error(- `brain-explorer.html template is missing the ${PLACEHOLDER} marker`,- );+ throw new Error(`brain-explorer.html template is missing the ${PLACEHOLDER} marker`);}if (first !== last) {throw new Error(- `brain-explorer.html template carries ${PLACEHOLDER} more than once;`- + ` substitution must be unique to keep the output deterministic`,+ `brain-explorer.html template carries ${PLACEHOLDER} more than once;` ++ ` substitution must be unique to keep the output deterministic`,);}templateCache = raw;@@ -273,10 +260,7 @@ function loadTemplate(): string {* / `$1` injection through the JSON body (principle bodies are free* text and may contain `$`).*/-export function renderExportedHtml(- graph: ExplorerGraph,- vaultPath?: string,-): string {+export function renderExportedHtml(graph: ExplorerGraph, vaultPath?: string): string {const json = JSON.stringify(graph).replace(/[<>&]/g, (c) => {switch (c) {case "<":@@ -366,10 +350,7 @@ export function buildLiveServer(vault: string, port: number): LiveServerHandle {// ---- Helpers -------------------------------------------------------------function deriveEdges(- index: BacklinkIndex,- knownIds: ReadonlySet<string>,-): ExplorerEdge[] {+function deriveEdges(index: BacklinkIndex, knownIds: ReadonlySet<string>): ExplorerEdge[] {const edges: ExplorerEdge[] = [];const seen = new Set<string>();for (const [target, refs] of index) {@@ -378,9 +359,7 @@ function deriveEdges(if (!knownIds.has(ref.source)) continue; // logs / signalsif (ref.source === target) continue;const kind: ExplorerEdgeKind =- ref.field === "supersedes" || ref.field === "superseded_by"- ? "supersedes"- : "wikilink";+ ref.field === "supersedes" || ref.field === "superseded_by" ? "supersedes" : "wikilink";const key = `${ref.source}\x00${target}\x00${kind}`;if (seen.has(key)) continue;seen.add(key);diff --git a/src/core/brain/health/concept-gap.ts b/src/core/brain/health/concept-gap.tsindex fa590fae..8538e9dc 100644--- a/src/core/brain/health/concept-gap.ts+++ b/src/core/brain/health/concept-gap.ts@@ -45,8 +45,7 @@ export function detectConceptGaps(for (const topic of coveredTopics) {for (const t of tokenise(topic.replace(/[-_]+/gu, " "))) covered.add(t);}- const isCovered = (term: string): boolean =>- term.split(/\s+/u).every((w) => covered.has(w));+ const isCovered = (term: string): boolean => term.split(/\s+/u).every((w) => covered.has(w));const docFreq = new Map<string, number>();for (const principle of principles) {diff --git a/src/core/brain/health/edit-history.ts b/src/core/brain/health/edit-history.tsindex 4e8921f5..feaab49a 100644--- a/src/core/brain/health/edit-history.ts+++ b/src/core/brain/health/edit-history.ts@@ -49,10 +49,7 @@ function isEntry(value: unknown): value is EditHistoryEntry {}/** Read the sidecar, skipping malformed lines. Missing file -> `[]`. */-export function readEditHistory(- vault: string,- slug: string,-): EditHistoryEntry[] {+export function readEditHistory(vault: string, slug: string): EditHistoryEntry[] {const path = preferenceHistoryPath(vault, slug);if (!existsSync(path)) return [];const out: EditHistoryEntry[] = [];@@ -100,13 +97,11 @@ export function appendEditHistory(* by revision then field; values are quoted so empty/whitespace edits* stay visible.*/-export function renderEditHistory(- entries: ReadonlyArray<EditHistoryEntry>,-): string {+export function renderEditHistory(entries: ReadonlyArray<EditHistoryEntry>): string {if (entries.length === 0) return "(no recorded edits)";const sorted = entries.slice()- .sort((a, b) => a.revision - b.revision || a.field.localeCompare(b.field));+ .toSorted((a, b) => a.revision - b.revision || a.field.localeCompare(b.field));const lines = sorted.map((e) => {const before = e.before === null ? "(absent)" : `"${e.before}"`;const after = e.after === null ? "(removed)" : `"${e.after}"`;diff --git a/src/core/brain/health/reconcile.ts b/src/core/brain/health/reconcile.tsindex ea4a65f2..b85ed212 100644--- a/src/core/brain/health/reconcile.ts+++ b/src/core/brain/health/reconcile.ts@@ -17,10 +17,7 @@ import {type ContradictionFinding,type PreferenceForContradiction,} from "./contradiction.ts";-import {- detectConceptGaps,- type ConceptGapFinding,-} from "./concept-gap.ts";+import { detectConceptGaps, type ConceptGapFinding } from "./concept-gap.ts";import {detectStaleClaims,type PreferenceForStaleClaim,@@ -28,8 +25,7 @@ import {} from "./stale-claim.ts";/** A preference shape sufficient for every semantic-health detector. */-export type PreferenceForHealth = PreferenceForContradiction &- PreferenceForStaleClaim;+export type PreferenceForHealth = PreferenceForContradiction & PreferenceForStaleClaim;export interface SemanticHealthInput {readonly preferences: ReadonlyArray<PreferenceForHealth>;@@ -61,16 +57,12 @@ export function reconcileSemanticHealth(input: SemanticHealthInput,config: SemanticHealthConfig,): SemanticHealthReport {- const contradictions = detectContradictions(- input.preferences,- input.signSignById,- { jaccard: config.contradictionJaccard },- );- const conceptGaps = detectConceptGaps(- input.corpusPrinciples,- input.coveredTopics,- { minFrequency: config.conceptGapMinFrequency },- );+ const contradictions = detectContradictions(input.preferences, input.signSignById, {+ jaccard: config.contradictionJaccard,+ });+ const conceptGaps = detectConceptGaps(input.corpusPrinciples, input.coveredTopics, {+ minFrequency: config.conceptGapMinFrequency,+ });const staleClaims = detectStaleClaims(input.preferences, {maxAgeDays: config.staleClaimMaxAgeDays,now: config.now,diff --git a/src/core/brain/health/remediation.ts b/src/core/brain/health/remediation.tsindex ccb1a41b..d7dd07e3 100644--- a/src/core/brain/health/remediation.ts+++ b/src/core/brain/health/remediation.ts@@ -111,7 +111,7 @@ export function collectDriftedSlugs(vault: string): string[] {// schema error - reported by the doctor}}- return out.sort((a, b) => a.localeCompare(b));+ return out.toSorted((a, b) => a.localeCompare(b));}export function planRemediation(@@ -228,9 +228,7 @@ export function applyRemediation(continue;}const didWrite =- step.action === "restamp-content-hash"- ? restampContentHash(vault, step.target)- : false;+ step.action === "restamp-content-hash" ? restampContentHash(vault, step.target) : false;if (didWrite) {applied.push(step);budget--;diff --git a/src/core/brain/health/stale-claim.ts b/src/core/brain/health/stale-claim.tsindex a170e6af..6a347920 100644--- a/src/core/brain/health/stale-claim.ts+++ b/src/core/brain/health/stale-claim.ts@@ -10,10 +10,7 @@* lint's concern), and a future-dated evidence is never stale.*/-import {- BRAIN_PREFERENCE_STATUS,- type BrainPreferenceStatus,-} from "../types.ts";+import { BRAIN_PREFERENCE_STATUS, type BrainPreferenceStatus } from "../types.ts";const DAY_MS = 24 * 60 * 60 * 1000;diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.tsindex c4668940..c09dcc6e 100644--- a/src/core/brain/import-claude-memory.ts+++ b/src/core/brain/import-claude-memory.ts@@ -8,10 +8,7 @@ import { createSnapshot } from "./snapshot.ts";import { isoSecond } from "./time.ts";import { resolveAgentName } from "../config.ts";import { parseClaudeMemoryFile } from "./claude-memory-parser.ts";-import {- loadManifest,- saveManifest,-} from "./claude-memory-manifest.ts";+import { loadManifest, saveManifest } from "./claude-memory-manifest.ts";import { planAction, type PlannedFile } from "./claude-memory-plan.ts";import { renderPreferenceFromMemory, slugifyMemoryName } from "./claude-memory-render.ts";import { assertSafeMemoryPath } from "./claude-memory-paths.ts";@@ -99,7 +96,7 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe// any duplicate into the skipped list with a clear reason.const seenPrefIds = new Map<string, string>();- for (const name of readdirSync(opts.memoryDir).sort()) {+ for (const name of readdirSync(opts.memoryDir).toSorted()) {if (name === "MEMORY.md") continue;if (!name.endsWith(".md")) continue;const text = readFileSync(join(opts.memoryDir, name), "utf8");diff --git a/src/core/brain/index.ts b/src/core/brain/index.tsindex 92c2eb62..cb4a9bdd 100644--- a/src/core/brain/index.ts+++ b/src/core/brain/index.ts@@ -75,11 +75,7 @@ export type { RegenerateActiveOptions, RegenerateActiveResult } from "./active.t// ----- Backlink index -------------------------------------------------------export { buildBacklinkIndex, backlinkCount } from "./backlinks.ts";-export type {- BacklinkIndex,- BacklinkRef,- BacklinkSourceKind,-} from "./backlinks.ts";+export type { BacklinkIndex, BacklinkRef, BacklinkSourceKind } from "./backlinks.ts";// ----- Operational status ---------------------------------------------------export { computeBrainStatus } from "./status.ts";@@ -89,11 +85,7 @@ export type {ComputeBrainStatusOptions,} from "./status.ts";-export type {- BrainDirs,- AllocateSlugOptions,- AllocateSlugResult,-} from "./paths.ts";+export type { BrainDirs, AllocateSlugOptions, AllocateSlugResult } from "./paths.ts";// ----- Configuration --------------------------------------------------------export {@@ -108,19 +100,11 @@ export {parseBrainYaml,} from "./policy.ts";-export type {- BrainConfigLoadWarning,- LoadBrainConfigResult,- ValidateResult,-} from "./policy.ts";+export type { BrainConfigLoadWarning, LoadBrainConfigResult, ValidateResult } from "./policy.ts";// ----- Time helpers ---------------------------------------------------------export { isoSecond, isoDate } from "./time.ts";// ----- Wikilink helpers ------------------------------------------------------export {- normaliseWikilinkTarget,- parseWikilink,- parseArtifactRef,-} from "./wikilink.ts";+export { normaliseWikilinkTarget, parseWikilink, parseArtifactRef } from "./wikilink.ts";export type { ArtifactRange, ArtifactRefParse } from "./wikilink.ts";diff --git a/src/core/brain/init.ts b/src/core/brain/init.tsindex a5afd5ea..7fcbe9ec 100644--- a/src/core/brain/init.ts+++ b/src/core/brain/init.ts@@ -20,13 +20,7 @@* never a torn hybrid.*/-import {- cpSync,- existsSync,- mkdirSync,- readdirSync,- statSync,-} from "node:fs";+import { cpSync, existsSync, mkdirSync, readdirSync, statSync } from "node:fs";import { basename, dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -39,10 +33,7 @@ import {brainManualPath,vaultRelative,} from "./paths.ts";-import {- DEFAULT_BRAIN_CONFIG_YAML,- formatPrimaryAgentYamlValue,-} from "./policy.ts";+import { DEFAULT_BRAIN_CONFIG_YAML, formatPrimaryAgentYamlValue } from "./policy.ts";import { renderBrainManual } from "./templates.ts";const STARTER_TARGETS = ["preferences", "retired", "inbox", "log"] as const;@@ -89,9 +80,7 @@ export function copyStarterBundle(const src = opts.starterPath ?? DEFAULT_STARTER_DIR;try {if (!statSync(src).isDirectory()) {- throw new BrainStarterError(- `starter source is not a directory: ${src}`,- );+ throw new BrainStarterError(`starter source is not a directory: ${src}`);}} catch (err) {if ((err as NodeJS.ErrnoException).code === "ENOENT") {@@ -130,8 +119,8 @@ export function copyStarterBundle(});if (hasUserContent) {throw new BrainStarterError(- `Brain/${sub} already has content — \`--starter\` is intended for fresh vaults. `- + `Inspect the bundle at ${src} and copy individual files manually if needed.`,+ `Brain/${sub} already has content — \`--starter\` is intended for fresh vaults. ` ++ `Inspect the bundle at ${src} and copy individual files manually if needed.`,);}}@@ -160,7 +149,6 @@ export function copyStarterBundle(return Object.freeze({ copied });}-export interface BootstrapBrainOptions {/** Overwrite `_brain.yaml` and `_BRAIN.md` if they already exist. */readonly force?: boolean;@@ -254,10 +242,7 @@ export function bootstrapBrain(// 2. `_brain.yaml` — default config (with optional primary_agent).const brainYamlPath = brainConfigPath(vault);const brainYamlRel = vaultRelative(brainYamlPath, vault);- const initialYaml = applyPrimaryAgentToYaml(- DEFAULT_BRAIN_CONFIG_YAML,- opts.primaryAgent,- );+ const initialYaml = applyPrimaryAgentToYaml(DEFAULT_BRAIN_CONFIG_YAML, opts.primaryAgent);if (existsSync(brainYamlPath)) {if (force) {atomicWriteFileSync(brainYamlPath, initialYaml);@@ -307,10 +292,7 @@ export function bootstrapBrain(* so re-running the helper against an already-customised YAML stays* idempotent for the relevant slot.*/-function applyPrimaryAgentToYaml(- yamlBody: string,- primaryAgent: string | undefined,-): string {+function applyPrimaryAgentToYaml(yamlBody: string, primaryAgent: string | undefined): string {if (primaryAgent === undefined) return yamlBody;const line = `primary_agent: ${formatPrimaryAgentYamlValue(primaryAgent)}`;return yamlBody.replace(/^primary_agent:.*$/m, line);diff --git a/src/core/brain/inline-rewrite.ts b/src/core/brain/inline-rewrite.tsindex e855e67c..b2938012 100644--- a/src/core/brain/inline-rewrite.ts+++ b/src/core/brain/inline-rewrite.ts@@ -44,10 +44,7 @@ export interface RewriteOp {* processing the op list in reverse (so earlier line indices stay* valid).*/-export async function rewriteMarkers(- path: string,- ops: ReadonlyArray<RewriteOp>,-): Promise<void> {+export async function rewriteMarkers(path: string, ops: ReadonlyArray<RewriteOp>): Promise<void> {if (ops.length === 0) return;// proper-lockfile requires the target to exist; locking the parent@@ -66,9 +63,7 @@ export async function rewriteMarkers(// Sort ops descending by originLine so that inserts in block-form// ops don't shift the line indices of earlier ops.- const sorted = [...ops].sort(- (a, b) => b.marker.originLine - a.marker.originLine,- );+ const sorted = [...ops].toSorted((a, b) => b.marker.originLine - a.marker.originLine);for (const op of sorted) {const idx = op.marker.originLine - 1;@@ -82,10 +77,7 @@ export async function rewriteMarkers(const line = lines[idx]!;// Replace the leading '@osb' with '@osb✓ [[id]]' — preserve any// leading whitespace.- const replaced = line.replace(- /@osb(?=\s)/,- `@osb✓ [[${op.signalId}]]`,- );+ const replaced = line.replace(/@osb(?=\s)/, `@osb✓ [[${op.signalId}]]`);lines[idx] = replaced;} else {// Block form: idx points at the opening ```osb line. Use andiff --git a/src/core/brain/inline-scan.ts b/src/core/brain/inline-scan.tsindex d1690fa9..20ad3b68 100644--- a/src/core/brain/inline-scan.ts+++ b/src/core/brain/inline-scan.ts@@ -25,19 +25,10 @@* file), not a new signal.*/-import {- Dirent,- readFileSync,- readdirSync,- statSync,-} from "node:fs";+import { Dirent, readFileSync, readdirSync, statSync } from "node:fs";import { join, relative, sep } from "node:path";-import {- buildDedupIndex,- computeDedupHash,- type DedupIndexEntry,-} from "./dedup-hash.ts";+import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "./dedup-hash.ts";import { discoverMarkersDetailed } from "./inline.ts";import { rewriteMarkers, type RewriteOp } from "./inline-rewrite.ts";import { BRAIN_ROOT_REL } from "./paths.ts";@@ -45,11 +36,7 @@ import { loadNotesConfigSafe } from "./policy.ts";import { writeSignal } from "./signal.ts";import { isoDate, isoSecond } from "./time.ts";import { BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";-import {- matchIgnore,- resolveVaultScope,- type VaultIgnoreRule,-} from "../vault-scope/index.ts";+import { matchIgnore, resolveVaultScope, type VaultIgnoreRule } from "../vault-scope/index.ts";const MAX_FILE_SIZE_BYTES = 1_048_576; // 1 MiB@@ -106,9 +93,7 @@ export async function scanInline(// the agent never walks the vault without an operator opt-in.const explicitPaths = (opts.paths ?? []).filter((p) => p.trim().length > 0);const resolvedPaths =- explicitPaths.length > 0- ? explicitPaths- : [...loadNotesConfigSafe(vault).read_paths];+ explicitPaths.length > 0 ? explicitPaths : [...loadNotesConfigSafe(vault).read_paths];if (resolvedPaths.length === 0) {return Object.freeze({scanned: 0,@@ -256,7 +241,10 @@ function normalisePrefix(rel: string): string {// strip leading/trailing slashes. On Windows `notes\\` must become// `notes` (not `notes/`), so the separator conversion has to happen// before the slash trim. `matchIgnore` expects POSIX rel-paths.- return rel.split(sep).join("/").replace(/^\/+|\/+$/g, "");+ return rel+ .split(sep)+ .join("/")+ .replace(/^\/+|\/+$/g, "");}function* walkVault(@@ -264,9 +252,7 @@ function* walkVault(includePrefixes: ReadonlyArray<string>,rules: ReadonlyArray<VaultIgnoreRule>,): Generator<string> {- const stack: Array<{ abs: string; rel: string }> = [- { abs: vault, rel: "" },- ];+ const stack: Array<{ abs: string; rel: string }> = [{ abs: vault, rel: "" }];while (stack.length > 0) {const { abs: dir, rel: relDir } = stack.pop()!;let entries: Dirent[];@@ -291,9 +277,7 @@ function* walkVault(if (!entry.name.endsWith(".md")) continue;if (includePrefixes.length > 0) {- const matches = includePrefixes.some(- (p) => relPosix === p || relPosix.startsWith(p + "/"),- );+ const matches = includePrefixes.some((p) => relPosix === p || relPosix.startsWith(p + "/"));if (!matches) continue;}diff --git a/src/core/brain/inline.ts b/src/core/brain/inline.tsindex 8a69fe0b..d13cdb8e 100644--- a/src/core/brain/inline.ts+++ b/src/core/brain/inline.ts@@ -32,7 +32,7 @@* misses as warnings separately; the parser itself is silent.*/-const KNOWN_KINDS: ReadonlyArray<string> = ["feedback"];+const KNOWN_KINDS: ReadonlySet<string> = new Set(["feedback"]);const KNOWN_SIGNALS: ReadonlyArray<string> = ["positive", "negative"];export type MarkerKind = "feedback";@@ -98,7 +98,7 @@ export function parseInlineMarker(line: string, lineNo: number): ParsedMarker |// Positional `kind`.const kindToken = readBareToken();- if (kindToken === null || !KNOWN_KINDS.includes(kindToken)) return null;+ if (kindToken === null || !KNOWN_KINDS.has(kindToken)) return null;skipWs();// Positional `signal`.@@ -126,8 +126,7 @@ export function parseInlineMarker(line: string, lineNo: number): ParsedMarker |}const topic = typeof fields["topic"] === "string" ? fields["topic"] : null;- const principle =- typeof fields["principle"] === "string" ? fields["principle"] : null;+ const principle = typeof fields["principle"] === "string" ? fields["principle"] : null;if (!topic || !principle) return null;const out: ParsedMarker = {@@ -265,12 +264,11 @@ export function parseBlockMarker(body: string, fenceStartLine: number): ParsedMa}const kind = typeof fields["kind"] === "string" ? fields["kind"] : null;- if (kind === null || !KNOWN_KINDS.includes(kind)) return null;+ if (kind === null || !KNOWN_KINDS.has(kind)) return null;const signal = typeof fields["signal"] === "string" ? fields["signal"] : null;if (signal === null || !KNOWN_SIGNALS.includes(signal)) return null;const topic = typeof fields["topic"] === "string" ? fields["topic"] : null;- const principle =- typeof fields["principle"] === "string" ? fields["principle"] : null;+ const principle = typeof fields["principle"] === "string" ? fields["principle"] : null;if (!topic || !principle) return null;return {@@ -353,10 +351,7 @@ export function discoverMarkersDetailed(content: string): MarkerDiscoveryResultmalformed++;continue;}- const parsed = parseBlockMarker(- bodyLines.join("\n"),- fenceStartLineNumber,- );+ const parsed = parseBlockMarker(bodyLines.join("\n"), fenceStartLineNumber);if (parsed) out.push(parsed);else malformed++;}@@ -392,5 +387,5 @@ function looksLikeInlineMarkerAttempt(trimmedLine: string): boolean {const rest = trimmedLine.slice(4);if (rest.length > 0 && rest[0] !== " " && rest[0] !== "\t") return false;const kind = rest.trimStart().split(/[ \t=]/, 1)[0] ?? "";- return KNOWN_KINDS.includes(kind);+ return KNOWN_KINDS.has(kind);}diff --git a/src/core/brain/link-graph/alias-index.ts b/src/core/brain/link-graph/alias-index.tsindex 6adf4c9a..04ed83a9 100644--- a/src/core/brain/link-graph/alias-index.ts+++ b/src/core/brain/link-graph/alias-index.ts@@ -84,7 +84,7 @@ function collect(// Sort the directory listing so the first-wins rule is// deterministic across filesystems that don't enumerate in// stable order.- const entries = readdirSync(dir).sort();+ const entries = readdirSync(dir).toSorted();for (const name of entries) {if (!name.endsWith(".md")) continue;const canonicalId = name.slice(0, -".md".length);diff --git a/src/core/brain/link-graph/concept-cluster.ts b/src/core/brain/link-graph/concept-cluster.tsindex 02b6b482..6875ad03 100644--- a/src/core/brain/link-graph/concept-cluster.ts+++ b/src/core/brain/link-graph/concept-cluster.ts@@ -21,10 +21,7 @@ import { buildBacklinkIndex, type BacklinkRef } from "../backlinks.ts";import { brainDirs } from "../paths.ts";import { isoSecond } from "../time.ts";import { normaliseWikilinkTarget } from "../wikilink.ts";-import {- findUnlinkedMentions,- type MentionRef,-} from "./unlinked-mentions.ts";+import { findUnlinkedMentions, type MentionRef } from "./unlinked-mentions.ts";/** One linker pointing at the target. */export interface ConceptLinker {@@ -82,18 +79,18 @@ export function buildConceptCluster(...(r.aliasSource !== undefined ? { aliasSource: r.aliasSource } : {}),}),)- .sort((a, b) => {+ .toSorted((a, b) => {const sa = a.source.localeCompare(b.source);if (sa !== 0) return sa;return a.field.localeCompare(b.field);});const unlinkedMentions = opts.includeUnlinked- ? findUnlinkedMentions(vault, normalised, {- ...(opts.unlinkedLimit !== undefined- ? { limit: opts.unlinkedLimit }- : {}),- })+ ? findUnlinkedMentions(+ vault,+ normalised,+ opts.unlinkedLimit !== undefined ? { limit: opts.unlinkedLimit } : {},+ ): Object.freeze([] as MentionRef[]);return Object.freeze({diff --git a/src/core/brain/link-graph/moc-audit.ts b/src/core/brain/link-graph/moc-audit.tsindex 532ecd26..6b1b121c 100644--- a/src/core/brain/link-graph/moc-audit.ts+++ b/src/core/brain/link-graph/moc-audit.ts@@ -68,11 +68,7 @@ export interface AuditMocOptions {readonly minLinkRatio?: number;}-export function auditMoc(- vault: string,- hubId: string,- opts: AuditMocOptions = {},-): MocAuditReport {+export function auditMoc(vault: string, hubId: string, opts: AuditMocOptions = {}): MocAuditReport {const hubCanonical = normaliseWikilinkTarget(hubId);const hubPath = locateArtifact(vault, hubCanonical);if (!hubPath) {@@ -103,9 +99,7 @@ export function auditMoc(const bodyChars = hubBody.replace(/\s+/g, "").length;const ratio = bodyChars > 0 ? linkChars / bodyChars : 0;if (ratio < minRatio) {- throw new MocAuditError(- `not a MOC: link ratio ${ratio.toFixed(2)} < threshold ${minRatio}`,- );+ throw new MocAuditError(`not a MOC: link ratio ${ratio.toFixed(2)} < threshold ${minRatio}`);}// Backlink index + cluster member metadata.@@ -126,9 +120,7 @@ export function auditMoc(// Don't count the hub's own outbound reference toward the// bucket assignment; the bucket measures coverage by OTHER// notes, not by the hub itself.- const inboundFromOthers = backlinks.filter(- (r) => r.source !== hubCanonical,- ).length;+ const inboundFromOthers = backlinks.filter((r) => r.source !== hubCanonical).length;const member: MocClusterMember = Object.freeze({id: target,backlinkCount: inboundFromOthers,@@ -186,10 +178,7 @@ export function auditMoc(function locateArtifact(vault: string, id: string): string | null {const dirs = brainDirs(vault);- const candidates = [- join(dirs.preferences, `${id}.md`),- join(dirs.retired, `${id}.md`),- ];+ const candidates = [join(dirs.preferences, `${id}.md`), join(dirs.retired, `${id}.md`)];for (const c of candidates) if (existsSync(c)) return c;return null;}@@ -215,10 +204,7 @@ function resolveThresholds(vault: string,opts: AuditMocOptions,): { minOutbound: number; minRatio: number } {- if (- opts.minOutboundLinks !== undefined &&- opts.minLinkRatio !== undefined- ) {+ if (opts.minOutboundLinks !== undefined && opts.minLinkRatio !== undefined) {return {minOutbound: opts.minOutboundLinks,minRatio: opts.minLinkRatio,@@ -232,11 +218,7 @@ function resolveThresholds(}const lg = cfg ? resolveLinkGraph(cfg) : null;return {- minOutbound:- opts.minOutboundLinks ??- (lg ? lg.moc_min_outbound_links : 5),- minRatio:- opts.minLinkRatio ?? (lg ? lg.moc_min_link_ratio : 0.3),+ minOutbound: opts.minOutboundLinks ?? (lg ? lg.moc_min_outbound_links : 5),+ minRatio: opts.minLinkRatio ?? (lg ? lg.moc_min_link_ratio : 0.3),};}-diff --git a/src/core/brain/link-graph/parse-wikilink.ts b/src/core/brain/link-graph/parse-wikilink.tsindex 50797b2e..953e5c6c 100644--- a/src/core/brain/link-graph/parse-wikilink.ts+++ b/src/core/brain/link-graph/parse-wikilink.ts@@ -54,9 +54,27 @@ const CODE_BLOCK_RE = /```[\s\S]*?```|`[^`]+`/g;* register as backlinks.*/const MEDIA_EXTENSIONS: ReadonlySet<string> = new Set([- ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".tiff",- ".avif", ".mp4", ".webm", ".ogv", ".mov", ".mkv", ".avi", ".mp3",- ".wav", ".ogg", ".flac", ".m4a", ".pdf",+ ".png",+ ".jpg",+ ".jpeg",+ ".gif",+ ".svg",+ ".webp",+ ".bmp",+ ".tiff",+ ".avif",+ ".mp4",+ ".webm",+ ".ogv",+ ".mov",+ ".mkv",+ ".avi",+ ".mp3",+ ".wav",+ ".ogg",+ ".flac",+ ".m4a",+ ".pdf",]);export interface WikilinkParse {diff --git a/src/core/brain/lint-consolidate.ts b/src/core/brain/lint-consolidate.tsindex f4cfa9b6..c841f7e4 100644--- a/src/core/brain/lint-consolidate.ts+++ b/src/core/brain/lint-consolidate.ts@@ -18,12 +18,7 @@* snapshot-test the report independently of writes.*/-import {- existsSync,- readFileSync,- readdirSync,- statSync,-} from "node:fs";+import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";import { join } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";@@ -82,10 +77,7 @@ function buildMergeMap(vault: string): MergeMap {const [meta] = parseFrontmatter(full);const target = readMergedInto(meta);if (target !== null) {- const id =- typeof meta["id"] === "string"- ? meta["id"]- : name.replace(/\.md$/, "");+ const id = typeof meta["id"] === "string" ? meta["id"] : name.replace(/\.md$/, "");forward.set(id, target);}} catch {@@ -113,11 +105,7 @@ function scanFileForMergedLinks(return { fixes, rewritten };}-function detectStaleStable(- vault: string,- now: Date,- staleDays: number,-): LintDemotion[] {+function detectStaleStable(vault: string, now: Date, staleDays: number): LintDemotion[] {const out: LintDemotion[] = [];const dirs = brainDirs(vault);if (!existsSync(dirs.preferences)) return out;@@ -142,12 +130,10 @@ function detectStaleStable(const evAge = ageDaysFromIso(lastEv, now);if (evAge < staleDays) continue;}- const createdAt =- typeof meta["created_at"] === "string" ? meta["created_at"] : "";+ const createdAt = typeof meta["created_at"] === "string" ? meta["created_at"] : "";const age = ageDaysFromIso(createdAt, now);if (age < staleDays) continue;- const id =- typeof meta["id"] === "string" ? meta["id"] : name.replace(/\.md$/, "");+ const id = typeof meta["id"] === "string" ? meta["id"] : name.replace(/\.md$/, "");out.push({kind: "demote-stale-stable",id,@@ -175,19 +161,13 @@ function applyDemotion(path: string): boolean {const tail = raw.slice(close);// Replace `_lifecycle: stable` (or legacy `lifecycle: stable`) with draft.// Preserve indentation/spacing.- const updatedHead = head.replace(- /^(_?lifecycle:\s+)stable\s*$/m,- `$1draft`,- );+ const updatedHead = head.replace(/^(_?lifecycle:\s+)stable\s*$/m, `$1draft`);if (updatedHead === head) return false;atomicWriteFileSync(path, updatedHead + tail);return true;}-export function lintConsolidate(- vault: string,- opts: LintOptions,-): LintReport {+export function lintConsolidate(vault: string, opts: LintOptions): LintReport {const now = opts.now ?? new Date();const staleDays = opts.staleDays ?? PAGE_STALE_DAYS_DEFAULT;const merge = buildMergeMap(vault);@@ -227,11 +207,7 @@ export function lintConsolidate(} catch {continue;}- const { fixes: fileFixes, rewritten } = scanFileForMergedLinks(- full,- raw,- merge,- );+ const { fixes: fileFixes, rewritten } = scanFileForMergedLinks(full, raw, merge);if (fileFixes.length === 0) continue;fixes.push(...fileFixes);if (opts.apply && rewritten !== raw) {diff --git a/src/core/brain/log-jsonl.ts b/src/core/brain/log-jsonl.tsindex a6fff29d..262fc172 100644--- a/src/core/brain/log-jsonl.ts+++ b/src/core/brain/log-jsonl.ts@@ -13,15 +13,8 @@import { existsSync, readFileSync } from "node:fs";import { logJsonlPath, logPath, validateIsoDate } from "./paths.ts";-import {- parseLogDay,- type BrainLogEntry,- type BrainLogParseWarning,-} from "./log.ts";-import {- BRAIN_LOG_EVENT_KIND_SET,- type BrainLogEventKind,-} from "./types.ts";+import { parseLogDay, type BrainLogEntry, type BrainLogParseWarning } from "./log.ts";+import { BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "./types.ts";export interface ReadLogDayResult {readonly entries: ReadonlyArray<BrainLogEntry>;diff --git a/src/core/brain/log.ts b/src/core/brain/log.tsindex 49fa47ab..b02b8923 100644--- a/src/core/brain/log.ts+++ b/src/core/brain/log.ts@@ -30,24 +30,13 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";import lockfile from "proper-lockfile";import { atomicWriteFileSync } from "../fs-atomic.ts";-import {- brainDirs,- logJsonlPath,- logPath,- validateIsoDate,-} from "./paths.ts";-import {- BRAIN_LOG_EVENT_KIND,- BRAIN_LOG_EVENT_KIND_SET,- type BrainLogEventKind,-} from "./types.ts";+import { brainDirs, logJsonlPath, logPath, validateIsoDate } from "./paths.ts";+import { BRAIN_LOG_EVENT_KIND, BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "./types.ts";// ----- Public types ---------------------------------------------------------/** Parsed bullet payload of a single log entry. */-export type BrainLogEntryPayload = Readonly<- Record<string, string | ReadonlyArray<string>>->;+export type BrainLogEntryPayload = Readonly<Record<string, string | ReadonlyArray<string>>>;/*** A parsed log entry. `timestamp` is the full ISO-8601 UTC moment@@ -245,10 +234,7 @@ function acquireLogLock(logDir: string): () => void {throw lastErr;}-export function appendLogEvent(- vault: string,- event: BrainLogEntry,-): AppendLogEventResult {+export function appendLogEvent(vault: string, event: BrainLogEntry): AppendLogEventResult {if (!BRAIN_LOG_EVENT_KIND_SET.has(event.eventType)) {throw new Error(`appendLogEvent: unknown event kind '${event.eventType}' — must be one of ${Object.values(@@ -269,8 +255,7 @@ export function appendLogEvent(typeof topLevelAgent === "string" && typeof event.body["agent"] !== "string"? Object.freeze({ ...event.body, agent: topLevelAgent }): event.body;- const diskEvent: BrainLogEntry =- eventBody === event.body ? event : { ...event, body: eventBody };+ const diskEvent: BrainLogEntry = eventBody === event.body ? event : { ...event, body: eventBody };// §23 (v0.10.8): each event lands in both `<date>.jsonl` (machine// surface, primary for `readLogDay`) and `<date>.md` (human-facing@@ -290,14 +275,10 @@ export function appendLogEvent(// One row per event. The row is a deterministic projection of the// markdown body so the markdown and JSONL representations describe// the same event byte-for-byte after JSON.parse.- const existingJsonl = existsSync(jsonlPath)- ? readFileSync(jsonlPath, "utf8")- : "";+ const existingJsonl = existsSync(jsonlPath) ? readFileSync(jsonlPath, "utf8") : "";const line = renderJsonlLine(diskEvent);const nextJsonl =- existingJsonl === ""- ? `${line}\n`- : `${existingJsonl.replace(/\s+$/, "")}\n${line}\n`;+ existingJsonl === "" ? `${line}\n` : `${existingJsonl.replace(/\s+$/, "")}\n${line}\n`;atomicWriteFileSync(jsonlPath, nextJsonl);// ---- Markdown (human surface) -------------------------------------@@ -470,10 +451,7 @@ interface IsoUtcParts {* heading shape is `HH:MM:SS` only.*/function parseIsoUtc(timestamp: string): IsoUtcParts {- const m =- /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z$/.exec(- timestamp,- );+ const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z$/.exec(timestamp);if (!m) {throw new Error(`appendLogEvent: timestamp must be ISO-8601 UTC (YYYY-MM-DDTHH:MM:SSZ); got ${JSON.stringify(timestamp)}`,diff --git a/src/core/brain/maintenance/action-scorer.ts b/src/core/brain/maintenance/action-scorer.tsindex 2266e6f7..f762cb55 100644--- a/src/core/brain/maintenance/action-scorer.ts+++ b/src/core/brain/maintenance/action-scorer.ts@@ -11,11 +11,7 @@* and `computeTokenFootprint` outputs upstream.*/-export type ActionCategory =- | "dedup"- | "lifecycle"- | "merged-link"- | "token-footprint";+export type ActionCategory = "dedup" | "lifecycle" | "merged-link" | "token-footprint";export interface ActionItem {readonly id: string;@@ -52,9 +48,7 @@ const WEIGHT = Object.freeze({tokenFootprintExcessPer10k: 3,});-function scoreDedup(- inputs: NonNullable<ActionInputs["dedupCandidates"]>,-): ActionItem[] {+function scoreDedup(inputs: NonNullable<ActionInputs["dedupCandidates"]>): ActionItem[] {const out: ActionItem[] = [];for (const c of inputs) {if (c.secondaryCount <= 0) continue;@@ -69,9 +63,7 @@ function scoreDedup(return out;}-function scoreStale(- inputs: NonNullable<ActionInputs["staleByLifecycle"]>,-): ActionItem[] {+function scoreStale(inputs: NonNullable<ActionInputs["staleByLifecycle"]>): ActionItem[] {const out: ActionItem[] = [];for (const s of inputs) {if (s.ageDays <= 0) continue;@@ -87,9 +79,7 @@ function scoreStale(return out;}-function scoreBrokenLinks(- inputs: NonNullable<ActionInputs["brokenLinks"]>,-): ActionItem[] {+function scoreBrokenLinks(inputs: NonNullable<ActionInputs["brokenLinks"]>): ActionItem[] {// Bucket by source path so the report does not duplicate noisy// file-level recommendations when one page has many broken links.const byPath = new Map<string, number>();@@ -109,9 +99,7 @@ function scoreBrokenLinks(return out;}-function scoreTokenFootprint(- input: NonNullable<ActionInputs["tokenFootprint"]>,-): ActionItem[] {+function scoreTokenFootprint(input: NonNullable<ActionInputs["tokenFootprint"]>): ActionItem[] {const excess = input.total - input.warnThreshold;if (excess <= 0) return [];const buckets = Math.ceil(excess / 10_000);@@ -139,8 +127,7 @@ export function scoreActions(if (inputs.dedupCandidates) all.push(...scoreDedup(inputs.dedupCandidates));if (inputs.staleByLifecycle) all.push(...scoreStale(inputs.staleByLifecycle));if (inputs.brokenLinks) all.push(...scoreBrokenLinks(inputs.brokenLinks));- if (inputs.tokenFootprint)- all.push(...scoreTokenFootprint(inputs.tokenFootprint));+ if (inputs.tokenFootprint) all.push(...scoreTokenFootprint(inputs.tokenFootprint));all.sort((a, b) => {if (b.impact !== a.impact) return b.impact - a.impact;diff --git a/src/core/brain/maintenance/collect.ts b/src/core/brain/maintenance/collect.tsindex d7428b28..5f2e5d52 100644--- a/src/core/brain/maintenance/collect.ts+++ b/src/core/brain/maintenance/collect.ts@@ -14,9 +14,7 @@ import { findDuplicateCandidates } from "../page-dedup.ts";import { computeTokenFootprint } from "../token-footprint.ts";import { scoreActions, type ActionItem } from "./action-scorer.ts";-export function collectMaintenanceActions(- vault: string,-): ReadonlyArray<ActionItem> {+export function collectMaintenanceActions(vault: string): ReadonlyArray<ActionItem> {let dedupCandidates: Array<{ canonicalId: string; secondaryCount: number }> = [];let staleByLifecycle: Array<{ id: string; ageDays: number }> = [];let brokenLinks: Array<{ path: string; from: string }> = [];diff --git a/src/core/brain/manifest.ts b/src/core/brain/manifest.tsindex e038f0b4..245e419e 100644--- a/src/core/brain/manifest.ts+++ b/src/core/brain/manifest.ts@@ -8,12 +8,7 @@*/import { createHash } from "node:crypto";-import {- existsSync,- lstatSync,- readFileSync,- readdirSync,-} from "node:fs";+import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";import { join, relative } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";@@ -127,7 +122,7 @@ function freezeManifest(): BrainManifest {// Materialise in sorted key order so JSON.stringify yields stable// bytes across runs.- const sorted = Array.from(entries.keys()).sort();+ const sorted = Array.from(entries.keys()).toSorted();const files: Record<string, BrainManifestEntry> = {};for (const k of sorted) files[k] = entries.get(k)!;return Object.freeze({@@ -147,10 +142,7 @@ function freezeManifest(** Each bucket is sorted by `path` ascending for stable rendering.*/-export function diffManifests(- before: BrainManifest,- after: BrainManifest,-): BrainManifestDiff {+export function diffManifests(before: BrainManifest, after: BrainManifest): BrainManifestDiff {const added: BrainManifestDiffEntry[] = [];const removed: BrainManifestDiffEntry[] = [];const changed: BrainManifestDiffEntry[] = [];@@ -188,11 +180,7 @@ export function diffManifests(/** Convenience: `true` when any of the three buckets is non-empty. */export function manifestDiffHasDrift(diff: BrainManifestDiff): boolean {- return (- diff.added.length > 0 ||- diff.removed.length > 0 ||- diff.changed.length > 0- );+ return diff.added.length > 0 || diff.removed.length > 0 || diff.changed.length > 0;}/**@@ -200,10 +188,7 @@ export function manifestDiffHasDrift(diff: BrainManifestDiff): boolean {* drift-detection abort message. Sections are emitted only when their* bucket is non-empty so the operator's eye lands on real differences.*/-export function renderManifestDriftMarkdown(- diff: BrainManifestDiff,- runId: string,-): string {+export function renderManifestDriftMarkdown(diff: BrainManifestDiff, runId: string): string {const lines: string[] = [`Drift detected between snapshot '${runId}' and the live Brain/ tree.`,`Pass --force-rollback to overwrite anyway.`,@@ -261,10 +246,7 @@ export function manifestSidecarPath(vault: string, runId: string): string {* schema_version — callers fall back to the legacy "no drift check"* path on a null return.*/-export function readManifestSidecar(- vault: string,- runId: string,-): BrainManifest | null {+export function readManifestSidecar(vault: string, runId: string): BrainManifest | null {const path = manifestSidecarPath(vault, runId);let raw: string;try {@@ -315,11 +297,7 @@ export function readManifestSidecar(* Write the sidecar manifest atomically. Pretty-printed with two-space* indent so a manual `cat` or `git diff` stays readable.*/-export function writeManifestSidecar(- vault: string,- runId: string,- manifest: BrainManifest,-): void {+export function writeManifestSidecar(vault: string, runId: string, manifest: BrainManifest): void {const path = manifestSidecarPath(vault, runId);atomicWriteFileSync(path, JSON.stringify(manifest, null, 2) + "\n");}diff --git a/src/core/brain/merge-candidates.ts b/src/core/brain/merge-candidates.tsindex 5217330b..76bd1a5c 100644--- a/src/core/brain/merge-candidates.ts+++ b/src/core/brain/merge-candidates.ts@@ -20,10 +20,7 @@ import { join } from "node:path";import { brainDirs } from "./paths.ts";import { parsePreference } from "./preference.ts";import { findSimilarPairs, tokenise } from "./similarity.ts";-import {- BRAIN_PREFERENCE_STATUS,- type BrainPreference,-} from "./types.ts";+import { BRAIN_PREFERENCE_STATUS, type BrainPreference } from "./types.ts";/** Inclusive lower bound for surfacing a pair to the digest. */export const JACCARD_MERGE_SUGGEST_THRESHOLD = 0.6;@@ -79,8 +76,8 @@ export function findMergeCandidates(const entries = [];for (const p of prefs) {if (- p.status !== BRAIN_PREFERENCE_STATUS.confirmed- && p.status !== BRAIN_PREFERENCE_STATUS.quarantine+ p.status !== BRAIN_PREFERENCE_STATUS.confirmed &&+ p.status !== BRAIN_PREFERENCE_STATUS.quarantine) {continue;}diff --git a/src/core/brain/merge.ts b/src/core/brain/merge.tsindex 5b3c73fc..2ec686ba 100644--- a/src/core/brain/merge.ts+++ b/src/core/brain/merge.ts@@ -28,16 +28,9 @@ import { join } from "node:path";import { regenerateActiveQuiet } from "./active.ts";import { appendLogEvent } from "./log.ts";import { brainDirs, preferencePath } from "./paths.ts";-import {- moveToRetired,- parsePreference,- writePreference,-} from "./preference.ts";+import { moveToRetired, parsePreference, writePreference } from "./preference.ts";import { isoDate, isoSecond } from "./time.ts";-import {- BRAIN_LOG_EVENT_KIND,- BRAIN_RETIRED_REASON,-} from "./types.ts";+import { BRAIN_LOG_EVENT_KIND, BRAIN_RETIRED_REASON } from "./types.ts";import { renderPrefLink } from "./wikilink.ts";export type BrainMergeErrorCode =@@ -87,10 +80,7 @@ export function mergePreferences(opts: MergeOptions = {},): MergePlan {if (keepId === dropId) {- throw new BrainMergeError(- "same-id",- `keep and drop refer to the same preference '${keepId}'`,- );+ throw new BrainMergeError("same-id", `keep and drop refer to the same preference '${keepId}'`);}const now = opts.now ?? new Date();const dryRun = opts.dryRun === true;@@ -144,9 +134,9 @@ export function mergePreferences(if (keep.topic !== drop.topic) {throw new BrainMergeError("topic-mismatch",- `topic mismatch: keep='${keep.topic}', drop='${drop.topic}'.`- + " Merge is for near-duplicate rules in the same bucket;"- + " use `o2b brain reject` if drop is wrong rather than redundant.",+ `topic mismatch: keep='${keep.topic}', drop='${drop.topic}'.` ++ " Merge is for near-duplicate rules in the same bucket;" ++ " use `o2b brain reject` if drop is wrong rather than redundant.",);}const keepScope = keep.scope ?? null;@@ -154,22 +144,19 @@ export function mergePreferences(if (keepScope !== dropScope) {throw new BrainMergeError("scope-mismatch",- `scope mismatch: keep='${keepScope ?? "(none)"}', drop='${dropScope ?? "(none)"}'.`- + " Use `o2b brain reject` instead.",+ `scope mismatch: keep='${keepScope ?? "(none)"}', drop='${dropScope ?? "(none)"}'.` ++ " Use `o2b brain reject` instead.",);}if (keep.pinned !== drop.pinned && drop.pinned) {throw new BrainMergeError("pin-parity",- `drop '${dropId}' is pinned but keep '${keepId}' is not;`- + " put the pinned pref first as <keep> if you want to merge.",+ `drop '${dropId}' is pinned but keep '${keepId}' is not;` ++ " put the pinned pref first as <keep> if you want to merge.",);}- const merged_evidenced_by = mergeEvidencedBy(- keep.evidenced_by,- drop.evidenced_by,- );+ const merged_evidenced_by = mergeEvidencedBy(keep.evidenced_by, drop.evidenced_by);const applied_sum = keep.applied_count + drop.applied_count;const violated_sum = keep.violated_count + drop.violated_count;const last_evidence_at = maxIso(keep.last_evidence_at, drop.last_evidence_at);@@ -252,10 +239,7 @@ export function mergePreferences(function stripPrefPrefix(id: string): string {if (!id.startsWith("pref-") || id.length <= "pref-".length) {- throw new BrainMergeError(- "keep-not-found",- `expected a 'pref-…' id; got '${id}'`,- );+ throw new BrainMergeError("keep-not-found", `expected a 'pref-…' id; got '${id}'`);}return id.slice("pref-".length);}diff --git a/src/core/brain/most-applied.ts b/src/core/brain/most-applied.tsindex 4780baec..80273769 100644--- a/src/core/brain/most-applied.ts+++ b/src/core/brain/most-applied.ts@@ -11,10 +11,7 @@ import { existsSync, readdirSync } from "node:fs";import { brainDirs } from "./paths.ts";import { readLogDay } from "./log-jsonl.ts";-import {- MOST_APPLIED_LIMIT_DEFAULT,- MOST_APPLIED_WINDOW_DAYS_DEFAULT,-} from "./policy.ts";+import { MOST_APPLIED_LIMIT_DEFAULT, MOST_APPLIED_WINDOW_DAYS_DEFAULT } from "./policy.ts";import { isoDate } from "./time.ts";import { normaliseWikilinkTarget } from "./wikilink.ts";import {diff --git a/src/core/brain/note.ts b/src/core/brain/note.tsindex 80d6bfd3..4d0379b7 100644--- a/src/core/brain/note.ts+++ b/src/core/brain/note.ts@@ -46,9 +46,7 @@ export interface AppendBrainNoteResult {* sidecar via `appendLogEvent`). Throws plain `Error` on empty text* — wrappers translate the error to their protocol's idiom.*/-export function appendBrainNote(- input: AppendBrainNoteInput,-): AppendBrainNoteResult {+export function appendBrainNote(input: AppendBrainNoteInput): AppendBrainNoteResult {const sanitised = sanitiseTextField(input.text, {maxLen: NOTE_TEXT_MAX_LEN,singleLine: true,diff --git a/src/core/brain/page-dedup.ts b/src/core/brain/page-dedup.tsindex 544e8bbf..d68b28d9 100644Binary files a/src/core/brain/page-dedup.ts and b/src/core/brain/page-dedup.ts differdiff --git a/src/core/brain/page-meta/confidence.ts b/src/core/brain/page-meta/confidence.tsindex 78eb8acf..365da206 100644--- a/src/core/brain/page-meta/confidence.ts+++ b/src/core/brain/page-meta/confidence.ts@@ -22,9 +22,7 @@ export function isPageConfidence(value: unknown): value is PageConfidence {* Unknown / absent values fall back to `low` so a page that has not* yet earned a confidence stamp does not get one for free.*/-export function readConfidence(- meta: Readonly<Record<string, unknown>>,-): PageConfidence {+export function readConfidence(meta: Readonly<Record<string, unknown>>): PageConfidence {const modern = meta["_confidence"];if (isPageConfidence(modern)) return modern;const legacy = meta["confidence"];diff --git a/src/core/brain/page-meta/lifecycle.ts b/src/core/brain/page-meta/lifecycle.tsindex 6ad9367c..73d32f52 100644--- a/src/core/brain/page-meta/lifecycle.ts+++ b/src/core/brain/page-meta/lifecycle.ts@@ -43,9 +43,7 @@ export function isPageLifecycle(value: unknown): value is PageLifecycle {* Unknown / absent values fall back to `stable` per the* backwards-compatibility contract.*/-export function readLifecycle(- meta: Readonly<Record<string, unknown>>,-): PageLifecycle {+export function readLifecycle(meta: Readonly<Record<string, unknown>>): PageLifecycle {const modern = meta["_lifecycle"];if (isPageLifecycle(modern)) return modern;const legacy = meta["lifecycle"];diff --git a/src/core/brain/page-meta/page-id.ts b/src/core/brain/page-meta/page-id.tsindex a7043672..b2aabae0 100644--- a/src/core/brain/page-meta/page-id.ts+++ b/src/core/brain/page-meta/page-id.ts@@ -37,9 +37,7 @@ export class MergeChainError extends Error {* Non-string values are treated as absent so a malformed file does* not poison the canonical lookup.*/-export function readMergedInto(- meta: Readonly<Record<string, unknown>>,-): string | null {+export function readMergedInto(meta: Readonly<Record<string, unknown>>): string | null {const v = meta["merged_into"];if (typeof v === "string" && v.trim().length > 0) return v.trim();return null;@@ -87,11 +85,7 @@ export function resolveCanonicalId(vault: string, startId: string): string {const path = pageIdToPath(vault, current);if (path === null) {- throw new MergeChainError(- "MALFORMED",- current,- `page id has no known prefix: ${current}`,- );+ throw new MergeChainError("MALFORMED", current, `page id has no known prefix: ${current}`);}if (!existsSync(path)) {// Dangling pointer - the canonical page was moved or deleted.@@ -125,11 +119,7 @@ export function resolveCanonicalId(vault: string, startId: string): string {* The caller is responsible for picking which side is the canonical* and which is the secondary; this function only writes the pointer.*/-export function setMergedInto(- vault: string,- secondaryId: string,- canonicalId: string,-): string {+export function setMergedInto(vault: string, secondaryId: string, canonicalId: string): string {if (!isValidPageId(secondaryId)) {throw new MergeChainError("MALFORMED",@@ -153,11 +143,7 @@ export function setMergedInto(}const secondaryPath = pageIdToPath(vault, secondaryId);if (secondaryPath === null || !existsSync(secondaryPath)) {- throw new MergeChainError(- "MALFORMED",- secondaryId,- `secondary page not found: ${secondaryId}`,- );+ throw new MergeChainError("MALFORMED", secondaryId, `secondary page not found: ${secondaryId}`);}const raw = readFileSync(secondaryPath, "utf8");if (raw.startsWith("---\n")) {@@ -187,9 +173,5 @@ export function setMergedInto(}return canonicalId;}- throw new MergeChainError(- "MALFORMED",- secondaryId,- `file has no frontmatter: ${secondaryPath}`,- );+ throw new MergeChainError("MALFORMED", secondaryId, `file has no frontmatter: ${secondaryPath}`);}diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.tsindex a410f12e..85c73565 100644--- a/src/core/brain/paths.ts+++ b/src/core/brain/paths.ts@@ -64,8 +64,7 @@ const ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;// shape check for the date-time stem.const RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;-const WINDOWS_RESERVED_BASENAME_RE =- /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;+const WINDOWS_RESERVED_BASENAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;export interface BrainDirs {readonly brain: string;@@ -99,18 +98,12 @@ export function brainDirs(vault: string): BrainDirs {/** Path of `Brain/_brain.yaml`. */export function brainConfigPath(vault: string): string {- return ensureInsideVault(- join(brainDirs(vault).brain, BRAIN_CONFIG_FILE),- vault,- );+ return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_CONFIG_FILE), vault);}/** Path of the Brain operating manual rendered into the vault. */export function brainManualPath(vault: string): string {- return ensureInsideVault(- join(brainDirs(vault).brain, BRAIN_MANUAL_FILE),- vault,- );+ return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_MANUAL_FILE), vault);}/**@@ -120,43 +113,27 @@ export function brainManualPath(vault: string): string {* `osb://preferences/active`.*/export function brainActivePath(vault: string): string {- return ensureInsideVault(- join(brainDirs(vault).brain, BRAIN_ACTIVE_FILE),- vault,- );+ return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_ACTIVE_FILE), vault);}/** Active-signal path: `Brain/inbox/sig-<date>-<slug>.md`. */export function signalPath(vault: string, date: string, slug: string): string {const d = validateIsoDate(date);const s = validateSlug(slug);- return ensureInsideVault(- join(brainDirs(vault).inbox, `sig-${d}-${s}.md`),- vault,- );+ return ensureInsideVault(join(brainDirs(vault).inbox, `sig-${d}-${s}.md`), vault);}/** Processed-signal path: `Brain/inbox/processed/sig-<date>-<slug>.md`. */-export function processedSignalPath(- vault: string,- date: string,- slug: string,-): string {+export function processedSignalPath(vault: string, date: string, slug: string): string {const d = validateIsoDate(date);const s = validateSlug(slug);- return ensureInsideVault(- join(brainDirs(vault).processed, `sig-${d}-${s}.md`),- vault,- );+ return ensureInsideVault(join(brainDirs(vault).processed, `sig-${d}-${s}.md`), vault);}/** Preference path: `Brain/preferences/pref-<slug>.md`. */export function preferencePath(vault: string, slug: string): string {const s = validateSlug(slug);- return ensureInsideVault(- join(brainDirs(vault).preferences, `pref-${s}.md`),- vault,- );+ return ensureInsideVault(join(brainDirs(vault).preferences, `pref-${s}.md`), vault);}/**@@ -166,19 +143,13 @@ export function preferencePath(vault: string, slug: string): string {*/export function preferenceHistoryPath(vault: string, slug: string): string {const s = validateSlug(slug);- return ensureInsideVault(- join(brainDirs(vault).preferences, `pref-${s}.history.jsonl`),- vault,- );+ return ensureInsideVault(join(brainDirs(vault).preferences, `pref-${s}.history.jsonl`), vault);}/** Retired-preference path: `Brain/retired/ret-<slug>.md`. */export function retiredPath(vault: string, slug: string): string {const s = validateSlug(slug);- return ensureInsideVault(- join(brainDirs(vault).retired, `ret-${s}.md`),- vault,- );+ return ensureInsideVault(join(brainDirs(vault).retired, `ret-${s}.md`), vault);}/** Log file for the given UTC date: `Brain/log/<YYYY-MM-DD>.md`. */@@ -227,10 +198,7 @@ export function snapshotsDir(vault: string): string {/** Snapshot archive path: `Brain/.snapshots/<run_id>.tar.zst`. */export function snapshotPath(vault: string, runId: string): string {const id = validateRunId(runId);- return ensureInsideVault(- join(brainDirs(vault).snapshots, `${id}.tar.zst`),- vault,- );+ return ensureInsideVault(join(brainDirs(vault).snapshots, `${id}.tar.zst`), vault);}// ----- Validators -----------------------------------------------------------@@ -252,21 +220,13 @@ export function validateSlug(slug: string): string {// ambiguous when round-tripped through cross-platform tooling (zip// archives, syncthing, git on Windows).if (/[:*?"<>|\x00-\x1F]/.test(trimmed)) {- throw new Error(- `slug contains invalid character: ${JSON.stringify(slug)}`,- );+ throw new Error(`slug contains invalid character: ${JSON.stringify(slug)}`);}- if (- trimmed === ".." ||- trimmed === "." ||- /(?:^|[^\w])\.\.(?:$|[^\w])/.test(trimmed)- ) {+ if (trimmed === ".." || trimmed === "." || /(?:^|[^\w])\.\.(?:$|[^\w])/.test(trimmed)) {throw new Error(`slug must not contain '..' traversal: ${slug}`);}if (/[. ]$/.test(trimmed)) {- throw new Error(- `slug must not end with '.' or whitespace (Windows-incompatible): ${slug}`,- );+ throw new Error(`slug must not end with '.' or whitespace (Windows-incompatible): ${slug}`);}if (WINDOWS_RESERVED_BASENAME_RE.test(trimmed)) {throw new Error(`slug uses a Windows-reserved filename: ${slug}`);@@ -305,15 +265,9 @@ export function validateRunId(runId: string): string {const trimmed = runId.trim();if (!trimmed) throw new Error("run_id must not be empty");if (!RUN_ID_RE.test(trimmed)) {- throw new Error(- `run_id must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/: ${runId}`,- );+ throw new Error(`run_id must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/: ${runId}`);}- if (- trimmed.includes("..") ||- trimmed.includes("/") ||- trimmed.includes("\\")- ) {+ if (trimmed.includes("..") || trimmed.includes("/") || trimmed.includes("\\")) {throw new Error(`run_id must not contain '..' or path separators: ${runId}`);}if (WINDOWS_RESERVED_BASENAME_RE.test(trimmed)) {@@ -378,10 +332,7 @@ export function allocateSlug(opts: AllocateSlugOptions): AllocateSlugResult {// test); the realistic worst case is a handful.for (let attempt = 1; attempt <= maxAttempts; attempt++) {const slug = attempt === 1 ? baseSlug : `${baseSlug}-${attempt}`;- const candidate = ensureInsideVault(- join(targetDir, `${prefix}-${slug}.md`),- vault,- );+ const candidate = ensureInsideVault(join(targetDir, `${prefix}-${slug}.md`), vault);if (!existsSync(candidate)) {return { slug, path: candidate, suffix: attempt === 1 ? null : attempt };}diff --git a/src/core/brain/pin.ts b/src/core/brain/pin.tsindex fb9fa40a..f454add6 100644--- a/src/core/brain/pin.ts+++ b/src/core/brain/pin.ts@@ -81,9 +81,7 @@ export function setPinned(throw new Error("setPinned missing field: pref_id");}if (typeof value !== "boolean") {- throw new Error(- `setPinned: 'value' must be a boolean; got ${JSON.stringify(value)}`,- );+ throw new Error(`setPinned: 'value' must be a boolean; got ${JSON.stringify(value)}`);}const trimmed = prefId.trim();@@ -146,4 +144,3 @@ export function setPinned(export function isPinned(pref: BrainPreference): boolean {return pref.pinned === true;}-diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex 6ffc7e05..ff091c47 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -42,10 +42,7 @@ import type {// break the module-init cycle: the resolver lives in `index.ts` and// itself imports `loadBrainConfig` from this file. See the// `defaults.ts` header for the rationale.-import {- classifyVaultIgnoreRule,- DEFAULT_VAULT_IGNORE_PATHS,-} from "../vault-scope/defaults.ts";+import { classifyVaultIgnoreRule, DEFAULT_VAULT_IGNORE_PATHS } from "../vault-scope/defaults.ts";import { brainConfigPath } from "./paths.ts";/** Schema versions this build understands. Bump on incompatible changes. */@@ -105,23 +102,18 @@ export const BRAIN_GUARDRAIL_DEFAULTS: ResolvedBrainGuardrailConfig = Object.fre* `BRAIN_GUARDRAIL_DEFAULTS`. Returns a fully-populated struct so* consumers do not branch on optional fields.*/-export function resolveGuardrails(- cfg: BrainConfig,-): ResolvedBrainGuardrailConfig {+export function resolveGuardrails(cfg: BrainConfig): ResolvedBrainGuardrailConfig {const g = cfg.guardrails;if (g === undefined) return BRAIN_GUARDRAIL_DEFAULTS;return {promotion_min_signals:g.promotion_min_signals ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_signals,promotion_min_distinct_agents:- g.promotion_min_distinct_agents ??- BRAIN_GUARDRAIL_DEFAULTS.promotion_min_distinct_agents,+ g.promotion_min_distinct_agents ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_distinct_agents,promotion_min_age_days:- g.promotion_min_age_days ??- BRAIN_GUARDRAIL_DEFAULTS.promotion_min_age_days,+ g.promotion_min_age_days ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_age_days,instruction_file_max_lines:- g.instruction_file_max_lines ??- BRAIN_GUARDRAIL_DEFAULTS.instruction_file_max_lines,+ g.instruction_file_max_lines ?? BRAIN_GUARDRAIL_DEFAULTS.instruction_file_max_lines,};}@@ -142,32 +134,25 @@ export function resolveGuardrails(* vault-root instruction file `brain_context` surfaces when* present. Configurable per vault.*/-export const BRAIN_LINK_GRAPH_DEFAULTS: ResolvedBrainLinkGraphConfig =- Object.freeze({- moc_min_outbound_links: 5,- moc_min_link_ratio: 0.3,- vault_instruction_file: "VAULT.md",- }) as ResolvedBrainLinkGraphConfig;+export const BRAIN_LINK_GRAPH_DEFAULTS: ResolvedBrainLinkGraphConfig = Object.freeze({+ moc_min_outbound_links: 5,+ moc_min_link_ratio: 0.3,+ vault_instruction_file: "VAULT.md",+}) as ResolvedBrainLinkGraphConfig;/*** Merge a parsed `link_graph` block (or `undefined`) with* `BRAIN_LINK_GRAPH_DEFAULTS`.*/-export function resolveLinkGraph(- cfg: BrainConfig,-): ResolvedBrainLinkGraphConfig {+export function resolveLinkGraph(cfg: BrainConfig): ResolvedBrainLinkGraphConfig {const lg = cfg.link_graph;if (lg === undefined) return BRAIN_LINK_GRAPH_DEFAULTS;return {moc_min_outbound_links:- lg.moc_min_outbound_links ??- BRAIN_LINK_GRAPH_DEFAULTS.moc_min_outbound_links,- moc_min_link_ratio:- lg.moc_min_link_ratio ??- BRAIN_LINK_GRAPH_DEFAULTS.moc_min_link_ratio,+ lg.moc_min_outbound_links ?? BRAIN_LINK_GRAPH_DEFAULTS.moc_min_outbound_links,+ moc_min_link_ratio: lg.moc_min_link_ratio ?? BRAIN_LINK_GRAPH_DEFAULTS.moc_min_link_ratio,vault_instruction_file:- lg.vault_instruction_file ??- BRAIN_LINK_GRAPH_DEFAULTS.vault_instruction_file,+ lg.vault_instruction_file ?? BRAIN_LINK_GRAPH_DEFAULTS.vault_instruction_file,};}@@ -186,36 +171,28 @@ export function resolveLinkGraph(* - `daily_window_offset_hours: 0` - daily-brief windows align* with UTC midnight by default.*/-export const BRAIN_TEMPORAL_DEFAULTS: ResolvedBrainTemporalConfig =- Object.freeze({- stale_pref_days: 90,- stale_signal_days: 30,- stale_log_days: 180,- weekly_start_dow: 1,- daily_window_offset_hours: 0,- }) as ResolvedBrainTemporalConfig;+export const BRAIN_TEMPORAL_DEFAULTS: ResolvedBrainTemporalConfig = Object.freeze({+ stale_pref_days: 90,+ stale_signal_days: 30,+ stale_log_days: 180,+ weekly_start_dow: 1,+ daily_window_offset_hours: 0,+}) as ResolvedBrainTemporalConfig;/*** Merge a parsed `temporal` block (or `undefined`) with* `BRAIN_TEMPORAL_DEFAULTS`.*/-export function resolveTemporal(- cfg: BrainConfig,-): ResolvedBrainTemporalConfig {+export function resolveTemporal(cfg: BrainConfig): ResolvedBrainTemporalConfig {const tp = cfg.temporal;if (tp === undefined) return BRAIN_TEMPORAL_DEFAULTS;return {- stale_pref_days:- tp.stale_pref_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_pref_days,- stale_signal_days:- tp.stale_signal_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_signal_days,- stale_log_days:- tp.stale_log_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_log_days,- weekly_start_dow:- tp.weekly_start_dow ?? BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow,+ stale_pref_days: tp.stale_pref_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_pref_days,+ stale_signal_days: tp.stale_signal_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_signal_days,+ stale_log_days: tp.stale_log_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_log_days,+ weekly_start_dow: tp.weekly_start_dow ?? BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow,daily_window_offset_hours:- tp.daily_window_offset_hours ??- BRAIN_TEMPORAL_DEFAULTS.daily_window_offset_hours,+ tp.daily_window_offset_hours ?? BRAIN_TEMPORAL_DEFAULTS.daily_window_offset_hours,};}@@ -249,16 +226,12 @@ export function resolveHealth(cfg: BrainConfig): ResolvedBrainHealthConfig {const h = cfg.health;if (h === undefined) return BRAIN_HEALTH_DEFAULTS;return {- contradiction_jaccard:- h.contradiction_jaccard ?? BRAIN_HEALTH_DEFAULTS.contradiction_jaccard,+ contradiction_jaccard: h.contradiction_jaccard ?? BRAIN_HEALTH_DEFAULTS.contradiction_jaccard,concept_gap_min_frequency:- h.concept_gap_min_frequency ??- BRAIN_HEALTH_DEFAULTS.concept_gap_min_frequency,+ h.concept_gap_min_frequency ?? BRAIN_HEALTH_DEFAULTS.concept_gap_min_frequency,stale_claim_max_age_days:- h.stale_claim_max_age_days ??- BRAIN_HEALTH_DEFAULTS.stale_claim_max_age_days,- remediation_step_cap:- h.remediation_step_cap ?? BRAIN_HEALTH_DEFAULTS.remediation_step_cap,+ h.stale_claim_max_age_days ?? BRAIN_HEALTH_DEFAULTS.stale_claim_max_age_days,+ remediation_step_cap: h.remediation_step_cap ?? BRAIN_HEALTH_DEFAULTS.remediation_step_cap,};}@@ -267,9 +240,9 @@ export function resolveHealth(cfg: BrainConfig): ResolvedBrainHealthConfig {* the agent does not scan any user-authored notes. The operator* opts in by listing folders in `_brain.yaml`.*/-export const BRAIN_NOTES_DEFAULTS: ResolvedBrainNotesConfig = Object.freeze(- { read_paths: Object.freeze([]) as ReadonlyArray<string> },-) as ResolvedBrainNotesConfig;+export const BRAIN_NOTES_DEFAULTS: ResolvedBrainNotesConfig = Object.freeze({+ read_paths: Object.freeze([]) as ReadonlyArray<string>,+}) as ResolvedBrainNotesConfig;/*** Merge a parsed `notes` block (or `undefined`) with@@ -309,9 +282,7 @@ export function loadNotesConfigSafe(vault: string): ResolvedBrainNotesConfig {* consumer (MCP wrappers, CLI verbs) so a freshly-initialised vault* still produces a useful report.*/-export function loadTemporalConfigSafe(- vault: string,-): ResolvedBrainTemporalConfig {+export function loadTemporalConfigSafe(vault: string): ResolvedBrainTemporalConfig {try {return resolveTemporal(loadBrainConfig(vault));} catch {@@ -338,7 +309,7 @@ export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({}),confidence: Object.freeze({low_max_applied: 2,- medium_min: 0.40,+ medium_min: 0.4,high_min: 0.75,}),snapshots: Object.freeze({@@ -455,7 +426,11 @@ export class BrainConfigError extends Error {readonly source: string | null;constructor(message: string, field: string | null, source: string | null) {- super(field ? `${source ?? "<config>"}: ${field}: ${message}` : `${source ?? "<config>"}: ${message}`);+ super(+ field+ ? `${source ?? "<config>"}: ${field}: ${message}`+ : `${source ?? "<config>"}: ${message}`,+ );this.name = "BrainConfigError";this.field = field;this.source = source;@@ -514,11 +489,7 @@ export function loadBrainConfigDetailed(vault: string): LoadBrainConfigResult {try {parsed = parseBrainYaml(text);} catch (err) {- throw new BrainConfigError(- (err as Error).message,- null,- path,- );+ throw new BrainConfigError((err as Error).message, null, path);}const { config, warnings } = validateBrainConfigDetailed(parsed, path);@@ -534,10 +505,7 @@ export function loadBrainConfigDetailed(vault: string): LoadBrainConfigResult {* a synthetic label like `"<test fixture>"` so the failure points at* something useful.*/-export function validateBrainConfig(- parsed: unknown,- source: string | null = null,-): BrainConfig {+export function validateBrainConfig(parsed: unknown, source: string | null = null): BrainConfig {return validateBrainConfigDetailed(parsed, source).config;}@@ -630,7 +598,11 @@ export function validateBrainConfigDetailed();requirePositiveInteger("dream.candidate_threshold", dream.candidate_threshold, source);requirePositiveInteger("dream.unconfirmed_window_days", dream.unconfirmed_window_days, source);- requirePositiveInteger("dream.contradiction_window_days", dream.contradiction_window_days, source);+ requirePositiveInteger(+ "dream.contradiction_window_days",+ dream.contradiction_window_days,+ source,+ );const retire = mergeBlock("retire",@@ -646,24 +618,10 @@ export function validateBrainConfigDetailed(DEFAULT_BRAIN_CONFIG.confidence as unknown as Readonly<Record<string, number>>,source,);- requireNonNegativeInteger(- "confidence.low_max_applied",- confidence.low_max_applied,- source,- );- requireUnitInterval(- "confidence.medium_min",- confidence.medium_min,- source,- );- requireUnitInterval(- "confidence.high_min",- confidence.high_min,- source,- );- if (- (confidence.medium_min as number) >= (confidence.high_min as number)- ) {+ requireNonNegativeInteger("confidence.low_max_applied", confidence.low_max_applied, source);+ requireUnitInterval("confidence.medium_min", confidence.medium_min, source);+ requireUnitInterval("confidence.high_min", confidence.high_min, source);+ if ((confidence.medium_min as number) >= (confidence.high_min as number)) {throw new BrainConfigError(`medium_min must be strictly less than high_min; got ` +`medium_min=${confidence.medium_min}, high_min=${confidence.high_min}`,@@ -898,9 +856,7 @@ export function validateBrainConfigDetailed(});ok = false;} else {- const badIdx = (drObj["known_agents"] as unknown[]).findIndex(- (v) => typeof v !== "string",- );+ const badIdx = (drObj["known_agents"] as unknown[]).findIndex((v) => typeof v !== "string");if (badIdx >= 0) {warnings.push({path: source ?? "<config>",@@ -958,9 +914,7 @@ export function validateBrainConfigDetailed(rawMap["promotion_min_distinct_agents"],source,);- partial.promotion_min_distinct_agents = rawMap[- "promotion_min_distinct_agents"- ] as number;+ partial.promotion_min_distinct_agents = rawMap["promotion_min_distinct_agents"] as number;}if ("promotion_min_age_days" in rawMap) {requireNonNegativeInteger(@@ -1024,11 +978,7 @@ export function validateBrainConfigDetailed(if ("link_graph" in obj) {const rawLg = obj["link_graph"];if (typeof rawLg !== "object" || rawLg === null || Array.isArray(rawLg)) {- throw new BrainConfigError(- "link_graph must be a mapping",- "link_graph",- source,- );+ throw new BrainConfigError("link_graph must be a mapping", "link_graph", source);}const lgObj = rawLg as Record<string, unknown>;const partialLg: Record<string, unknown> = {};@@ -1070,11 +1020,7 @@ export function validateBrainConfigDetailed(// Reject absolute paths and `..` traversal at load time so// the config surface fails loudly instead of silently// omitting the envelope field at read time.- if (- trimmed.startsWith("/") ||- trimmed.startsWith("\\") ||- trimmed.includes("..")- ) {+ if (trimmed.startsWith("/") || trimmed.startsWith("\\") || trimmed.includes("..")) {throw new BrainConfigError("must be a vault-relative path without '..' segments","link_graph.vault_instruction_file",@@ -1096,10 +1042,7 @@ export function validateBrainConfigDetailed(});}}- linkGraph =- Object.keys(partialLg).length > 0- ? (partialLg as BrainLinkGraphConfig)- : {};+ linkGraph = Object.keys(partialLg).length > 0 ? (partialLg as BrainLinkGraphConfig) : {};}// Optional `temporal` block (v0.10.18). Shape:@@ -1115,11 +1058,7 @@ export function validateBrainConfigDetailed(if ("temporal" in obj) {const rawTp = obj["temporal"];if (typeof rawTp !== "object" || rawTp === null || Array.isArray(rawTp)) {- throw new BrainConfigError(- "temporal must be a mapping",- "temporal",- source,- );+ throw new BrainConfigError("temporal must be a mapping", "temporal", source);}const tpObj = rawTp as Record<string, unknown>;const partialTp: Record<string, unknown> = {};@@ -1130,23 +1069,14 @@ export function validateBrainConfigDetailed(if (key in tpObj) {const v = tpObj[key];if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {- throw new BrainConfigError(- "must be a positive integer",- `temporal.${key}`,- source,- );+ throw new BrainConfigError("must be a positive integer", `temporal.${key}`, source);}partialTp[key] = v;}}if ("weekly_start_dow" in tpObj) {const v = tpObj["weekly_start_dow"];- if (- typeof v !== "number" ||- !Number.isInteger(v) ||- v < 1 ||- v > 7- ) {+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 7) {throw new BrainConfigError("must be an ISO-8601 weekday number (1..7)","temporal.weekly_start_dow",@@ -1157,12 +1087,7 @@ export function validateBrainConfigDetailed(}if ("daily_window_offset_hours" in tpObj) {const v = tpObj["daily_window_offset_hours"];- if (- typeof v !== "number" ||- !Number.isInteger(v) ||- v < -23 ||- v > 23- ) {+ if (typeof v !== "number" || !Number.isInteger(v) || v < -23 || v > 23) {throw new BrainConfigError("must be an integer in [-23, 23]","temporal.daily_window_offset_hours",@@ -1187,10 +1112,7 @@ export function validateBrainConfigDetailed(});}}- temporal =- Object.keys(partialTp).length > 0- ? (partialTp as BrainTemporalConfig)- : {};+ temporal = Object.keys(partialTp).length > 0 ? (partialTp as BrainTemporalConfig) : {};}// Optional `health:` block (v0.14.0). Shape:@@ -1222,20 +1144,12 @@ export function validateBrainConfigDetailed(}const positiveIntKeys: ReadonlyArray<"concept_gap_min_frequency" | "stale_claim_max_age_days" | "remediation_step_cap"- > = [- "concept_gap_min_frequency",- "stale_claim_max_age_days",- "remediation_step_cap",- ];+ > = ["concept_gap_min_frequency", "stale_claim_max_age_days", "remediation_step_cap"];for (const key of positiveIntKeys) {if (key in hObj) {const v = hObj[key];if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {- throw new BrainConfigError(- "must be a positive integer",- `health.${key}`,- source,- );+ throw new BrainConfigError("must be a positive integer", `health.${key}`, source);}partialH[key] = v;}@@ -1254,10 +1168,7 @@ export function validateBrainConfigDetailed(});}}- health =- Object.keys(partialH).length > 0- ? (partialH as BrainHealthConfig)- : {};+ health = Object.keys(partialH).length > 0 ? (partialH as BrainHealthConfig) : {};}// Optional `notes:` block (v0.11.0). Shape:@@ -1271,16 +1182,8 @@ export function validateBrainConfigDetailed(let notes: BrainNotesConfig | undefined;if ("notes" in obj) {const rawNotes = obj["notes"];- if (- typeof rawNotes !== "object" ||- rawNotes === null ||- Array.isArray(rawNotes)- ) {- throw new BrainConfigError(- "notes must be a mapping",- "notes",- source,- );+ if (typeof rawNotes !== "object" || rawNotes === null || Array.isArray(rawNotes)) {+ throw new BrainConfigError("notes must be a mapping", "notes", source);}const notesObj = rawNotes as Record<string, unknown>;const partialNotes: Record<string, unknown> = {};@@ -1338,10 +1241,7 @@ export function validateBrainConfigDetailed(});}}- notes =- Object.keys(partialNotes).length > 0- ? (partialNotes as BrainNotesConfig)- : {};+ notes = Object.keys(partialNotes).length > 0 ? (partialNotes as BrainNotesConfig) : {};}// Forward-compat: unknown top-level keys → warning, not error.@@ -1432,25 +1332,13 @@ function mergeBlock(return merged;}-function requirePositiveInteger(- field: string,- value: unknown,- source: string | null,-): void {+function requirePositiveInteger(field: string, value: unknown, source: string | null): void {if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {- throw new BrainConfigError(- `must be a positive integer; got ${describe(value)}`,- field,- source,- );+ throw new BrainConfigError(`must be a positive integer; got ${describe(value)}`, field, source);}}-function requireNonNegativeInteger(- field: string,- value: unknown,- source: string | null,-): void {+function requireNonNegativeInteger(field: string, value: unknown, source: string | null): void {if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {throw new BrainConfigError(`must be a non-negative integer; got ${describe(value)}`,@@ -1460,22 +1348,9 @@ function requireNonNegativeInteger(}}-function requireUnitInterval(- field: string,- value: unknown,- source: string | null,-): void {- if (- typeof value !== "number" ||- !Number.isFinite(value) ||- value < 0 ||- value > 1- ) {- throw new BrainConfigError(- `must be a number in [0, 1]; got ${describe(value)}`,- field,- source,- );+function requireUnitInterval(field: string, value: unknown, source: string | null): void {+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {+ throw new BrainConfigError(`must be a number in [0, 1]; got ${describe(value)}`, field, source);}}@@ -1507,7 +1382,10 @@ function describe(value: unknown): string {// anchors, and aliases — none of which the schema needs.type ParsedScalar = number | string | boolean | null;-type ParsedBlockValue = ParsedScalar | Record<string, ParsedScalar | ParsedScalar[]> | ParsedScalar[];+type ParsedBlockValue =+ | ParsedScalar+ | Record<string, ParsedScalar | ParsedScalar[]>+ | ParsedScalar[];type ParsedBlock = Record<string, ParsedBlockValue>;interface Line {@@ -1524,9 +1402,7 @@ export function parseBrainYaml(text: string): ParsedBlock {while (i < lines.length) {const line = lines[i]!;if (line.indent !== 0) {- throw new Error(- `line ${line.lineNumber}: unexpected indentation at top level`,- );+ throw new Error(`line ${line.lineNumber}: unexpected indentation at top level`);}const kv = splitKeyValue(line);if (kv.value === "") {@@ -1670,9 +1546,7 @@ function splitKeyValue(line: Line): KeyValue {}const key = line.content.slice(0, idx).trim();if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key)) {- throw new Error(- `line ${line.lineNumber}: invalid key name: ${JSON.stringify(key)}`,- );+ throw new Error(`line ${line.lineNumber}: invalid key name: ${JSON.stringify(key)}`);}const value = line.content.slice(idx + 1).trim();return { key, value };@@ -1691,8 +1565,7 @@ function parseScalar(text: string, lineNumber: number): ParsedScalar | ParsedSca}if (text.length >= 2 &&- ((text.startsWith('"') && text.endsWith('"')) ||- (text.startsWith("'") && text.endsWith("'")))+ ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'")))) {return text.slice(1, -1);}diff --git a/src/core/brain/preference-txn.ts b/src/core/brain/preference-txn.tsindex 74d2cdb7..7ec5cfd8 100644--- a/src/core/brain/preference-txn.ts+++ b/src/core/brain/preference-txn.ts@@ -31,10 +31,7 @@ import { existsSync } from "node:fs";import { computeContentHash } from "./content-hash.ts";import { appendEditHistory, type EditHistoryEntry } from "./health/edit-history.ts";-import {- preferencePath,- validateSlug,-} from "./paths.ts";+import { preferencePath, validateSlug } from "./paths.ts";import {parsePreference,writePreference,@@ -44,10 +41,7 @@ import {type WritePreferenceResult,} from "./preference.ts";import { acquireLockSync } from "./sync-lockfile.ts";-import {- BRAIN_PREFERENCE_STATUS,- type BrainPreference,-} from "./types.ts";+import { BRAIN_PREFERENCE_STATUS, type BrainPreference } from "./types.ts";/*** Machine-friendly discriminants for the four collision modes covered@@ -62,8 +56,7 @@ export const BRAIN_COLLISION_KIND = Object.freeze({duplicateWrite: "DuplicateWrite",} as const);-export type BrainCollisionKind =- (typeof BRAIN_COLLISION_KIND)[keyof typeof BRAIN_COLLISION_KIND];+export type BrainCollisionKind = (typeof BRAIN_COLLISION_KIND)[keyof typeof BRAIN_COLLISION_KIND];/*** Typed error surfaced by every txn collision mode. `kind` is the@@ -110,10 +103,13 @@ function editHistoryEntries(opts: EditHistoryOptions,): EditHistoryEntry[] {const ts = (opts.now?.() ?? new Date()).toISOString();- const reader: Record<(typeof HISTORY_TRACKED_FIELDS)[number], {- before: string | null;- after: string | null;- }> = {+ const reader: Record<+ (typeof HISTORY_TRACKED_FIELDS)[number],+ {+ before: string | null;+ after: string | null;+ }+ > = {principle: {before: existing?.principle ?? null,after: proposed.principle ?? null,@@ -155,9 +151,7 @@ export interface WritePreferenceContext {* {@link BrainCollisionError} to abort the write; returning normally* signals "ok, keep going".*/-export type WritePreferenceExpectation = (- ctx: WritePreferenceContext,-) => void;+export type WritePreferenceExpectation = (ctx: WritePreferenceContext) => void;/*** Write a preference under an exclusive sync lock, running the@@ -221,23 +215,20 @@ export function writePreferenceTxn(//// Callers that bypass the txn keep pre-v0.12.0 semantics.const autoHash =- input.content_hash === undefined- && input.status === BRAIN_PREFERENCE_STATUS.confirmed+ input.content_hash === undefined && input.status === BRAIN_PREFERENCE_STATUS.confirmed? { content_hash: computeContentHash(input.principle, input.scope) }: {};const candidate: WritePreferenceInput = {...input,...autoHash,- revision: input.revision ?? (existing?.revision ?? 0),+ revision: input.revision ?? existing?.revision ?? 0,};const willChange =- input.revision !== undefined- || existing === null- || wouldRewritePreference(vault, candidate);+ input.revision !== undefined || existing === null || wouldRewritePreference(vault, candidate);const inputWithDefaults: WritePreferenceInput = willChange? {...candidate,- revision: input.revision ?? ((existing?.revision ?? 0) + 1),+ revision: input.revision ?? (existing?.revision ?? 0) + 1,}: candidate;const result = writePreference(vault, inputWithDefaults, options);@@ -273,9 +264,7 @@ export function writePreferenceTxn(* Treats a missing on-disk `_revision` field as 0 - the absent-as-zero* convention from {@link BrainPreference.revision}'s reader.*/-export function expectRevision(- expected: number,-): WritePreferenceExpectation {+export function expectRevision(expected: number): WritePreferenceExpectation {return (ctx) => {const current = ctx.existing?.revision ?? 0;if (current !== expected) {@@ -338,10 +327,7 @@ export function noDuplicateWriteWithin(if (!existing) return;const existingHash = existing.content_hash;if (!existingHash) return;- const proposedHash = computeContentHash(- ctx.input.principle,- ctx.input.scope,- );+ const proposedHash = computeContentHash(ctx.input.principle, ctx.input.scope);if (existingHash !== proposedHash) return;const lastEv = existing.last_evidence_at;if (!lastEv) return;diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.tsindex a109863a..cfbf449d 100644--- a/src/core/brain/preference.ts+++ b/src/core/brain/preference.ts@@ -37,17 +37,8 @@ import { existsSync, readFileSync, unlinkSync } from "node:fs";import { basename, dirname, join } from "node:path";import type { FrontmatterMap } from "../types.ts";-import {- formatFrontmatter,- parseFrontmatter,- writeFrontmatterAtomic,-} from "../vault.ts";-import {- brainDirs,- preferencePath,- retiredPath,- validateSlug,-} from "./paths.ts";+import { formatFrontmatter, parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";+import { brainDirs, preferencePath, retiredPath, validateSlug } from "./paths.ts";import {BRAIN_CONFIDENCE,BRAIN_PREFERENCE_STATUS,@@ -74,12 +65,7 @@ export class BrainStatusFolderMismatchError extends Error {readonly status: string;readonly folder: "preferences" | "retired";- constructor(- message: string,- path: string,- status: string,- folder: "preferences" | "retired",- ) {+ constructor(message: string, path: string, status: string, folder: "preferences" | "retired") {super(`${message} (path=${path}, status=${status}, folder=${folder})`);this.name = "BrainStatusFolderMismatchError";this.path = path;@@ -258,7 +244,6 @@ export function writePreference(}}-writeFrontmatterAtomic(path, metadata, body, {overwrite: options.overwrite ?? false,existsErrorKind: "preference",@@ -281,10 +266,7 @@ export function writePreference(* body. Caller-side cost is negligible compared with the writePref* + log overhead avoided when the body is up to date.*/-export function wouldRewritePreference(- vault: string,- input: WritePreferenceInput,-): boolean {+export function wouldRewritePreference(vault: string, input: WritePreferenceInput): boolean {const slug = validateSlug(input.slug);const path = preferencePath(vault, slug);if (!existsSync(path)) return true;@@ -302,10 +284,7 @@ export function wouldRewritePreference(}}-function preferenceFrontmatter(- input: WritePreferenceInput,- id: string,-): FrontmatterMap {+function preferenceFrontmatter(input: WritePreferenceInput, id: string): FrontmatterMap {const tags = composePreferenceTags(input);const confidence = input.confidence ?? BRAIN_CONFIDENCE.low;const pinned = input.pinned ?? false;@@ -442,10 +421,7 @@ function renderPreferenceBody(input: WritePreferenceInput): string {return sections.join("\n\n");}-function renderEvidenceSection(- heading: string,- rows: ReadonlyArray<BrainEvidenceSummary>,-): string {+function renderEvidenceSection(heading: string, rows: ReadonlyArray<BrainEvidenceSummary>): string {const lines: string[] = [`## ${heading}`, ""];for (const ev of rows) {const parts: string[] = [`- ${ev.artifact}`, `— ${ev.timestamp}`];@@ -730,9 +706,7 @@ export function moveToRetired(// file: a misrouted call fails fast with no destructive side effect.const dirs = brainDirs(vault);if (dirname(prefPath) !== dirs.preferences) {- throw new Error(- `moveToRetired: source path was not under preferences/: ${prefPath}`,- );+ throw new Error(`moveToRetired: source path was not under preferences/: ${prefPath}`);}const [meta, body] = parseFrontmatter(prefPath);@@ -770,9 +744,7 @@ export function moveToRetired(if (k === "tags") {// Replace the `brain/preference` tag with `brain/retired`.const arr = Array.isArray(v) ? [...v] : [];- newMeta["tags"] = arr.map((t) =>- t === "brain/preference" ? "brain/retired" : t,- );+ newMeta["tags"] = arr.map((t) => (t === "brain/preference" ? "brain/retired" : t));continue;}// Group C derived fields go to disk in the `_`-prefixed shape so@@ -825,12 +797,8 @@ export function moveToRetired(unconfirmed_until: requireString(meta, "unconfirmed_until", prefPath),status: BRAIN_PREFERENCE_STATUS.confirmed, // body render is status-agnosticevidenced_by: optionalStringArray(meta, "evidenced_by"),- ...(opts.evidenceApplied !== undefined- ? { recentApplied: opts.evidenceApplied }- : {}),- ...(opts.evidenceViolated !== undefined- ? { recentViolated: opts.evidenceViolated }- : {}),+ ...(opts.evidenceApplied !== undefined ? { recentApplied: opts.evidenceApplied } : {}),+ ...(opts.evidenceViolated !== undefined ? { recentViolated: opts.evidenceViolated } : {}),};// moveToRetired is also called outside dream (CLI reject) — when the// caller did not pre-fetch evidence, we collect it here so the@@ -863,9 +831,7 @@ export function moveToRetired(// Confirm the new file actually landed before unlinking the source.if (!existsSync(newPath)) {- throw new Error(- `moveToRetired: write of ${newPath} reported success but file is absent`,- );+ throw new Error(`moveToRetired: write of ${newPath} reported success but file is absent`);}unlinkSync(prefPath);@@ -940,11 +906,7 @@ function enforceStatusFolderInvariant(}}-function requireField(- meta: Record<string, unknown>,- field: string,- path: string,-): void {+function requireField(meta: Record<string, unknown>, field: string, path: string): void {if (!(field in meta) || meta[field] === undefined || meta[field] === null) {throw new Error(`preference missing field: ${field} (${path})`);}@@ -953,11 +915,7 @@ function requireField(}}-function requireString(- meta: Record<string, unknown>,- field: string,- path: string,-): string {+function requireString(meta: Record<string, unknown>, field: string, path: string): string {requireField(meta, field, path);const v = meta[field];if (typeof v !== "string") {@@ -978,18 +936,13 @@ function requireStringArray(}for (const item of v) {if (typeof item !== "string") {- throw new Error(- `preference field '${field}' must be an array of strings (${path})`,- );+ throw new Error(`preference field '${field}' must be an array of strings (${path})`);}}return [...(v as ReadonlyArray<string>)];}-function optionalStringArray(- meta: Record<string, unknown>,- field: string,-): ReadonlyArray<string> {+function optionalStringArray(meta: Record<string, unknown>, field: string): ReadonlyArray<string> {const v = meta[field];if (v === undefined || v === null) return [];if (!Array.isArray(v)) {@@ -997,9 +950,7 @@ function optionalStringArray(}for (const item of v) {if (typeof item !== "string") {- throw new Error(- `preference field '${field}' must be an array of strings`,- );+ throw new Error(`preference field '${field}' must be an array of strings`);}}return [...(v as ReadonlyArray<string>)];@@ -1011,10 +962,7 @@ function optionalStringArray(* the on-disk roundtrip survives the simple YAML emitter (which has no* native null token).*/-function optionalNullableString(- meta: Record<string, unknown>,- field: string,-): string | null {+function optionalNullableString(meta: Record<string, unknown>, field: string): string | null {const v = meta[field];if (v === undefined || v === null) return null;if (typeof v !== "string") {@@ -1025,11 +973,7 @@ function optionalNullableString(return v;}-function optionalNumber(- meta: Record<string, unknown>,- field: string,- fallback: number,-): number {+function optionalNumber(meta: Record<string, unknown>, field: string, fallback: number): number {const v = meta[field];if (v === undefined || v === null || v === "") return fallback;// The simple parser surfaces all values as strings; numerics included.@@ -1046,10 +990,7 @@ function optionalNumber(throw new Error(`preference field '${field}' must be a number`);}-function optionalScalarString(- meta: Record<string, unknown>,- field: string,-): string | undefined {+function optionalScalarString(meta: Record<string, unknown>, field: string): string | undefined {const v = meta[field];if (v === undefined || v === null) return undefined;if (typeof v !== "string") return undefined;@@ -1057,10 +998,7 @@ function optionalScalarString(return trimmed === "" ? undefined : v;}-function parseConfidence(- meta: Record<string, unknown>,- path: string,-): BrainConfidence {+function parseConfidence(meta: Record<string, unknown>, path: string): BrainConfidence {const v = meta["confidence"];if (v === undefined || v === null || v === "") return BRAIN_CONFIDENCE.low;if (typeof v !== "string") {@@ -1085,10 +1023,7 @@ function parseConfidence(* hard parse error — drifting numeric confidence into `> 1` or* `NaN` would corrupt every downstream comparison silently.*/-function parseConfidenceValue(- meta: Record<string, unknown>,- path: string,-): number | null {+function parseConfidenceValue(meta: Record<string, unknown>, path: string): number | null {const v = meta["confidence_value"];if (v === undefined || v === null || v === "" || v === "null") return null;let n: number | null = null;diff --git a/src/core/brain/protect.ts b/src/core/brain/protect.tsindex c7d10db2..4ae0d7dd 100644--- a/src/core/brain/protect.ts+++ b/src/core/brain/protect.ts@@ -27,11 +27,7 @@* exactly the entries the matching `applyProtect` added.*/-import {- existsSync,- mkdirSync,- readFileSync,-} from "node:fs";+import { existsSync, mkdirSync, readFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";@@ -46,17 +42,17 @@ export const PROTECT_TARGETS = ["claudecode", "codex"] as const;export type ProtectTarget = (typeof PROTECT_TARGETS)[number];export function isProtectTarget(value: string | undefined): value is ProtectTarget {- return (- typeof value === "string"- && (PROTECT_TARGETS as readonly string[]).includes(value)- );+ return typeof value === "string" && (PROTECT_TARGETS as readonly string[]).includes(value);}export class BrainProtectError extends Error {readonly code: string;readonly detail?: unknown;- constructor(message: string, info: { code: string; detail?: unknown } = { code: "BRAIN_PROTECT" }) {+ constructor(+ message: string,+ info: { code: string; detail?: unknown } = { code: "BRAIN_PROTECT" },+ ) {super(message);this.name = "BrainProtectError";this.code = info.code;@@ -161,12 +157,8 @@ export function renderClaudeCode(rules: ReadonlyArray<ProtectRule>,vault: string = inferVault(rules),): ClaudeCodeRender {- const deny = rules- .filter((r) => r.kind === "deny")- .map((r) => `${r.action}(${r.path})`);- const allow = rules- .filter((r) => r.kind === "allow")- .map((r) => `${r.action}(${r.path})`);+ const deny = rules.filter((r) => r.kind === "deny").map((r) => `${r.action}(${r.path})`);+ const allow = rules.filter((r) => r.kind === "allow").map((r) => `${r.action}(${r.path})`);return Object.freeze({snippet: { permissions: { deny, allow } },manifest: {@@ -182,10 +174,9 @@ export function renderClaudeCode(function inferVault(rules: ReadonlyArray<ProtectRule>): string {const first = rules[0];if (!first) {- throw new BrainProtectError(- "renderClaudeCode requires at least one rule to infer the vault",- { code: "EMPTY_RULES" },- );+ throw new BrainProtectError("renderClaudeCode requires at least one rule to infer the vault", {+ code: "EMPTY_RULES",+ });}return first.path.split(`/${BRAIN_ROOT_REL}/`)[0]!;}@@ -215,9 +206,7 @@ export function renderCodex(rules: ReadonlyArray<ProtectRule>): CodexRender {return renderCodexEntries(codexEntriesFromRules(rules));}-function renderCodexEntries(- entries: ReadonlyArray<CodexFilesystemEntry>,-): CodexRender {+function renderCodexEntries(entries: ReadonlyArray<CodexFilesystemEntry>): CodexRender {const lines: string[] = [FENCE_OPEN,`# schema_version = ${PROTECT_SCHEMA_VERSION}`,@@ -302,22 +291,18 @@ function parseManifestFile(raw: string, path: string): ManifestFile {});}if (- parsed === null- || typeof parsed !== "object"- || !Array.isArray((parsed as { entries?: unknown }).entries)+ parsed === null ||+ typeof parsed !== "object" ||+ !Array.isArray((parsed as { entries?: unknown }).entries)) {- throw new BrainProtectError(- `manifest at ${path} missing 'entries' array`,- { code: "MANIFEST_MALFORMED" },- );+ throw new BrainProtectError(`manifest at ${path} missing 'entries' array`, {+ code: "MANIFEST_MALFORMED",+ });}return parsed as ManifestFile;}-export function readManifest(- vault: string,- target: ProtectTarget,-): ManifestRecord | null {+export function readManifest(vault: string, target: ProtectTarget): ManifestRecord | null {const path = manifestPath(vault);if (!existsSync(path)) return null;const file = parseManifestFile(readFileSync(path, "utf8"), path);@@ -325,8 +310,8 @@ export function readManifest(if (entry === undefined) return null;if (entry.schema_version > PROTECT_SCHEMA_VERSION) {throw new BrainProtectError(- `manifest schema_version ${entry.schema_version} is newer than `- + `this binary (${PROTECT_SCHEMA_VERSION}); update o2b first`,+ `manifest schema_version ${entry.schema_version} is newer than ` ++ `this binary (${PROTECT_SCHEMA_VERSION}); update o2b first`,{ code: "MANIFEST_NEWER_SCHEMA" },);}@@ -374,10 +359,7 @@ function readFileOrEmpty(path: string): string {}}-export function removeManifestEntry(- vault: string,- target: ProtectTarget,-): void {+export function removeManifestEntry(vault: string, target: ProtectTarget): void {const path = manifestPath(vault);if (!existsSync(path)) return;const file = parseManifestFile(readFileSync(path, "utf8"), path);@@ -459,9 +441,7 @@ function applyClaudeCode(vault: string): ApplyResult {const dest = join(settingsDir, "settings.json");mkdirSync(settingsDir, { recursive: true });- const prev = readManifest(vault, "claudecode") as- | ManifestRecordClaudeCode- | null;+ const prev = readManifest(vault, "claudecode") as ManifestRecordClaudeCode | null;const { raw: before, parsed: settings } = readSettingsJson(dest);settings.permissions ??= {};@@ -472,12 +452,8 @@ function applyClaudeCode(vault: string): ApplyResult {// history (idempotency under repeated `--apply`).const priorDeny = prev?.owned_deny ?? [];const priorAllow = prev?.owned_allow ?? [];- settings.permissions.deny = settings.permissions.deny.filter(- (e) => !priorDeny.includes(e),- );- settings.permissions.allow = settings.permissions.allow.filter(- (e) => !priorAllow.includes(e),- );+ settings.permissions.deny = settings.permissions.deny.filter((e) => !priorDeny.includes(e));+ settings.permissions.allow = settings.permissions.allow.filter((e) => !priorAllow.includes(e));for (const e of rendered.snippet.permissions.deny) {if (!settings.permissions.deny.includes(e)) {@@ -509,9 +485,7 @@ function applyClaudeCode(vault: string): ApplyResult {function unprotectClaudeCode(vault: string): void {const dest = join(vault, ".claude", "settings.json");- const prev = readManifest(vault, "claudecode") as- | ManifestRecordClaudeCode- | null;+ const prev = readManifest(vault, "claudecode") as ManifestRecordClaudeCode | null;if (prev === null || !existsSync(dest)) {removeManifestEntry(vault, "claudecode");return;@@ -561,8 +535,8 @@ function parseCodexFence(raw: string): ReadonlyArray<CodexFilesystemEntry> {const version = Number(schema[1]);if (Number.isFinite(version) && version > PROTECT_SCHEMA_VERSION) {throw new BrainProtectError(- `codex managed block schema_version ${version} is newer than `- + `this binary (${PROTECT_SCHEMA_VERSION}); update o2b first`,+ `codex managed block schema_version ${version} is newer than ` ++ `this binary (${PROTECT_SCHEMA_VERSION}); update o2b first`,{ code: "CODEX_FENCE_NEWER_SCHEMA" },);}@@ -585,10 +559,9 @@ function parseTomlStringLiteral(raw: string): string {try {return JSON.parse(`"${raw}"`) as string;} catch {- throw new BrainProtectError(- "codex managed block contains an invalid quoted filesystem path",- { code: "CODEX_FENCE_MALFORMED" },- );+ throw new BrainProtectError("codex managed block contains an invalid quoted filesystem path", {+ code: "CODEX_FENCE_MALFORMED",+ });}}@@ -661,12 +634,9 @@ function unprotectCodex(vault: string, homeOverride?: string): void {// a hand-edited fence whose manifest was deleted out-of-band.const prev = readManifest(vault, "codex") as ManifestRecordCodex | null;const ownedPaths = new Set<string>(- prev?.owned_paths- ?? codexEntriesFromRules(buildProtectRules(vault)).map((e) => e.path),- );- const remaining = parseCodexFence(raw).filter(- (e) => !ownedPaths.has(e.path),+ prev?.owned_paths ?? codexEntriesFromRules(buildProtectRules(vault)).map((e) => e.path),);+ const remaining = parseCodexFence(raw).filter((e) => !ownedPaths.has(e.path));const after = replaceCodexFence(raw,remaining.length > 0 ? renderCodexEntries(remaining).body : null,diff --git a/src/core/brain/query.ts b/src/core/brain/query.tsindex e883ae6b..0b561396 100644--- a/src/core/brain/query.ts+++ b/src/core/brain/query.ts@@ -35,11 +35,7 @@ import { parsePreference, parseRetired } from "./preference.ts";import { parseSignal } from "./signal.ts";import { normaliseWikilinkTarget } from "./wikilink.ts";import { BRAIN_LOG_EVENT_KIND } from "./types.ts";-import type {- BrainPreference,- BrainRetired,- BrainSignal,-} from "./types.ts";+import type { BrainPreference, BrainRetired, BrainSignal } from "./types.ts";// ----- Errors ---------------------------------------------------------------@@ -115,10 +111,7 @@ export interface QueryByTopicResult {* - A `ret-...` id is searched in `retired/` only.* - Any other prefix raises {@link BrainNotFoundError} immediately.*/-export function queryByPreference(- vault: string,- pref_id: string,-): QueryByPreferenceResult {+export function queryByPreference(vault: string, pref_id: string): QueryByPreferenceResult {const id = pref_id.trim();if (!id) {throw new BrainNotFoundError(pref_id);@@ -178,7 +171,7 @@ export function queryByPreference(e.eventType === BRAIN_LOG_EVENT_KIND.applyEvidence &&matchPreferencePayload(e.body["preference"], matchIds),)- .sort(byTimestampAsc);+ .toSorted(byTimestampAsc);return Object.freeze({preference,@@ -192,10 +185,7 @@ export function queryByPreference(* retired), and every log entry mentioning the preference id (active* or retired form). Unknown topic → empty result with `preference: null`.*/-export function queryByTopic(- vault: string,- topic: string,-): QueryByTopicResult {+export function queryByTopic(vault: string, topic: string): QueryByTopicResult {const want = topic.trim();if (!want) {return Object.freeze({@@ -236,7 +226,7 @@ export function queryByTopic(all_log_events = Object.freeze(all.filter((e) => matchPreferencePayload(e.body["preference"], matchIds))- .sort(byTimestampAsc),+ .toSorted(byTimestampAsc),);}@@ -254,17 +244,12 @@ export function queryByTopic(* entries are silently skipped (their warnings are the doctor's* concern, not this surface's).*/-export function queryByLogSince(- vault: string,- since: Date,-): ReadonlyArray<BrainLogEntry> {+export function queryByLogSince(vault: string, since: Date): ReadonlyArray<BrainLogEntry> {if (!(since instanceof Date) || Number.isNaN(since.getTime())) {throw new TypeError("queryByLogSince: `since` must be a valid Date");}const sinceIso = since.toISOString();- const entries = readAllLogEntries(vault).filter(- (e) => e.timestamp >= sinceIso,- );+ const entries = readAllLogEntries(vault).filter((e) => e.timestamp >= sinceIso);entries.sort(byTimestampAsc);return Object.freeze(entries);}@@ -284,7 +269,7 @@ export function readAllLogEntries(vault: string): BrainLogEntry[] {.filter((d) => d.isFile() && d.name.endsWith(".md")).map((d) => d.name.slice(0, -".md".length)).filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n))- .sort();+ .toSorted();const out: BrainLogEntry[] = [];for (const date of names) {const { entries } = parseLogDay(vault, date);@@ -293,11 +278,7 @@ export function readAllLogEntries(vault: string): BrainLogEntry[] {return out;}-function collectSignals(- dir: string,- topic: string,- out: BrainSignal[],-): void {+function collectSignals(dir: string, topic: string, out: BrainSignal[]): void {if (!existsSync(dir)) return;for (const entry of readdirSync(dir, { withFileTypes: true })) {if (!entry.isFile()) continue;@@ -329,7 +310,7 @@ function findPreferenceForTopic(// different orders on different machines.const entries = readdirSync(dir, { withFileTypes: true }).slice()- .sort((a, b) => a.name.localeCompare(b.name));+ .toSorted((a, b) => a.name.localeCompare(b.name));for (const entry of entries) {if (!entry.isFile()) continue;if (!entry.name.startsWith(prefix) || !entry.name.endsWith(".md")) {@@ -337,8 +318,7 @@ function findPreferenceForTopic(}const path = join(dir, entry.name);try {- const parsed =- kind === "preference" ? parsePreference(path) : parseRetired(path);+ const parsed = kind === "preference" ? parsePreference(path) : parseRetired(path);if (parsed.topic === topic) return parsed;} catch {// Doctor's job, not query's.diff --git a/src/core/brain/review-candidates.ts b/src/core/brain/review-candidates.tsindex b991f410..535a15f4 100644--- a/src/core/brain/review-candidates.ts+++ b/src/core/brain/review-candidates.ts@@ -75,9 +75,7 @@ export function buildReviewCandidates(would_create: Object.freeze([...summary.new_unconfirmed]),would_promote: Object.freeze([...summary.confirmed]),would_retire: Object.freeze(- summary.retired.map((r) =>- Object.freeze({ id: r.id, reason: r.reason }),- ),+ summary.retired.map((r) => Object.freeze({ id: r.id, reason: r.reason })),),would_supersede: Object.freeze(summary.retireddiff --git a/src/core/brain/sessions/claude.ts b/src/core/brain/sessions/claude.tsindex 76beace1..70a47b83 100644--- a/src/core/brain/sessions/claude.ts+++ b/src/core/brain/sessions/claude.ts@@ -19,11 +19,7 @@import { readFileSync } from "node:fs";-import type {- SessionAdapter,- SessionToolCall,- SessionTurn,-} from "./types.ts";+import type { SessionAdapter, SessionToolCall, SessionTurn } from "./types.ts";interface ClaudeBlock {readonly type?: string;@@ -43,9 +39,7 @@ function turnFromLine(obj: unknown, fallbackIndex: number): SessionTurn | null {if (role !== "user" && role !== "assistant") return null;const turnId =- typeof o["uuid"] === "string" && o["uuid"].length > 0- ? o["uuid"]- : `synth-${fallbackIndex}`;+ typeof o["uuid"] === "string" && o["uuid"].length > 0 ? o["uuid"] : `synth-${fallbackIndex}`;const timestamp =typeof o["timestamp"] === "string" && o["timestamp"].length > 0? o["timestamp"]@@ -101,8 +95,7 @@ export const claudeAdapter: SessionAdapter = {if (obj === null || typeof obj !== "object") return false;const o = obj as Record<string, unknown>;if (o["type"] === "queue-operation") return true;- const hasClaudeShape =- "parentUuid" in o && "sessionId" in o && "entrypoint" in o;+ const hasClaudeShape = "parentUuid" in o && "sessionId" in o && "entrypoint" in o;return hasClaudeShape;},async *iterate(path: string): AsyncIterable<SessionTurn> {diff --git a/src/core/brain/sessions/codex.ts b/src/core/brain/sessions/codex.tsindex 8986d29d..fe3d9869 100644--- a/src/core/brain/sessions/codex.ts+++ b/src/core/brain/sessions/codex.ts@@ -23,21 +23,14 @@import { readFileSync } from "node:fs";-import type {- SessionAdapter,- SessionToolCall,- SessionTurn,-} from "./types.ts";+import type { SessionAdapter, SessionToolCall, SessionTurn } from "./types.ts";interface CodexBlock {readonly type?: string;readonly text?: string;}-function buildMessageTurn(- obj: Record<string, unknown>,- fallbackIndex: number,-): SessionTurn | null {+function buildMessageTurn(obj: Record<string, unknown>, fallbackIndex: number): SessionTurn | null {const payload = obj["payload"] as Record<string, unknown> | undefined;if (!payload) return null;const role = payload["role"];@@ -54,10 +47,7 @@ function buildMessageTurn(for (const raw of content) {if (raw === null || typeof raw !== "object") continue;const b = raw as CodexBlock;- if (- (b.type === "input_text" || b.type === "output_text") &&- typeof b.text === "string"- ) {+ if ((b.type === "input_text" || b.type === "output_text") && typeof b.text === "string") {texts.push(b.text);}}@@ -104,8 +94,7 @@ function buildFunctionCallTurn(input,...(callId !== undefined ? { id: callId } : {}),};- const turnId =- callId !== undefined ? `codex-fc-${callId}` : `codex-fc-${fallbackIndex}`;+ const turnId = callId !== undefined ? `codex-fc-${callId}` : `codex-fc-${fallbackIndex}`;const timestamp =typeof obj["timestamp"] === "string" ? (obj["timestamp"] as string) : new Date(0).toISOString();return {diff --git a/src/core/brain/sessions/hermes.ts b/src/core/brain/sessions/hermes.tsindex e59f1aae..5d6e57d2 100644--- a/src/core/brain/sessions/hermes.ts+++ b/src/core/brain/sessions/hermes.ts@@ -23,11 +23,7 @@import { readFileSync } from "node:fs";-import type {- SessionAdapter,- SessionToolCall,- SessionTurn,-} from "./types.ts";+import type { SessionAdapter, SessionToolCall, SessionTurn } from "./types.ts";interface HermesToolCall {readonly id?: string;@@ -57,10 +53,7 @@ function decodeArguments(raw: unknown): Record<string, unknown> {return {};}-function buildTurn(- obj: Record<string, unknown>,- fallbackIndex: number,-): SessionTurn | null {+function buildTurn(obj: Record<string, unknown>, fallbackIndex: number): SessionTurn | null {const role = obj["role"];if (role !== "user" && role !== "assistant") return null;const turnId = `hermes-${fallbackIndex}`;diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.tsindex 566f0f90..319909fb 100644--- a/src/core/brain/sessions/import.ts+++ b/src/core/brain/sessions/import.ts@@ -25,20 +25,10 @@* second run on the same file finds every hash already present.*/-import {- existsSync,- lstatSync,- readdirSync,- readFileSync,- statSync,-} from "node:fs";+import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs";import { join, resolve } from "node:path";-import {- buildDedupIndex,- computeDedupHash,- type DedupIndexEntry,-} from "../dedup-hash.ts";+import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "../dedup-hash.ts";import { discoverMarkersDetailed } from "../inline.ts";import { writeSignal } from "../signal.ts";import { isoDate, isoSecond } from "../time.ts";@@ -266,11 +256,7 @@ export async function importSession(* the caller, not here), then a per-adapter default, finally* `opts.agent`.*/-function agentLabelForTurn(- turn: SessionTurn,- adapter: SessionAdapterId,- fallback: string,-): string {+function agentLabelForTurn(turn: SessionTurn, adapter: SessionAdapterId, fallback: string): string {void turn; // reserved for future per-turn role-aware fallbackswitch (adapter) {case "claude":diff --git a/src/core/brain/sessions/types.ts b/src/core/brain/sessions/types.tsindex f3323d09..5f9dc79d 100644--- a/src/core/brain/sessions/types.ts+++ b/src/core/brain/sessions/types.ts@@ -63,10 +63,7 @@ export interface SessionAdapter {export class SessionImportError extends Error {readonly code: "DETECT_FAIL" | "IO" | "PARSE" | "UNKNOWN_FORMAT";- constructor(- code: "DETECT_FAIL" | "IO" | "PARSE" | "UNKNOWN_FORMAT",- message: string,- ) {+ constructor(code: "DETECT_FAIL" | "IO" | "PARSE" | "UNKNOWN_FORMAT", message: string) {super(message);this.name = "SessionImportError";this.code = code;diff --git a/src/core/brain/sessions/validate-feedback.ts b/src/core/brain/sessions/validate-feedback.tsindex 81833620..e320b94a 100644--- a/src/core/brain/sessions/validate-feedback.ts+++ b/src/core/brain/sessions/validate-feedback.ts@@ -69,10 +69,7 @@ export function validateBrainFeedbackInput(input: unknown): ValidationResult {if (signalRaw === null) {return { ok: false, reason: "brain_feedback missing required field: signal" };}- if (- signalRaw !== BRAIN_SIGNAL_SIGN.positive &&- signalRaw !== BRAIN_SIGNAL_SIGN.negative- ) {+ if (signalRaw !== BRAIN_SIGNAL_SIGN.positive && signalRaw !== BRAIN_SIGNAL_SIGN.negative) {return {ok: false,reason: `brain_feedback field 'signal' must be 'positive' or 'negative'; got ${JSON.stringify(signalRaw)}`,diff --git a/src/core/brain/set-primary.ts b/src/core/brain/set-primary.tsindex 804cb4f2..fcd20244 100644--- a/src/core/brain/set-primary.ts+++ b/src/core/brain/set-primary.ts@@ -60,10 +60,7 @@ const LINE_RE = /^primary_agent:.*$/m;* surfaces as a typed error instead of writing back something that* the loader will reject on the next read.*/-export function setPrimaryAgent(- vault: string,- name: string | null,-): SetPrimaryAgentResult {+export function setPrimaryAgent(vault: string, name: string | null): SetPrimaryAgentResult {const path = brainConfigPath(vault);if (!existsSync(path)) {throw new BrainConfigError(diff --git a/src/core/brain/sign.ts b/src/core/brain/sign.tsindex 398e99f6..c795f608 100644--- a/src/core/brain/sign.ts+++ b/src/core/brain/sign.ts@@ -24,9 +24,7 @@ import { parseWikilink } from "./wikilink.ts";export type ResolvedSign = BrainSignalSign | "unknown";/** Count positive vs negative signs in an iterable of polarities. */-export function countSigns(- signs: Iterable<BrainSignalSign>,-): { pos: number; neg: number } {+export function countSigns(signs: Iterable<BrainSignalSign>): { pos: number; neg: number } {let pos = 0;let neg = 0;for (const s of signs) {diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex cfcec347..5280d2bd 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -135,10 +135,7 @@ export function writeSignal(`signal field 'signal' must be 'positive' or 'negative'; got ${JSON.stringify(sanitised.signal)}`,);}- if (- sanitised.source_type !== undefined &&- !isBrainSignalSourceType(sanitised.source_type)- ) {+ if (sanitised.source_type !== undefined && !isBrainSignalSourceType(sanitised.source_type)) {throw new Error(`signal field 'source_type' must be 'live', 'inline', or 'session'; got ${JSON.stringify(sanitised.source_type)}`,);@@ -225,9 +222,7 @@ function sanitiseSignalInput(input: WriteSignalInput): WriteSignalInput {const scope = input.scope? sanitiseTextField(input.scope, { maxLen: SCOPE_MAX_LEN, singleLine: true }): input.scope;- const raw = input.raw- ? sanitiseTextField(input.raw, { maxLen: RAW_MAX_LEN })- : input.raw;+ const raw = input.raw ? sanitiseTextField(input.raw, { maxLen: RAW_MAX_LEN }) : input.raw;const source = input.source? input.source.map((s) =>sanitiseTextField(s, { maxLen: SOURCE_ITEM_MAX_LEN, singleLine: true }),@@ -265,10 +260,7 @@ export function parseSignal(path: string): BrainSignal {const tags = requireStringArray(meta, "tags");const topic = requireString(meta, "topic");const signalValue = requireString(meta, "signal");- if (- signalValue !== BRAIN_SIGNAL_SIGN.positive &&- signalValue !== BRAIN_SIGNAL_SIGN.negative- ) {+ if (signalValue !== BRAIN_SIGNAL_SIGN.positive && signalValue !== BRAIN_SIGNAL_SIGN.negative) {throw new Error(`signal field 'signal' must be 'positive' or 'negative'; got ${JSON.stringify(signalValue)} (${path})`,);@@ -295,9 +287,7 @@ export function parseSignal(path: string): BrainSignal {}for (const item of meta["source"]) {if (typeof item !== "string") {- throw new Error(- `signal field 'source' must be an array of strings (${path})`,- );+ throw new Error(`signal field 'source' must be an array of strings (${path})`);}}source = [...(meta["source"] as ReadonlyArray<string>)];@@ -431,10 +421,7 @@ function composeSignalTags(input: WriteSignalInput): string[] {// Non-default source_type gets its own tag so Obsidian users can// filter `tag:brain/source/inline` etc. `live` is the implicit// default and stays tag-less.- if (- input.source_type !== undefined &&- input.source_type !== BRAIN_SIGNAL_SOURCE_TYPE.live- ) {+ if (input.source_type !== undefined && input.source_type !== BRAIN_SIGNAL_SOURCE_TYPE.live) {push(`brain/source/${input.source_type}`);}for (const t of input.extraTags ?? []) {@@ -494,10 +481,7 @@ function requireString(meta: Record<string, unknown>, field: string): string {return v;}-function requireStringArray(- meta: Record<string, unknown>,- field: string,-): ReadonlyArray<string> {+function requireStringArray(meta: Record<string, unknown>, field: string): ReadonlyArray<string> {requireField(meta, field);const v = meta[field];if (!Array.isArray(v)) {@@ -505,9 +489,7 @@ function requireStringArray(}for (const item of v) {if (typeof item !== "string") {- throw new Error(- `signal field '${field}' must be an array of strings`,- );+ throw new Error(`signal field '${field}' must be an array of strings`);}}return [...(v as ReadonlyArray<string>)];diff --git a/src/core/brain/snapshot-diff-render.ts b/src/core/brain/snapshot-diff-render.tsindex 76e066fb..b6f7abdb 100644--- a/src/core/brain/snapshot-diff-render.ts+++ b/src/core/brain/snapshot-diff-render.ts@@ -24,15 +24,14 @@ const SECTION_ORDER: ReadonlyArray<BrainTreeEntryKind> = Object.freeze(["other",]);-const SECTION_TITLE: Readonly<Record<BrainTreeEntryKind, string>> =- Object.freeze({- preference: "Preferences",- retired: "Retired",- signal: "Signals",- log: "Logs",- config: "Config",- other: "Other",- });+const SECTION_TITLE: Readonly<Record<BrainTreeEntryKind, string>> = Object.freeze({+ preference: "Preferences",+ retired: "Retired",+ signal: "Signals",+ log: "Logs",+ config: "Config",+ other: "Other",+});export interface RenderDiffMarkdownOptions {/** Display label for the "A" side (typically a run id). */@@ -85,10 +84,7 @@ export function renderDiffJson(diff: BrainTreeDiff): BrainTreeDiff {// ----- Internal helpers -----------------------------------------------------function renderSection(- diff: BrainTreeDiff,- kind: BrainTreeEntryKind,-): string[] {+function renderSection(diff: BrainTreeDiff, kind: BrainTreeEntryKind): string[] {const out: string[] = [];for (const entry of diff.added.filter((e) => e.kind === kind)) {out.push(`- + ${renderEntryRef(entry)} (added)`);@@ -103,10 +99,7 @@ function renderSection(}function renderEntryRef(entry: BrainTreeEntry): string {- if (- (entry.kind === "preference" || entry.kind === "retired")- && entry.id !== null- ) {+ if ((entry.kind === "preference" || entry.kind === "retired") && entry.id !== null) {return renderPrefLink({ id: entry.id, principle: entry.principle });}if (entry.id !== null) {diff --git a/src/core/brain/snapshot-diff.ts b/src/core/brain/snapshot-diff.tsindex d8a2a85d..e9516ed4 100644--- a/src/core/brain/snapshot-diff.ts+++ b/src/core/brain/snapshot-diff.ts@@ -27,13 +27,7 @@ import type { BrainPreference, BrainRetired } from "./types.ts";// ----- Public types ---------------------------------------------------------export type BrainTreeEntryKind =- | "preference"- | "retired"- | "signal"- | "log"- | "config"- | "other";+export type BrainTreeEntryKind = "preference" | "retired" | "signal" | "log" | "config" | "other";export interface BrainTreeEntry {/** Vault-relative path under `Brain/<…>`. */@@ -100,10 +94,7 @@ const TRACKED_RETIRED_FIELDS: ReadonlyArray<keyof BrainRetired> = Object.freeze(* treated as "not present", not as errors. The function never* mutates either tree. Returned arrays are frozen for caller safety.*/-export function diffBrainTrees(- rootA: string,- rootB: string,-): BrainTreeDiff {+export function diffBrainTrees(rootA: string, rootB: string): BrainTreeDiff {const a = walkBrain(rootA);const b = walkBrain(rootB);@@ -269,10 +260,7 @@ function scanFile(_root: string, abs: string, rel: string): ScannedFile {};}}- if (- (rel.startsWith("inbox/") || rel.startsWith("processed/"))- && baseName.startsWith("sig-")- ) {+ if ((rel.startsWith("inbox/") || rel.startsWith("processed/")) && baseName.startsWith("sig-")) {return {entry: {path: `Brain/${rel}`,@@ -296,11 +284,7 @@ function scanFile(_root: string, abs: string, rel: string): ScannedFile {bytes: readFileSafe(abs),};}- if (- rel === "_brain.yaml"- || rel === "_BRAIN.md"- || rel === "active.md"- ) {+ if (rel === "_brain.yaml" || rel === "_BRAIN.md" || rel === "active.md") {return {entry: {path: `Brain/${rel}`,@@ -388,9 +372,7 @@ function diffRetired(a: ScannedFile, b: ScannedFile): BrainTreeChange {return { entry: b.entry, fields, bodyChanged };}-function normaliseValue(- v: unknown,-): string | number | boolean | null {+function normaliseValue(v: unknown): string | number | boolean | null {if (v === undefined) return null;if (v === null) return null;if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {diff --git a/src/core/brain/snapshot.ts b/src/core/brain/snapshot.tsindex aa96b246..dd705b15 100644--- a/src/core/brain/snapshot.ts+++ b/src/core/brain/snapshot.ts@@ -49,17 +49,8 @@ import {import { tmpdir } from "node:os";import { basename, join } from "node:path";-import {- buildManifest,- manifestSidecarPath,- writeManifestSidecar,-} from "./manifest.ts";-import {- BRAIN_ROOT_REL,- brainDirs,- snapshotPath,- validateRunId,-} from "./paths.ts";+import { buildManifest, manifestSidecarPath, writeManifestSidecar } from "./manifest.ts";+import { BRAIN_ROOT_REL, brainDirs, snapshotPath, validateRunId } from "./paths.ts";// ----- Errors ---------------------------------------------------------------@@ -70,9 +61,7 @@ import {*/export class BrainSnapshotToolingMissingError extends Error {constructor(tool: string, hint: string) {- super(- `snapshot tooling missing: '${tool}' not found on PATH. ${hint}`,- );+ super(`snapshot tooling missing: '${tool}' not found on PATH. ${hint}`);this.name = "BrainSnapshotToolingMissingError";}}@@ -176,10 +165,7 @@ function detectTooling(): ToolAvailability {* on filenames containing whitespace. Enumerating the kept entries* explicitly is byte-stable and easy to reason about.*/-export function createSnapshot(- vault: string,- runId: string,-): CreateSnapshotResult {+export function createSnapshot(vault: string, runId: string): CreateSnapshotResult {validateRunId(runId);const dirs = brainDirs(vault);mkdirSync(dirs.snapshots, { recursive: true });@@ -233,10 +219,7 @@ export function createSnapshot(}if (!existsSync(outPath)) {- throw new BrainSnapshotError(- `archive write reported success but ${outPath} is absent`,- runId,- );+ throw new BrainSnapshotError(`archive write reported success but ${outPath} is absent`, runId);}// Sidecar manifest. Failure is non-fatal: the archive is the@@ -295,10 +278,7 @@ function runArchivePipeline(stdio: ["ignore", "pipe", "pipe"],});if (tarResult.error) {- throw new BrainSnapshotError(- `${prodCmd} failed to start: ${tarResult.error.message}`,- runId,- );+ throw new BrainSnapshotError(`${prodCmd} failed to start: ${tarResult.error.message}`, runId);}if (tarResult.status !== 0) {const stderr = (tarResult.stderr ?? Buffer.from("")).toString("utf8").trim();@@ -321,17 +301,11 @@ function runArchivePipeline(stdio: ["pipe", "inherit", "pipe"],});if (r.error) {- throw new BrainSnapshotError(- `${consCmd} failed to start: ${r.error.message}`,- runId,- );+ throw new BrainSnapshotError(`${consCmd} failed to start: ${r.error.message}`, runId);}if (r.status !== 0) {const stderr = (r.stderr ?? Buffer.from("")).toString("utf8").trim();- throw new BrainSnapshotError(- `${consCmd} exited with status ${r.status}: ${stderr}`,- runId,- );+ throw new BrainSnapshotError(`${consCmd} exited with status ${r.status}: ${stderr}`, runId);}} else {// gzip pipeline → capture stdout, write to file.@@ -341,17 +315,11 @@ function runArchivePipeline(maxBuffer: 256 * 1024 * 1024,});if (r.error) {- throw new BrainSnapshotError(- `${consCmd} failed to start: ${r.error.message}`,- runId,- );+ throw new BrainSnapshotError(`${consCmd} failed to start: ${r.error.message}`, runId);}if (r.status !== 0) {const stderr = (r.stderr ?? Buffer.from("")).toString("utf8").trim();- throw new BrainSnapshotError(- `${consCmd} exited with status ${r.status}: ${stderr}`,- runId,- );+ throw new BrainSnapshotError(`${consCmd} exited with status ${r.status}: ${stderr}`, runId);}// Write the compressed payload to the snapshot file atomically.// Use writeFileSync since the file is binary and lives inside@@ -419,10 +387,7 @@ export function listSnapshots(vault: string): SnapshotInfo[] {* paths that were deleted, vault-relative. Idempotent — a second run* on the same dir returns `deleted: []`.*/-export function pruneSnapshots(- vault: string,- retentionCount: number,-): PruneSnapshotsResult {+export function pruneSnapshots(vault: string, retentionCount: number): PruneSnapshotsResult {if (!Number.isInteger(retentionCount) || retentionCount < 0) {throw new Error(`pruneSnapshots: retentionCount must be a non-negative integer; got ${retentionCount}`,@@ -504,10 +469,7 @@ export interface ExtractSnapshotResult {* missing root, {@link BrainSnapshotToolingMissingError} when the* host lacks the required external tool.*/-export function extractSnapshotToTemp(- vault: string,- runId: string,-): ExtractSnapshotResult {+export function extractSnapshotToTemp(vault: string, runId: string): ExtractSnapshotResult {validateRunId(runId);const archive = snapshotPath(vault, runId);if (!existsSync(archive)) {@@ -568,10 +530,7 @@ export function extractSnapshotToTemp(});if (tar.error || tar.status !== 0) {const stderr = (tar.stderr ?? Buffer.from("")).toString("utf8").trim();- throw new BrainSnapshotError(- `tar extract failed: ${tar.error?.message ?? stderr}`,- runId,- );+ throw new BrainSnapshotError(`tar extract failed: ${tar.error?.message ?? stderr}`, runId);}} else {const tar = spawnSync("tar", ["-x", "-z", "-f", archive, "-C", tmp], {@@ -579,19 +538,13 @@ export function extractSnapshotToTemp(});if (tar.error || tar.status !== 0) {const stderr = (tar.stderr ?? Buffer.from("")).toString("utf8").trim();- throw new BrainSnapshotError(- `tar extract failed: ${tar.error?.message ?? stderr}`,- runId,- );+ throw new BrainSnapshotError(`tar extract failed: ${tar.error?.message ?? stderr}`, runId);}}const extractedBrain = join(tmp, BRAIN_ROOT_REL);if (!existsSync(extractedBrain)) {- throw new BrainSnapshotError(- `archive does not contain a ${BRAIN_ROOT_REL}/ root`,- runId,- );+ throw new BrainSnapshotError(`archive does not contain a ${BRAIN_ROOT_REL}/ root`, runId);}return Object.freeze({ tmpRoot: tmp, brainRoot: extractedBrain, cleanup });} catch (err) {@@ -613,9 +566,7 @@ export function restoreSnapshot(// The exclusion is the load-bearing safety guarantee: rolling back// an older state must not erase newer snapshots, otherwise the// operator is one click away from losing their forward path.- const replacementEntries = readdirSync(ext.brainRoot).filter(- (e) => e !== ".snapshots",- );+ const replacementEntries = readdirSync(ext.brainRoot).filter((e) => e !== ".snapshots");// The correct semantics are "live tree == snapshot tree minus// `.snapshots/`". Delete every live top-level entry exceptdiff --git a/src/core/brain/status.ts b/src/core/brain/status.tsindex e7bbed56..93797897 100644--- a/src/core/brain/status.ts+++ b/src/core/brain/status.ts@@ -24,10 +24,7 @@ import { brainDirs } from "./paths.ts";import { parseLogDay } from "./log.ts";import { loadBrainConfig } from "./policy.ts";import { parseSignal } from "./signal.ts";-import {- BRAIN_LOG_EVENT_KIND,- BRAIN_PREFERENCE_STATUS,-} from "./types.ts";+import { BRAIN_LOG_EVENT_KIND, BRAIN_PREFERENCE_STATUS } from "./types.ts";// ----- Public types --------------------------------------------------------@@ -185,8 +182,8 @@ function scanLogTimestamps(vault: string): {const days = readdirSync(dirs.log).filter((n) => n.endsWith(".md") && /^\d{4}-\d{2}-\d{2}\.md$/.test(n)).map((n) => n.slice(0, -".md".length))- .sort()- .reverse(); // newest day first+ .toSorted()+ .toReversed(); // newest day firstlet lastDreamAt: string | null = null;let lastApplyEvidenceAt: string | null = null;@@ -204,10 +201,7 @@ function scanLogTimestamps(vault: string): {if (lastDreamAt === null && e.eventType === BRAIN_LOG_EVENT_KIND.dream) {lastDreamAt = e.timestamp;}- if (- lastApplyEvidenceAt === null &&- e.eventType === BRAIN_LOG_EVENT_KIND.applyEvidence- ) {+ if (lastApplyEvidenceAt === null && e.eventType === BRAIN_LOG_EVENT_KIND.applyEvidence) {lastApplyEvidenceAt = e.timestamp;}if (lastDreamAt !== null && lastApplyEvidenceAt !== null) break;diff --git a/src/core/brain/sync-lockfile.ts b/src/core/brain/sync-lockfile.tsindex e6636d5c..fc7dd3d0 100644--- a/src/core/brain/sync-lockfile.ts+++ b/src/core/brain/sync-lockfile.ts@@ -21,14 +21,7 @@* remove them by hand.*/-import {- closeSync,- mkdirSync,- openSync,- readdirSync,- unlinkSync,- writeSync,-} from "node:fs";+import { closeSync, mkdirSync, openSync, readdirSync, unlinkSync, writeSync } from "node:fs";import { dirname, join } from "node:path";export interface LockHandle {@@ -80,9 +73,7 @@ export function acquireLockSync(target: string): LockHandle {} catch (err) {const e = err as NodeJS.ErrnoException;if (e.code === "EEXIST") {- const collision: NodeJS.ErrnoException = new Error(- `lock busy: ${lockPath}`,- );+ const collision: NodeJS.ErrnoException = new Error(`lock busy: ${lockPath}`);collision.code = "ELOCKED";collision.path = lockPath;throw collision;@@ -95,10 +86,7 @@ export function acquireLockSync(target: string): LockHandle {// stale locks. Failure to write is non-fatal: the lock semantics// come from the exclusive create, not from the body.try {- const stamp = Buffer.from(- `${process.pid}\n${new Date().toISOString()}\n`,- "utf8",- );+ const stamp = Buffer.from(`${process.pid}\n${new Date().toISOString()}\n`, "utf8");writeSync(fd, stamp, 0, stamp.byteLength);} catch {// ignore; diagnostic-only payloaddiff --git a/src/core/brain/templates.ts b/src/core/brain/templates.tsindex ffd7e3cb..e82bcacd 100644--- a/src/core/brain/templates.ts+++ b/src/core/brain/templates.ts@@ -20,10 +20,7 @@ import type { BrainConfig } from "./types.ts";// Template files ship in the same directory as the source so a future// bundled build that keeps assets alongside the JS output keeps// working without path surgery.-const TEMPLATE_DIR = resolve(- dirname(fileURLToPath(import.meta.url)),- "templates",-);+const TEMPLATE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "templates");/** Operating manual rendered at `Brain/_BRAIN.md`. */export const BRAIN_MANUAL_TEMPLATE_PATH = join(TEMPLATE_DIR, "_BRAIN.md.tpl");@@ -42,6 +39,7 @@ export function readTemplate(path: string): string {`Failed to load Brain template at ${path}: ${message}. ` +"This indicates a broken open-second-brain install — the " +"src/core/brain/templates/ directory must ship alongside templates.ts.",+ { cause: err },);}}diff --git a/src/core/brain/temporal/belief-evolution.ts b/src/core/brain/temporal/belief-evolution.tsindex 2efe1c3e..ec870040 100644--- a/src/core/brain/temporal/belief-evolution.ts+++ b/src/core/brain/temporal/belief-evolution.ts@@ -25,19 +25,13 @@ import { join } from "node:path";import { parseFrontmatter } from "../../vault.ts";import { brainDirs } from "./../paths.ts";-import {- BRAIN_APPLY_RESULT,- BRAIN_LOG_EVENT_KIND,- type BrainApplyResult,-} from "./../types.ts";+import { BRAIN_APPLY_RESULT, BRAIN_LOG_EVENT_KIND, type BrainApplyResult } from "./../types.ts";import { extractId } from "./period-common.ts";import { selectEvents } from "./select-events.ts";import type { TemporalEvent, TimelineIndex } from "./types.ts";/** What the caller wants the evolution for. */-export type BeliefEvolutionTarget =- | { readonly prefId: string }- | { readonly topic: string };+export type BeliefEvolutionTarget = { readonly prefId: string } | { readonly topic: string };/** One status-change row. */export interface BeliefTransition {@@ -179,27 +173,9 @@ function collectTransitions(for (const ev of dreamEvents) {const summary = ev.dreamSummary;if (summary === undefined) continue;- appendTransitionsFromLinks(- ev.at,- summary.newUnconfirmed,- "creation",- targetIds,- out,- );- appendTransitionsFromLinks(- ev.at,- summary.confirmed,- "promotion",- targetIds,- out,- );- appendTransitionsFromLinks(- ev.at,- summary.retired,- "retirement",- targetIds,- out,- );+ appendTransitionsFromLinks(ev.at, summary.newUnconfirmed, "creation", targetIds, out);+ appendTransitionsFromLinks(ev.at, summary.confirmed, "promotion", targetIds, out);+ appendTransitionsFromLinks(ev.at, summary.retired, "retirement", targetIds, out);}out.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));return out;@@ -228,10 +204,7 @@ function appendTransitionsFromLinks(}}-function matchesTarget(- candidateId: string,- targetIds: ReadonlySet<string>,-): boolean {+function matchesTarget(candidateId: string, targetIds: ReadonlySet<string>): boolean {if (targetIds.has(candidateId)) return true;// pref-foo / ret-foo share lifecycle; treat the alternate prefix as// matching too so a `retirement` entry against `ret-foo` resolves@@ -321,13 +294,9 @@ function collectRetirements(const retiredAt = readScalar(meta["retired_at"]);if (retiredAt === undefined) continue;const supersededByLink = readScalar(meta["superseded_by"]);- const supersededBy = supersededByLink !== undefined- ? extractId(supersededByLink)- : undefined;+ const supersededBy = supersededByLink !== undefined ? extractId(supersededByLink) : undefined;const supersedesLink = readScalar(meta["supersedes"]);- const supersedes = supersedesLink !== undefined- ? extractId(supersedesLink)- : undefined;+ const supersedes = supersedesLink !== undefined ? extractId(supersedesLink) : undefined;const row: BeliefRetirement = {prefId: id,retiredAt,@@ -339,9 +308,7 @@ function collectRetirements(: {}),...(supersededBy !== undefined ? { supersededBy } : {}),...(supersedes !== undefined ? { supersedes } : {}),- ...(readScalar(meta["topic"]) !== undefined- ? { topic: readScalar(meta["topic"])! }- : {}),+ ...(readScalar(meta["topic"]) !== undefined ? { topic: readScalar(meta["topic"])! } : {}),};out.push(Object.freeze(row));// Walk the chain: `supersedes` points to the previous retireddiff --git a/src/core/brain/temporal/build-index.ts b/src/core/brain/temporal/build-index.tsindex 7d3d8342..ab4b7c2c 100644--- a/src/core/brain/temporal/build-index.ts+++ b/src/core/brain/temporal/build-index.ts@@ -102,9 +102,7 @@ function pushToMap<K, V>(m: Map<K, V[]>, key: K, value: V): void {}}-function freezeMap<K, V>(- m: Map<K, V[]>,-): ReadonlyMap<K, ReadonlyArray<V>> {+function freezeMap<K, V>(m: Map<K, V[]>): ReadonlyMap<K, ReadonlyArray<V>> {const out = new Map<K, ReadonlyArray<V>>();for (const [k, v] of m) {out.set(k, Object.freeze(v));@@ -127,9 +125,7 @@ function resolveWindow(opts: BuildTimelineIndexOptions): TimelineWindow {const untilRaw = opts.until;const now = opts.now ?? new Date();const since =- sinceRaw !== undefined- ? normalizeWindowBound(sinceRaw, "since")- : "1970-01-01T00:00:00Z";+ sinceRaw !== undefined ? normalizeWindowBound(sinceRaw, "since") : "1970-01-01T00:00:00Z";const until =untilRaw !== undefined? normalizeWindowBound(untilRaw, "until")@@ -166,11 +162,7 @@ function addDays(day: string, delta: number): string {return new Date(t + delta * ONE_DAY_MS).toISOString().slice(0, 10);}-function collectLogEvents(- vault: string,- window: TimelineWindow,- out: TemporalEvent[],-): void {+function collectLogEvents(vault: string, window: TimelineWindow, out: TemporalEvent[]): void {const logDir = brainDirs(vault).log;if (!existsSync(logDir)) return;const sinceDay = dateKeyFromIso(window.since);@@ -185,7 +177,7 @@ function collectLogEvents(const base = stripKnownLogExtension(entry.name);if (base !== null && ISO_DATE_ONLY_RE.test(base)) dates.add(base);}- const sortedDates = [...dates].sort();+ const sortedDates = [...dates].toSorted();for (const date of sortedDates) {if (date < lowerBound) continue;if (date > upperBound) continue;@@ -193,10 +185,7 @@ function collectLogEvents(// Reflect the actual source `readLogDay` consumed so the// audit pointer stays accurate when the JSONL sidecar is// missing and the markdown fallback is used.- const filePath = join(- logDir,- source === "markdown-fallback" ? `${date}.md` : `${date}.jsonl`,- );+ const filePath = join(logDir, source === "markdown-fallback" ? `${date}.md` : `${date}.jsonl`);const vaultPath = relative(vault, filePath);for (let i = 0; i < entries.length; i++) {const entry = entries[i]!;@@ -226,10 +215,7 @@ function stripKnownLogExtension(name: string): string | null {* populated; consumers that care about a specific kind read the* narrower slot off the timeline event directly.*/-function normaliseLogEntry(- entry: BrainLogEntry,- source: TemporalEventSource,-): TemporalEvent {+function normaliseLogEntry(entry: BrainLogEntry, source: TemporalEventSource): TemporalEvent {const body = entry.body;const prefId = extractPrefIdFromBody(entry.eventType, body);const topic = readScalar(body["topic"]);@@ -247,16 +233,10 @@ function normaliseLogEntry(// that helper collapses folder segments to a basename, which would// lose the `src/cli/main.ts` shape operators expect from an audit// pointer.- const artifact =- artifactRaw !== undefined ? stripWikilinkBrackets(artifactRaw) : undefined;- const text =- entry.eventType === BRAIN_LOG_EVENT_KIND.note- ? readScalar(body["text"])- : undefined;+ const artifact = artifactRaw !== undefined ? stripWikilinkBrackets(artifactRaw) : undefined;+ const text = entry.eventType === BRAIN_LOG_EVENT_KIND.note ? readScalar(body["text"]) : undefined;const dreamSummary =- entry.eventType === BRAIN_LOG_EVENT_KIND.dream- ? readDreamSummary(body)- : undefined;+ entry.eventType === BRAIN_LOG_EVENT_KIND.dream ? readDreamSummary(body) : undefined;return Object.freeze({at: entry.timestamp,kind: entry.eventType,@@ -276,17 +256,11 @@ function normaliseLogEntry(* `undefined` when no slot is populated so the spread above omits the* `dreamSummary` field on no-op runs.*/-function readDreamSummary(- body: BrainLogEntry["body"],-): DreamSummarySlots | undefined {+function readDreamSummary(body: BrainLogEntry["body"]): DreamSummarySlots | undefined {const newUnconfirmed = readStringArray(body["new_unconfirmed"]);const confirmed = readStringArray(body["confirmed"]);const retired = readStringArray(body["retired"]);- if (- newUnconfirmed === undefined &&- confirmed === undefined &&- retired === undefined- ) {+ if (newUnconfirmed === undefined && confirmed === undefined && retired === undefined) {return undefined;}return Object.freeze({@@ -354,9 +328,7 @@ function extractPrefIdFromBody(case BRAIN_LOG_EVENT_KIND.signalSuppressed:// The retired pref is the lifecycle-meaningful anchor for a// suppression event; the inbound signal slug is one-off.- return (- readWikilinkId(body["retired"]) ?? readWikilinkId(body["signal"])- );+ return readWikilinkId(body["retired"]) ?? readWikilinkId(body["signal"]);case BRAIN_LOG_EVENT_KIND.feedback:return readWikilinkId(body["signal"]);default:@@ -372,11 +344,7 @@ function readWikilinkId(value: unknown): string | undefined {return PREF_ID_RE.test(target) ? target : undefined;}-function collectRetiredEvents(- vault: string,- window: TimelineWindow,- out: TemporalEvent[],-): void {+function collectRetiredEvents(vault: string, window: TimelineWindow, out: TemporalEvent[]): void {const retiredDir = brainDirs(vault).retired;if (!existsSync(retiredDir)) return;for (const entry of readdirSync(retiredDir, { withFileTypes: true })) {diff --git a/src/core/brain/temporal/period-common.ts b/src/core/brain/temporal/period-common.tsindex 40ee5ae9..c864b275 100644--- a/src/core/brain/temporal/period-common.ts+++ b/src/core/brain/temporal/period-common.ts@@ -7,11 +7,7 @@*/import { parseWikilink } from "./../wikilink.ts";-import {- BRAIN_APPLY_RESULT,- BRAIN_LOG_EVENT_KIND,- type BrainLogEventKind,-} from "./../types.ts";+import { BRAIN_APPLY_RESULT, BRAIN_LOG_EVENT_KIND, type BrainLogEventKind } from "./../types.ts";import type { TemporalEvent } from "./types.ts";const LINK_REASON_RE = /\(([^)]+)\)\s*$/;@@ -49,9 +45,7 @@ export function countByKind(* from `new_unconfirmed` / `confirmed` / `retired` arrays, and return* them in chronological order.*/-export function collectTransitions(- events: ReadonlyArray<TemporalEvent>,-): PeriodStatusTransition[] {+export function collectTransitions(events: ReadonlyArray<TemporalEvent>): PeriodStatusTransition[] {const out: PeriodStatusTransition[] = [];for (const ev of events) {if (ev.kind !== BRAIN_LOG_EVENT_KIND.dream) continue;@@ -110,9 +104,7 @@ export function computeVaultDelta(}/** Deduplicated list of artifact wikilinks cited by apply-evidence rows. */-export function collectSourcePointers(- events: ReadonlyArray<TemporalEvent>,-): string[] {+export function collectSourcePointers(events: ReadonlyArray<TemporalEvent>): string[] {const seen = new Set<string>();const out: string[] = [];for (const ev of events) {diff --git a/src/core/brain/temporal/select-events.ts b/src/core/brain/temporal/select-events.tsindex d7308a12..56ea4ba2 100644--- a/src/core/brain/temporal/select-events.ts+++ b/src/core/brain/temporal/select-events.ts@@ -34,8 +34,7 @@ export function selectEvents(// Pick the narrowest pre-grouped bucket the filter set permits to// avoid scanning the full event list when the caller has already// committed to a kind / prefId / topic.- const source =- pickNarrowSource(index, filters) ?? index.events;+ const source = pickNarrowSource(index, filters) ?? index.events;const out: TemporalEvent[] = [];for (const ev of source) {if (!matchesFilters(ev, filters)) continue;@@ -60,10 +59,7 @@ function pickNarrowSource(return undefined;}-function matchesFilters(- ev: TemporalEvent,- filters: SelectEventsFilters,-): boolean {+function matchesFilters(ev: TemporalEvent, filters: SelectEventsFilters): boolean {if (filters.prefId !== undefined && ev.prefId !== filters.prefId) return false;if (filters.topic !== undefined && ev.topic !== filters.topic) return false;if (filters.kind !== undefined && ev.kind !== filters.kind) return false;diff --git a/src/core/brain/temporal/stale-watch.ts b/src/core/brain/temporal/stale-watch.tsindex 78d16ece..c873f6f9 100644--- a/src/core/brain/temporal/stale-watch.ts+++ b/src/core/brain/temporal/stale-watch.ts@@ -71,15 +71,9 @@ export function findStaleEntries(const generatedAt = now.toISOString();const nowMs = now.getTime();return Object.freeze({- stalePreferences: Object.freeze(- scanPreferences(index, vault, cfg.stale_pref_days, nowMs),- ),- staleSignals: Object.freeze(- scanSignals(vault, cfg.stale_signal_days, nowMs),- ),- staleLogFiles: Object.freeze(- scanLogFiles(vault, cfg.stale_log_days, nowMs),- ),+ stalePreferences: Object.freeze(scanPreferences(index, vault, cfg.stale_pref_days, nowMs)),+ staleSignals: Object.freeze(scanSignals(vault, cfg.stale_signal_days, nowMs)),+ staleLogFiles: Object.freeze(scanLogFiles(vault, cfg.stale_log_days, nowMs)),thresholds: cfg,generatedAt,});@@ -104,8 +98,8 @@ function scanPreferences(} catch {continue;}- const lastSeenAt = mostRecentEventAt(index, pref.id) ??- pref.last_evidence_at ?? pref.created_at;+ const lastSeenAt =+ mostRecentEventAt(index, pref.id) ?? pref.last_evidence_at ?? pref.created_at;const ageDays = computeAgeDays(lastSeenAt, nowMs);if (ageDays === undefined) continue;if (ageDays < thresholdDays) continue;@@ -123,11 +117,7 @@ function scanPreferences(return out;}-function scanSignals(- vault: string,- thresholdDays: number,- nowMs: number,-): StaleSignalRow[] {+function scanSignals(vault: string, thresholdDays: number, nowMs: number): StaleSignalRow[] {const out: StaleSignalRow[] = [];const dirs = brainDirs(vault);if (!existsSync(dirs.inbox)) return out;@@ -158,11 +148,7 @@ function scanSignals(return out;}-function scanLogFiles(- vault: string,- thresholdDays: number,- nowMs: number,-): StaleLogFileRow[] {+function scanLogFiles(vault: string, thresholdDays: number, nowMs: number): StaleLogFileRow[] {const out: StaleLogFileRow[] = [];const dirs = brainDirs(vault);if (!existsSync(dirs.log)) return out;@@ -186,10 +172,7 @@ function scanLogFiles(return out;}-function mostRecentEventAt(- index: TimelineIndex,- prefId: string,-): string | undefined {+function mostRecentEventAt(index: TimelineIndex, prefId: string): string | undefined {const events = index.eventsByPrefId.get(prefId);if (events === undefined || events.length === 0) return undefined;// events is sorted ascending; last element is most recent.diff --git a/src/core/brain/temporal/types.ts b/src/core/brain/temporal/types.tsindex 9519823d..a5dbe569 100644--- a/src/core/brain/temporal/types.ts+++ b/src/core/brain/temporal/types.ts@@ -10,11 +10,7 @@* Design anchor: `docs/brainstorm/temporal-synthesis/design.md`.*/-import type {- BrainApplyResult,- BrainLogEventKind,- BrainPreferenceStatus,-} from "../types.ts";+import type { BrainApplyResult, BrainLogEventKind, BrainPreferenceStatus } from "../types.ts";/*** Vault-relative location an event was sourced from. The reader keeps@@ -115,10 +111,7 @@ export interface TimelineIndex {*/readonly events: ReadonlyArray<TemporalEvent>;/** Events grouped by `kind`. */- readonly eventsByKind: ReadonlyMap<- BrainLogEventKind,- ReadonlyArray<TemporalEvent>- >;+ readonly eventsByKind: ReadonlyMap<BrainLogEventKind, ReadonlyArray<TemporalEvent>>;/** Events grouped by `prefId` (only events that carry one). */readonly eventsByPrefId: ReadonlyMap<string, ReadonlyArray<TemporalEvent>>;/** Events grouped by `topic` (only events that carry one). */diff --git a/src/core/brain/temporal/weekly-brief.ts b/src/core/brain/temporal/weekly-brief.tsindex 27a20afe..88f08745 100644--- a/src/core/brain/temporal/weekly-brief.ts+++ b/src/core/brain/temporal/weekly-brief.ts@@ -17,10 +17,7 @@*/import { isoSecond } from "./../time.ts";-import type {- BrainLogEventKind,- ResolvedBrainTemporalConfig,-} from "./../types.ts";+import type { BrainLogEventKind, ResolvedBrainTemporalConfig } from "./../types.ts";import { BRAIN_LOG_EVENT_KIND } from "./../types.ts";import { selectEvents } from "./select-events.ts";import {@@ -81,9 +78,7 @@ export function buildWeeklySynthesis(// index and does not re-touch disk.const windowEndMs = Date.parse(`${weekEnd}T00:00:00Z`);if (!Number.isFinite(windowEndMs)) {- throw new Error(- `buildWeeklySynthesis: invalid weekEnd ${JSON.stringify(weekEnd)}`,- );+ throw new Error(`buildWeeklySynthesis: invalid weekEnd ${JSON.stringify(weekEnd)}`);}const windowStartMs = windowEndMs - 7 * ONE_DAY_MS;const windowStart = isoSecond(new Date(windowStartMs));@@ -99,9 +94,7 @@ export function buildWeeklySynthesis(const vaultDelta = computeVaultDelta(events, transitions);const retired = transitions.filter((t) => t.kind === "retirement")- .map((t) =>- Object.freeze({ at: t.at, prefId: t.prefId, link: t.link }),- );+ .map((t) => Object.freeze({ at: t.at, prefId: t.prefId, link: t.link }));const contradictions = collectContradictions(events);return Object.freeze({@@ -117,17 +110,12 @@ export function buildWeeklySynthesis(});}-function collectContradictions(- events: ReadonlyArray<TemporalEvent>,-): WeeklyContradiction[] {+function collectContradictions(events: ReadonlyArray<TemporalEvent>): WeeklyContradiction[] {const out: WeeklyContradiction[] = [];for (const ev of events) {if (ev.kind === BRAIN_LOG_EVENT_KIND.signalSuppressed) {out.push(makeContradiction("signal-suppressed", ev));- } else if (- ev.kind === BRAIN_LOG_EVENT_KIND.applyEvidence &&- ev.result === "violated"- ) {+ } else if (ev.kind === BRAIN_LOG_EVENT_KIND.applyEvidence && ev.result === "violated") {out.push(makeContradiction("evidence-violated", ev));}}diff --git a/src/core/brain/token-footprint.ts b/src/core/brain/token-footprint.tsindex fa78ef0b..8ea6c648 100644--- a/src/core/brain/token-footprint.ts+++ b/src/core/brain/token-footprint.ts@@ -9,12 +9,7 @@* Brain/ but does not match a known subdirectory.*/-import {- existsSync,- readFileSync,- readdirSync,- statSync,-} from "node:fs";+import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";import { join } from "node:path";import { BRAIN_ROOT_REL, brainDirs } from "./paths.ts";@@ -140,8 +135,7 @@ export function computeTokenFootprint(totalFiles += otherFiles;}- const warnThreshold =- opts.warnThreshold ?? resolveWarnThreshold(opts.envWarnThreshold);+ const warnThreshold = opts.warnThreshold ?? resolveWarnThreshold(opts.envWarnThreshold);return Object.freeze({total,files: totalFiles,diff --git a/src/core/brain/trust/check-role-permission.ts b/src/core/brain/trust/check-role-permission.tsindex 5909b95b..b49776cb 100644--- a/src/core/brain/trust/check-role-permission.ts+++ b/src/core/brain/trust/check-role-permission.ts@@ -14,15 +14,8 @@* rejected with `wrong-source-state`.*/-import type {- BrainPreferenceStatus,-} from "../types.ts";-import {- BRAIN_OPERATIONS,- BRAIN_ROLES,- type BrainOperation,- type BrainRole,-} from "./role.ts";+import type { BrainPreferenceStatus } from "../types.ts";+import { BRAIN_OPERATIONS, BRAIN_ROLES, type BrainOperation, type BrainRole } from "./role.ts";export interface RolePermissionResult {readonly allowed: boolean;@@ -51,10 +44,7 @@ const ALLOWED: ReadonlyMap<BrainRole, ReadonlySet<BrainOperation>> = new Map([],[BRAIN_ROLES.applier,- new Set<BrainOperation>([- BRAIN_OPERATIONS.evidence_record,- BRAIN_OPERATIONS.log_append,- ]),+ new Set<BrainOperation>([BRAIN_OPERATIONS.evidence_record, BRAIN_OPERATIONS.log_append]),],[BRAIN_ROLES.unknown, new Set<BrainOperation>()],]);@@ -86,8 +76,7 @@ export function checkRolePermission(if (currentStatus === undefined) {return Object.freeze({allowed: false,- reason:- "wrong-source-state: currentStatus is required for preference_promote_confirmed",+ reason: "wrong-source-state: currentStatus is required for preference_promote_confirmed",});}if (currentStatus !== "unconfirmed") {diff --git a/src/core/brain/trust/compute-verification-delta.ts b/src/core/brain/trust/compute-verification-delta.tsindex 78400c39..1399fd2b 100644--- a/src/core/brain/trust/compute-verification-delta.ts+++ b/src/core/brain/trust/compute-verification-delta.ts@@ -31,11 +31,7 @@ import type { DreamRunSummary } from "../dream.ts";import { preferencePath, retiredPath, vaultRelative } from "../paths.ts";import { parsePreference } from "../preference.ts";-export type VerificationDeltaState =- | "confirmed"- | "drift"- | "regression"- | "missing_evidence";+export type VerificationDeltaState = "confirmed" | "drift" | "regression" | "missing_evidence";export interface VerificationDeltaEntry {/** `pref-*` id from the dream summary. */diff --git a/src/core/brain/trust/instruction-file-ceiling.ts b/src/core/brain/trust/instruction-file-ceiling.tsindex ea77ec7b..d2f5f71b 100644--- a/src/core/brain/trust/instruction-file-ceiling.ts+++ b/src/core/brain/trust/instruction-file-ceiling.ts@@ -19,11 +19,7 @@ import { join } from "node:path";import type { InstructionFileCeilingWarning } from "../doctor.ts";-const TRACKED_FILES: ReadonlyArray<string> = Object.freeze([- "CLAUDE.md",- "AGENTS.md",- "GEMINI.md",-]);+const TRACKED_FILES: ReadonlyArray<string> = Object.freeze(["CLAUDE.md", "AGENTS.md", "GEMINI.md"]);export interface CheckInstructionFileCeilingOptions {readonly maxLines: number;diff --git a/src/core/brain/trust/operator-summary.ts b/src/core/brain/trust/operator-summary.tsindex d4b7dbd1..0f8283c5 100644--- a/src/core/brain/trust/operator-summary.ts+++ b/src/core/brain/trust/operator-summary.ts@@ -23,14 +23,10 @@ import { existsSync, readdirSync, statSync } from "node:fs";import type { DoctorIssue } from "../doctor.ts";import { runDoctor, type RunDoctorResult, type TrustVerdict } from "../doctor.ts";import type { DreamRunSummary } from "../dream.ts";-import {- collectMaintenanceActions,-} from "../maintenance/collect.ts";+import { collectMaintenanceActions } from "../maintenance/collect.ts";import type { ActionItem } from "../maintenance/action-scorer.ts";import { brainDirs } from "../paths.ts";-import {- BRAIN_GUARDRAIL_DEFAULTS,-} from "../policy.ts";+import { BRAIN_GUARDRAIL_DEFAULTS } from "../policy.ts";import type { ResolvedBrainGuardrailConfig } from "../types.ts";import {computeVerificationDelta,diff --git a/src/core/brain/trust/role.ts b/src/core/brain/trust/role.tsindex dfe98ec6..c8d718e2 100644--- a/src/core/brain/trust/role.ts+++ b/src/core/brain/trust/role.ts@@ -56,12 +56,9 @@ export const BRAIN_OPERATIONS = Object.freeze({log_append: "log_append",} as const);-export type BrainOperation =- (typeof BRAIN_OPERATIONS)[keyof typeof BRAIN_OPERATIONS];+export type BrainOperation = (typeof BRAIN_OPERATIONS)[keyof typeof BRAIN_OPERATIONS];-const OPERATION_SET: ReadonlySet<string> = new Set(- Object.values(BRAIN_OPERATIONS),-);+const OPERATION_SET: ReadonlySet<string> = new Set(Object.values(BRAIN_OPERATIONS));export function isBrainOperation(value: unknown): value is BrainOperation {return typeof value === "string" && OPERATION_SET.has(value);diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 59432731..16dfc379 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -22,8 +22,7 @@ export const BRAIN_SIGNAL_SIGN = {positive: "positive",negative: "negative",} as const;-export type BrainSignalSign =- (typeof BRAIN_SIGNAL_SIGN)[keyof typeof BRAIN_SIGNAL_SIGN];+export type BrainSignalSign = (typeof BRAIN_SIGNAL_SIGN)[keyof typeof BRAIN_SIGNAL_SIGN];/*** Where the signal came from (§9 / §16 capture extensions). Absent@@ -49,8 +48,9 @@ const BRAIN_SIGNAL_SOURCE_TYPE_VALUES: ReadonlyArray<BrainSignalSourceType> =/** Type-guard for the enum union — used by writer + parser. */export function isBrainSignalSourceType(v: unknown): v is BrainSignalSourceType {- return typeof v === "string"- && (BRAIN_SIGNAL_SOURCE_TYPE_VALUES as ReadonlyArray<string>).includes(v);+ return (+ typeof v === "string" && (BRAIN_SIGNAL_SOURCE_TYPE_VALUES as ReadonlyArray<string>).includes(v)+ );}export const BRAIN_PREFERENCE_STATUS = {@@ -74,8 +74,7 @@ export const BRAIN_CONFIDENCE = {medium: "medium",high: "high",} as const;-export type BrainConfidence =- (typeof BRAIN_CONFIDENCE)[keyof typeof BRAIN_CONFIDENCE];+export type BrainConfidence = (typeof BRAIN_CONFIDENCE)[keyof typeof BRAIN_CONFIDENCE];export const BRAIN_RETIRED_REASON = {staleNoEvidence: "stale-no-evidence",@@ -100,8 +99,7 @@ export const BRAIN_RETIRED_REASON = {// no contradiction, the two rules said the same thing.mergedInto: "merged-into",} as const;-export type BrainRetiredReason =- (typeof BRAIN_RETIRED_REASON)[keyof typeof BRAIN_RETIRED_REASON];+export type BrainRetiredReason = (typeof BRAIN_RETIRED_REASON)[keyof typeof BRAIN_RETIRED_REASON];export const BRAIN_APPLY_RESULT = {applied: "applied",@@ -114,8 +112,7 @@ export const BRAIN_APPLY_RESULT = {// `retain-pinned` log entry instead.outdated: "outdated",} as const;-export type BrainApplyResult =- (typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];+export type BrainApplyResult = (typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];/*** All possible log event types. `dream` summarises a run; `feedback`@@ -190,8 +187,7 @@ export const BRAIN_LOG_EVENT_KIND = {*/note: "note",} as const;-export type BrainLogEventKind =- (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];+export type BrainLogEventKind = (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];/*** Precomputed set of every event-kind string. Both the markdowndiff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.tsindex e6bbaf26..ebfd39ed 100644--- a/src/core/brain/upgrade.ts+++ b/src/core/brain/upgrade.ts@@ -18,16 +18,8 @@ import { join } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";import { defaultConfigPath, resolveAgentName } from "../config.ts";import { appendLogEvent } from "./log.ts";-import {- brainConfigPath,- brainManualPath,- vaultRelative,-} from "./paths.ts";-import {- BrainConfigError,- DEFAULT_BRAIN_CONFIG_YAML,- loadBrainConfig,-} from "./policy.ts";+import { brainConfigPath, brainManualPath, vaultRelative } from "./paths.ts";+import { BrainConfigError, DEFAULT_BRAIN_CONFIG_YAML, loadBrainConfig } from "./policy.ts";import { createSnapshot } from "./snapshot.ts";import { renderBrainManual } from "./templates.ts";import { isoSecond } from "./time.ts";@@ -179,8 +171,7 @@ export function applyUpgrade(updated.push(file.path);}- const agent =- opts.agent ?? resolveAgentName(defaultConfigPathOrEmpty());+ const agent = opts.agent ?? resolveAgentName(defaultConfigPathOrEmpty());try {appendLogEvent(vault, {timestamp: isoSecond(now),@@ -195,9 +186,7 @@ export function applyUpgrade(} catch (err) {// Audit-only failure — the files are already on disk. Surface so// the operator can record manually if needed.- process.stderr.write(- `warning: append upgrade log failed: ${(err as Error).message}\n`,- );+ process.stderr.write(`warning: append upgrade log failed: ${(err as Error).message}\n`);}return Object.freeze({@@ -284,11 +273,7 @@ function makeNoop(path: string): UpgradeFilePlan {});}-function makeUpdate(- path: string,- before: string,- after: string,-): UpgradeFilePlan {+function makeUpdate(path: string, before: string, after: string): UpgradeFilePlan {return Object.freeze({path,status: "update" as const,@@ -362,13 +347,9 @@ export function mergeBrainYaml(live: string, target: string): string {const targetBlocks = parseYamlBlocks(target);const liveBlocks = parseYamlBlocks(live);const liveByName = new Map(liveBlocks.map((b) => [b.name, b]));- const liveScalars = new Set(- liveBlocks.filter((b) => b.kind === "scalar").map((b) => b.name),- );+ const liveScalars = new Set(liveBlocks.filter((b) => b.kind === "scalar").map((b) => b.name));const liveSections = new Map(- liveBlocks- .filter((b) => b.kind === "section")- .map((b) => [b.name, b] as const),+ liveBlocks.filter((b) => b.kind === "section").map((b) => [b.name, b] as const),);let result = live;@@ -460,17 +441,14 @@ function parseYamlBlocks(yaml: string): YamlBlock[] {}break;}- const text =- [...preface, lines[start]!, ...nestedLines].join("\n") + "\n";+ const text = [...preface, lines[start]!, ...nestedLines].join("\n") + "\n";preface = [];blocks.push({kind: "section",name: key,text,nestedLines: nestedLines.filter((l) => l.trim() !== ""),- nestedKeys: nestedLines- .filter((l) => /^\s+[A-Za-z_]/.test(l))- .map(extractKey),+ nestedKeys: nestedLines.filter((l) => /^\s+[A-Za-z_]/.test(l)).map(extractKey),});continue;}diff --git a/src/core/brain/vault-instruction-file.ts b/src/core/brain/vault-instruction-file.tsindex 7d6f8fc9..17b18537 100644--- a/src/core/brain/vault-instruction-file.ts+++ b/src/core/brain/vault-instruction-file.ts@@ -12,13 +12,7 @@* surface.*/-import {- existsSync,- lstatSync,- readFileSync,- realpathSync,- statSync,-} from "node:fs";+import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from "node:fs";import { isAbsolute, join, relative, sep } from "node:path";import { loadBrainConfig, resolveLinkGraph } from "./policy.ts";@@ -56,9 +50,7 @@ export function readVaultInstructionFile(throw new Error("vault_instruction_file must not be empty");}if (resolvedName.split(/[\\/]/).includes("..")) {- throw new Error(- `vault_instruction_file must not contain '..' segments: ${resolvedName}`,- );+ throw new Error(`vault_instruction_file must not contain '..' segments: ${resolvedName}`);}const full = join(vault, resolvedName);if (!existsSync(full)) return null;diff --git a/src/core/brain/wikilink.ts b/src/core/brain/wikilink.tsindex f9cbb334..115c66cd 100644--- a/src/core/brain/wikilink.ts+++ b/src/core/brain/wikilink.ts@@ -226,7 +226,7 @@ export function renderPrefLink(input: {// in Obsidian: zero-width space/joiner, LRM/RLM, BiDi embedding +// override + isolates, soft hyphen, BOM..replace(/[---]/g, " ")- .replace(/[\[\]|]/g, " ")+ .replace(/[[\]|]/g, " ").replace(/\s+/g, " ").trim();if (title.length === 0) return `[[${input.id}]]`;diff --git a/src/core/config.ts b/src/core/config.tsindex 00d7d9b2..f14a5886 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -101,11 +101,29 @@ export function setConfigValue(key: string, value: string, path?: string): strinconst resolved = path ?? defaultConfigPath();const discovery = discoverConfig(resolved);const data = { ...discovery.data, [key]: value };- const body = Object.entries(data).map(([k, v]) => `${k}: "${v}"`).join("\n") + "\n";+ const body =+ Object.entries(data)+ .map(([k, v]) => `${k}: "${v}"`)+ .join("\n") + "\n";atomicWriteFileSync(resolved, body);return resolved;}+export interface TimezoneValidationResult {+ readonly ok: boolean;+ readonly error: string | null;+}++/** Validate an IANA timezone name without normalising or trimming it. */+export function validateTimezoneName(name: string): TimezoneValidationResult {+ try {+ new Intl.DateTimeFormat("en-US", { timeZone: name });+ return { ok: true, error: null };+ } catch (exc) {+ return { ok: false, error: (exc as Error).message ?? String(exc) };+ }+}+/*** Resolve the IANA timezone for stamping Daily entries.*@@ -119,12 +137,7 @@ export function resolveTimezone(configPath?: string): string | null {name = discoverConfig(configPath).data["timezone"];}if (!name) return null;- try {- new Intl.DateTimeFormat("en-US", { timeZone: name });- return name;- } catch {- return null;- }+ return validateTimezoneName(name).ok ? name : null;}/**diff --git a/src/core/discipline/activity-git.ts b/src/core/discipline/activity-git.tsindex 3e59be53..706d3546 100644--- a/src/core/discipline/activity-git.ts+++ b/src/core/discipline/activity-git.ts@@ -14,10 +14,7 @@ export interface GitActivity {readonly deletions: number;}-export function gitActivity(- path: string,- win: ActivityWindow,-): GitActivity | null {+export function gitActivity(path: string, win: ActivityWindow): GitActivity | null {if (!existsSync(join(path, ".git"))) return null;const since = win.startUtc.toISOString();const until = win.endUtc.toISOString();@@ -26,9 +23,13 @@ export function gitActivity(raw = execFileSync("git",[- "-C", path, "log",- `--since=${since}`, `--until=${until}`,- "--no-merges", "--numstat",+ "-C",+ path,+ "log",+ `--since=${since}`,+ `--until=${until}`,+ "--no-merges",+ "--numstat","--pretty=tformat:__COMMIT__",],{ encoding: "utf8" },diff --git a/src/core/discipline/activity-mtime.ts b/src/core/discipline/activity-mtime.tsindex cdf0d549..e854ee47 100644--- a/src/core/discipline/activity-mtime.ts+++ b/src/core/discipline/activity-mtime.ts@@ -3,11 +3,18 @@ import { join } from "node:path";import type { ActivityWindow } from "./activity-git.ts";const EXCLUDE_DIRS: ReadonlySet<string> = new Set([- ".git", ".hg", ".svn",- "node_modules", ".cache",- "__pycache__", ".venv", "venv",+ ".git",+ ".hg",+ ".svn",+ "node_modules",+ ".cache",+ "__pycache__",+ ".venv",+ "venv",".snapshots",- "dist", "build", "out",+ "dist",+ "build",+ "out",]);export interface MtimeActivity {diff --git a/src/core/discipline/log-counts.ts b/src/core/discipline/log-counts.tsindex bf25f3e7..26ea34ba 100644--- a/src/core/discipline/log-counts.ts+++ b/src/core/discipline/log-counts.ts@@ -21,7 +21,8 @@ function zero(): AgentCounts {function bump(c: AgentCounts, kind: string): AgentCounts {if (kind === "feedback") return { ...c, feedback: c.feedback + 1, total: c.total + 1 };- if (kind === "apply-evidence") return { ...c, apply_evidence: c.apply_evidence + 1, total: c.total + 1 };+ if (kind === "apply-evidence")+ return { ...c, apply_evidence: c.apply_evidence + 1, total: c.total + 1 };if (kind === "note") return { ...c, note: c.note + 1, total: c.total + 1 };return { ...c, other: c.other + 1, total: c.total + 1 };}diff --git a/src/core/discipline/render.ts b/src/core/discipline/render.tsindex 6d1d1ac2..a24fe938 100644--- a/src/core/discipline/render.ts+++ b/src/core/discipline/render.ts@@ -1,10 +1,6 @@import { escapeMarkdownV2 as e } from "./telegram.ts";import type { BrainEventCounts } from "./log-counts.ts";-import {- transcriptConfirmed,- type ActivitySummary,- type DisciplineStatus,-} from "./decision.ts";+import { transcriptConfirmed, type ActivitySummary, type DisciplineStatus } from "./decision.ts";export interface RenderInput {readonly localDate: string;diff --git a/src/core/discipline/telegram.ts b/src/core/discipline/telegram.tsindex 5761844e..bc34c11c 100644--- a/src/core/discipline/telegram.ts+++ b/src/core/discipline/telegram.ts@@ -1,5 +1,5 @@// Telegram MarkdownV2 reserves these — backslash-escape them.-const RESERVED = /([_*\[\]()~`>#+\-=|{}.!\\])/g;+const RESERVED = /([_*[\]()~`>#+\-=|{}.!\\])/g;export function escapeMarkdownV2(s: string): string {return s.replace(RESERVED, "\\$1");diff --git a/src/core/discipline/transcripts/cursor.ts b/src/core/discipline/transcripts/cursor.tsindex 6a76931d..31a36d4f 100644--- a/src/core/discipline/transcripts/cursor.ts+++ b/src/core/discipline/transcripts/cursor.ts@@ -40,7 +40,11 @@ function findDatabases(home: string): string[] {return out;}-function queryCursorDb(dbPath: string, dayStartMs: number, dayEndMs: number): TranscriptDetail | null {+function queryCursorDb(+ dbPath: string,+ dayStartMs: number,+ dayEndMs: number,+): TranscriptDetail | null {let Database: typeof import("bun:sqlite").Database;try {Database = require("bun:sqlite").Database;diff --git a/src/core/discipline/transcripts/index.ts b/src/core/discipline/transcripts/index.tsindex 0ee491e0..de94e201 100644--- a/src/core/discipline/transcripts/index.ts+++ b/src/core/discipline/transcripts/index.ts@@ -30,9 +30,7 @@ export interface CollectTranscriptOpts {readonly runtimes?: ReadonlyArray<TranscriptRuntime>;}-export function collectTranscriptActivity(- opts: CollectTranscriptOpts,-): TranscriptActivity {+export function collectTranscriptActivity(opts: CollectTranscriptOpts): TranscriptActivity {const runtimes = opts.runtimes ?? DEFAULT_TRANSCRIPT_RUNTIMES;const byRuntime = [];let total = 0;diff --git a/src/core/discipline/vault-delta.ts b/src/core/discipline/vault-delta.tsindex ef273375..81f43ccb 100644--- a/src/core/discipline/vault-delta.ts+++ b/src/core/discipline/vault-delta.ts@@ -1,11 +1,7 @@import { existsSync, readdirSync, statSync } from "node:fs";import { join } from "node:path";-import {- BRAIN_INBOX_REL,- BRAIN_PREFERENCES_REL,- BRAIN_RETIRED_REL,-} from "../brain/paths.ts";+import { BRAIN_INBOX_REL, BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL } from "../brain/paths.ts";import type { ActivityWindow } from "./activity-git.ts";export interface VaultDelta {@@ -47,7 +43,9 @@ export function vaultDelta(vault: string, win: ActivityWindow): VaultDelta {const newPreferences = countInWindow(join(vault, BRAIN_PREFERENCES_REL), win);const newRetired = countInWindow(join(vault, BRAIN_RETIRED_REL), win);return {- newSignals, newPreferences, newRetired,+ newSignals,+ newPreferences,+ newRetired,total: newSignals + newPreferences + newRetired,};}diff --git a/src/core/discipline/window.ts b/src/core/discipline/window.tsindex 7b548f13..babf98b3 100644--- a/src/core/discipline/window.ts+++ b/src/core/discipline/window.ts@@ -24,9 +24,7 @@ export function yesterdayWindow(now: Date, tz: string): YesterdayWindow {const m = parts[1]!;const d = parts[2]!;const todayLocalMidnightUtc = localMidnightUtc(y, m, d, tz);- const yesterdayLocalMidnightUtc = new Date(- todayLocalMidnightUtc.getTime() - 24 * 60 * 60 * 1000,- );+ const yesterdayLocalMidnightUtc = new Date(todayLocalMidnightUtc.getTime() - 24 * 60 * 60 * 1000);const localDate = new Intl.DateTimeFormat("en-CA", {timeZone: tz,year: "numeric",@@ -78,8 +76,7 @@ function localMidnightUtc(y: number, m: number, d: number, tz: string): Date {// Whole-day signed offset between the observed local date and the// target civil date. UTC-based midnight arithmetic is safe here// because both inputs are already date-only.- const dayDelta =- (Date.UTC(ly, lm - 1, ld) - Date.UTC(y, m - 1, d)) / 86_400_000;+ const dayDelta = (Date.UTC(ly, lm - 1, ld) - Date.UTC(y, m - 1, d)) / 86_400_000;const drift = dayDelta * 86400 + hh * 3600 + mm * 60 + ss;if (date === expected && drift === 0) return guess;guess = new Date(guess.getTime() - drift * 1000);diff --git a/src/core/doctor.ts b/src/core/doctor.tsindex 797c83b2..2d75672a 100644--- a/src/core/doctor.ts+++ b/src/core/doctor.ts@@ -146,7 +146,11 @@ export function checkCodexManifest(path: string): CheckResult {["keywords", "list"],]);if (problems.length > 0) {- return { name: "codex_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };+ return {+ name: "codex_manifest",+ ok: false,+ message: `schema invalid: ${path} (${problems.join("; ")})`,+ };}return { name: "codex_manifest", ok: true, message: `valid Codex manifest: ${path}` };}@@ -172,7 +176,10 @@ export function checkClaudeManifest(path: string): CheckResult {}if ("author" in data) {const author = data["author"];- const authorName = typeof author === "object" && author !== null ? (author as Record<string, unknown>)["name"] : null;+ const authorName =+ typeof author === "object" && author !== null+ ? (author as Record<string, unknown>)["name"]+ : null;if (typeof author !== "object" ||author === null ||@@ -192,7 +199,11 @@ export function checkClaudeManifest(path: string): CheckResult {);}if (problems.length > 0) {- return { name: "claude_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };+ return {+ name: "claude_manifest",+ ok: false,+ message: `schema invalid: ${path} (${problems.join("; ")})`,+ };}return { name: "claude_manifest", ok: true, message: `valid Claude manifest: ${path}` };}@@ -238,7 +249,11 @@ export function checkOpenclawManifest(path: string): CheckResult {problems.push("missing or empty field 'configSchema'");}if (problems.length > 0) {- return { name: "openclaw_manifest", ok: false, message: `schema invalid: ${path} (${problems.join("; ")})` };+ return {+ name: "openclaw_manifest",+ ok: false,+ message: `schema invalid: ${path} (${problems.join("; ")})`,+ };}return { name: "openclaw_manifest", ok: true, message: `valid OpenClaw manifest: ${path}` };}diff --git a/src/core/fs-atomic.ts b/src/core/fs-atomic.tsindex 4ec28a57..e61ed71b 100644--- a/src/core/fs-atomic.ts+++ b/src/core/fs-atomic.ts@@ -68,11 +68,7 @@ export function atomicCreateFileSyncExclusive(target: string, contents: string):* file is unlinked on any failure; durability fsync of the parent directory* is best-effort after a successful commit.*/-function withTempFile(- target: string,- contents: string,- commit: (tmpPath: string) => void,-): void {+function withTempFile(target: string, contents: string, commit: (tmpPath: string) => void): void {const dir = dirname(target);mkdirSync(dir, { recursive: true });diff --git a/src/core/identity-reminder.ts b/src/core/identity-reminder.tsindex 2f0aa964..0882d1fa 100644--- a/src/core/identity-reminder.ts+++ b/src/core/identity-reminder.ts@@ -43,10 +43,7 @@ export const KNOWN_RUNTIME_TARGETS = ["hermes", "openclaw"] as const;export type RuntimeTarget = (typeof KNOWN_RUNTIME_TARGETS)[number];export function isRuntimeTarget(value: string | undefined): value is RuntimeTarget {- return (- typeof value === "string"- && (KNOWN_RUNTIME_TARGETS as readonly string[]).includes(value)- );+ return typeof value === "string" && (KNOWN_RUNTIME_TARGETS as readonly string[]).includes(value);}let commonTemplateCache: string | undefined;@@ -64,25 +61,17 @@ export function loadReminderTemplate(): string {return commonTemplateCache;} catch (err) {const message = err instanceof Error ? err.message : String(err);- throw new Error(- `Failed to load identity reminder template from ${TEMPLATE_PATH}: ${message}`,- );+ throw new Error(`Failed to load identity reminder template from ${TEMPLATE_PATH}: ${message}`, {+ cause: err,+ });}}-const TEMPLATES_DIR = resolve(- dirname(fileURLToPath(import.meta.url)),- "..",- "..",- "templates",-);+const TEMPLATES_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "templates");const PER_TARGET_PATHS: Readonly<Record<RuntimeTarget, string>> = Object.freeze(Object.fromEntries(- KNOWN_RUNTIME_TARGETS.map((t) => [- t,- resolve(TEMPLATES_DIR, `identity-reminder.${t}.txt`),- ]),+ KNOWN_RUNTIME_TARGETS.map((t) => [t, resolve(TEMPLATES_DIR, `identity-reminder.${t}.txt`)]),),) as Readonly<Record<RuntimeTarget, string>>;diff --git a/src/core/install/adapters/_json-mcp.ts b/src/core/install/adapters/_json-mcp.tsindex 8fabc761..d05307f1 100644--- a/src/core/install/adapters/_json-mcp.ts+++ b/src/core/install/adapters/_json-mcp.ts@@ -13,12 +13,7 @@ import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";import { dirname } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";-import {- mergeMcpServers,- removeMcpServers,- OSB_KEY_FULL,- OSB_KEY_WRITER,-} from "../json-merge.ts";+import { mergeMcpServers, removeMcpServers, OSB_KEY_FULL, OSB_KEY_WRITER } from "../json-merge.ts";import { recordEntry, readManifest, removeEntry } from "../manifest.ts";import { expectedPayloadFromEnv, payloadKeyEquals } from "../payload-equals.ts";import {@@ -105,17 +100,38 @@ interface OnDiskState {function readOnDisk(spec: JsonMcpAdapterSpec, env: InstallEnv, payload: McpPayload): OnDiskState {const path = spec.resolveConfigPath(env);if (!existsSync(path)) {- return { exists: false, canonical: false, full: undefined, writer: undefined, raw: "", mtimeMs: null };+ return {+ exists: false,+ canonical: false,+ full: undefined,+ writer: undefined,+ raw: "",+ mtimeMs: null,+ };}const raw = readFileOrEmpty(path);const topKey = spec.topLevelKey ?? "mcpServers";const parsed = parseJsonObject(raw);if (parsed === null) {- return { exists: true, canonical: false, full: undefined, writer: undefined, raw, mtimeMs: fileMtimeMs(path) };+ return {+ exists: true,+ canonical: false,+ full: undefined,+ writer: undefined,+ raw,+ mtimeMs: fileMtimeMs(path),+ };}const block = readMcpBlock(parsed, topKey);if (block === null) {- return { exists: true, canonical: false, full: undefined, writer: undefined, raw, mtimeMs: fileMtimeMs(path) };+ return {+ exists: true,+ canonical: false,+ full: undefined,+ writer: undefined,+ raw,+ mtimeMs: fileMtimeMs(path),+ };}const full = block[OSB_KEY_FULL] as Record<string, unknown> | undefined;const writer = block[OSB_KEY_WRITER] as Record<string, unknown> | undefined;@@ -192,7 +208,8 @@ export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {plan(payload: McpPayload, env: InstallEnv): InstallPlan {const path = spec.resolveConfigPath(env);- const preview = `json-merge two keys into ${topKey} at ${path}: ` ++ const preview =+ `json-merge two keys into ${topKey} at ${path}: ` +`${OSB_KEY_FULL} → ${payload.full.command} ${payload.full.args.join(" ")}; ` +`${OSB_KEY_WRITER} → ${payload.writer.command} ${payload.writer.args.join(" ")}`;return {@@ -202,12 +219,7 @@ export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {};},- apply(- _plan: InstallPlan,- payload: McpPayload,- env: InstallEnv,- opts: ApplyOpts,- ): ApplyResult {+ apply(_plan: InstallPlan, payload: McpPayload, env: InstallEnv, opts: ApplyOpts): ApplyResult {const path = spec.resolveConfigPath(env);const onDisk = readOnDisk(spec, env, payload);const manifestEntry = readManifest(env.vault).installs[spec.target];@@ -252,9 +264,7 @@ export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {// compare disk mtime against the actual install moment, not the// current wall clock.const existing = readManifest(env.vault).installs[spec.target];- const appliedAt = !contentChanged && existing- ? existing.applied_at- : env.now.toISOString();+ const appliedAt = !contentChanged && existing ? existing.applied_at : env.now.toISOString();const manifest: ManifestEntry = {target: spec.target,applied_at: appliedAt,@@ -273,10 +283,7 @@ export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {};},- uninstall(- env: InstallEnv,- opts: ApplyOpts & { fromSnippet?: boolean },- ): UninstallResult {+ uninstall(env: InstallEnv, opts: ApplyOpts & { fromSnippet?: boolean }): UninstallResult {const path = spec.resolveConfigPath(env);const stored = readManifest(env.vault).installs[spec.target];const skipped: Array<readonly [string, string]> = [];@@ -361,8 +368,14 @@ export function createJsonMcpAdapter(spec: JsonMcpAdapterSpec): InstallAdapter {}const expected = expectedPayloadFromEnv(env);if (- !payloadKeyEquals(block[OSB_KEY_FULL] as Record<string, unknown> | undefined, expected.full) ||- !payloadKeyEquals(block[OSB_KEY_WRITER] as Record<string, unknown> | undefined, expected.writer)+ !payloadKeyEquals(+ block[OSB_KEY_FULL] as Record<string, unknown> | undefined,+ expected.full,+ ) ||+ !payloadKeyEquals(+ block[OSB_KEY_WRITER] as Record<string, unknown> | undefined,+ expected.writer,+ )) {return {target: spec.target,diff --git a/src/core/install/adapters/aider.ts b/src/core/install/adapters/aider.tsindex adf36a8f..ac44f3af 100644--- a/src/core/install/adapters/aider.ts+++ b/src/core/install/adapters/aider.ts@@ -87,11 +87,7 @@ function fileMtimeMs(path: string): number | null {}function resolveAgentName(env: InstallEnv, payload: McpPayload): string {- return (- payload.full.env?.["VAULT_AGENT_NAME"] ??- env.env["VAULT_AGENT_NAME"] ??- "agent"- );+ return payload.full.env?.["VAULT_AGENT_NAME"] ?? env.env["VAULT_AGENT_NAME"] ?? "agent";}function renderTemplate(env: InstallEnv, payload: McpPayload): string {@@ -173,12 +169,7 @@ export const aiderAdapter: InstallAdapter = {};},- apply(- _plan: InstallPlan,- payload: McpPayload,- env: InstallEnv,- opts: ApplyOpts,- ): ApplyResult {+ apply(_plan: InstallPlan, payload: McpPayload, env: InstallEnv, opts: ApplyOpts): ApplyResult {const conf = resolveConfPath(env);const sidecar = resolveSidecarPath(env, opts);const stored = readManifest(env.vault).installs[TARGET];diff --git a/src/core/install/adapters/copilot-cli.ts b/src/core/install/adapters/copilot-cli.tsindex 38146791..56ef93cc 100644--- a/src/core/install/adapters/copilot-cli.ts+++ b/src/core/install/adapters/copilot-cli.ts@@ -20,12 +20,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";import { dirname, join } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";-import {- mergeMcpServers,- removeMcpServers,- OSB_KEY_FULL,- OSB_KEY_WRITER,-} from "../json-merge.ts";+import { mergeMcpServers, removeMcpServers, OSB_KEY_FULL, OSB_KEY_WRITER } from "../json-merge.ts";import { expectedPayloadFromEnv, payloadKeyEquals } from "../payload-equals.ts";import { recordEntry, readManifest, removeEntry } from "../manifest.ts";import { defaultRegistry } from "../registry.ts";@@ -148,9 +143,7 @@ function applyViaCli(] as const) {const r = activeRunner.run(addArgs(name, entry));if (r.exitCode !== 0) {- stderr.write(- `copilot mcp add failed for ${name} (exit ${r.exitCode}): ${r.stderr.trim()}\n`,- );+ stderr.write(`copilot mcp add failed for ${name} (exit ${r.exitCode}): ${r.stderr.trim()}\n`);return { ok: false, reason: r.stderr.trim() || `exit ${r.exitCode}` };}}@@ -254,7 +247,12 @@ export const copilotCliAdapter: InstallAdapter = {}} catch {// parse error → drift- return { target: TARGET, status: "drift", configPath: fb, notes: ["fallback file not valid JSON"] };+ return {+ target: TARGET,+ status: "drift",+ configPath: fb,+ notes: ["fallback file not valid JSON"],+ };}}return {@@ -297,19 +295,16 @@ export const copilotCliAdapter: InstallAdapter = {};},- apply(- _plan: InstallPlan,- payload: McpPayload,- env: InstallEnv,- opts: ApplyOpts,- ): ApplyResult {+ apply(_plan: InstallPlan, payload: McpPayload, env: InstallEnv, opts: ApplyOpts): ApplyResult {let outcome: ApplyOutcome;if (activeRunner.available()) {const r = opts.dryRun ? { ok: true } : applyViaCli(payload, opts.stderr);if (r.ok) {outcome = { viaCli: true, fallbackFile: null };} else {- const file = opts.dryRun ? fallbackPath(env) : applyViaFile(env, payload, opts.stderr, false);+ const file = opts.dryRun+ ? fallbackPath(env)+ : applyViaFile(env, payload, opts.stderr, false);outcome = { viaCli: false, fallbackFile: file };}} else {@@ -394,14 +389,17 @@ export const copilotCliAdapter: InstallAdapter = {}const has = (n: string) => lst.names.includes(n);if (has(OSB_KEY_FULL) && has(OSB_KEY_WRITER)) {- return { target: TARGET, status: "ok", details: ["both OSB names registered with copilot CLI"], fix_hint: null };+ return {+ target: TARGET,+ status: "ok",+ details: ["both OSB names registered with copilot CLI"],+ fix_hint: null,+ };}return {target: TARGET,status: "drift",- details: [- `missing: ${[OSB_KEY_FULL, OSB_KEY_WRITER].filter((n) => !has(n)).join(", ")}`,- ],+ details: [`missing: ${[OSB_KEY_FULL, OSB_KEY_WRITER].filter((n) => !has(n)).join(", ")}`],fix_hint: "o2b install --target copilot-cli --apply",};}@@ -420,10 +418,21 @@ export const copilotCliAdapter: InstallAdapter = {const block = (parsed["mcpServers"] ?? {}) as Record<string, unknown>;const expected = expectedPayloadFromEnv(env);if (- payloadKeyEquals(block[OSB_KEY_FULL] as Record<string, unknown> | undefined, expected.full) &&- payloadKeyEquals(block[OSB_KEY_WRITER] as Record<string, unknown> | undefined, expected.writer)+ payloadKeyEquals(+ block[OSB_KEY_FULL] as Record<string, unknown> | undefined,+ expected.full,+ ) &&+ payloadKeyEquals(+ block[OSB_KEY_WRITER] as Record<string, unknown> | undefined,+ expected.writer,+ )) {- return { target: TARGET, status: "ok", details: [`${path}: both keys present`], fix_hint: null };+ return {+ target: TARGET,+ status: "ok",+ details: [`${path}: both keys present`],+ fix_hint: null,+ };}if (block[OSB_KEY_FULL] && block[OSB_KEY_WRITER]) {return {diff --git a/src/core/install/adapters/cursor.ts b/src/core/install/adapters/cursor.tsindex 80fd4117..1672153a 100644--- a/src/core/install/adapters/cursor.ts+++ b/src/core/install/adapters/cursor.ts@@ -23,9 +23,7 @@ export const cursorAdapter = createJsonMcpAdapter({target: "cursor",label: "Cursor",resolveConfigPath: configPath,- postNotes: [- "Restart the Cursor app to load the new MCP servers.",- ],+ postNotes: ["Restart the Cursor app to load the new MCP servers."],notes: ["scope: user-global (~/.cursor/mcp.json)"],});diff --git a/src/core/install/adapters/gemini-cli.ts b/src/core/install/adapters/gemini-cli.tsindex 3223618e..f5e72104 100644--- a/src/core/install/adapters/gemini-cli.ts+++ b/src/core/install/adapters/gemini-cli.ts@@ -17,9 +17,7 @@ export const geminiCliAdapter = createJsonMcpAdapter({target: "gemini-cli",label: "Google Gemini CLI",resolveConfigPath: configPath,- postNotes: [- "Start `gemini` to load the registered MCP servers.",- ],+ postNotes: ["Start `gemini` to load the registered MCP servers."],});defaultRegistry.register(geminiCliAdapter);diff --git a/src/core/install/adapters/generic.ts b/src/core/install/adapters/generic.tsindex 9d88f5ab..82ea21b1 100644--- a/src/core/install/adapters/generic.ts+++ b/src/core/install/adapters/generic.ts@@ -67,7 +67,7 @@ function renderYaml(payload: McpPayload): string {function yamlScalar(s: string): string {// Quote when needed (contains special chars or starts/ends with whitespace).- if (/[:#\[\]\{\}\,&\*!\|>\'"%@`]/.test(s) || /^\s|\s$/.test(s) || /^[\-?!]/.test(s)) {+ if (/[:#[\]{},&*!|>'"%@`]/.test(s) || /^\s|\s$/.test(s) || /^[-?!]/.test(s)) {return JSON.stringify(s);}return s;@@ -102,18 +102,11 @@ export const genericAdapter: InstallAdapter = {preview: "render OSB MCP payload to stdout or --out <path>",},],- postNotes: [- "Copy the printed snippet into your runtime's MCP config manually.",- ],+ postNotes: ["Copy the printed snippet into your runtime's MCP config manually."],};},- apply(- _plan: InstallPlan,- payload: McpPayload,- env: InstallEnv,- opts: ApplyOpts,- ): ApplyResult {+ apply(_plan: InstallPlan, payload: McpPayload, env: InstallEnv, opts: ApplyOpts): ApplyResult {const format = opts.format ?? "json";const text = format === "yaml" ? renderYaml(payload) : renderJson(payload);const explicitStdout = opts.outPath === "-";@@ -148,10 +141,7 @@ export const genericAdapter: InstallAdapter = {skipped.push([p, "generic: file left in place; remove manually if no longer needed"]);}} else {- skipped.push([- "(no recorded path)",- "generic: never wrote to disk; nothing to do",- ]);+ skipped.push(["(no recorded path)", "generic: never wrote to disk; nothing to do"]);}if (!opts.dryRun) removeEntry(env.vault, TARGET);return { target: TARGET, removed_keys: [], removed_paths: [], skipped };@@ -171,7 +161,9 @@ export const genericAdapter: InstallAdapter = {return {target: TARGET,status: "ok",- details: [`generic: payload written to ${m.owned_paths[0]} (runtime wiring is operator-managed)`],+ details: [+ `generic: payload written to ${m.owned_paths[0]} (runtime wiring is operator-managed)`,+ ],fix_hint: null,};},diff --git a/src/core/install/adapters/kiro.ts b/src/core/install/adapters/kiro.tsindex 230b9aee..e0f499e0 100644--- a/src/core/install/adapters/kiro.ts+++ b/src/core/install/adapters/kiro.ts@@ -21,9 +21,7 @@ export const kiroAdapter = createJsonMcpAdapter({target: "kiro",label: "kiro",resolveConfigPath: configPath,- postNotes: [- "Restart kiro to load the new MCP servers.",- ],+ postNotes: ["Restart kiro to load the new MCP servers."],});defaultRegistry.register(kiroAdapter);diff --git a/src/core/install/adapters/opencode.ts b/src/core/install/adapters/opencode.tsindex 1257812a..5ab89aa6 100644--- a/src/core/install/adapters/opencode.ts+++ b/src/core/install/adapters/opencode.ts@@ -24,9 +24,7 @@ export const opencodeAdapter = createJsonMcpAdapter({target: "opencode",label: "opencode",resolveConfigPath: configPath,- postNotes: [- "Restart opencode to load the new MCP servers.",- ],+ postNotes: ["Restart opencode to load the new MCP servers."],});defaultRegistry.register(opencodeAdapter);diff --git a/src/core/install/adapters/pi.ts b/src/core/install/adapters/pi.tsindex 31b98c86..906a54b1 100644--- a/src/core/install/adapters/pi.ts+++ b/src/core/install/adapters/pi.ts@@ -119,18 +119,11 @@ export const piAdapter: InstallAdapter = {preview: `symlink ${target} → <plugin>/skills/brain-memory`,},],- postNotes: [- "Pi reads skills from its own skills directory; no MCP registration needed.",- ],+ postNotes: ["Pi reads skills from its own skills directory; no MCP registration needed."],};},- apply(- _plan: InstallPlan,- _payload: McpPayload,- env: InstallEnv,- opts: ApplyOpts,- ): ApplyResult {+ apply(_plan: InstallPlan, _payload: McpPayload, env: InstallEnv, opts: ApplyOpts): ApplyResult {const target = resolveTargetPath(env, opts);const source = resolveSourcePath(opts);diff --git a/src/core/install/managed-block.ts b/src/core/install/managed-block.tsindex a3ff1598..de7939d0 100644--- a/src/core/install/managed-block.ts+++ b/src/core/install/managed-block.ts@@ -102,11 +102,7 @@ function join(lines: ReadonlyArray<string>, ending: LineEnding): string {* Insert or replace the managed block. Idempotent: re-applying with* the same body yields byte-equal output.*/-export function insertManagedBlock(- current: string,- body: string,- opts: BlockOpts = {},-): string {+export function insertManagedBlock(current: string, body: string, opts: BlockOpts = {}): string {const resolved = resolve(opts);const ending = detectLineEnding(current);const lines = splitLines(current);@@ -129,13 +125,7 @@ export function insertManagedBlock(// Append; ensure one blank line separating user content from our block// when the prior content didn't already end empty.const sep = lines.length > 0 && lines[lines.length - 1] !== "" ? [""] : [];- nextLines = [- ...lines,- ...sep,- resolved.begin,- ...bodyLines,- resolved.end,- ];+ nextLines = [...lines, ...sep, resolved.begin, ...bodyLines, resolved.end];}return join(nextLines, { newline: ending.newline, trailing: true });diff --git a/src/core/install/manifest.ts b/src/core/install/manifest.tsindex 607ffc42..d0996546 100644--- a/src/core/install/manifest.ts+++ b/src/core/install/manifest.ts@@ -48,8 +48,8 @@ export function readManifest(vault: string): Manifest {parsed = JSON.parse(raw);} catch (e) {throw new Error(- `install manifest is corrupted JSON: ${path}\n` +- `Original error: ${(e as Error).message}`,+ `install manifest is corrupted JSON: ${path}\n` + `Original error: ${(e as Error).message}`,+ { cause: e },);}if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {diff --git a/src/core/install/payload-equals.ts b/src/core/install/payload-equals.tsindex b99d6cb4..bce191d2 100644--- a/src/core/install/payload-equals.ts+++ b/src/core/install/payload-equals.ts@@ -24,8 +24,8 @@ export function payloadKeyEquals(if (expected.env) {if (!env || typeof env !== "object") return false;const e = env as Record<string, unknown>;- const expectedKeys = Object.keys(expected.env).sort();- const actualKeys = Object.keys(e).sort();+ const expectedKeys = Object.keys(expected.env).toSorted();+ const actualKeys = Object.keys(e).toSorted();if (expectedKeys.length !== actualKeys.length) return false;for (const k of expectedKeys) {if (e[k] !== expected.env[k]) return false;diff --git a/src/core/install/registry.ts b/src/core/install/registry.tsindex d1fe7c16..ca898372 100644--- a/src/core/install/registry.ts+++ b/src/core/install/registry.ts@@ -7,11 +7,7 @@* leak across cases.*/-import type {- DetectResult,- InstallAdapter,- InstallEnv,-} from "./types.ts";+import type { DetectResult, InstallAdapter, InstallEnv } from "./types.ts";export interface Registry {register(adapter: InstallAdapter): void;diff --git a/src/core/install/update.ts b/src/core/install/update.tsindex 0f75af8f..10f98dea 100644--- a/src/core/install/update.ts+++ b/src/core/install/update.ts@@ -36,7 +36,7 @@ export interface UpdateOptions {function sortedReplacer(_key: string, value: unknown): unknown {if (value && typeof value === "object" && !Array.isArray(value)) {const out: Record<string, unknown> = {};- for (const key of Object.keys(value as Record<string, unknown>).sort()) {+ for (const key of Object.keys(value as Record<string, unknown>).toSorted()) {out[key] = (value as Record<string, unknown>)[key];}return out;diff --git a/src/core/partner/codegraph.ts b/src/core/partner/codegraph.tsindex de15f74f..beb48be5 100644--- a/src/core/partner/codegraph.ts+++ b/src/core/partner/codegraph.ts@@ -136,9 +136,7 @@ export interface CodegraphCheckOptions {function defaultWhichCodegraph(): string | null {if (typeof Bun !== "undefined" && typeof (Bun as { which?: unknown }).which === "function") {- const found = (Bun as unknown as { which: (cmd: string) => string | null }).which(- "codegraph",- );+ const found = (Bun as unknown as { which: (cmd: string) => string | null }).which("codegraph");return found ?? null;}return null;diff --git a/src/core/pay-memory/approval.ts b/src/core/pay-memory/approval.tsindex 1f9099de..31f3b496 100644--- a/src/core/pay-memory/approval.ts+++ b/src/core/pay-memory/approval.ts@@ -30,13 +30,7 @@ import { join } from "node:path";import type { FrontmatterMap } from "../types.ts";import { parseFrontmatter, slugify, writeFrontmatterAtomic } from "../vault.ts";-import {- formatCode,- frontmatterStr,- nowIsoZ,- NOT_PROVIDED,- putIfPresent,-} from "./_md.ts";+import { formatCode, frontmatterStr, nowIsoZ, NOT_PROVIDED, putIfPresent } from "./_md.ts";import {ensureInsideVault,isoDateNow,@@ -405,8 +399,7 @@ async function transitionRequest(policyDecision: {status: parseDecisionStatus(frontmatterStr(loaded.metadata["policy_status"])),allowed: frontmatterStr(loaded.metadata["policy_status"]) === "allowed",- approvalRequired:- frontmatterStr(loaded.metadata["policy_status"]) === "approval_required",+ approvalRequired: frontmatterStr(loaded.metadata["policy_status"]) === "approval_required",reasons: [],rule: frontmatterStr(loaded.metadata["policy_rule"]) || null,hasPolicy: Boolean(frontmatterStr(loaded.metadata["policy_status"])),@@ -419,11 +412,7 @@ async function transitionRequest(}}-function defaultRequestSlug(- input: PendingRequestInput,- date: string,- time: string,-): string {+function defaultRequestSlug(input: PendingRequestInput, date: string, time: string): string {const tail = input.service.split("/").pop() ?? input.service;return slugify(`req-${date}-${time.replace(":", "")}-${tail}-${input.reason}`);}@@ -463,12 +452,7 @@ function renderRequestBody(input: PendingRequestInput, decision: PolicyDecision)} else {lines.push(NOT_PROVIDED);}- lines.push(- "",- "## Policy check",- "",- `Status: \`${decision.status}\``,- );+ lines.push("", "## Policy check", "", `Status: \`${decision.status}\``);if (decision.rule) lines.push(`Rule fired: \`${decision.rule}\``);if (decision.reasons.length > 0) {lines.push("", "Reasons:", "");@@ -492,12 +476,7 @@ function renderRequestBody(input: PendingRequestInput, decision: PolicyDecision)}function parseStatus(raw: string): RequestStatus {- if (- raw === "pending" ||- raw === "approved" ||- raw === "rejected" ||- raw === "consumed"- ) {+ if (raw === "pending" || raw === "approved" || raw === "rejected" || raw === "consumed") {return raw;}// Reject malformed / hand-edited status values rather than silentlydiff --git a/src/core/pay-memory/asset.ts b/src/core/pay-memory/asset.tsindex 8534d777..983652b7 100644--- a/src/core/pay-memory/asset.ts+++ b/src/core/pay-memory/asset.ts@@ -8,11 +8,7 @@import type { FrontmatterMap } from "../types.ts";import { slugify, writeFrontmatterAtomic } from "../vault.ts";-import {- nowIsoZ,- NOT_PROVIDED,- wikiLink,-} from "./_md.ts";+import { nowIsoZ, NOT_PROVIDED, wikiLink } from "./_md.ts";import { assetPath, ensureInsideVault, vaultRelative } from "./paths.ts";import type { AssetInput, AssetOutput } from "./types.ts";@@ -94,11 +90,6 @@ function renderAssetBody(input: AssetInput): string {}lines.push("");- lines.push(- "## Notes",- "",- "Generated through a paid API call recorded in the linked receipt.",- );+ lines.push("## Notes", "", "Generated through a paid API call recorded in the linked receipt.");return lines.join("\n");}-diff --git a/src/core/pay-memory/digest.ts b/src/core/pay-memory/digest.tsindex 4eccb38c..c99ab813 100644--- a/src/core/pay-memory/digest.ts+++ b/src/core/pay-memory/digest.ts@@ -106,9 +106,7 @@ export function renderPaymentDigestTelegram(return SILENT_TOKEN;}- const lines: string[] = [- `💳 Оплачено сервисов: **${digest.services}**`,- ];+ const lines: string[] = [`💳 Оплачено сервисов: **${digest.services}**`];if (digest.totalAmount !== null) {const amount = formatAmount(digest.totalAmount);const cur = digest.currency ?? "?";diff --git a/src/core/pay-memory/index.ts b/src/core/pay-memory/index.tsindex 1f26fd07..ce6dc26a 100644--- a/src/core/pay-memory/index.ts+++ b/src/core/pay-memory/index.ts@@ -26,22 +26,14 @@ export type { PayMemoryDirs } from "./paths.ts";export { redactRawOutput, SECRET_KEYS } from "./redactor.ts";-export {- DEFAULT_POLICY_TEMPLATE,- writePolicyIfMissing,- readPolicy,-} from "./policy.ts";+export { DEFAULT_POLICY_TEMPLATE, writePolicyIfMissing, readPolicy } from "./policy.ts";export type { WritePolicyOptions, WritePolicyResult } from "./policy.ts";export { writeReceipt, RECEIPT_FRONTMATTER_TYPE } from "./receipt.ts";export { writeAsset, ASSET_FRONTMATTER_TYPE } from "./asset.ts";-export {- aggregateReceipts,- writeReport,- REPORT_FRONTMATTER_TYPE,-} from "./report.ts";+export { aggregateReceipts, writeReport, REPORT_FRONTMATTER_TYPE } from "./report.ts";export {POLICY_SCHEMA_VERSION,@@ -57,11 +49,7 @@ export type {PolicyDecisionStatus,} from "./policy-rules.ts";-export {- buildPaymentDigest,- renderPaymentDigestTelegram,- DIGEST_SILENT_TOKEN,-} from "./digest.ts";+export { buildPaymentDigest, renderPaymentDigestTelegram, DIGEST_SILENT_TOKEN } from "./digest.ts";export type { PaymentDigest, BuildPaymentDigestOptions, RenderDigestOptions } from "./digest.ts";export {diff --git a/src/core/pay-memory/paths.ts b/src/core/pay-memory/paths.tsindex 61a471de..7ddf465a 100644--- a/src/core/pay-memory/paths.ts+++ b/src/core/pay-memory/paths.ts@@ -17,10 +17,7 @@ import { join, posix } from "node:path";import { BRAIN_ROOT_REL } from "../brain/paths.ts";-export {- ensureInsideVault,- vaultRelative,-} from "../path-safety.ts";+export { ensureInsideVault, vaultRelative } from "../path-safety.ts";// ----- Canonical Pay Memory path constants ----------------------------------//@@ -40,14 +37,8 @@ export const PAY_MEMORY_REPORTS_REL = posix.join(PAY_MEMORY_ROOT_REL, "reports")export const PAY_MEMORY_PENDING_REL = posix.join(PAY_MEMORY_ROOT_REL, "_pending");/** Spending-policy file paths (vault-relative). */-export const PAY_MEMORY_SPENDING_MD_REL = posix.join(- PAY_MEMORY_POLICIES_REL,- "spending.md",-);-export const PAY_MEMORY_SPENDING_JSON_REL = posix.join(- PAY_MEMORY_POLICIES_REL,- "spending.json",-);+export const PAY_MEMORY_SPENDING_MD_REL = posix.join(PAY_MEMORY_POLICIES_REL, "spending.md");+export const PAY_MEMORY_SPENDING_JSON_REL = posix.join(PAY_MEMORY_POLICIES_REL, "spending.json");const ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;const HHMM_RE = /^(\d{2}):(\d{2})$/;@@ -96,8 +87,7 @@ export function reportPath(vault: string, slug: string): string {// rejects any path whose final component matches them — even with an// extension. We reject these here so the same vault can be cloned to a// Windows host without surprise EINVALs at write time.-const WINDOWS_RESERVED_BASENAME_RE =- /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;+const WINDOWS_RESERVED_BASENAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;/*** Reject slugs that could escape the intended Pay Memory subdirectory or@@ -118,9 +108,7 @@ export function validateSlug(slug: string): string {throw new Error(`slug must not contain '..' traversal: ${slug}`);}if (/[. ]$/.test(trimmed)) {- throw new Error(- `slug must not end with '.' or whitespace (Windows-incompatible): ${slug}`,- );+ throw new Error(`slug must not end with '.' or whitespace (Windows-incompatible): ${slug}`);}if (WINDOWS_RESERVED_BASENAME_RE.test(trimmed)) {throw new Error(`slug uses a Windows-reserved filename: ${slug}`);@@ -157,9 +145,7 @@ export function validateIsoTime(value: string): string {const hour = parseInt(m[1]!, 10);const minute = parseInt(m[2]!, 10);if (hour > 23 || minute > 59) {- throw new Error(- `payment time out of range: ${value} (hour must be 0-23, minute 0-59)`,- );+ throw new Error(`payment time out of range: ${value} (hour must be 0-23, minute 0-59)`);}return value;}@@ -251,4 +237,3 @@ function tzOffsetMinutes(instantMs: number, tz: string): number {);return Math.round((localUtcMs - instantMs) / 60_000);}-diff --git a/src/core/pay-memory/policy-rules.ts b/src/core/pay-memory/policy-rules.tsindex 37e07d9e..a0587cd1 100644--- a/src/core/pay-memory/policy-rules.ts+++ b/src/core/pay-memory/policy-rules.ts@@ -85,17 +85,17 @@ export function loadPolicyRules(vault: string): PolicyRules | null {// ENOENT into a `null` return. Other I/O errors (EACCES, EISDIR …)// are surfaced so the user sees the real cause.if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return null;- throw new Error(- `failed to read ${target}: ${(err as Error).message ?? String(err)}`,- );+ throw new Error(`failed to read ${target}: ${(err as Error).message ?? String(err)}`, {+ cause: err,+ });}let parsed: unknown;try {parsed = JSON.parse(text);} catch (err) {- throw new Error(- `${target} is not valid JSON: ${(err as Error).message ?? String(err)}`,- );+ throw new Error(`${target} is not valid JSON: ${(err as Error).message ?? String(err)}`, {+ cause: err,+ });}return validatePolicyRules(parsed, target);}@@ -155,9 +155,7 @@ function validatePolicyRules(value: unknown, source: string): PolicyRules {const map: Record<string, number> = {};for (const [k, n] of Object.entries(v as Record<string, unknown>)) {if (typeof n !== "number" || !Number.isInteger(n) || n < 0) {- throw new Error(- `${source}: max_per_category.${k} must be a non-negative integer`,- );+ throw new Error(`${source}: max_per_category.${k} must be a non-negative integer`);}map[k] = n;}@@ -198,9 +196,7 @@ export function evaluatePolicy(// 1. Allowlist on `service`.if (rules.allowed_services && rules.allowed_services.length > 0) {if (!rules.allowed_services.includes(request.service)) {- reasons.push(- `service ${JSON.stringify(request.service)} is not in allowed_services`,- );+ reasons.push(`service ${JSON.stringify(request.service)} is not in allowed_services`);denyRule ??= "allowed_services";}}@@ -239,11 +235,7 @@ export function evaluatePolicy(}// 3. Single-call cap.- if (- rules.max_single_call !== undefined &&- amount !== null &&- amount > rules.max_single_call- ) {+ if (rules.max_single_call !== undefined && amount !== null && amount > rules.max_single_call) {reasons.push(`expected amount ${amount} ${reqCurrency} exceeds max_single_call ` +`${rules.max_single_call} ${policyCurrency}`,@@ -292,8 +284,8 @@ export function evaluatePolicy(const status: PolicyDecisionStatus = denyRule? "denied": approvalRule- ? "approval_required"- : "allowed";+ ? "approval_required"+ : "allowed";return {status,@@ -311,10 +303,7 @@ export function evaluatePolicy(* Top-level convenience: load the policy, aggregate today's receipts to* compute spend/count context, and evaluate.*/-export function checkPolicy(- vault: string,- request: PolicyCheckRequest,-): PolicyDecision {+export function checkPolicy(vault: string, request: PolicyCheckRequest): PolicyDecision {const rules = loadPolicyRules(vault);const date = validateIsoDate(request.date ?? isoDateNow(request.tz));const summaries = aggregateReceipts(vault, date);diff --git a/src/core/pay-memory/policy.ts b/src/core/pay-memory/policy.tsindex 87132b1e..9e86df56 100644--- a/src/core/pay-memory/policy.ts+++ b/src/core/pay-memory/policy.ts@@ -11,10 +11,7 @@import { existsSync, mkdirSync, readFileSync } from "node:fs";import { dirname } from "node:path";-import {- atomicCreateFileSyncExclusive,- atomicWriteFileSync,-} from "../fs-atomic.ts";+import { atomicCreateFileSyncExclusive, atomicWriteFileSync } from "../fs-atomic.ts";import { PAY_MEMORY_ROOT_REL, policyPath } from "./paths.ts";export const DEFAULT_POLICY_TEMPLATE = `# Agent Spending Policydiff --git a/src/core/pay-memory/receipt.ts b/src/core/pay-memory/receipt.tsindex d46cd406..6c9f683c 100644--- a/src/core/pay-memory/receipt.ts+++ b/src/core/pay-memory/receipt.ts@@ -160,17 +160,10 @@ function renderPolicySection(input: ReceiptInput): string[] {if (input.policyCheckedAt?.trim()) {out.push("", `Policy checked at: \`${input.policyCheckedAt.trim()}\``);}- if (- input.approvalRequestId?.trim() ||- input.approvalStatus?.trim() ||- input.approvedBy?.trim()- ) {+ if (input.approvalRequestId?.trim() || input.approvalStatus?.trim() || input.approvedBy?.trim()) {out.push("", "Approval:");if (input.approvalRequestId?.trim()) {- out.push(- "",- `Request: [[${PAY_MEMORY_PENDING_REL}/${input.approvalRequestId.trim()}]]`,- );+ out.push("", `Request: [[${PAY_MEMORY_PENDING_REL}/${input.approvalRequestId.trim()}]]`);}if (input.approvalStatus?.trim()) {out.push(`Status: \`${input.approvalStatus.trim()}\``);@@ -272,4 +265,3 @@ function renderReceiptBody(input: ReceiptInput): string {);return lines.join("\n");}-diff --git a/src/core/pay-memory/redactor.ts b/src/core/pay-memory/redactor.tsindex 421d84f2..04712812 100644--- a/src/core/pay-memory/redactor.ts+++ b/src/core/pay-memory/redactor.ts@@ -9,8 +9,4 @@* `src/core/redactor.ts` directly.*/-export {- MAX_REDACTOR_INPUT,- SECRET_KEYS,- redactRawOutput,-} from "../redactor.ts";+export { MAX_REDACTOR_INPUT, SECRET_KEYS, redactRawOutput } from "../redactor.ts";diff --git a/src/core/pay-memory/report.ts b/src/core/pay-memory/report.tsindex 457ac5a7..6a8d8b94 100644--- a/src/core/pay-memory/report.ts+++ b/src/core/pay-memory/report.ts@@ -17,12 +17,7 @@ import { join } from "node:path";import type { FrontmatterMap, FrontmatterValue } from "../types.ts";import { parseFrontmatter, slugify, writeFrontmatterAtomic } from "../vault.ts";-import {- frontmatterStr,- nowIsoZ,- NOT_PROVIDED,- stripMarkdownExt,-} from "./_md.ts";+import { frontmatterStr, nowIsoZ, NOT_PROVIDED, stripMarkdownExt } from "./_md.ts";import {ensureInsideVault,paymentsDateDir,@@ -164,4 +159,3 @@ function renderReportBody(}return lines.join("\n");}-diff --git a/src/core/pay-memory/types.ts b/src/core/pay-memory/types.tsindex 6cf4079e..4ff3c5a0 100644--- a/src/core/pay-memory/types.ts+++ b/src/core/pay-memory/types.ts@@ -7,11 +7,7 @@* delegate, so the helpers stay pure and easy to test.*/-export type ReceiptPolicyStatus =- | "allowed"- | "approval_required"- | "denied"- | "not_checked";+export type ReceiptPolicyStatus = "allowed" | "approval_required" | "denied" | "not_checked";export interface ReceiptInput {readonly agent: string;@@ -55,12 +51,7 @@ export interface ReceiptInput {readonly policyReasons?: ReadonlyArray<string> | null;readonly policyCheckedAt?: string | null;readonly approvalRequestId?: string | null;- readonly approvalStatus?:- | "pending"- | "approved"- | "rejected"- | "consumed"- | null;+ readonly approvalStatus?: "pending" | "approved" | "rejected" | "consumed" | null;readonly approvedBy?: string | null;readonly approvedAt?: string | null;}diff --git a/src/core/redactor.ts b/src/core/redactor.tsindex 3b057608..f77b4eca 100644--- a/src/core/redactor.ts+++ b/src/core/redactor.ts@@ -91,9 +91,7 @@ export function redactRawOutput(text: string): string {if (!text) return text;let out =- text.length > MAX_REDACTOR_INPUT- ? text.slice(0, MAX_REDACTOR_INPUT) + TRUNCATION_MARKER- : text;+ text.length > MAX_REDACTOR_INPUT ? text.slice(0, MAX_REDACTOR_INPUT) + TRUNCATION_MARKER : text;// Order matters: handle JSON entries first so the COLON_VALUE_RE// doesn't also match inside JSON pairs (the negative-lookbehind@@ -174,10 +172,7 @@ export interface NormaliseTextFieldOptions {* Trim is left to the caller — the writer for a given field decides* whether leading / trailing whitespace is significant.*/-export function normaliseTextField(- value: unknown,- opts: NormaliseTextFieldOptions,-): string {+export function normaliseTextField(value: unknown, opts: NormaliseTextFieldOptions): string {if (typeof value !== "string") return "";let s = value.replace(FORBIDDEN_C0_RE, "");s = s.replace(UNICODE_LINE_SEP_RE, "\n");@@ -200,10 +195,7 @@ export function normaliseTextField(* writers (`writeSignal`, `appendApplyEvidence`) to keep field* sanitisation consistent across surfaces.*/-export function sanitiseTextField(- value: unknown,- opts: NormaliseTextFieldOptions,-): string {+export function sanitiseTextField(value: unknown, opts: NormaliseTextFieldOptions): string {if (typeof value !== "string") return "";return normaliseTextField(redactRawOutput(value), opts);}diff --git a/src/core/search/chunker.ts b/src/core/search/chunker.tsindex 24359348..91fd1a8c 100644--- a/src/core/search/chunker.ts+++ b/src/core/search/chunker.ts@@ -116,9 +116,11 @@ function splitLines(text: string): Line[] {return out;}-function extractFrontmatter(- lines: ReadonlyArray<Line>,-): { block: Block | null; remaining: ReadonlyArray<Line>; warnings: string[] } {+function extractFrontmatter(lines: ReadonlyArray<Line>): {+ block: Block | null;+ remaining: ReadonlyArray<Line>;+ warnings: string[];+} {if (lines.length === 0 || lines[0]!.text.trim() !== "---") {return { block: null, remaining: lines, warnings: [] };}@@ -217,7 +219,7 @@ function splitIntoBlocks(lines: ReadonlyArray<Line>): { blocks: Block[]; warning}if (FENCE_RE.test(text)) {const { end } = readCodeBlock(remaining, i);- blocks.push(makeBlock("code", [...remaining.slice(i, end + 1)]));+ blocks.push(makeBlock("code", remaining.slice(i, end + 1)));i = end + 1;continue;}@@ -228,18 +230,18 @@ function splitIntoBlocks(lines: ReadonlyArray<Line>): { blocks: Block[]; warning}if (LIST_ITEM_RE.test(text)) {const { end } = readList(remaining, i);- blocks.push(makeBlock("list", [...remaining.slice(i, end + 1)]));+ blocks.push(makeBlock("list", remaining.slice(i, end + 1)));i = end + 1;continue;}if (isTableStart(remaining, i)) {const { end } = readTable(remaining, i);- blocks.push(makeBlock("table", [...remaining.slice(i, end + 1)]));+ blocks.push(makeBlock("table", remaining.slice(i, end + 1)));i = end + 1;continue;}const { end } = readParagraph(remaining, i);- blocks.push(makeBlock("paragraph", [...remaining.slice(i, end + 1)]));+ blocks.push(makeBlock("paragraph", remaining.slice(i, end + 1)));i = end + 1;}@@ -273,17 +275,10 @@ function takeOverlap(prev: DraftChunk, overlapTokens: number): Line[] {return tail;}-function emitChunk(- index: number,- overlap: ReadonlyArray<Line>,- draft: DraftChunk,-): MarkdownChunk {+function emitChunk(index: number, overlap: ReadonlyArray<Line>, draft: DraftChunk): MarkdownChunk {const bodyLines: Line[] = [];for (const b of draft.blocks) for (const l of b.lines) bodyLines.push(l);- const allText = [- ...overlap.map((l) => l.text),- ...bodyLines.map((l) => l.text),- ].join("\n");+ const allText = [...overlap.map((l) => l.text), ...bodyLines.map((l) => l.text)].join("\n");const tokenCount = countTokens(allText);return Object.freeze({chunkIndex: index,@@ -375,7 +370,10 @@ function packBlocks(function stripQuotes(s: string): string {const t = s.trim();- if (t.length >= 2 && ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'")))) {+ if (+ t.length >= 2 &&+ ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'")))+ ) {return t.slice(1, -1);}return t;@@ -477,9 +475,7 @@ export function chunkMarkdown(const chunks =headings.length === 0? packed- : packed.map((c) =>- Object.freeze({ ...c, headingPath: headingPathAt(headings, c.endLine) }),- );+ : packed.map((c) => Object.freeze({ ...c, headingPath: headingPathAt(headings, c.endLine) }));return Object.freeze({title,diff --git a/src/core/search/embeddings/openai-compat.ts b/src/core/search/embeddings/openai-compat.tsindex 406bdb2a..2a07c010 100644--- a/src/core/search/embeddings/openai-compat.ts+++ b/src/core/search/embeddings/openai-compat.ts@@ -24,7 +24,10 @@ import type { EmbeddingProvider } from "./provider.ts";const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504]);interface OpenAiEmbeddingResponse {- readonly data: ReadonlyArray<{ readonly embedding: ReadonlyArray<number>; readonly index: number }>;+ readonly data: ReadonlyArray<{+ readonly embedding: ReadonlyArray<number>;+ readonly index: number;+ }>;readonly model?: string;}@@ -81,7 +84,10 @@ interface ResolvedHttp {function resolveHttp(config: ResolvedEmbeddingConfig): ResolvedHttp {if (!config.baseUrl) {- throw new SearchError("INVALID_INPUT", "embedding_base_url is required when semantic is enabled");+ throw new SearchError(+ "INVALID_INPUT",+ "embedding_base_url is required when semantic is enabled",+ );}if (!config.model) {throw new SearchError("INVALID_INPUT", "embedding_model is required when semantic is enabled");@@ -140,9 +146,12 @@ export class OpenAICompatProvider implements EmbeddingProvider {await sem.acquire();try {if (cancel.signal.aborted) return;- const vectors = await this.embedBatchWithRetry(batch.map((b) => b.text), {- parentSignal: cancel.signal,- });+ const vectors = await this.embedBatchWithRetry(+ batch.map((b) => b.text),+ {+ parentSignal: cancel.signal,+ },+ );for (let i = 0; i < vectors.length; i++) {out[batch[i]!.originalIndex] = vectors[i]!;}@@ -199,7 +208,9 @@ export class OpenAICompatProvider implements EmbeddingProvider {if (!err.retriable || attempt >= maxAttempts) throw err.error;lastError = err.error;this.retriesSeen++;- const wait = jittered(this.backoffMs[attempt - 1] ?? (this.backoffMs[this.backoffMs.length - 1] ?? 4000));+ const wait = jittered(+ this.backoffMs[attempt - 1] ?? this.backoffMs[this.backoffMs.length - 1] ?? 4000,+ );await sleep(wait);}}@@ -216,10 +227,7 @@ export class OpenAICompatProvider implements EmbeddingProvider {return n;}- private async embedBatchOnce(- texts: string[],- parentSignal?: AbortSignal,- ): Promise<number[][]> {+ private async embedBatchOnce(texts: string[], parentSignal?: AbortSignal): Promise<number[][]> {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), this.config.timeoutMs);const onParentAbort = () => controller.abort();@@ -286,7 +294,10 @@ export class OpenAICompatProvider implements EmbeddingProvider {const ordered: number[][] = new Array(texts.length);for (const item of json.data) {if (typeof item.index !== "number" || item.index < 0 || item.index >= texts.length) {- throw new SearchError("EMBEDDING_PROVIDER_HTTP", `embedding response: out-of-range index ${item.index}`);+ throw new SearchError(+ "EMBEDDING_PROVIDER_HTTP",+ `embedding response: out-of-range index ${item.index}`,+ );}if (!Array.isArray(item.embedding)) {throw new SearchError(@@ -307,7 +318,10 @@ export class OpenAICompatProvider implements EmbeddingProvider {}for (let i = 0; i < ordered.length; i++) {if (!Array.isArray(ordered[i])) {- throw new SearchError("EMBEDDING_PROVIDER_HTTP", `embedding response: missing vector for index ${i}`);+ throw new SearchError(+ "EMBEDDING_PROVIDER_HTTP",+ `embedding response: missing vector for index ${i}`,+ );}}return ordered;diff --git a/src/core/search/embeddings/provider.ts b/src/core/search/embeddings/provider.tsindex 10f519d9..10e10810 100644--- a/src/core/search/embeddings/provider.ts+++ b/src/core/search/embeddings/provider.ts@@ -34,7 +34,8 @@ export function makeProvider(config: ResolvedEmbeddingConfig): EmbeddingProvider}if (config.provider === "openai-compat") {// eslint-disable-next-line @typescript-eslint/no-require-imports- const { OpenAICompatProvider } = require("./openai-compat.ts") as typeof import("./openai-compat.ts");+ const { OpenAICompatProvider } =+ require("./openai-compat.ts") as typeof import("./openai-compat.ts");return new OpenAICompatProvider(config);}throw new SearchError(diff --git a/src/core/search/entities.ts b/src/core/search/entities.tsindex 1a4ebf74..a2cd823e 100644--- a/src/core/search/entities.ts+++ b/src/core/search/entities.ts@@ -32,7 +32,10 @@ const ALLCAPS_OR_DIGIT_RE = /[\p{Lu}\p{N}]*\p{Lu}[\p{Lu}\p{N}]+|\p{L}+\p{N}+|\p{/** Lowercase + collapse internal whitespace. */function normalize(raw: string): string {- return raw.trim().replace(/[ \t]+/g, " ").toLowerCase();+ return raw+ .trim()+ .replace(/[ \t]+/g, " ")+ .toLowerCase();}/** Last path segment without a markdown extension, for wikilink targets. */diff --git a/src/core/search/fts.ts b/src/core/search/fts.tsindex 09e47439..66ca79e0 100644--- a/src/core/search/fts.ts+++ b/src/core/search/fts.ts@@ -26,11 +26,7 @@ export interface RunFtsOptions {readonly pathPrefix?: string | null;}-export function runFtsQuery(- store: Store,- rawQuery: string,- opts: RunFtsOptions,-): KeywordHit[] {+export function runFtsQuery(store: Store, rawQuery: string, opts: RunFtsOptions): KeywordHit[] {const match = buildFtsMatch(rawQuery);if (match === "") return [];return store.keywordTopK(match, opts);diff --git a/src/core/search/index.ts b/src/core/search/index.tsindex a14630d5..e55edbe7 100644--- a/src/core/search/index.ts+++ b/src/core/search/index.ts@@ -97,11 +97,7 @@ function parseBool(raw: string | null, fallback: boolean, fieldName: string): bo}}-function validateIntegerRange(- n: number,- fieldName: string,- range?: IntegerRange,-): void {+function validateIntegerRange(n: number, fieldName: string, range?: IntegerRange): void {if (range?.min !== undefined && n < range.min) {throw new SearchError("INVALID_INPUT", `${fieldName} must be >= ${range.min}, got ${n}`);}@@ -297,7 +293,7 @@ export function resolveSearchConfig(opts: {const merged = Object.freeze({...base,...opts.overrides,- semantic: Object.freeze({ ...base.semantic, ...(opts.overrides.semantic ?? {}) }),+ semantic: Object.freeze({ ...base.semantic, ...opts.overrides.semantic }),ignoreRules: opts.overrides.ignoreRules? Object.freeze([...opts.overrides.ignoreRules]): base.ignoreRules,diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.tsindex 56e85989..82618e3a 100644--- a/src/core/search/indexer.ts+++ b/src/core/search/indexer.ts@@ -269,18 +269,18 @@ async function populateEmbeddings("set search_semantic_enabled=true and embedding_* keys to compute embeddings",);}- if (!store.vecLoaded()) {- throw new SearchError(- "VEC_EXTENSION_UNAVAILABLE",- "sqlite-vec did not load; cannot store embeddings",- );- }if (!config.semantic.apiKey) {throw new SearchError("EMBEDDING_KEY_MISSING","embedding_api_key is required when computing embeddings",);}+ if (!store.vecLoaded()) {+ throw new SearchError(+ "VEC_EXTENSION_UNAVAILABLE",+ "sqlite-vec did not load; cannot store embeddings",+ );+ }const pending = store.findChunksWithoutEmbeddings();if (pending.length === 0) return;@@ -308,7 +308,10 @@ async function populateEmbeddings(// Lock in the auto-detected dimension on the very first batch.const dim = provider.dimension ?? vectors[0]?.length ?? 0;if (dim <= 0) {- throw new SearchError("EMBEDDING_DIMENSION_MISMATCH", "provider returned vectors of zero length");+ throw new SearchError(+ "EMBEDDING_DIMENSION_MISMATCH",+ "provider returned vectors of zero length",+ );}store.ensureEmbeddingModel(model, dim);for (let j = 0; j < batch.length; j++) {@@ -603,4 +606,3 @@ function buildRecommendations(input: BuildRecommendationsInput): string[] {return recs;}-diff --git a/src/core/search/links.ts b/src/core/search/links.tsindex eaea43a3..3acfebf0 100644--- a/src/core/search/links.ts+++ b/src/core/search/links.ts@@ -28,7 +28,7 @@ const WIKILINK_RE = /\[\[([^\]\n|]+?)(?:\|([^\]\n]+))?\]\]/g;const MD_LINK_RE = /(?<!!)\[([^\]\n]*)\]\(([^)\n\s]+)(?:\s+"[^"\n]*")?\)/g;// Obsidian-style tag: #word where word starts with a letter/_ and may contain// letters, digits, dashes, underscores, and '/' for hierarchy.-const TAG_RE = /(^|[^\w\/])#([A-Za-z_][\w\-/]*)/g;+const TAG_RE = /(^|[^\w/])#([A-Za-z_][\w\-/]*)/g;function stripCode(text: string): string {let out = text.replace(CODE_FENCE_RE, "\n");@@ -37,7 +37,7 @@ function stripCode(text: string): string {}function isUrl(target: string): boolean {- return /^[a-z][a-z0-9+.\-]*:/i.test(target) || target.startsWith("//");+ return /^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith("//");}function isMailto(target: string): boolean {diff --git a/src/core/search/property-filter.ts b/src/core/search/property-filter.tsindex 97139050..d47d2f34 100644--- a/src/core/search/property-filter.ts+++ b/src/core/search/property-filter.ts@@ -18,9 +18,7 @@*/export type PropertyFilterMap = ReadonlyMap<string, ReadonlyArray<string>>;-export type PropertyFrontmatterReader = (- path: string,-) => Record<string, unknown> | null;+export type PropertyFrontmatterReader = (path: string) => Record<string, unknown> | null;export function filterByProperties<T extends { readonly path: string }>(results: ReadonlyArray<T>,@@ -38,10 +36,7 @@ export function filterByProperties<T extends { readonly path: string }>(return Object.freeze(out) as ReadonlyArray<T>;}-function matchesAll(- fm: Record<string, unknown>,- filters: PropertyFilterMap,-): boolean {+function matchesAll(fm: Record<string, unknown>, filters: PropertyFilterMap): boolean {for (const [key, accepted] of filters) {if (!Object.prototype.hasOwnProperty.call(fm, key)) return false;const value = fm[key];@@ -51,10 +46,7 @@ function matchesAll(return true;}-function matchesAny(- value: unknown,- accepted: ReadonlyArray<string>,-): boolean {+function matchesAny(value: unknown, accepted: ReadonlyArray<string>): boolean {const acceptedSet = new Set(accepted);if (Array.isArray(value)) {for (const v of value) {diff --git a/src/core/search/ranker.ts b/src/core/search/ranker.tsindex 161b5fe1..f159a3f6 100644--- a/src/core/search/ranker.ts+++ b/src/core/search/ranker.ts@@ -9,11 +9,7 @@* testable and substitutable.*/-import {- PAGE_TIER_DEFAULT,- tierWeight,- type PageTier,-} from "../brain/page-meta/tier.ts";+import { PAGE_TIER_DEFAULT, tierWeight, type PageTier } from "../brain/page-meta/tier.ts";import type { KeywordHit, SemanticHit, HydratedChunk } from "./store.ts";import type { BrainSearchResult } from "./types.ts";diff --git a/src/core/search/schema.ts b/src/core/search/schema.tsindex 8e6b1646..9be3acaf 100644--- a/src/core/search/schema.ts+++ b/src/core/search/schema.ts@@ -177,9 +177,7 @@ export const MIGRATIONS: ReadonlyArray<Migration> = Object.freeze([version: 2,up(db) {db.exec(DDL_V2_ENTITIES);- const cols = db- .query<{ name: string }, []>("PRAGMA table_info(chunks)")- .all();+ const cols = db.query<{ name: string }, []>("PRAGMA table_info(chunks)").all();if (!cols.some((c) => c.name === "heading_path")) {db.exec("ALTER TABLE chunks ADD COLUMN heading_path TEXT NOT NULL DEFAULT ''");}diff --git a/src/core/search/search.ts b/src/core/search/search.tsindex 8a44d247..d2a7c4dd 100644--- a/src/core/search/search.ts+++ b/src/core/search/search.ts@@ -35,10 +35,7 @@ interface SemanticPolicy {readonly wantSemantic: boolean;}-function resolveSemanticPolicy(- config: ResolvedSearchConfig,- opts: SearchOptions,-): SemanticPolicy {+function resolveSemanticPolicy(config: ResolvedSearchConfig, opts: SearchOptions): SemanticPolicy {if (opts.keywordOnly === true) {return { explicit: true, wantSemantic: false };}@@ -112,9 +109,7 @@ export async function search(// query names no entities or the index predates the entity store.const queryEntities = extractEntities(query);const entityMatchByChunk =- queryEntities.length > 0- ? store.chunkEntityMatches(idsList, queryEntities)- : undefined;+ queryEntities.length > 0 ? store.chunkEntityMatches(idsList, queryEntities) : undefined;// When a property filter is active, overfetch the ranked// candidates so the post-filter result set still has a chance@@ -122,8 +117,7 @@ export async function search(// top-`limit` ranked hits can lose all their property-matching// candidates to the filter and surface zero results even when// matches exist deeper in the rank.- const hasPropertyFilter =- opts.properties !== undefined && opts.properties.size > 0;+ const hasPropertyFilter = opts.properties !== undefined && opts.properties.size > 0;// MMR and traversal both need a candidate pool wider than `limit`:// MMR diversifies from it, and traversal seeds expansion from it (a@@ -288,6 +282,12 @@ async function runSemanticPhase(): Promise<SemanticPhaseOutcome> {const warnings: string[] = [];+ const counts = store.counts();+ if (counts.embeddings === 0) {+ warnings.push("no compatible embeddings; run: o2b search index --embeddings");+ return { attempted: false, hits: [], warnings };+ }+if (!store.vecLoaded()) {if (opts.explicit) {throw new SearchError(@@ -312,13 +312,6 @@ async function runSemanticPhase(return { attempted: false, hits: [], warnings };}- // Data-state check: are there embeddings to search against at all?- const counts = store.counts();- if (counts.embeddings === 0) {- warnings.push("no compatible embeddings; run: o2b search index --embeddings");- return { attempted: false, hits: [], warnings };- }-let queryVec: number[];try {const provider = makeProvider(config.semantic);@@ -331,10 +324,7 @@ async function runSemanticPhase(// so callers always see a typed code rather than a bare Error.if (e instanceof SearchError) throw e;const msg = e instanceof Error ? e.message : String(e);- throw new SearchError(- "EMBEDDING_PROVIDER_HTTP",- `embedding provider failure: ${msg}`,- );+ throw new SearchError("EMBEDDING_PROVIDER_HTTP", `embedding provider failure: ${msg}`);}const msg = e instanceof Error ? e.message : String(e);warnings.push(`embedding provider unavailable: ${msg}`);@@ -346,6 +336,9 @@ async function runSemanticPhase(return { attempted: false, hits: [], warnings };}- const hits = store.semanticTopK(queryVec, { limit: opts.limit, pathPrefix: opts.pathPrefix });+ const hits = store.semanticTopK(queryVec, {+ limit: opts.limit,+ pathPrefix: opts.pathPrefix,+ });return { attempted: true, hits, warnings };}diff --git a/src/core/search/store.ts b/src/core/search/store.tsindex 3d238f18..841d01cb 100644--- a/src/core/search/store.ts+++ b/src/core/search/store.ts@@ -284,10 +284,7 @@ export class Store {});} catch (e) {const msg = e instanceof Error ? e.message : String(e);- throw new SearchError(- "INDEX_LOCKED",- `another writer holds the search index lock: ${msg}`,- );+ throw new SearchError("INDEX_LOCKED", `another writer holds the search index lock: ${msg}`);}let db: Database;@@ -401,7 +398,10 @@ export class Store {const now = nowIso();// SQLite RETURNING on INSERT...ON CONFLICT works in 3.35+; bun:sqlite ships modern SQLite.const row = this.db- .query<{ id: number }, [string, string | null, string, number, number, string, string, string]>(+ .query<+ { id: number },+ [string, string | null, string, number, number, string, string, string]+ >("INSERT INTO documents(path, title, content_hash, mtime, size, created_at, updated_at, indexed_at) " +"VALUES (?, ?, ?, ?, ?, ?, ?, ?) " +"ON CONFLICT(path) DO UPDATE SET " +@@ -609,19 +609,20 @@ export class Store {const buf = vecToBuffer(vector);let vecRowid: number;if (existing) {- this.db.run("UPDATE chunk_vec SET embedding = ? WHERE rowid = ?", [buf, existing.vec_rowid]);+ this.db.run("UPDATE chunk_vec SET embedding = ? WHERE rowid = ?", [+ buf,+ existing.vec_rowid,+ ]);vecRowid = existing.vec_rowid;} else {this.db.run("INSERT INTO chunk_vec(embedding) VALUES (?)", [buf]);- const row = this.db- .query<{ id: number }, []>("SELECT last_insert_rowid() AS id")- .get();+ const row = this.db.query<{ id: number }, []>("SELECT last_insert_rowid() AS id").get();if (!row) throw new SearchError("INDEX_UNREADABLE", "chunk_vec insert returned no rowid");vecRowid = row.id;- this.db.run(- "INSERT INTO chunk_vec_map(chunk_id, vec_rowid) VALUES (?, ?)",- [chunkId, vecRowid],- );+ this.db.run("INSERT INTO chunk_vec_map(chunk_id, vec_rowid) VALUES (?, ?)", [+ chunkId,+ vecRowid,+ ]);}const now = nowIso();this.db.run(@@ -826,7 +827,11 @@ export class Store {"ORDER BY v.distance ASC",).all(buf, limit);- return rows.map((r) => ({ chunkId: r.chunk_id, documentId: r.document_id, distance: r.distance }));+ return rows.map((r) => ({+ chunkId: r.chunk_id,+ documentId: r.document_id,+ distance: r.distance,+ }));}hydrateChunks(chunkIds: ReadonlyArray<number>): Map<number, HydratedChunk> {@@ -878,10 +883,7 @@ export class Store {if (candidateChunkIds.length === 0) return out;const placeholders = candidateChunkIds.map(() => "?").join(",");const rows = this.db- .query<- { chunk_id: number; source_document_id: number },- number[]- >(+ .query<{ chunk_id: number; source_document_id: number }, number[]>("SELECT c.id AS chunk_id, l.source_document_id " +`FROM chunks c JOIN links l ON l.target_document_id = c.document_id ` +`WHERE c.id IN (${placeholders}) AND l.link_type IN ('wikilink','markdown_link') ` +@@ -910,10 +912,7 @@ export class Store {if (sourceDocumentIds.length === 0) return out;const placeholders = sourceDocumentIds.map(() => "?").join(",");const rows = this.db- .query<- { source_document_id: number; target_document_id: number },- number[]- >(+ .query<{ source_document_id: number; target_document_id: number }, number[]>("SELECT DISTINCT l.source_document_id, l.target_document_id " +`FROM links l ` +`WHERE l.source_document_id IN (${placeholders}) ` +@@ -1042,10 +1041,7 @@ export class Store {if (candidateChunkIds.length === 0) return out;const placeholders = candidateChunkIds.map(() => "?").join(",");const rows = this.db- .query<- { chunk_id: number; tag: string },- number[]- >(+ .query<{ chunk_id: number; tag: string }, number[]>("SELECT c.id AS chunk_id, l.link_text AS tag " +`FROM chunks c JOIN links l ON l.source_document_id = c.document_id ` +`WHERE c.id IN (${placeholders}) AND l.link_type = 'tag' AND l.link_text IS NOT NULL`,@@ -1111,6 +1107,8 @@ export class Store {/** Escape hatch for status queries that don't fit the typed API. */rawQuery<T>(sql: string, params: ReadonlyArray<string | number | null> = []): T[] {- return this.db.query<T, (string | number | null)[]>(sql).all(...(params as (string | number | null)[]));+ return this.db+ .query<T, (string | number | null)[]>(sql)+ .all(...(params as (string | number | null)[]));}}diff --git a/src/core/search/traversal.ts b/src/core/search/traversal.tsindex 1de9175a..0cf1006b 100644--- a/src/core/search/traversal.ts+++ b/src/core/search/traversal.ts@@ -135,10 +135,7 @@ export function expandByTraversal(// skipped target (dup / weaker path / missing chunk) does not burn// the per-hit budget and starve a valid later target.expanded++;- added.set(- targetId,- makeLinkResult(doc, hopScore, node.hop + 1, node.fromPath),- );+ added.set(targetId, makeLinkResult(doc, hopScore, node.hop + 1, node.fromPath));queue.push({documentId: targetId,hop: node.hop + 1,diff --git a/src/core/validate.ts b/src/core/validate.tsindex c76f3ab7..d4de0d88 100644--- a/src/core/validate.ts+++ b/src/core/validate.ts@@ -43,11 +43,7 @@ export function parseInteger(* 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 {+export function parseFloat01(raw: string | null, default_: number, fieldName: string): number {if (raw === null) return default_;if (raw.trim() === "") {throw new Error(`${fieldName} must be a number in [0, 1], got empty string`);@@ -59,15 +55,38 @@ export function parseFloat01(return n;}+export type OptionalFiniteNumberInputError = "finite-number" | "number-or-numeric-string";++export interface OptionalFiniteNumberInputResult {+ readonly value: number | null;+ readonly error: OptionalFiniteNumberInputError | null;+}++/**+ * Parse an optional finite number accepted at external API boundaries.+ * `null`, `undefined`, and blank strings mean "not provided".+ */+export function parseOptionalFiniteNumberInput(raw: unknown): OptionalFiniteNumberInputResult {+ if (raw === undefined || raw === null) return { value: null, error: null };+ if (typeof raw === "number") {+ if (!Number.isFinite(raw)) return { value: null, error: "finite-number" };+ return { value: raw, error: null };+ }+ if (typeof raw === "string") {+ const trimmed = raw.trim();+ if (trimmed === "") return { value: null, error: null };+ const parsed = Number(trimmed);+ if (!Number.isFinite(parsed)) return { value: null, error: "number-or-numeric-string" };+ return { value: parsed, error: null };+ }+ return { value: null, error: "number-or-numeric-string" };+}+/*** 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 {+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;diff --git a/src/core/vault-scope/index.ts b/src/core/vault-scope/index.tsindex 73f53c81..ef112e2b 100644--- a/src/core/vault-scope/index.ts+++ b/src/core/vault-scope/index.ts@@ -13,13 +13,7 @@* a `VaultScope` with classified rules.*/-import {- existsSync,- readdirSync,- realpathSync,- statSync,- type Dirent,-} from "node:fs";+import { existsSync, readdirSync, realpathSync, statSync, type Dirent } from "node:fs";import { join, sep } from "node:path";import { loadBrainConfig } from "../brain/policy.ts";@@ -31,11 +25,7 @@ import {type VaultIgnoreRule,} from "./defaults.ts";-export {- DEFAULT_VAULT_IGNORE_PATHS,- classifyVaultIgnoreRule,- type VaultIgnoreRule,-};+export { DEFAULT_VAULT_IGNORE_PATHS, classifyVaultIgnoreRule, type VaultIgnoreRule };// ----- matchIgnore ---------------------------------------------------------@@ -62,10 +52,7 @@ const NEGATIVE_MATCH: IgnoreMatch = Object.freeze({* normalisation. Callers (`walkVaultScope`, `inspectPath`) prepare* the input.*/-export function matchIgnore(- relPath: string,- rules: ReadonlyArray<VaultIgnoreRule>,-): IgnoreMatch {+export function matchIgnore(relPath: string, rules: ReadonlyArray<VaultIgnoreRule>): IgnoreMatch {if (relPath === "" || rules.length === 0) return NEGATIVE_MATCH;const segments = relPath.split("/").filter((s) => s.length > 0);let prefix = "";@@ -97,19 +84,13 @@ export interface VaultScope {readonly source: "_brain.yaml" | "defaults";}-function buildScope(- paths: ReadonlyArray<string>,- source: VaultScope["source"],-): VaultScope {+function buildScope(paths: ReadonlyArray<string>, source: VaultScope["source"]): VaultScope {const ignorePaths = Object.freeze([...paths]);const rules = Object.freeze(ignorePaths.map(classifyVaultIgnoreRule));return Object.freeze({ ignorePaths, rules, source });}-const DEFAULT_SCOPE: VaultScope = buildScope(- DEFAULT_VAULT_IGNORE_PATHS,- "defaults",-);+const DEFAULT_SCOPE: VaultScope = buildScope(DEFAULT_VAULT_IGNORE_PATHS, "defaults");/*** Read `<vault>/Brain/_brain.yaml` and project the `vault.ignore_paths`@@ -157,7 +138,11 @@ export interface VaultScopeWalk {*/export function walkVaultScope(vault: string, scope: VaultScope): VaultScopeWalk {const vaultReal = (() => {- try { return realpathSync(vault); } catch { return vault; }+ try {+ return realpathSync(vault);+ } catch {+ return vault;+ }})();const excludedDirs: ExcludedEntry[] = [];const excludedFiles: ExcludedEntry[] = [];@@ -175,12 +160,14 @@ export function walkVaultScope(vault: string, scope: VaultScope): VaultScopeWalkentries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));for (const entry of entries) {const abs = join(absDir, entry.name);- const rel = relDir === ""- ? toPosix(entry.name)- : `${relDir}/${toPosix(entry.name)}`;+ const rel = relDir === "" ? toPosix(entry.name) : `${relDir}/${toPosix(entry.name)}`;const isLinkHint = entry.isSymbolicLink();let stat;- try { stat = statSync(abs); } catch { continue; }+ try {+ stat = statSync(abs);+ } catch {+ continue;+ }if (stat.isDirectory()) {const m = matchIgnore(rel, scope.rules);if (m.excluded && m.rule) {@@ -188,7 +175,11 @@ export function walkVaultScope(vault: string, scope: VaultScope): VaultScopeWalkcontinue;}let real: string;- try { real = realpathSync(abs); } catch { continue; }+ try {+ real = realpathSync(abs);+ } catch {+ continue;+ }if (real !== vaultReal && !real.startsWith(vaultReal + sep)) continue;if (seenDirs.has(real)) continue;seenDirs.add(real);@@ -204,7 +195,11 @@ export function walkVaultScope(vault: string, scope: VaultScope): VaultScopeWalk// the kind of drift v0.10.9 is meant to eliminate.if (isLinkHint) {let real: string;- try { real = realpathSync(abs); } catch { continue; }+ try {+ real = realpathSync(abs);+ } catch {+ continue;+ }if (real !== vaultReal && !real.startsWith(vaultReal + sep)) continue;}const m = matchIgnore(rel, scope.rules);@@ -255,11 +250,7 @@ export interface InspectResult {* the filesystem only to set `existsOnDisk`; the rule decision is* determined by `scope.rules` alone.*/-export function inspectPath(- relPath: string,- scope: VaultScope,- vault: string,-): InspectResult {+export function inspectPath(relPath: string, scope: VaultScope, vault: string): InspectResult {// Segment-based normalisation: tolerate leading `./`, trailing// slashes, double slashes. Throw on any `..` component — silently// resolving them would let the caller probe outside the vault.@@ -267,9 +258,7 @@ export function inspectPath(for (const raw of toPosix(relPath).split("/")) {if (raw === "" || raw === ".") continue;if (raw === "..") {- throw new Error(- `relPath must not traverse outside the vault: ${relPath}`,- );+ throw new Error(`relPath must not traverse outside the vault: ${relPath}`);}segments.push(raw);}diff --git a/src/core/vault.ts b/src/core/vault.tsindex a213c858..b4a7198c 100644--- a/src/core/vault.ts+++ b/src/core/vault.ts@@ -10,10 +10,7 @@import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";import { dirname, join, relative } from "node:path";-import {- atomicCreateFileSyncExclusive,- atomicWriteFileSync,-} from "./fs-atomic.ts";+import { atomicCreateFileSyncExclusive, atomicWriteFileSync } from "./fs-atomic.ts";import { stem } from "./fs-utils.ts";import type { FrontmatterMap, FrontmatterValue, VaultPage } from "./types.ts";@@ -26,9 +23,26 @@ const SLUG_INVALID_RE = /[^a-z0-9]+/g;const SLUG_MAX_LEN = 64;const MEDIA_EXTENSIONS = new Set([- ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".tiff", ".avif",- ".mp4", ".webm", ".ogv", ".mov", ".mkv", ".avi",- ".mp3", ".wav", ".ogg", ".flac", ".m4a",+ ".png",+ ".jpg",+ ".jpeg",+ ".gif",+ ".svg",+ ".webp",+ ".bmp",+ ".tiff",+ ".avif",+ ".mp4",+ ".webm",+ ".ogv",+ ".mov",+ ".mkv",+ ".avi",+ ".mp3",+ ".wav",+ ".ogg",+ ".flac",+ ".m4a",".pdf",]);@@ -162,16 +176,13 @@ export function writeFrontmatterAtomic(try {atomicCreateFileSyncExclusive(path, contents);} catch (err) {- if (- opts.existsErrorKind &&- (err as NodeJS.ErrnoException)?.code === "EEXIST"- ) {+ if (opts.existsErrorKind && (err as NodeJS.ErrnoException)?.code === "EEXIST") {const rel = opts.vaultForRelativePath? path.startsWith(opts.vaultForRelativePath + "/")? path.slice(opts.vaultForRelativePath.length + 1): path: path;- throw new Error(`${opts.existsErrorKind} already exists: ${rel}`);+ throw new Error(`${opts.existsErrorKind} already exists: ${rel}`, { cause: err });}throw err;}@@ -373,12 +384,7 @@ function splitInlineArray(inner: string): string[] {function formatYamlScalar(value: FrontmatterValue): string {const text = typeof value === "string" ? value : String(value);- if (- text &&- PLAIN_SCALAR_RE.test(text) &&- !text.includes(": ") &&- !text.includes(" #")- ) {+ if (text && PLAIN_SCALAR_RE.test(text) && !text.includes(": ") && !text.includes(" #")) {return text;}const escaped = textdiff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex 4a24200b..9c4a7a2e 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -38,14 +38,8 @@ import { isAbsolute, relative, resolve } from "node:path";import { existsSync, readFileSync } from "node:fs";import { resolveAgentName } from "../core/config.ts";-import {- brainActivePath,- brainDirs,-} from "../core/brain/paths.ts";-import {- regenerateActive,- type RegenerateActiveResult,-} from "../core/brain/active.ts";+import { brainActivePath, brainDirs } from "../core/brain/paths.ts";+import { regenerateActive, type RegenerateActiveResult } from "../core/brain/active.ts";import { parseFrontmatter } from "../core/vault.ts";import {appendApplyEvidence,@@ -64,17 +58,11 @@ import { findStaleEntries } from "../core/brain/temporal/stale-watch.ts";import { buildDailyBrief } from "../core/brain/temporal/daily-brief.ts";import { buildWeeklySynthesis } from "../core/brain/temporal/weekly-brief.ts";import { loadTemporalConfigSafe } from "../core/brain/policy.ts";-import {- isBrainLogEventKind,- type BrainLogEventKind,-} from "../core/brain/types.ts";+import { isBrainLogEventKind, type BrainLogEventKind } from "../core/brain/types.ts";import { packContext } from "../core/brain/context-pack.ts";import { collectMaintenanceActions } from "../core/brain/maintenance/collect.ts";import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";-import {- renderDigest,- type DigestFormat,-} from "../core/brain/digest.ts";+import { renderDigest, type DigestFormat } from "../core/brain/digest.ts";import { dream } from "../core/brain/dream.ts";import { buildReviewCandidates } from "../core/brain/review-candidates.ts";import { runDoctor } from "../core/brain/doctor.ts";@@ -135,8 +123,15 @@ async function toolBrainFeedback(if (!validated.ok) {throw new MCPError(INVALID_PARAMS, validated.reason);}- const { topic, signal: signalRaw, principle, scope, raw, source, force_confirmed } =- validated.value;+ const {+ topic,+ signal: signalRaw,+ principle,+ scope,+ raw,+ source,+ force_confirmed,+ } = validated.value;const forceConfirmed = force_confirmed ?? false;// Agent-fallback stays MCP-side: validator just hands back the user-@@ -179,9 +174,7 @@ async function toolBrainFeedback(},});} catch (err) {- process.stderr.write(- `warning: append feedback log failed: ${(err as Error).message}\n`,- );+ process.stderr.write(`warning: append feedback log failed: ${(err as Error).message}\n`);}let prefResult: { path: string; id: string } | null = null;@@ -255,9 +248,7 @@ async function toolBrainDream(const dryRun = coerceBool(args, "dry_run");const nowDate = coerceIsoDate(args, "now");const agentArg = coerceStr(args, "agent", false);- const agent =- normalizeAgentArgument(agentArg)- ?? resolveAgentName(ctx.configPath ?? undefined);+ const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);const summary = dream(ctx.vault, {dryRun,@@ -294,9 +285,7 @@ async function toolBrainDream(snapshot_path: summary.snapshot_path? vaultRelativeSafe(ctx.vault, summary.snapshot_path): null,- log_path: summary.log_path- ? vaultRelativeSafe(ctx.vault, summary.log_path)- : null,+ log_path: summary.log_path ? vaultRelativeSafe(ctx.vault, summary.log_path) : null,};}@@ -307,9 +296,7 @@ async function toolBrainReviewCandidates(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const nowDate = coerceIsoDate(args, "now");- const report = buildReviewCandidates(ctx.vault, {- ...(nowDate ? { now: nowDate } : {}),- });+ const report = buildReviewCandidates(ctx.vault, nowDate ? { now: nowDate } : {});return {would_create: [...report.would_create],would_promote: [...report.would_promote],@@ -361,8 +348,7 @@ async function toolBrainApplyEvidence(const agentArg = coerceStr(args, "agent", false);const note = coerceStr(args, "note", false);- const agent =- normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);+ const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);const input: AppendApplyEvidenceInput = {pref_id: prefId,@@ -393,7 +379,7 @@ async function toolBrainApplyEvidence(// Re-throw as a non-MCPError so `server.handleToolsCall` packs it// into a `toolError` envelope (isError: true, single-text content).// This matches the pay-memory "pending request not found" pattern.- throw new Error(exc.message);+ throw new Error(exc.message, { cause: exc });}throw exc;}@@ -468,9 +454,7 @@ const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {* rewrite; the on-disk body is* returned verbatim.*/-async function toolBrainContext(- ctx: ServerContext,-): Promise<Record<string, unknown>> {+async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unknown>> {const dirs = brainDirs(ctx.vault);const activePath = brainActivePath(ctx.vault);if (!existsSync(dirs.brain)) {@@ -607,7 +591,7 @@ async function toolBrainQuery(};} catch (exc) {if (exc instanceof BrainNotFoundError) {- throw new Error(exc.message);+ throw new Error(exc.message, { cause: exc });}throw exc;}@@ -673,8 +657,7 @@ async function toolBrainDoctor(// Decide a single ok flag — `strict` only changes the CLI exit code,// so we mirror that semantic here: with `strict`, warnings demote ok// to false. Errors always do.- const ok =- result.errors.length === 0 && (!strict || result.warnings.length === 0);+ const ok = result.errors.length === 0 && (!strict || result.warnings.length === 0);return {format,@@ -709,16 +692,12 @@ async function toolBrainDoctor(// surface, so it stays absent here). `instruction_file_warnings`// surfaces vault-root instruction files exceeding the configured// ceiling.- ...(result.trust_verdict !== undefined- ? { trust_verdict: result.trust_verdict }- : {}),- instruction_file_warnings: (result.instruction_file_warnings ?? []).map(- (w) => ({- path: w.path,- lines: w.lines,- ceiling: w.ceiling,- }),- ),+ ...(result.trust_verdict !== undefined ? { trust_verdict: result.trust_verdict } : {}),+ instruction_file_warnings: (result.instruction_file_warnings ?? []).map((w) => ({+ path: w.path,+ lines: w.lines,+ ceiling: w.ceiling,+ })),};}@@ -772,9 +751,7 @@ function serializeSignal(s: BrainSignal): Record<string, unknown> {};}-function serializePreference(- p: BrainPreference | BrainRetired,-): Record<string, unknown> {+function serializePreference(p: BrainPreference | BrainRetired): Record<string, unknown> {if (p.kind === "brain-retired") {return {kind: p.kind,@@ -919,10 +896,7 @@ async function toolBrainOperatorSummary(} else if (typeof includeDreamRaw === "boolean") {includeDream = includeDreamRaw;} else {- throw new MCPError(- INVALID_PARAMS,- "brain_operator_summary: include_dream must be a boolean",- );+ throw new MCPError(INVALID_PARAMS, "brain_operator_summary: include_dream must be a boolean");}let dreamSummary;@@ -974,10 +948,7 @@ async function toolBrainUnlinkedMentions(): Promise<Record<string, unknown>> {const idRaw = args["id"];if (typeof idRaw !== "string" || idRaw.trim().length === 0) {- throw new MCPError(- INVALID_PARAMS,- "brain_unlinked_mentions: id must be a non-empty string",- );+ throw new MCPError(INVALID_PARAMS, "brain_unlinked_mentions: id must be a non-empty string");}const targetId = normaliseWikilinkTarget(idRaw);// Limit coercion mirrors the v0.10.16 `brain_operator_summary`@@ -1018,9 +989,7 @@ async function toolBrainUnlinkedMentions();}}- const mentions = findUnlinkedMentions(ctx.vault, targetId, {- ...(limit !== undefined ? { limit } : {}),- });+ const mentions = findUnlinkedMentions(ctx.vault, targetId, limit !== undefined ? { limit } : {});return {vault_path: ctx.vault,target_id: targetId,@@ -1045,10 +1014,7 @@ async function toolBrainConceptSynthesis(): Promise<Record<string, unknown>> {const idRaw = args["id"];if (typeof idRaw !== "string" || idRaw.trim().length === 0) {- throw new MCPError(- INVALID_PARAMS,- "brain_concept_synthesis: id must be a non-empty string",- );+ throw new MCPError(INVALID_PARAMS, "brain_concept_synthesis: id must be a non-empty string");}const includeUnlinkedRaw = args["include_unlinked"];let includeUnlinked = false;@@ -1089,10 +1055,7 @@ async function toolBrainMocAudit(): Promise<Record<string, unknown>> {const idRaw = args["id"];if (typeof idRaw !== "string" || idRaw.trim().length === 0) {- throw new MCPError(- INVALID_PARAMS,- "brain_moc_audit: id must be a non-empty string",- );+ throw new MCPError(INVALID_PARAMS, "brain_moc_audit: id must be a non-empty string");}const targetId = normaliseWikilinkTarget(idRaw);try {@@ -1104,9 +1067,7 @@ async function toolBrainMocAudit(well_covered: report.wellCovered,fragile: report.fragile,candidate_missing: report.candidateMissing,- ...(report.suggestedNext- ? { suggested_next: report.suggestedNext }- : {}),+ ...(report.suggestedNext ? { suggested_next: report.suggestedNext } : {}),};} catch (err) {if (err instanceof MocAuditError) {@@ -1118,42 +1079,26 @@ async function toolBrainMocAudit(// ----- Temporal subsystem MCP wrappers (v0.10.18) ---------------------------function coercePositiveInteger(- tool: string,- field: string,- raw: unknown,-): number | undefined {+function coercePositiveInteger(tool: string, field: string, raw: unknown): number | undefined {if (raw === undefined || raw === null) return undefined;if (typeof raw === "number") {if (!Number.isInteger(raw) || raw < 1) {- throw new MCPError(- INVALID_PARAMS,- `${tool}: ${field} must be a positive integer`,- );+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);}return raw;}if (typeof raw === "string") {const trimmed = raw.trim();if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {- throw new MCPError(- INVALID_PARAMS,- `${tool}: ${field} must be a positive integer`,- );+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);}const parsed = Number.parseInt(trimmed, 10);if (parsed < 1) {- throw new MCPError(- INVALID_PARAMS,- `${tool}: ${field} must be a positive integer`,- );+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);}return parsed;}- throw new MCPError(- INVALID_PARAMS,- `${tool}: ${field} must be a positive integer`,- );+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);}const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;@@ -1189,19 +1134,13 @@ function coerceIsoTimestampOrDate(return v;}-function coerceEventKind(- tool: string,- raw: unknown,-): BrainLogEventKind | undefined {+function coerceEventKind(tool: string, raw: unknown): BrainLogEventKind | undefined {if (raw === undefined || raw === null) return undefined;if (typeof raw !== "string") {throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a string`);}if (!isBrainLogEventKind(raw)) {- throw new MCPError(- INVALID_PARAMS,- `${tool}: kind must be a known BrainLogEventKind`,- );+ throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a known BrainLogEventKind`);}return raw;}@@ -1318,12 +1257,7 @@ async function toolBrainDailyBrief(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const dateRaw = args["date"];- const dateCoerced = coerceIsoTimestampOrDate(- "brain_daily_brief",- "date",- dateRaw,- "date-only",- );+ const dateCoerced = coerceIsoTimestampOrDate("brain_daily_brief", "date", dateRaw, "date-only");const date = dateCoerced ?? new Date().toISOString().slice(0, 10);const cfg = loadTemporalConfigSafe(ctx.vault);const index = buildTimelineIndex(ctx.vault, {});@@ -1388,10 +1322,7 @@ async function toolBrainContextPack(const maxRaw = args["max_tokens"];const maxTokens = typeof maxRaw === "number" ? maxRaw : Number.parseInt(String(maxRaw ?? ""), 10);if (!Number.isFinite(maxTokens) || maxTokens <= 0) {- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack: max_tokens must be a positive integer",- );+ throw new MCPError(INVALID_PARAMS, "brain_context_pack: max_tokens must be a positive integer");}const query = typeof args["query"] === "string" ? (args["query"] as string) : undefined;const report = packContext(ctx.vault, {@@ -1427,8 +1358,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {topic: {type: "string",- description:- "Stable kebab-slug for the rule, e.g. `no-internal-abbrev`.",+ description: "Stable kebab-slug for the rule, e.g. `no-internal-abbrev`.",},signal: {type: "string",@@ -1438,8 +1368,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},principle: {type: "string",- description:- "One-line, agent-readable formulation of the rule (imperative voice).",+ description: "One-line, agent-readable formulation of the rule (imperative voice).",},scope: {type: "string",@@ -1449,18 +1378,15 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([source: {type: "array",items: { type: "string" },- description:- "Optional wikilinks to the artifacts or notes that triggered the signal.",+ description: "Optional wikilinks to the artifacts or notes that triggered the signal.",},agent: {type: "string",- description:- "Optional agent identity override; defaults to the server-resolved name.",+ description: "Optional agent identity override; defaults to the server-resolved name.",},raw: {type: "string",- description:- "Optional free-form raw quote (rendered under `## Raw` in the signal file).",+ description: "Optional free-form raw quote (rendered under `## Raw` in the signal file).",},force_confirmed: {type: "boolean",@@ -1482,8 +1408,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {dry_run: {type: "boolean",- description:- "When true, compute the plan without writing any files.",+ description: "When true, compute the plan without writing any files.",},now: {type: "string",@@ -1526,8 +1451,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {pref_id: {type: "string",- description:- "Preference id (`pref-<slug>` or bare `<slug>`).",+ description: "Preference id (`pref-<slug>` or bare `<slug>`).",},artifact: {type: "string",@@ -1542,8 +1466,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},agent: {type: "string",- description:- "Optional agent identity override; defaults to the server-resolved name.",+ description: "Optional agent identity override; defaults to the server-resolved name.",},note: {type: "string",@@ -1569,8 +1492,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},agent: {type: "string",- description:- "Optional agent identity override; defaults to the server-resolved name.",+ description: "Optional agent identity override; defaults to the server-resolved name.",},},required: ["text"],@@ -1598,13 +1520,11 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {since: {type: "string",- description:- "Inclusive lower bound (ISO-8601). Defaults to `until - 24h`.",+ description: "Inclusive lower bound (ISO-8601). Defaults to `until - 24h`.",},until: {type: "string",- description:- "Exclusive upper bound (ISO-8601). Defaults to `now`.",+ description: "Exclusive upper bound (ISO-8601). Defaults to `now`.",},format: {type: "string",@@ -1630,13 +1550,11 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},topic: {type: "string",- description:- "Topic slug to aggregate signals + active/retired preference + log events.",+ description: "Topic slug to aggregate signals + active/retired preference + log events.",},since: {type: "string",- description:- "ISO-8601 timestamp; returns every Brain log event with timestamp >= since.",+ description: "ISO-8601 timestamp; returns every Brain log event with timestamp >= since.",},format: {type: "string",@@ -1658,8 +1576,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {strict: {type: "boolean",- description:- "When true, warnings demote `ok` to false (CLI exit-code parity).",+ description: "When true, warnings demote `ok` to false (CLI exit-code parity).",},format: {type: "string",@@ -1722,8 +1639,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},query: {type: "string",- description:- "Optional case/Unicode-insensitive substring filter on topic + principle.",+ description: "Optional case/Unicode-insensitive substring filter on topic + principle.",},},required: ["max_tokens"],@@ -1764,8 +1680,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {id: {type: "string",- description:- "Target id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",+ description: "Target id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",},include_unlinked: {type: "boolean",@@ -1787,8 +1702,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {id: {type: "string",- description:- "Hub note id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",+ description: "Hub note id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",},},required: ["id"],@@ -1805,8 +1719,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {pref_id: {type: "string",- description:- "Restrict to events for this preference / retired / signal id.",+ description: "Restrict to events for this preference / retired / signal id.",},topic: {type: "string",@@ -1814,24 +1727,20 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},kind: {type: "string",- description:- "Restrict to events of this BrainLogEventKind (e.g. `apply-evidence`).",+ description: "Restrict to events of this BrainLogEventKind (e.g. `apply-evidence`).",},since: {type: "string",- description:- "Inclusive lower bound (ISO date or ISO timestamp). Defaults to epoch.",+ description: "Inclusive lower bound (ISO date or ISO timestamp). Defaults to epoch.",},until: {type: "string",- description:- "Exclusive upper bound (ISO date or ISO timestamp). Defaults to now.",+ description: "Exclusive upper bound (ISO date or ISO timestamp). Defaults to now.",},limit: {type: "integer",minimum: 1,- description:- "Maximum number of events to return after filtering. Omit for no cap.",+ description: "Maximum number of events to return after filtering. Omit for no cap.",},},additionalProperties: false,@@ -1847,8 +1756,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {pref_id: {type: "string",- description:- "Target preference id (e.g. `pref-foo`). Mutually exclusive with `topic`.",+ description: "Target preference id (e.g. `pref-foo`). Mutually exclusive with `topic`.",},topic: {type: "string",@@ -1880,8 +1788,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {date: {type: "string",- description:- "ISO date (`YYYY-MM-DD`) the brief targets. Defaults to today UTC.",+ description: "ISO date (`YYYY-MM-DD`) the brief targets. Defaults to today UTC.",},},additionalProperties: false,diff --git a/src/mcp/coerce.ts b/src/mcp/coerce.tsindex 612fd8a8..36f6bd00 100644--- a/src/mcp/coerce.ts+++ b/src/mcp/coerce.ts@@ -7,6 +7,7 @@*/import { INVALID_PARAMS, MCPError } from "./protocol.ts";+import { parseOptionalFiniteNumberInput } from "../core/validate.ts";export function coerceStr(args: Record<string, unknown>,@@ -19,7 +20,8 @@ export function coerceStr(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`);+ if (typeof value !== "string")+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a string`);return value;}@@ -49,38 +51,34 @@ export function coerceInt(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;+export function coerceOptionalNumber(args: Record<string, unknown>, key: string): number | null {+ const parsed = parseOptionalFiniteNumberInput(args[key]);+ if (parsed.error === "finite-number") {+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a finite number`);}- 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;+ if (parsed.error === "number-or-numeric-string") {+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a number or numeric string`);}- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a number or numeric string`);+ return parsed.value;}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`);+ 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 {+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`);+ if (typeof v !== "boolean")+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a boolean`);return v;}@@ -92,8 +90,10 @@ export function coerceStringOptional(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`);+ 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;}@@ -101,7 +101,8 @@ export function coerceIsoDate(args: Record<string, unknown>, key: string): Dateconst 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`);+ if (Number.isNaN(d.getTime()))+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a valid ISO-8601 timestamp`);return d;}diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex 587dff8b..9ea6fac9 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -57,8 +57,8 @@ export function buildInstructions(opts: BuildInstructionsOpts | string): string"Always log under this identity; do not invent or change the name.\n\n" +"Brain tools are the agent-facing writable surface (design doc §9).\n" +" - brain_feedback — call once per taste signal the user (or a " +- "teammate agent) expresses: corrections (\"don't do X\"), stated " +- "preferences (\"use A instead of B\"), or process rules that " ++ 'teammate agent) expresses: corrections ("don\'t do X"), stated ' ++ 'preferences ("use A instead of B"), or process rules that ' +"should outlast the current turn. With `force_confirmed: true` " +"the preference is created directly (skipping the dream trial " +"window).\n" +@@ -85,7 +85,7 @@ export function buildInstructions(opts: BuildInstructionsOpts | string): string"any files. Use it when you want to be deliberate before " +"triggering the learning pass.\n" +" - brain_digest — read-only summary of the last activity " +- "window. Default format is Markdown; pass `format: \"json\"` for " ++ 'window. Default format is Markdown; pass `format: "json"` for ' +"programmatic use.\n" +" - brain_query — read-only lookup by `preference`, `topic`, " +"or `since` (exactly one). Use this to discover applicable rules " +diff --git a/src/mcp/pay-memory-tools.ts b/src/mcp/pay-memory-tools.tsindex 025c1ce1..8cf17f4f 100644--- a/src/mcp/pay-memory-tools.ts+++ b/src/mcp/pay-memory-tools.ts@@ -44,8 +44,7 @@ async function toolPaymentMemoryInit(): 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 agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);const dirs = payMemoryDirs(ctx.vault);const dirList = [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports];@@ -72,21 +71,15 @@ async function toolPaymentReceiptAppend(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const agentArg = coerceStr(args, "agent", false);- const agent =- normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);+ 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 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")- ) {+ 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[];@@ -121,10 +114,7 @@ async function toolPaymentReceiptAppend("not_checked",];if (!allowed.includes(policyStatus)) {- throw new MCPError(- INVALID_PARAMS,- `policy_status must be one of: ${allowed.join(", ")}`,- );+ throw new MCPError(INVALID_PARAMS, `policy_status must be one of: ${allowed.join(", ")}`);}}@@ -194,8 +184,7 @@ async function toolPaymentRequestApproval(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const agentArg = coerceStr(args, "agent", false);- const agent =- normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);+ const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);const tz = resolveTimezone(ctx.configPath ?? undefined);const expectedAmount = coerceOptionalNumber(args, "expected_amount");@@ -307,9 +296,7 @@ async function toolPaymentPolicyCheck(reasons: decision.reasons,has_policy: decision.hasPolicy,policy_path:- decision.policyPath !== null- ? vaultRelativePath(decision.policyPath, ctx.vault)- : null,+ decision.policyPath !== null ? vaultRelativePath(decision.policyPath, ctx.vault) : null,currency: decision.currency,};}@@ -341,7 +328,10 @@ export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([inputSchema: {type: "object",properties: {- agent: { type: "string", description: "Agent identity (defaults to server-resolved name)." },+ agent: {+ type: "string",+ description: "Agent identity (defaults to server-resolved name).",+ },overwrite: {type: "boolean",description: "Overwrite an existing policy file. Directories are always idempotent.",@@ -358,22 +348,52 @@ export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([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." },+ 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)." },+ 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)." },+ 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",@@ -401,11 +421,13 @@ export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},payment_layer: {type: "string",- description: "Payment rail (default `pay.sh`). Override only when a different rail was used.",+ 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.",+ description:+ "Settlement network (default `solana`). Override only when a different network was used.",},},required: ["service", "status", "reason"],@@ -421,12 +443,24 @@ export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([type: "object",properties: {title: { type: "string", description: "Human-readable asset title." },- service: { type: "string", description: "Provider/skill identifier that produced the asset." },+ 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." },+ 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"],@@ -494,17 +528,22 @@ export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "payment_policy_check",- description:- `Evaluate a prospective paid call against ${PAY_MEMORY_SPENDING_JSON_REL}. Returns allowed / approval_required / denied + the rule that fired.`,+ description: `Evaluate a prospective paid call against ${PAY_MEMORY_SPENDING_JSON_REL}. Returns allowed / approval_required / denied + the rule that fired.`,inputSchema: {type: "object",properties: {- service: { type: "string", description: "Provider/skill identifier, e.g. 'paysponge/fal'." },+ 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." },+ 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)." },},@@ -515,12 +554,14 @@ export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "payment_report_generate",- description:- `Aggregate a date's payment receipts into a Markdown report under ${PAY_MEMORY_REPORTS_REL}/.`,+ description: `Aggregate a date's payment receipts into a Markdown report under ${PAY_MEMORY_REPORTS_REL}/.`,inputSchema: {type: "object",properties: {- date: { type: "string", description: "Date in YYYY-MM-DD whose receipts will be aggregated." },+ 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." },diff --git a/src/mcp/resources.ts b/src/mcp/resources.tsindex 5538ea5e..5d3bd5cb 100644--- a/src/mcp/resources.ts+++ b/src/mcp/resources.ts@@ -39,10 +39,7 @@ import { regenerateActive } from "../core/brain/active.ts";import { buildBacklinkIndex } from "../core/brain/backlinks.ts";import type { BacklinkRef } from "../core/brain/backlinks.ts";import { renderDigest } from "../core/brain/digest.ts";-import {- computeBrainStatus,- type BrainStatusSnapshot,-} from "../core/brain/status.ts";+import { computeBrainStatus, type BrainStatusSnapshot } from "../core/brain/status.ts";import {brainActivePath,logPath,@@ -51,16 +48,9 @@ import {validateIsoDate,validateSlug,} from "../core/brain/paths.ts";-import {- BrainNotFoundError,- queryByPreference,- queryByTopic,-} from "../core/brain/query.ts";+import { BrainNotFoundError, queryByPreference, queryByTopic } from "../core/brain/query.ts";import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";-import type {- BrainPreference,- BrainRetired,-} from "../core/brain/types.ts";+import type { BrainPreference, BrainRetired } from "../core/brain/types.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";export interface ResourceContext {@@ -100,8 +90,7 @@ const CONCRETE: ReadonlyArray<ResourceDescriptor> = [{uri: "osb://digest/latest",name: "Latest Brain digest",- description:- "Same body as `brain_digest` (default window: last 24h). Markdown.",+ description: "Same body as `brain_digest` (default window: last 24h). Markdown.",mimeType: MIME_MARKDOWN,},{@@ -131,8 +120,7 @@ const TEMPLATES: ReadonlyArray<ResourceTemplateDescriptor> = [{uriTemplate: "osb://log/{date}",name: "Brain daily log",- description:- "Body of `Brain/log/<date>.md` (YYYY-MM-DD).",+ description: "Body of `Brain/log/<date>.md` (YYYY-MM-DD).",mimeType: MIME_MARKDOWN,},{@@ -257,11 +245,7 @@ function readStatus(ctx: ResourceContext, uri: string): ResourceContent {};}-function readPreference(- ctx: ResourceContext,- uri: string,- rawId: string,-): ResourceContent {+function readPreference(ctx: ResourceContext, uri: string, rawId: string): ResourceContent {if (!rawId.trim()) {throw new MCPError(INVALID_PARAMS, `resource id must not be empty: ${uri}`);}@@ -281,9 +265,8 @@ function readPreference(} catch (err) {throw new MCPError(INVALID_PARAMS, (err as Error).message);}- const normalized = rawId.startsWith("pref-") || rawId.startsWith("ret-")- ? rawId- : `pref-${rawId}`;+ const normalized =+ rawId.startsWith("pref-") || rawId.startsWith("ret-") ? rawId : `pref-${rawId}`;let result;try {result = queryByPreference(ctx.vault, normalized);@@ -307,11 +290,7 @@ function readPreference(return readMarkdown(uri, filePath);}-function readTopic(- ctx: ResourceContext,- uri: string,- rawSlug: string,-): ResourceContent {+function readTopic(ctx: ResourceContext, uri: string, rawSlug: string): ResourceContent {if (!rawSlug.trim()) {throw new MCPError(INVALID_PARAMS, `topic slug must not be empty: ${uri}`);}@@ -332,11 +311,7 @@ function readTopic(};}-function readLog(- ctx: ResourceContext,- uri: string,- rawDate: string,-): ResourceContent {+function readLog(ctx: ResourceContext, uri: string, rawDate: string): ResourceContent {validateIsoDate(rawDate);const path = logPath(ctx.vault, rawDate);if (!existsSync(path)) {@@ -345,11 +320,7 @@ function readLog(return readMarkdown(uri, path);}-function readBacklinks(- ctx: ResourceContext,- uri: string,- rawId: string,-): ResourceContent {+function readBacklinks(ctx: ResourceContext, uri: string, rawId: string): ResourceContent {if (!rawId.trim()) {throw new MCPError(INVALID_PARAMS, `backlinks target must not be empty: ${uri}`);}@@ -390,7 +361,7 @@ function renderStatusMarkdown(s: BrainStatusSnapshot): string {lines.push("");lines.push(`- inbox: ${s.counts.inbox} (processed: ${s.counts.inbox_processed})`);lines.push(`- preferences: ${s.counts.preferences}`);- for (const [status, n] of Object.entries(s.counts.preferences_by_status).sort()) {+ for (const [status, n] of Object.entries(s.counts.preferences_by_status).toSorted()) {lines.push(` - ${status}: ${n}`);}lines.push(`- retired: ${s.counts.retired}`);@@ -414,10 +385,7 @@ function renderStatusMarkdown(s: BrainStatusSnapshot): string {return lines.join("\n") + "\n";}-function renderBacklinksMarkdown(- target: string,- refs: ReadonlyArray<BacklinkRef>,-): string {+function renderBacklinksMarkdown(target: string, refs: ReadonlyArray<BacklinkRef>): string {const lines: string[] = [];lines.push(`# Backlinks to \`${target}\``);lines.push("");@@ -449,10 +417,7 @@ function renderBacklinksMarkdown(return lines.join("\n") + "\n";}-function renderTopicMarkdown(- slug: string,- result: ReturnType<typeof queryByTopic>,-): string {+function renderTopicMarkdown(slug: string, result: ReturnType<typeof queryByTopic>): string {const lines: string[] = [];lines.push(`# Brain topic: ${slug}`);lines.push("");@@ -469,9 +434,7 @@ function renderTopicMarkdown(const p = pref as BrainPreference;lines.push("## Current preference");lines.push("");- lines.push(- `- \`${p.id}\` — status: \`${p.status}\`, confidence: \`${p.confidence}\``,- );+ lines.push(`- \`${p.id}\` — status: \`${p.status}\`, confidence: \`${p.confidence}\``);lines.push(` - ${p.principle}`);}lines.push("");@@ -481,9 +444,7 @@ function renderTopicMarkdown(lines.push(`## Signals (${sigs.length})`);lines.push("");for (const s of sigs) {- lines.push(- `- \`${s.id}\` — ${s.signal} signal by ${s.agent} at ${s.created_at}`,- );+ lines.push(`- \`${s.id}\` — ${s.signal} signal by ${s.agent} at ${s.created_at}`);}lines.push("");}diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.tsindex 89aab885..cd23cd5c 100644--- a/src/mcp/search-tools.ts+++ b/src/mcp/search-tools.ts@@ -10,16 +10,8 @@* Anchored in docs/plans/2026-05-16-brain-search-design.md §9.*/-import {- indexStatus,- resolveSearchConfig,- search,- SearchError,-} from "../core/search/index.ts";-import type {- BrainSearchResult,- SearchOutcome,-} from "../core/search/index.ts";+import { indexStatus, resolveSearchConfig, search, SearchError } from "../core/search/index.ts";+import type { BrainSearchResult, SearchOutcome } from "../core/search/index.ts";import { withTimeout } from "../core/search/with-timeout.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";import type { ServerContext, ToolDefinition } from "./tools.ts";@@ -74,26 +66,17 @@ function parsePropertiesArgument(const map = new Map<string, ReadonlyArray<string>>();for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {if (!Array.isArray(v)) {- throw new MCPError(- INVALID_PARAMS,- `argument 'properties.${k}' must be an array of strings`,- );+ throw new MCPError(INVALID_PARAMS, `argument 'properties.${k}' must be an array of strings`);}const accepted: string[] = [];for (const item of v) {if (typeof item !== "string") {- throw new MCPError(- INVALID_PARAMS,- `argument 'properties.${k}' must contain only strings`,- );+ throw new MCPError(INVALID_PARAMS, `argument 'properties.${k}' must contain only strings`);}accepted.push(item);}if (accepted.length === 0) {- throw new MCPError(- INVALID_PARAMS,- `argument 'properties.${k}' must not be empty`,- );+ throw new MCPError(INVALID_PARAMS, `argument 'properties.${k}' must not be empty`);}map.set(k, Object.freeze(accepted));}diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 7dd9d945..6fd44400 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -17,12 +17,14 @@ import {SERVER_NAME,SERVER_VERSION,} from "./protocol.ts";+import { listResources, listResourceTemplates, readResource } from "./resources.ts";import {- listResources,- listResourceTemplates,- readResource,-} from "./resources.ts";-import { buildToolTable, findTool, type ServerContext, type ToolDefinition, type ToolScope } from "./tools.ts";+ buildToolTable,+ findTool,+ type ServerContext,+ type ToolDefinition,+ type ToolScope,+} from "./tools.ts";export interface MCPServerOptions {readonly vault: string;@@ -100,11 +102,7 @@ export class MCPServer {const isNotification = !("id" in request);if (!isNotification) {const idType = typeof request.id;- if (- idType !== "string" &&- idType !== "number" &&- request.id !== null- ) {+ if (idType !== "string" && idType !== "number" && request.id !== null) {return errorResponse(null, INVALID_REQUEST, "id must be string, number, or null");}}@@ -232,7 +230,7 @@ function toolError(message: string): Record<string, unknown> {function sortedReplacer(_key: string, value: unknown): unknown {if (value !== null && typeof value === "object" && !Array.isArray(value)) {- const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));+ const entries = Object.entries(value).toSorted(([a], [b]) => a.localeCompare(b));return Object.fromEntries(entries);}return value;diff --git a/src/mcp/stdio.ts b/src/mcp/stdio.tsindex 3f380906..19af71cc 100644--- a/src/mcp/stdio.ts+++ b/src/mcp/stdio.ts@@ -43,13 +43,20 @@ export async function serveStdio(try {request = JSON.parse(line);} catch (exc) {- writeFrame(stdout, errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`));+ writeFrame(+ stdout,+ errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`),+ );continue;}if (Array.isArray(request)) {writeFrame(stdout,- errorResponse(null, INVALID_REQUEST, "batch requests are not supported by the 2025-06-18 spec"),+ errorResponse(+ null,+ INVALID_REQUEST,+ "batch requests are not supported by the 2025-06-18 spec",+ ),);continue;}@@ -90,13 +97,19 @@ export async function serveStdioFromString(try {request = JSON.parse(line);} catch (exc) {- out.push(JSON.stringify(errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`)));+ out.push(+ JSON.stringify(errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`)),+ );continue;}if (Array.isArray(request)) {out.push(JSON.stringify(- errorResponse(null, INVALID_REQUEST, "batch requests are not supported by the 2025-06-18 spec"),+ errorResponse(+ null,+ INVALID_REQUEST,+ "batch requests are not supported by the 2025-06-18 spec",+ ),),);continue;diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex e7b7e231..ec8f700e 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -19,24 +19,15 @@* only assembles them in a stable order and applies scope filtering.*/-import {- discoverConfig,- redactMapping,-} from "../core/config.ts";+import { discoverConfig, redactMapping } 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 {- resolveVaultScope,- walkVaultScope,-} from "../core/vault-scope/index.ts";+import { resolveVaultScope, walkVaultScope } from "../core/vault-scope/index.ts";import { BRAIN_TOOLS } from "./brain-tools.ts";import { SEARCH_TOOLS, buildSearchStatusBlock } from "./search-tools.ts";import { PAY_MEMORY_TOOLS } from "./pay-memory-tools.ts";-import {- normalizeAgentArgument,- PLACEHOLDER_AGENT_VALUES,-} from "../core/agent-identity.ts";+import { normalizeAgentArgument, PLACEHOLDER_AGENT_VALUES } from "../core/agent-identity.ts";import { vaultRelative } from "../core/path-safety.ts";import { listVaultPages } from "../core/vault.ts";import { INVALID_PARAMS, METHOD_NOT_FOUND, MCPError } from "./protocol.ts";@@ -52,7 +43,10 @@ export interface ToolDefinition {readonly name: string;readonly description: string;readonly inputSchema: Record<string, unknown>;- readonly handler: (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown;+ readonly handler: (+ ctx: ServerContext,+ args: Record<string, unknown>,+ ) => Promise<unknown> | unknown;}// PLACEHOLDER_AGENT_VALUES + normalizeAgentArgument live in@@ -80,7 +74,7 @@ function vaultRelpath(target: string, vault: string): string {async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>> {const discovery = discoverConfig(ctx.configPath ?? undefined);const vaultExists = isDir(ctx.vault);- const configKeys = Object.keys(discovery.data).sort();+ const configKeys = Object.keys(discovery.data).toSorted();// Safe to call on a vault that has no Brain layer yet — returns// `present: false` with zero counts.const brain = vaultExists ? computeBrainStatus(ctx.vault) : null;@@ -128,7 +122,10 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>};}-async function toolQuery(ctx: ServerContext, args: Record<string, unknown>): Promise<Record<string, unknown>> {+async function toolQuery(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {if (!isDir(ctx.vault)) {throw new MCPError(INVALID_PARAMS, `vault directory missing: ${ctx.vault}`);}@@ -178,7 +175,6 @@ async function toolVaultHealth(};}-export type ToolScope = "full" | "writer";// The set is named after the original payload (mutating writers). Asdiff --git a/src/openclaw/index.ts b/src/openclaw/index.tsindex f29e41f3..664b2bd7 100644--- a/src/openclaw/index.ts+++ b/src/openclaw/index.ts@@ -18,6 +18,7 @@ import {redactMapping,resolveAgentName,resolveTimezone,+ validateTimezoneName,} from "../core/config.ts";import { doctor } from "../core/doctor.ts";import { buildReminder } from "../core/identity-reminder.ts";@@ -39,6 +40,7 @@ import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";import { mkdirSync } from "node:fs";import { listVaultPages } from "../core/vault.ts";import { normalizeAgentArgument } from "../core/agent-identity.ts";+import { parseOptionalFiniteNumberInput } from "../core/validate.ts";interface PluginConfig {vault?: string;@@ -56,12 +58,7 @@ function resolveOpenclawTimezone(api: { pluginConfig?: Record<string, unknown> }const cfg = (api.pluginConfig ?? {}) as PluginConfig;const candidate = cfg.timezone || process.env["VAULT_TIMEZONE"] || null;if (!candidate) return null;- try {- new Intl.DateTimeFormat("en-US", { timeZone: candidate });- return candidate;- } catch {- return null;- }+ return validateTimezoneName(candidate).ok ? candidate : null;}function resolveOpenclawAgent(@@ -84,23 +81,14 @@ function resolveOpenclawAgent(* silently change a policy decision.*/function coerceExpectedAmount(value: unknown): number | null {- if (value === undefined || value === null) return null;- if (typeof value === "number") {- if (!Number.isFinite(value)) {- throw new Error("expected_amount must be a finite number");- }- return value;+ const parsed = parseOptionalFiniteNumberInput(value);+ if (parsed.error === "finite-number") {+ throw new Error("expected_amount must be a finite number");}- if (typeof value === "string") {- const trimmed = value.trim();- if (trimmed === "") return null;- const parsed = Number(trimmed);- if (!Number.isFinite(parsed)) {- throw new Error("expected_amount must be a number or numeric string");- }- return parsed;+ if (parsed.error === "number-or-numeric-string") {+ throw new Error("expected_amount must be a number or numeric string");}- throw new Error("expected_amount must be a number or numeric string");+ return parsed.value;}function strOrNull(value: unknown): string | null {@@ -110,7 +98,9 @@ function strOrNull(value: unknown): string | null {return trimmed ? trimmed : null;}-function asJson(payload: unknown): { content: Array<{ type: "text"; text: string }> } {+function asJson(payload: unknown): {+ content: Array<{ type: "text"; text: string }>;+} {return {content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],};@@ -138,107 +128,118 @@ export default definePluginEntry({return { prependContext: buildReminder(agent, "openclaw") };});- api.registerTool(- {- name: "second_brain_status",- description: "Report Open Second Brain configuration and vault status.",- parameters: { type: "object", properties: {}, additionalProperties: false },- async execute(): Promise<unknown> {- const vault = resolveVaultPath(api);- const discovery = discoverConfig();- const result = {- config_path: discovery.path,- config_exists: discovery.exists,- config_keys: Object.keys(discovery.data).sort(),- config: redactMapping(discovery.data),- vault_path: vault,- vault_exists: existsSync(vault),- };- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };- },+ api.registerTool({+ name: "second_brain_status",+ description: "Report Open Second Brain configuration and vault status.",+ parameters: {+ type: "object",+ properties: {},+ additionalProperties: false,+ },+ async execute(): Promise<unknown> {+ const vault = resolveVaultPath(api);+ const discovery = discoverConfig();+ const result = {+ config_path: discovery.path,+ config_exists: discovery.exists,+ config_keys: Object.keys(discovery.data).toSorted(),+ config: redactMapping(discovery.data),+ vault_path: vault,+ vault_exists: existsSync(vault),+ };+ return {+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],+ };},- );+ });- api.registerTool(- {- name: "second_brain_query",- description: "List vault pages with optional title substring filter.",- parameters: {- type: "object",- properties: {- pattern: {- type: "string",- description: "Optional case-insensitive substring matched against page titles.",- },- limit: {- type: "integer",- minimum: 1,- maximum: 500,- description: "Maximum number of matched pages to return (default 50).",- },+ api.registerTool({+ name: "second_brain_query",+ description: "List vault pages with optional title substring filter.",+ parameters: {+ type: "object",+ properties: {+ pattern: {+ type: "string",+ description: "Optional case-insensitive substring matched against page titles.",+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: 500,+ description: "Maximum number of matched pages to return (default 50).",},- additionalProperties: false,},- async execute(_id, params): Promise<unknown> {- const vault = resolveVaultPath(api);- if (!existsSync(vault)) throw new Error(`vault directory missing: ${vault}`);- const pattern = (params["pattern"] as string | undefined) ?? null;- const limit = typeof params["limit"] === "number" ? (params["limit"] as number) : 50;- if (limit < 1 || limit > 500) throw new Error("argument 'limit' must be between 1 and 500");+ additionalProperties: false,+ },+ async execute(_id, params): Promise<unknown> {+ const vault = resolveVaultPath(api);+ if (!existsSync(vault)) throw new Error(`vault directory missing: ${vault}`);+ const pattern = (params["pattern"] as string | undefined) ?? null;+ const limit = typeof params["limit"] === "number" ? (params["limit"] as number) : 50;+ if (limit < 1 || limit > 500) throw new Error("argument 'limit' must be between 1 and 500");- const pages = listVaultPages(vault);- const needle = pattern ? pattern.toLowerCase() : null;- const matched = (needle === null- ? pages- : pages.filter((p) => p.title.toLowerCase().includes(needle))- )- .slice(0, limit)- .map((p) => ({ title: p.title, path: vaultRelativePath(p.path, vault), metadata: p.metadata }));+ const pages = listVaultPages(vault);+ const needle = pattern ? pattern.toLowerCase() : null;+ const matched = (+ needle === null ? pages : pages.filter((p) => p.title.toLowerCase().includes(needle))+ )+ .slice(0, limit)+ .map((p) => ({+ title: p.title,+ path: vaultRelativePath(p.path, vault),+ metadata: p.metadata,+ }));- const result = {- vault_path: vault,- total_pages: pages.length,- returned: matched.length,- limit,- pattern,- pages: matched,- };- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };- },+ const result = {+ vault_path: vault,+ total_pages: pages.length,+ returned: matched.length,+ limit,+ pattern,+ pages: matched,+ };+ return {+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],+ };},- );+ });// Agents on this runtime record observations via the Brain writer// tools served by the MCP server (`brain_feedback`,// `brain_apply_evidence`, `brain_note`).- api.registerTool(- {- name: "vault_health",- description: "Run vault, config, and plugin manifest health checks.",- parameters: {- type: "object",- properties: {- repo: {- type: "string",- description: "Optional repository root to validate plugin manifests.",- },+ api.registerTool({+ name: "vault_health",+ description: "Run vault, config, and plugin manifest health checks.",+ parameters: {+ type: "object",+ properties: {+ repo: {+ type: "string",+ description: "Optional repository root to validate plugin manifests.",},- additionalProperties: false,- },- async execute(_id, params): Promise<unknown> {- const vault = resolveVaultPath(api);- const repoRoot = (params["repo"] as string | undefined) ?? null;- const results = doctor({ vault, repoRoot });- const result = {- vault_path: vault,- ok: results.every((r) => r.ok),- checks: results.map((r) => ({ name: r.name, ok: r.ok, message: r.message })),- };- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };},+ additionalProperties: false,+ },+ async execute(_id, params): Promise<unknown> {+ const vault = resolveVaultPath(api);+ const repoRoot = (params["repo"] as string | undefined) ?? null;+ const results = doctor({ vault, repoRoot });+ const result = {+ vault_path: vault,+ ok: results.every((r) => r.ok),+ checks: results.map((r) => ({+ name: r.name,+ ok: r.ok,+ message: r.message,+ })),+ };+ return {+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],+ };},- );+ });// ── Pay Memory tools ───────────────────────────────────────────────────@@ -322,9 +323,7 @@ export default definePluginEntry({const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();const agent = resolveOpenclawAgent(api, (params["agent"] as string | undefined) ?? null);- let policyStatus = strOrNull(params["policy_status"]) as- | ReceiptPolicyStatus- | null;+ let policyStatus = strOrNull(params["policy_status"]) as ReceiptPolicyStatus | null;let policyRule = strOrNull(params["policy_rule"]);const policyReasonsRaw = params["policy_reasons"];let policyReasons: string[] | null = null;@@ -338,12 +337,7 @@ export default definePluginEntry({policyReasons = [...policyReasonsRaw] as string[];}let policyCheckedAt = strOrNull(params["policy_checked_at"]);- let approvalStatus:- | "pending"- | "approved"- | "rejected"- | "consumed"- | null = null;+ let approvalStatus: "pending" | "approved" | "rejected" | "consumed" | null = null;let approvedBy: string | null = null;let approvedAt: string | null = null;const fromRequest = strOrNull(params["from_request"]);@@ -370,9 +364,7 @@ export default definePluginEntry({"not_checked",];if (!allowed.includes(policyStatus)) {- throw new Error(- `policy_status must be one of: ${allowed.join(", ")}`,- );+ throw new Error(`policy_status must be one of: ${allowed.join(", ")}`);}}@@ -458,8 +450,7 @@ export default definePluginEntry({api.registerTool({name: "payment_report_generate",- description:- `Aggregate a date's payment receipts into a Markdown report under ${PAY_MEMORY_REPORTS_REL}/.`,+ description: `Aggregate a date's payment receipts into a Markdown report under ${PAY_MEMORY_REPORTS_REL}/.`,parameters: {type: "object",properties: {@@ -492,8 +483,7 @@ export default definePluginEntry({api.registerTool({name: "payment_policy_check",- description:- `Evaluate a prospective paid call against ${PAY_MEMORY_SPENDING_JSON_REL}. Returns allowed / approval_required / denied + the rule that fired.`,+ description: `Evaluate a prospective paid call against ${PAY_MEMORY_SPENDING_JSON_REL}. Returns allowed / approval_required / denied + the rule that fired.`,parameters: {type: "object",properties: {@@ -525,9 +515,7 @@ export default definePluginEntry({reasons: decision.reasons,has_policy: decision.hasPolicy,policy_path:- decision.policyPath !== null- ? vaultRelativePath(decision.policyPath, vault)- : null,+ decision.policyPath !== null ? vaultRelativePath(decision.policyPath, vault) : null,currency: decision.currency,});},@@ -564,10 +552,7 @@ export default definePluginEntry({const vaultFilesRaw = params["vault_files"];let vaultFiles: string[] | null = null;if (vaultFilesRaw !== undefined && vaultFilesRaw !== null) {- if (- !Array.isArray(vaultFilesRaw) ||- !vaultFilesRaw.every((s) => typeof s === "string")- ) {+ if (!Array.isArray(vaultFilesRaw) || !vaultFilesRaw.every((s) => typeof s === "string")) {throw new Error("vault_files must be an array of strings");}vaultFiles = [...vaultFilesRaw] as string[];diff --git a/tests/cli/brain-digest-window-cli.test.ts b/tests/cli/brain-digest-window-cli.test.tsindex ab403c3c..c7095e59 100644--- a/tests/cli/brain-digest-window-cli.test.ts+++ b/tests/cli/brain-digest-window-cli.test.ts@@ -2,29 +2,21 @@ import { describe, expect, test } from "bun:test";import { parseWindow, cmdBrainDigest } from "../../src/cli/brain/verbs/digest.ts";describe("parseWindow", () => {- test("parses '7d' as 7 days", () => {- expect(parseWindow("7d")).toBe(7);+ test("parses day windows with or without the d suffix", () => {+ for (const [raw, days] of [+ ["7d", 7],+ ["7", 7],+ ["1d", 1],+ ["30d", 30],+ ] as const) {+ expect(parseWindow(raw)).toBe(days);+ }});- test("parses bare '7' as 7 days", () => {- expect(parseWindow("7")).toBe(7);- });- test("parses '1d' as 1 day", () => {- expect(parseWindow("1d")).toBe(1);- });- test("parses '30d' as 30 days", () => {- expect(parseWindow("30d")).toBe(30);- });- test("rejects '0d'", () => {- expect(() => parseWindow("0d")).toThrow();- });- test("rejects '-1d'", () => {- expect(() => parseWindow("-1d")).toThrow();- });- test("rejects 'abc'", () => {- expect(() => parseWindow("abc")).toThrow();- });- test("rejects '1.5d'", () => {- expect(() => parseWindow("1.5d")).toThrow();++ test("rejects non-positive and malformed windows", () => {+ for (const raw of ["0d", "-1d", "abc", "1.5d"]) {+ expect(() => parseWindow(raw)).toThrow();+ }});});diff --git a/tests/cli/brain-explorer.test.ts b/tests/cli/brain-explorer.test.tsindex 4cb76c40..3a5d4260 100644--- a/tests/cli/brain-explorer.test.ts+++ b/tests/cli/brain-explorer.test.ts@@ -7,13 +7,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- existsSync,- mkdtempSync,- readFileSync,- rmSync,- writeFileSync,-} from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -83,10 +77,9 @@ describe("o2b brain explorer --export", () => {await bootstrap();seedOnePref();const out = join(tmp, "brain.html");- const r = await runCli(- ["brain", "explorer", "--vault", vault, "--export", out],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "explorer", "--vault", vault, "--export", out], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("exported");expect(existsSync(out)).toBe(true);@@ -105,10 +98,9 @@ describe("o2b brain explorer --export", () => {seedOnePref();const out = join(tmp, "brain.html");writeFileSync(out, "pre-existing");- const r = await runCli(- ["brain", "explorer", "--vault", vault, "--export", out],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "explorer", "--vault", vault, "--export", out], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("exists");expect(readFileSync(out, "utf8")).toBe("pre-existing");@@ -119,35 +111,22 @@ describe("o2b brain explorer --export", () => {seedOnePref();const out = join(tmp, "brain.html");writeFileSync(out, "pre-existing");- const r = await runCli(- [- "brain", "explorer", "--vault", vault,- "--export", out, "--force",- ],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "explorer", "--vault", vault, "--export", out, "--force"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(readFileSync(out, "utf8").startsWith("<!doctype html>")).toBe(true);});- test("invalid --port value exits 1", async () => {+ test("invalid --port values exit 1", async () => {await bootstrap();- const r = await runCli(- ["brain", "explorer", "--vault", vault, "--port", "garbage"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );- expect(r.returncode).toBe(1);- expect(r.stderr).toContain("invalid --port");- });-- test("partially numeric --port value exits 1", async () => {- await bootstrap();- const r = await runCli(- ["brain", "explorer", "--vault", vault, "--port", "123abc"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );- expect(r.returncode).toBe(1);- expect(r.stderr).toContain("invalid --port");+ for (const port of ["garbage", "123abc"]) {+ const r = await runCli(["brain", "explorer", "--vault", vault, "--port", port], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(1);+ expect(r.stderr).toContain("invalid --port");+ }});});@@ -162,10 +141,15 @@ describe("o2b brain explorer (live)", () => {const isolatedConfig = config;const proc = Bun.spawn([- "bun", "run", "src/cli/main.ts",- "brain", "explorer",- "--vault", vault,- "--port", String(port),+ "bun",+ "run",+ "src/cli/main.ts",+ "brain",+ "explorer",+ "--vault",+ vault,+ "--port",+ String(port),],{cwd: process.cwd(),@@ -223,10 +207,9 @@ describe("o2b brain explorer (live)", () => {fetch: () => new Response("blocker"),});try {- const r = await runCli(- ["brain", "explorer", "--vault", vault, "--port", String(port)],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "explorer", "--vault", vault, "--port", String(port)], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toMatch(/already in use|in use/);} finally {diff --git a/tests/cli/brain-export.test.ts b/tests/cli/brain-export.test.tsindex 3307e89b..1ef8606d 100644--- a/tests/cli/brain-export.test.ts+++ b/tests/cli/brain-export.test.ts@@ -58,20 +58,18 @@ async function seedPreference(slug: string): Promise<void> {describe("brain export", () => {test("missing --format → exit 2", async () => {await bootstrap();- const r = await runCli(- ["brain", "export", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "export", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);expect(r.stderr).toContain("--format");});test("--format json on empty vault → schema envelope, empty list", async () => {await bootstrap();- const r = await runCli(- ["brain", "export", "--vault", vault, "--format", "json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "export", "--vault", vault, "--format", "json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout) as {schema: number;@@ -88,33 +86,26 @@ describe("brain export", () => {await bootstrap();await seedPreference("alpha");await seedPreference("beta");- const r = await runCli(- ["brain", "export", "--vault", vault, "--format", "json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "export", "--vault", vault, "--format", "json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout) as {preferences: Array<{ id: string; topic: string; principle: string }>;};- expect(payload.preferences.map((p) => p.id).sort()).toEqual([- "pref-alpha",- "pref-beta",- ]);+ expect(payload.preferences.map((p) => p.id).toSorted()).toEqual(["pref-alpha", "pref-beta"]);});test("--format llms-txt emits H1 + section + bullet", async () => {await bootstrap();await seedPreference("alpha");- const r = await runCli(- ["brain", "export", "--vault", vault, "--format", "llms-txt"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "export", "--vault", vault, "--format", "llms-txt"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toMatch(/^# .*Brain preferences/);expect(r.stdout).toContain("## Confirmed");- expect(r.stdout).toContain(- "- pref-alpha (topic: alpha, scope: writing): principle alpha",- );+ expect(r.stdout).toContain("- pref-alpha (topic: alpha, scope: writing): principle alpha");});test("--out writes a file (and refuses to overwrite without --force)", async () => {@@ -122,16 +113,7 @@ describe("brain export", () => {await seedPreference("alpha");const out = join(tmp, "out.json");const r1 = await runCli(- [- "brain",- "export",- "--vault",- vault,- "--format",- "json",- "--out",- out,- ],+ ["brain", "export", "--vault", vault, "--format", "json", "--out", out],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r1.returncode).toBe(0);@@ -143,16 +125,7 @@ describe("brain export", () => {// Second call without --force should refuse.const r2 = await runCli(- [- "brain",- "export",- "--vault",- vault,- "--format",- "json",- "--out",- out,- ],+ ["brain", "export", "--vault", vault, "--format", "json", "--out", out],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r2.returncode).toBe(1);@@ -161,17 +134,7 @@ describe("brain export", () => {// With --force the overwrite goes through.writeFileSync(out, "stale");const r3 = await runCli(- [- "brain",- "export",- "--vault",- vault,- "--format",- "json",- "--out",- out,- "--force",- ],+ ["brain", "export", "--vault", vault, "--format", "json", "--out", out, "--force"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r3.returncode).toBe(0);diff --git a/tests/cli/brain-import-claude-memory.test.ts b/tests/cli/brain-import-claude-memory.test.tsindex 0dfcd892..6a910b05 100644--- a/tests/cli/brain-import-claude-memory.test.ts+++ b/tests/cli/brain-import-claude-memory.test.ts@@ -20,8 +20,14 @@ describe("o2b brain import-claude-memory CLI", () => {);const res = await runCli([- "brain", "import-claude-memory", "--vault", vault,- "--memory", mem, "--dry-run", "--allow-arbitrary-memory-path",+ "brain",+ "import-claude-memory",+ "--vault",+ vault,+ "--memory",+ mem,+ "--dry-run",+ "--allow-arbitrary-memory-path",],{ env },);@@ -48,8 +54,15 @@ describe("o2b brain import-claude-memory CLI", () => {);const res = await runCli([- "brain", "import-claude-memory", "--vault", vault,- "--memory", mem, "--apply", "--yes", "--allow-arbitrary-memory-path",+ "brain",+ "import-claude-memory",+ "--vault",+ vault,+ "--memory",+ mem,+ "--apply",+ "--yes",+ "--allow-arbitrary-memory-path",],{ env },);@@ -61,7 +74,12 @@ describe("o2b brain import-claude-memory CLI", () => {test("--apply + --dry-run is rejected", async () => {const res = await runCli([- "brain", "import-claude-memory", "--vault", "/tmp", "--apply", "--dry-run",+ "brain",+ "import-claude-memory",+ "--vault",+ "/tmp",+ "--apply",+ "--dry-run",]);expect(res.returncode).toBe(2);expect(res.stderr).toMatch(/--apply.*--dry-run|--dry-run.*--apply/);diff --git a/tests/cli/brain-merge.test.ts b/tests/cli/brain-merge.test.tsindex 5bf14b35..c24340a6 100644--- a/tests/cli/brain-merge.test.ts+++ b/tests/cli/brain-merge.test.ts@@ -9,11 +9,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- existsSync,- mkdtempSync,- rmSync,-} from "node:fs";+import { existsSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -95,10 +91,9 @@ describe("o2b brain merge — guards", () => {test("same id exits 1 with explanatory message", async () => {await bootstrap();makePref("a");- const r = await runCli(- ["brain", "merge", "pref-a", "pref-a", "--vault", vault, "--force"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "merge", "pref-a", "pref-a", "--vault", vault, "--force"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("same preference");});@@ -118,16 +113,13 @@ describe("o2b brain merge — guards", () => {await bootstrap();makePref("a", { topic: "x" });makePref("b", { topic: "y" });- const r = await runCli(- ["brain", "merge", "pref-a", "pref-b", "--vault", vault, "--force"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "merge", "pref-a", "pref-b", "--vault", vault, "--force"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("topic mismatch");// Drop is still present in preferences/ — guard refused the write.- expect(- existsSync(join(vault, "Brain", "preferences", "pref-b.md")),- ).toBe(true);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-b.md"))).toBe(true);});});@@ -137,10 +129,7 @@ describe("o2b brain merge — happy paths", () => {makePref("keep", { applied_count: 3 });makePref("drop", { applied_count: 2 });const r = await runCli(- [- "brain", "merge", "pref-keep", "pref-drop",- "--vault", vault, "--dry-run",- ],+ ["brain", "merge", "pref-keep", "pref-drop", "--vault", vault, "--dry-run"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);@@ -148,12 +137,8 @@ describe("o2b brain merge — happy paths", () => {expect(r.stdout).toContain("applied_sum: 5");expect(r.stdout).toContain("dry-run; no changes written");// Drop is still in preferences/.- expect(- existsSync(join(vault, "Brain", "preferences", "pref-drop.md")),- ).toBe(true);- expect(- existsSync(join(vault, "Brain", "retired", "ret-drop.md")),- ).toBe(false);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-drop.md"))).toBe(true);+ expect(existsSync(join(vault, "Brain", "retired", "ret-drop.md"))).toBe(false);});test("--force commits without prompt", async () => {@@ -161,20 +146,13 @@ describe("o2b brain merge — happy paths", () => {makePref("keep");makePref("drop");const r = await runCli(- [- "brain", "merge", "pref-keep", "pref-drop",- "--vault", vault, "--force",- ],+ ["brain", "merge", "pref-keep", "pref-drop", "--vault", vault, "--force"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);expect(r.stdout).toContain("merged:");- expect(- existsSync(join(vault, "Brain", "preferences", "pref-drop.md")),- ).toBe(false);- expect(- existsSync(join(vault, "Brain", "retired", "ret-drop.md")),- ).toBe(true);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-drop.md"))).toBe(false);+ expect(existsSync(join(vault, "Brain", "retired", "ret-drop.md"))).toBe(true);});test("non-TTY without --force exits 1 with the TTY guard message", async () => {@@ -186,22 +164,15 @@ describe("o2b brain merge — happy paths", () => {await bootstrap();makePref("keep");makePref("drop");- const r = await runCli(- ["brain", "merge", "pref-keep", "pref-drop", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "merge", "pref-keep", "pref-drop", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("--force required when stdin is not a TTY");// No mutation: drop still in preferences/, no retired/ entry.- expect(- existsSync(join(vault, "Brain", "preferences", "pref-drop.md")),- ).toBe(true);- expect(- existsSync(join(vault, "Brain", "retired", "ret-drop.md")),- ).toBe(false);- expect(- existsSync(join(vault, "Brain", "retired", "ret-drop.md")),- ).toBe(false);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-drop.md"))).toBe(true);+ expect(existsSync(join(vault, "Brain", "retired", "ret-drop.md"))).toBe(false);+ expect(existsSync(join(vault, "Brain", "retired", "ret-drop.md"))).toBe(false);});test("--json --dry-run emits parseable payload", async () => {@@ -209,10 +180,7 @@ describe("o2b brain merge — happy paths", () => {makePref("keep", { applied_count: 3, violated_count: 1 });makePref("drop", { applied_count: 2, violated_count: 0 });const r = await runCli(- [- "brain", "merge", "pref-keep", "pref-drop",- "--vault", vault, "--dry-run", "--json",- ],+ ["brain", "merge", "pref-keep", "pref-drop", "--vault", vault, "--dry-run", "--json"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);diff --git a/tests/cli/brain-moc-audit-cli.test.ts b/tests/cli/brain-moc-audit-cli.test.tsindex 95b01e35..1767e689 100644--- a/tests/cli/brain-moc-audit-cli.test.ts+++ b/tests/cli/brain-moc-audit-cli.test.ts@@ -14,11 +14,7 @@ let vault: string;let configHome: string;let configPath: string;-function writePref(- slug: string,- frontmatter: Record<string, string>,- body = "",-): void {+function writePref(slug: string, frontmatter: Record<string, string>, body = ""): void {const lines = ["---"];for (const [k, v] of Object.entries(frontmatter)) lines.push(`${k}: ${v}`);lines.push("---", "", body);diff --git a/tests/cli/brain-note.test.ts b/tests/cli/brain-note.test.tsindex 6abf62eb..f75152fc 100644--- a/tests/cli/brain-note.test.ts+++ b/tests/cli/brain-note.test.ts@@ -6,13 +6,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- readFileSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -55,12 +49,9 @@ describe("o2b brain note", () => {test("--json emits the structured result", async () => {writeFileSync(configPath, `vault: ${vault}\nagent_name: tester\n`, "utf8");- const r = await runCli(- ["brain", "note", "json output check", "--json"],- {- env: { OPEN_SECOND_BRAIN_CONFIG: configPath, VAULT_AGENT_NAME: "" },- },- );+ const r = await runCli(["brain", "note", "json output check", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath, VAULT_AGENT_NAME: "" },+ });expect(r.returncode).toBe(0);const parsed = JSON.parse(r.stdout);expect(parsed.ok).toBe(true);diff --git a/tests/cli/brain-summary-cli.test.ts b/tests/cli/brain-summary-cli.test.tsindex 43300e22..31d66d57 100644--- a/tests/cli/brain-summary-cli.test.ts+++ b/tests/cli/brain-summary-cli.test.ts@@ -62,10 +62,9 @@ describe("o2b brain summary", () => {});test("rejects --top-actions=-1", async () => {- const r = await runCli(- ["brain", "summary", "--skip-dream", "--top-actions", "-1"],- { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },- );+ const r = await runCli(["brain", "summary", "--skip-dream", "--top-actions", "-1"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });expect(r.returncode).toBe(1);});});diff --git a/tests/cli/brain-synthesise-cli.test.ts b/tests/cli/brain-synthesise-cli.test.tsindex a2055cc2..2ef1e213 100644--- a/tests/cli/brain-synthesise-cli.test.ts+++ b/tests/cli/brain-synthesise-cli.test.ts@@ -27,11 +27,7 @@ const DERIVED_KEYS = new Set(["confirmed_at",]);-function writePref(- slug: string,- frontmatter: Record<string, string>,- body = "",-): void {+function writePref(slug: string, frontmatter: Record<string, string>, body = ""): void {const lines = ["---"];for (const [k, v] of Object.entries(frontmatter)) {const key = DERIVED_KEYS.has(k) ? `_${k}` : k;@@ -120,10 +116,9 @@ describe("o2b brain synthesise", () => {},"I mention Subject Line in prose.",);- const r = await runCli(- ["brain", "synthesise", "pref-tgt", "--include-unlinked", "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },- );+ const r = await runCli(["brain", "synthesise", "pref-tgt", "--include-unlinked", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout) as {unlinked_mentions: Array<{ source: string }>;diff --git a/tests/cli/brain-temporal-cli.test.ts b/tests/cli/brain-temporal-cli.test.tsindex 42387f04..b03c8fa0 100644--- a/tests/cli/brain-temporal-cli.test.ts+++ b/tests/cli/brain-temporal-cli.test.ts@@ -23,14 +23,9 @@ interface FixtureEvent {readonly body: Record<string, string | ReadonlyArray<string>>;}-function writeJsonl(- date: string,- events: ReadonlyArray<FixtureEvent>,-): void {+function writeJsonl(date: string, events: ReadonlyArray<FixtureEvent>): void {const lines = events- .map((e) =>- JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),- )+ .map((e) => JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body })).join("\n");writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");}@@ -78,20 +73,18 @@ describe("o2b brain timeline", () => {});test("--limit -3 surfaces as exit 1", async () => {- const r = await runCli(- ["brain", "timeline", "--limit", "-3", "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },- );+ const r = await runCli(["brain", "timeline", "--limit", "-3", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });expect(r.returncode).toBe(1);});});describe("o2b brain evolution", () => {test("--pref-id --json exits 0", async () => {- const r = await runCli(- ["brain", "evolution", "--pref-id", "pref-foo", "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },- );+ const r = await runCli(["brain", "evolution", "--pref-id", "pref-foo", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout);expect(payload.target).toEqual({ prefId: "pref-foo" });@@ -106,15 +99,7 @@ describe("o2b brain evolution", () => {test("both --pref-id and --topic exits non-zero", async () => {const r = await runCli(- [- "brain",- "evolution",- "--pref-id",- "pref-foo",- "--topic",- "foo",- "--json",- ],+ ["brain", "evolution", "--pref-id", "pref-foo", "--topic", "foo", "--json"],{ env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },);expect(r.returncode).toBe(1);@@ -135,10 +120,9 @@ describe("o2b brain stale", () => {describe("o2b brain daily", () => {test("--date --json exits 0", async () => {- const r = await runCli(- ["brain", "daily", "--date", "2026-05-20", "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },- );+ const r = await runCli(["brain", "daily", "--date", "2026-05-20", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout);expect(payload.date).toBe("2026-05-20");@@ -147,10 +131,9 @@ describe("o2b brain daily", () => {describe("o2b brain weekly", () => {test("--week-end --json exits 0", async () => {- const r = await runCli(- ["brain", "weekly", "--week-end", "2026-05-25", "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },- );+ const r = await runCli(["brain", "weekly", "--week-end", "2026-05-25", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout);expect(payload.windowEnd).toBe("2026-05-25T00:00:00Z");diff --git a/tests/cli/brain-unlinked-cli.test.ts b/tests/cli/brain-unlinked-cli.test.tsindex 877e2475..3e625dca 100644--- a/tests/cli/brain-unlinked-cli.test.ts+++ b/tests/cli/brain-unlinked-cli.test.ts@@ -14,11 +14,7 @@ let vault: string;let configHome: string;let configPath: string;-function writePref(- slug: string,- frontmatter: Record<string, string>,- body = "",-): void {+function writePref(slug: string, frontmatter: Record<string, string>, body = ""): void {const lines = ["---"];for (const [k, v] of Object.entries(frontmatter)) lines.push(`${k}: ${v}`);lines.push("---", "", body);@@ -86,7 +82,12 @@ describe("o2b brain unlinked", () => {const payload = JSON.parse(r.stdout) as {id: string;count: number;- mentions: Array<{ source: string; line: number; term: string; context: string }>;+ mentions: Array<{+ source: string;+ line: number;+ term: string;+ context: string;+ }>;};expect(payload.id).toBe("pref-tgt");expect(payload.count).toBe(1);@@ -94,17 +95,12 @@ describe("o2b brain unlinked", () => {expect(payload.mentions[0]!.term).toBe("Subject Line");});- test("rejects --limit=0", async () => {- const r = await runCli(["brain", "unlinked", "pref-x", "--limit", "0"], {- env: { OPEN_SECOND_BRAIN_CONFIG: configPath },- });- expect(r.returncode).toBe(1);- });-- test("rejects --limit=abc", async () => {- const r = await runCli(["brain", "unlinked", "pref-x", "--limit", "abc"], {- env: { OPEN_SECOND_BRAIN_CONFIG: configPath },- });- expect(r.returncode).toBe(1);+ test("rejects invalid --limit values", async () => {+ for (const limit of ["0", "abc"]) {+ const r = await runCli(["brain", "unlinked", "pref-x", "--limit", limit], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(1);+ }});});diff --git a/tests/cli/brain-upgrade.test.ts b/tests/cli/brain-upgrade.test.tsindex f1d4f789..932cdadf 100644--- a/tests/cli/brain-upgrade.test.ts+++ b/tests/cli/brain-upgrade.test.ts@@ -8,13 +8,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- existsSync,- mkdtempSync,- readFileSync,- rmSync,- writeFileSync,-} from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -45,20 +39,18 @@ async function bootstrap(): Promise<void> {describe("brain upgrade", () => {test("clean vault → dry-run reports up-to-date, exit 0", async () => {await bootstrap();- const r = await runCli(- ["brain", "upgrade", "--vault", vault, "--dry-run"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("up to date");});test("--check on clean vault → exit 0", async () => {await bootstrap();- const r = await runCli(- ["brain", "upgrade", "--vault", vault, "--check"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--check"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);});@@ -66,10 +58,9 @@ describe("brain upgrade", () => {await bootstrap();// Drift: stale operator copy of _BRAIN.md.writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");- const r = await runCli(- ["brain", "upgrade", "--vault", vault, "--check"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--check"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);expect(r.stdout).toContain("Brain/_BRAIN.md");});@@ -77,10 +68,9 @@ describe("brain upgrade", () => {test("--dry-run with pending updates → exit 0, shows the diff", async () => {await bootstrap();writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");- const r = await runCli(- ["brain", "upgrade", "--vault", vault, "--dry-run"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("update");expect(r.stdout).toContain("--- Brain/_BRAIN.md (live)");@@ -90,10 +80,9 @@ describe("brain upgrade", () => {test("--apply --yes rewrites pending files and creates upgrade-<ts> snapshot", async () => {await bootstrap();writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");- const r = await runCli(- ["brain", "upgrade", "--vault", vault, "--apply", "--yes"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--apply", "--yes"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toMatch(/run_id: upgrade-/);expect(r.stdout).toContain("Brain/_BRAIN.md");@@ -102,21 +91,16 @@ describe("brain upgrade", () => {const body = readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8");expect(body).not.toBe("stale\n");// A snapshot named upgrade-<ts> landed under .snapshots/.- const snapEntries = require("node:fs").readdirSync(- join(vault, "Brain", ".snapshots"),- );- expect(- snapEntries.some((n: string) => n.startsWith("upgrade-")),- ).toBe(true);+ const snapEntries = require("node:fs").readdirSync(join(vault, "Brain", ".snapshots"));+ expect(snapEntries.some((n: string) => n.startsWith("upgrade-"))).toBe(true);});test("--apply in --json mode requires --yes (non-interactive guard)", async () => {await bootstrap();writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");- const r = await runCli(- ["brain", "upgrade", "--vault", vault, "--apply", "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--apply", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("--yes");});@@ -124,49 +108,40 @@ describe("brain upgrade", () => {test("--apply on clean vault → no snapshot, no log, exit 0", async () => {await bootstrap();const snapsBefore = existsSync(join(vault, "Brain", ".snapshots"))- ? require("node:fs").readdirSync(join(vault, "Brain", ".snapshots"))- .length+ ? require("node:fs").readdirSync(join(vault, "Brain", ".snapshots")).length: 0;- const r = await runCli(- ["brain", "upgrade", "--vault", vault, "--apply", "--yes"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--apply", "--yes"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("nothing to do");const snapsAfter = existsSync(join(vault, "Brain", ".snapshots"))- ? require("node:fs").readdirSync(join(vault, "Brain", ".snapshots"))- .length+ ? require("node:fs").readdirSync(join(vault, "Brain", ".snapshots")).length: 0;expect(snapsAfter).toBe(snapsBefore);});test("malformed _brain.yaml reports error in plan and refuses --apply", async () => {await bootstrap();- writeFileSync(- join(vault, "Brain", "_brain.yaml"),- "not: a valid: brain yaml\n",- );- const dry = await runCli(- ["brain", "upgrade", "--vault", vault, "--dry-run"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "not: a valid: brain yaml\n");+ const dry = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(dry.returncode).toBe(0);expect(dry.stdout).toMatch(/ERROR/);- const apply = await runCli(- ["brain", "upgrade", "--vault", vault, "--apply", "--yes"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const apply = await runCli(["brain", "upgrade", "--vault", vault, "--apply", "--yes"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(apply.returncode).toBe(1);expect(apply.stderr).toContain("upgrade aborted");});test("--dry-run and --apply are mutually exclusive", async () => {await bootstrap();- const r = await runCli(- ["brain", "upgrade", "--vault", vault, "--dry-run", "--apply"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run", "--apply"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("mutually exclusive");});@@ -174,10 +149,9 @@ describe("brain upgrade", () => {test("--json --dry-run emits structured plan", async () => {await bootstrap();writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");- const r = await runCli(- ["brain", "upgrade", "--vault", vault, "--dry-run", "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout) as {pending: number;@@ -185,8 +159,8 @@ describe("brain upgrade", () => {files: Array<{ path: string; status: string }>;};expect(payload.pending).toBeGreaterThanOrEqual(1);- expect(- payload.files.some((f) => f.path === "Brain/_BRAIN.md" && f.status === "update"),- ).toBe(true);+ expect(payload.files.some((f) => f.path === "Brain/_BRAIN.md" && f.status === "update")).toBe(+ true,+ );});});diff --git a/tests/cli/brain.snapshot-diff.test.ts b/tests/cli/brain.snapshot-diff.test.tsindex 240bcd8a..19ba4abf 100644--- a/tests/cli/brain.snapshot-diff.test.ts+++ b/tests/cli/brain.snapshot-diff.test.ts@@ -8,13 +8,7 @@* markdown / JSON output channels.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -50,12 +44,18 @@ async function seedDream(): Promise<string> {for (const slug of ["a", "b", "c"]) {const r = await runCli([- "brain", "feedback",- "--vault", vault,- "--topic", "diff-demo",- "--signal", "positive",- "--principle", "Take care",- "--slug", `diff-demo-${slug}`,+ "brain",+ "feedback",+ "--vault",+ vault,+ "--topic",+ "diff-demo",+ "--signal",+ "positive",+ "--principle",+ "Take care",+ "--slug",+ `diff-demo-${slug}`,],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -65,10 +65,9 @@ async function seedDream(): Promise<string> {env: { OPEN_SECOND_BRAIN_CONFIG: config },});expect(d.returncode).toBe(0);- const list = await runCli(- ["brain", "rollback", "--list", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const list = await runCli(["brain", "rollback", "--list", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(list.returncode).toBe(0);const snaps = JSON.parse(list.stdout) as ReadonlyArray<{ run_id: string }>;expect(snaps.length).toBeGreaterThan(0);@@ -104,27 +103,24 @@ pinned: false`,"utf8",);- const r = await runCli(- ["brain", "rollback", runId, "--dry-run", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "rollback", runId, "--dry-run", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toMatch(/^# Brain snapshot diff$/m);expect(r.stdout).toMatch(/^- A: live$/m);expect(r.stdout).toContain(`- B: ${runId}`);expect(r.stdout).toMatch(/^- - \[\[pref-extra\|Added after snapshot\]\] \(removed\)$/m);// Live tree must NOT have been touched.- expect(existsSync(join(vault, "Brain", "preferences", "pref-extra.md")))- .toBe(true);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-extra.md"))).toBe(true);});test("--dry-run + --yes is an error", async () => {await bootstrap();const runId = await seedDream();- const r = await runCli(- ["brain", "rollback", runId, "--dry-run", "--yes", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "rollback", runId, "--dry-run", "--yes", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toMatch(/mutually exclusive/);});@@ -132,10 +128,9 @@ pinned: falsetest("--dry-run --json returns parseable JSON", async () => {await bootstrap();const runId = await seedDream();- const r = await runCli(- ["brain", "rollback", runId, "--dry-run", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "rollback", runId, "--dry-run", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout);expect(payload).toHaveProperty("added");@@ -145,10 +140,9 @@ pinned: falsetest("unknown run_id exits 2", async () => {await bootstrap();- const r = await runCli(- ["brain", "rollback", "no-such-run", "--dry-run", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "rollback", "no-such-run", "--dry-run", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);});});@@ -181,10 +175,9 @@ pinned: false`,"utf8",);- const r = await runCli(- ["brain", "snapshot", "diff", runId, "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "snapshot", "diff", runId, "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toMatch(/^- B: live$/m);expect(r.stdout).toMatch(/\[\[pref-added\|Added principle\]\]/);@@ -196,12 +189,18 @@ pinned: false// Add evidence and run dream again so a second snapshot is created.const fb = await runCli([- "brain", "feedback",- "--vault", vault,- "--topic", "again",- "--signal", "positive",- "--principle", "Be careful",- "--slug", "again-1",+ "brain",+ "feedback",+ "--vault",+ vault,+ "--topic",+ "again",+ "--signal",+ "positive",+ "--principle",+ "Be careful",+ "--slug",+ "again-1",],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -209,12 +208,18 @@ pinned: falsefor (const s of ["2", "3"]) {const seed = await runCli([- "brain", "feedback",- "--vault", vault,- "--topic", "again",- "--signal", "positive",- "--principle", "Be careful",- "--slug", `again-${s}`,+ "brain",+ "feedback",+ "--vault",+ vault,+ "--topic",+ "again",+ "--signal",+ "positive",+ "--principle",+ "Be careful",+ "--slug",+ `again-${s}`,],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -224,17 +229,15 @@ pinned: falseenv: { OPEN_SECOND_BRAIN_CONFIG: config },});expect(d2.returncode).toBe(0);- const list = await runCli(- ["brain", "rollback", "--list", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const list = await runCli(["brain", "rollback", "--list", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });const snaps = JSON.parse(list.stdout) as ReadonlyArray<{ run_id: string }>;expect(snaps.length).toBeGreaterThanOrEqual(2);const second = snaps.find((s) => s.run_id !== first)!.run_id;- const r = await runCli(- ["brain", "snapshot", "diff", first, second, "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "snapshot", "diff", first, second, "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain(`- A: ${first}`);expect(r.stdout).toContain(`- B: ${second}`);@@ -243,10 +246,9 @@ pinned: falsetest("--json returns parseable JSON", async () => {await bootstrap();const runId = await seedDream();- const r = await runCli(- ["brain", "snapshot", "diff", runId, "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "snapshot", "diff", runId, "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const parsed = JSON.parse(r.stdout);expect(parsed).toHaveProperty("added");@@ -254,19 +256,17 @@ pinned: falsetest("missing positional arg exits 1", async () => {await bootstrap();- const r = await runCli(- ["brain", "snapshot", "diff", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "snapshot", "diff", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);});test("unknown run_id exits 2", async () => {await bootstrap();- const r = await runCli(- ["brain", "snapshot", "diff", "no-such-run", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "snapshot", "diff", "no-such-run", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);});@@ -283,10 +283,9 @@ pinned: falsetest("unknown sub-verb exits 2", async () => {await bootstrap();- const r = await runCli(- ["brain", "snapshot", "no-such-verb", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "snapshot", "no-such-verb", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);});});diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.tsindex 61b530fe..5864d854 100644--- a/tests/cli/brain.test.ts+++ b/tests/cli/brain.test.ts@@ -147,10 +147,9 @@ describe("brain init", () => {env: { OPEN_SECOND_BRAIN_CONFIG: config },});expect(init.returncode).toBe(0);- const r = await runCli(- ["brain", "init", "--vault", vault, "--primary-agent", "hermes-vps"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "init", "--vault", vault, "--primary-agent", "hermes-vps"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");expect(yaml).toMatch(/^primary_agent: "hermes-vps"$/m);@@ -161,10 +160,9 @@ describe("brain init", () => {env: { OPEN_SECOND_BRAIN_CONFIG: config },});expect(init.returncode).toBe(0);- const r = await runCli(- ["brain", "init", "--vault", vault, "--primary-agent", " "],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "init", "--vault", vault, "--primary-agent", " "], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr.toLowerCase()).toContain("primary-agent");});@@ -173,10 +171,9 @@ describe("brain init", () => {describe("brain set-primary", () => {test("writes the agent name into _brain.yaml", async () => {await bootstrap();- const r = await runCli(- ["brain", "set-primary", "hermes-vps", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("primary_agent: null → hermes-vps");const yaml = readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8");@@ -185,47 +182,41 @@ describe("brain set-primary", () => {test("repeat call is a no-op", async () => {await bootstrap();- await runCli(- ["brain", "set-primary", "hermes-vps", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );- const r = await runCli(- ["brain", "set-primary", "hermes-vps", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const r = await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("already set to hermes-vps");});test("--clear restores null", async () => {await bootstrap();- await runCli(- ["brain", "set-primary", "hermes-vps", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );- const r = await runCli(- ["brain", "set-primary", "--clear", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const r = await runCli(["brain", "set-primary", "--clear", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("hermes-vps → null");});test("missing positional and missing --clear exits 1", async () => {await bootstrap();- const r = await runCli(- ["brain", "set-primary", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "set-primary", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);});test("--json emits structured output", async () => {await bootstrap();- const r = await runCli(- ["brain", "set-primary", "hermes-vps", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "set-primary", "hermes-vps", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const parsed = JSON.parse(r.stdout);expect(parsed.previous).toBeNull();@@ -257,8 +248,7 @@ describe("brain feedback", () => {expect(r.returncode).toBe(0);expect(r.stdout).toContain("signal: ");expect(r.stdout).toContain("id: sig-");- const inbox = readdirSync(join(vault, "Brain", "inbox"))- .filter((n) => n.endsWith(".md"));+ const inbox = readdirSync(join(vault, "Brain", "inbox")).filter((n) => n.endsWith(".md"));expect(inbox.length).toBe(1);const body = readFileSync(join(vault, "Brain", "inbox", inbox[0]!), "utf8");expect(body).toContain("no-abbrev");@@ -268,16 +258,7 @@ describe("brain feedback", () => {test("missing --topic exits 1 naming the flag", async () => {await bootstrap();const r = await runCli(- [- "brain",- "feedback",- "--vault",- vault,- "--signal",- "positive",- "--principle",- "x",- ],+ ["brain", "feedback", "--vault", vault, "--signal", "positive", "--principle", "x"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(1);@@ -337,10 +318,9 @@ describe("brain feedback", () => {describe("brain dream", () => {test("happy path on empty vault returns no-op", async () => {await bootstrap();- const r = await runCli(- ["brain", "dream", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "dream", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout);expect(payload.changed).toBe(false);@@ -348,43 +328,18 @@ describe("brain dream", () => {test("--now must be ISO-8601", async () => {await bootstrap();- const r = await runCli(- ["brain", "dream", "--vault", vault, "--now", "not-a-date"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );- expect(r.returncode).toBe(1);- expect(r.stderr).toContain("--now");- });-- test("--now rejects permissive partial dates like a bare year", async () => {- // `new Date("2026")` happily returns 2026-01-01T00:00:00Z, which- // would silently let an under-specified `--now` value through. The- // strict ISO-8601 pattern rejects it.- await bootstrap();- const r = await runCli(- ["brain", "dream", "--vault", vault, "--now", "2026"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );- expect(r.returncode).toBe(1);- expect(r.stderr).toContain("--now");- });-- test("--now rejects date-only strings without time/timezone", async () => {- await bootstrap();- const r = await runCli(- ["brain", "dream", "--vault", vault, "--now", "2026-05-15"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "dream", "--vault", vault, "--now", "not-a-date"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("--now");});test("blank --agent exits 1 instead of falling back to the resolved default", async () => {await bootstrap();- const r = await runCli(- ["brain", "dream", "--vault", vault, "--agent", " "],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "dream", "--vault", vault, "--agent", " "], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("--agent");});@@ -393,10 +348,9 @@ describe("brain dream", () => {describe("brain apply-evidence", () => {test("missing required flag exits 1 naming the flag", async () => {await bootstrap();- const r = await runCli(- ["brain", "apply-evidence", "--vault", vault, "--artifact", "[[foo]]"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "apply-evidence", "--vault", vault, "--artifact", "[[foo]]"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("--pref");});@@ -467,9 +421,7 @@ describe("brain apply-evidence", () => {);expect(r.returncode).toBe(0);expect(r.stdout).toContain("logged:");- const logs = readdirSync(join(vault, "Brain", "log")).filter((n) =>- n.endsWith(".md"),- );+ const logs = readdirSync(join(vault, "Brain", "log")).filter((n) => n.endsWith(".md"));expect(logs.length).toBe(1);const body = readFileSync(join(vault, "Brain", "log", logs[0]!), "utf8");expect(body).toContain("apply-evidence");@@ -489,20 +441,18 @@ describe("brain digest", () => {test("--silent-if-empty exits 2 with no body", async () => {await bootstrap();- const r = await runCli(- ["brain", "digest", "--vault", vault, "--silent-if-empty"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "digest", "--vault", vault, "--silent-if-empty"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);expect(r.stdout.trim()).toBe("");});test("--json emits structured payload", async () => {await bootstrap();- const r = await runCli(- ["brain", "digest", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "digest", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout);expect(payload.schema_version).toBe(1);@@ -534,20 +484,18 @@ describe("brain query", () => {test("--preference on missing pref exits 2", async () => {await bootstrap();- const r = await runCli(- ["brain", "query", "--vault", vault, "--preference", "pref-nope"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "query", "--vault", vault, "--preference", "pref-nope"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);expect(r.stderr).toContain("brain query");});test("--since requires ISO timestamp", async () => {await bootstrap();- const r = await runCli(- ["brain", "query", "--vault", vault, "--since", "garbage"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "query", "--vault", vault, "--since", "garbage"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("--since");});@@ -605,10 +553,9 @@ describe("brain reject", () => {test("missing --reason exits 1 (mandatory from v0.10.1)", async () => {await bootstrap();- const r = await runCli(- ["brain", "reject", "--vault", vault, "--id", "pref-ghost"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "reject", "--vault", vault, "--id", "pref-ghost"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("--reason");});@@ -616,16 +563,7 @@ describe("brain reject", () => {test("unknown pref exits 2", async () => {await bootstrap();const r = await runCli(- [- "brain",- "reject",- "--vault",- vault,- "--id",- "pref-ghost",- "--reason",- "ghost",- ],+ ["brain", "reject", "--vault", vault, "--id", "pref-ghost", "--reason", "ghost"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(2);@@ -652,10 +590,9 @@ describe("brain reject", () => {],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);- const pin = await runCli(- ["brain", "pin", "--vault", vault, "--id", "pref-important"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const pin = await runCli(["brain", "pin", "--vault", vault, "--id", "pref-important"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(pin.returncode).toBe(0);const r = await runCli(@@ -698,10 +635,9 @@ describe("brain reject", () => {],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);- await runCli(- ["brain", "pin", "--vault", vault, "--id", "pref-important"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ await runCli(["brain", "pin", "--vault", vault, "--id", "pref-important"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });const r = await runCli(["brain",@@ -719,10 +655,7 @@ describe("brain reject", () => {expect(r.returncode).toBe(0);expect(existsSync(join(vault, "Brain", "retired", "ret-important.md"))).toBe(true);// §6: the user reason must land on the retired file's frontmatter.- const ret = readFileSync(- join(vault, "Brain", "retired", "ret-important.md"),- "utf8",- );+ const ret = readFileSync(join(vault, "Brain", "retired", "ret-important.md"), "utf8");expect(ret).toContain("user_rejected_reason: no longer the right call");});});@@ -752,16 +685,14 @@ describe("brain pin / unpin", () => {test("pin then idempotent rerun", async () => {await seedPref();- const r1 = await runCli(- ["brain", "pin", "--vault", vault, "--id", "pref-rule"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r1 = await runCli(["brain", "pin", "--vault", vault, "--id", "pref-rule"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r1.returncode).toBe(0);expect(r1.stdout).toContain("pinned: pref-rule");- const r2 = await runCli(- ["brain", "pin", "--vault", vault, "--id", "pref-rule"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r2 = await runCli(["brain", "pin", "--vault", vault, "--id", "pref-rule"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r2.returncode).toBe(0);expect(r2.stdout).toContain("already pinned");});@@ -771,10 +702,9 @@ describe("brain pin / unpin", () => {await runCli(["brain", "pin", "--vault", vault, "--id", "pref-rule"], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});- const r = await runCli(- ["brain", "unpin", "--vault", vault, "--id", "pref-rule"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "unpin", "--vault", vault, "--id", "pref-rule"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("unpinned: pref-rule");});@@ -814,10 +744,9 @@ describe("brain rollback", () => {await runCli(["brain", "dream", "--vault", vault], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});- const r = await runCli(- ["brain", "rollback", "--vault", vault, "--list", "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "rollback", "--vault", vault, "--list", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const list = JSON.parse(r.stdout) as Array<{ run_id: string }>;// Snapshot may or may not have been written depending on whether@@ -837,10 +766,9 @@ describe("brain rollback", () => {test("unknown run_id exits 2", async () => {await bootstrap();- const r = await runCli(- ["brain", "rollback", "--vault", vault, "no-such-run", "--yes"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "rollback", "--vault", vault, "no-such-run", "--yes"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);expect(r.stderr.toLowerCase()).toContain("snapshot not found");});@@ -851,10 +779,9 @@ describe("brain rollback", () => {// --json — otherwise scripted callers deadlock waiting for stdin.// The new non-interactive guard short-circuits before the snapshot// existence probe; we treat that as the contract under test.- const r = await runCli(- ["brain", "rollback", "--vault", vault, "any-run", "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "rollback", "--vault", vault, "any-run", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });// Either 1 (non-interactive guard) or 2 (snapshot-not-found) is// acceptable as long as the call returns without hanging. The// crucial bit is no timeout.@@ -882,10 +809,9 @@ describe("brain rollback", () => {{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);// 2. Dream creates a snapshot.- const dr = await runCli(- ["brain", "dream", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const dr = await runCli(["brain", "dream", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(dr.returncode).toBe(0);const dpayload = JSON.parse(dr.stdout) as {run_id: string;@@ -916,23 +842,13 @@ describe("brain rollback", () => {{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(- readdirSync(join(vault, "Brain", "inbox")).filter((n) =>- n.endsWith(".md"),- ).length,+ readdirSync(join(vault, "Brain", "inbox")).filter((n) => n.endsWith(".md")).length,).toBeGreaterThanOrEqual(1);// 4. Rollback to the snapshot. State B drifted (a new signal// landed after the snapshot), so v0.10.6 rollback requires// --force-rollback to overwrite the live tree.const r = await runCli(- [- "brain",- "rollback",- "--vault",- vault,- dpayload.run_id,- "--yes",- "--force-rollback",- ],+ ["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes", "--force-rollback"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);@@ -959,11 +875,13 @@ describe("brain rollback", () => {],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);- const dr = await runCli(- ["brain", "dream", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );- const dpayload = JSON.parse(dr.stdout) as { run_id: string; changed: boolean };+ const dr = await runCli(["brain", "dream", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const dpayload = JSON.parse(dr.stdout) as {+ run_id: string;+ changed: boolean;+ };if (!dpayload.changed) return;// Drift: second signal lands after the snapshot.@@ -984,17 +902,9 @@ describe("brain rollback", () => {],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);- const r = await runCli(- [- "brain",- "rollback",- "--vault",- vault,- dpayload.run_id,- "--yes",- ],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);expect(r.stderr).toContain("Drift detected");expect(r.stderr).toContain("--force-rollback");@@ -1019,11 +929,13 @@ describe("brain rollback", () => {],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);- const dr = await runCli(- ["brain", "dream", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );- const dpayload = JSON.parse(dr.stdout) as { run_id: string; changed: boolean };+ const dr = await runCli(["brain", "dream", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const dpayload = JSON.parse(dr.stdout) as {+ run_id: string;+ changed: boolean;+ };if (!dpayload.changed) return;await runCli(@@ -1044,15 +956,7 @@ describe("brain rollback", () => {{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);const r = await runCli(- [- "brain",- "rollback",- "--vault",- vault,- dpayload.run_id,- "--yes",- "--json",- ],+ ["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes", "--json"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(2);@@ -1086,33 +990,22 @@ describe("brain rollback", () => {],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);- const dr = await runCli(- ["brain", "dream", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );- const dpayload = JSON.parse(dr.stdout) as { run_id: string; changed: boolean };+ const dr = await runCli(["brain", "dream", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const dpayload = JSON.parse(dr.stdout) as {+ run_id: string;+ changed: boolean;+ };if (!dpayload.changed) return;// Simulate a pre-v0.10.6 snapshot: archive with no manifest.- const sidecar = join(- vault,- "Brain",- ".snapshots",- `${dpayload.run_id}.manifest.json`,- );+ const sidecar = join(vault, "Brain", ".snapshots", `${dpayload.run_id}.manifest.json`);rmSync(sidecar, { force: true });- const r = await runCli(- [- "brain",- "rollback",- "--vault",- vault,- dpayload.run_id,- "--yes",- ],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stderr).toContain("no manifest sidecar");expect(r.stderr).toContain("predates v0.10.6");@@ -1131,10 +1024,9 @@ describe("brain doctor", () => {test("--json emits structured output", async () => {await bootstrap();- const r = await runCli(- ["brain", "doctor", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "doctor", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout);expect(Array.isArray(payload.warnings)).toBe(true);@@ -1145,12 +1037,7 @@ describe("brain doctor", () => {await bootstrap();// Introduce a status-vs-folder warning: drop a `pref-` file whose// status doesn't match the folder.- const corrupt = join(- vault,- "Brain",- "preferences",- "pref-broken.md",- );+ const corrupt = join(vault, "Brain", "preferences", "pref-broken.md");// Use the same canonical shape as the writer so the parser surfaces// a status-folder mismatch (status='retired' under preferences/).mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });@@ -1181,10 +1068,9 @@ describe("brain doctor", () => {].join("\n"),"utf8",);- const r = await runCli(- ["brain", "doctor", "--vault", vault, "--strict"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "doctor", "--vault", vault, "--strict"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });// Status-folder mismatch is a warning; --strict promotes to exit 2.// An invariant-error path would land at exit 1 (errors), and that// also satisfies the spirit of "doctor surfaced the corruption", so@@ -1200,11 +1086,7 @@ describe("brain scan-inline", () => {await bootstrap();const notePath = join(vault, "Daily", "2026-05-16.md");mkdirSync(join(vault, "Daily"), { recursive: true });- writeFileSync(- notePath,- "@osb feedback negative topic=cli-test principle=p\n",- "utf8",- );+ writeFileSync(notePath, "@osb feedback negative topic=cli-test principle=p\n", "utf8");const r = await runCli(["brain", "scan-inline", "--vault", vault, "--path", "Daily"], {env: { OPEN_SECOND_BRAIN_CONFIG: config },@@ -1224,11 +1106,7 @@ describe("brain scan-inline", () => {await bootstrap();const notePath = join(vault, "Daily", "2026-05-16.md");mkdirSync(join(vault, "Daily"), { recursive: true });- writeFileSync(- notePath,- "@osb feedback negative topic=dry principle=p\n",- "utf8",- );+ writeFileSync(notePath, "@osb feedback negative topic=dry principle=p\n", "utf8");const before = readFileSync(notePath, "utf8");const r = await runCli(@@ -1282,14 +1160,10 @@ describe("brain scan-inline", () => {describe("brain import-session", () => {test("imports a single .jsonl file and creates signals", async () => {await bootstrap();- const fixture = join(- process.cwd(),- "tests/fixtures/sessions/claude-minimal.jsonl",- );- const r = await runCli(- ["brain", "import-session", fixture, "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const fixture = join(process.cwd(), "tests/fixtures/sessions/claude-minimal.jsonl");+ const r = await runCli(["brain", "import-session", fixture, "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toMatch(/signals_created: [1-9]/);@@ -1300,31 +1174,21 @@ describe("brain import-session", () => {test("--dry-run does not create signals", async () => {await bootstrap();- const fixture = join(- process.cwd(),- "tests/fixtures/sessions/claude-minimal.jsonl",- );- const r = await runCli(- ["brain", "import-session", fixture, "--vault", vault, "--dry-run"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const fixture = join(process.cwd(), "tests/fixtures/sessions/claude-minimal.jsonl");+ const r = await runCli(["brain", "import-session", fixture, "--vault", vault, "--dry-run"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const inbox = join(vault, "Brain", "inbox");- expect(- readdirSync(inbox).filter((n) => n.startsWith("sig-")).length,- ).toBe(0);+ expect(readdirSync(inbox).filter((n) => n.startsWith("sig-")).length).toBe(0);});test("--json structured output", async () => {await bootstrap();- const fixture = join(- process.cwd(),- "tests/fixtures/sessions/codex-minimal.jsonl",- );- const r = await runCli(- ["brain", "import-session", fixture, "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const fixture = join(process.cwd(), "tests/fixtures/sessions/codex-minimal.jsonl");+ const r = await runCli(["brain", "import-session", fixture, "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const parsed = JSON.parse(r.stdout);expect(parsed.ok).toBe(true);@@ -1336,10 +1200,9 @@ describe("brain import-session", () => {await bootstrap();const junk = join(tmp, "junk.jsonl");writeFileSync(junk, '{"foo":"bar"}\n', "utf8");- const r = await runCli(- ["brain", "import-session", junk, "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "import-session", junk, "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);expect(r.stderr.toLowerCase()).toMatch(/autodetect|format/);});@@ -1359,10 +1222,9 @@ describe("brain vault resolution", () => {describe("brain protect", () => {test("--target claudecode --print returns the JSON shape, exit 0", async () => {await bootstrap();- const r = await runCli(- ["brain", "protect", "--target", "claudecode", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "protect", "--target", "claudecode", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("Write(");expect(r.stdout).toContain("preview only");@@ -1371,20 +1233,18 @@ describe("brain protect", () => {test("--target codex --print includes the managed fence", async () => {await bootstrap();- const r = await runCli(- ["brain", "protect", "--target", "codex", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "protect", "--target", "codex", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("# >>> open-second-brain managed >>>");});test("unknown --target exits 1 with a clear message", async () => {await bootstrap();- const r = await runCli(- ["brain", "protect", "--target", "vim", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["brain", "protect", "--target", "vim", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("unknown");expect(r.stderr).toContain("claudecode");@@ -1393,15 +1253,7 @@ describe("brain protect", () => {test("--apply writes settings.json and is idempotent", async () => {await bootstrap();const first = await runCli(- [- "brain",- "protect",- "--target",- "claudecode",- "--vault",- vault,- "--apply",- ],+ ["brain", "protect", "--target", "claudecode", "--vault", vault, "--apply"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(first.returncode).toBe(0);@@ -1411,15 +1263,7 @@ describe("brain protect", () => {expect(bytesAfterFirst).toContain("Write(");const second = await runCli(- [- "brain",- "protect",- "--target",- "claudecode",- "--vault",- vault,- "--apply",- ],+ ["brain", "protect", "--target", "claudecode", "--vault", vault, "--apply"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(second.returncode).toBe(0);@@ -1429,27 +1273,15 @@ describe("brain protect", () => {test("apply + unprotect round-trip leaves no managed entries", async () => {await bootstrap();- await runCli(- [- "brain",- "protect",- "--target",- "claudecode",- "--vault",- vault,- "--apply",- ],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );- const r = await runCli(- ["brain", "unprotect", "--target", "claudecode", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ await runCli(["brain", "protect", "--target", "claudecode", "--vault", vault, "--apply"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const r = await runCli(["brain", "unprotect", "--target", "claudecode", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("removed");- const parsed = JSON.parse(- readFileSync(join(vault, ".claude", "settings.json"), "utf8"),- );+ const parsed = JSON.parse(readFileSync(join(vault, ".claude", "settings.json"), "utf8"));// After unprotect, OSB-owned deny entries are gone. The keys may// remain empty (user could have other rules) — assert via filter.const ownedLeft = (parsed.permissions?.deny ?? []).filter((e: string) =>diff --git a/tests/cli/cli.test.ts b/tests/cli/cli.test.tsindex d1cb4f7f..1cf165c4 100644--- a/tests/cli/cli.test.ts+++ b/tests/cli/cli.test.ts@@ -1,5 +1,13 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync, readdirSync } from "node:fs";+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+ existsSync,+ readdirSync,+} from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";@@ -73,7 +81,17 @@ describe("init", () => {const vault = join(tmp, "vault");const config = join(tmp, "config.yaml");const r = await runCli(- ["init", "--vault", vault, "--name", "Test", "--agent-name", "hermes-vps-agent", "--timezone", "Europe/Belgrade"],+ [+ "init",+ "--vault",+ vault,+ "--name",+ "Test",+ "--agent-name",+ "hermes-vps-agent",+ "--timezone",+ "Europe/Belgrade",+ ],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);@@ -106,7 +124,6 @@ describe("init", () => {expect(r.stdout).toContain("agent name persisted to:");expect(readFileSync(config, "utf8")).toContain("hermes-vps-agent");});-});describe("doctor", () => {diff --git a/tests/cli/coerce.test.ts b/tests/cli/coerce.test.tsnew file mode 100644index 00000000..eb97c1e1--- /dev/null+++ b/tests/cli/coerce.test.ts@@ -0,0 +1,19 @@+import { describe, expect, test } from "bun:test";++import { parseOptionalIsoDate } from "../../src/cli/coerce.ts";++describe("parseOptionalIsoDate", () => {+ test("requires complete ISO-8601 timestamps instead of permissive Date input", () => {+ for (const raw of ["not-a-date", "2026", "2026-05-15"]) {+ const parsed = parseOptionalIsoDate({ now: raw }, "now");+ expect(parsed.value).toBeNull();+ expect(parsed.error).toContain("--now");+ }++ expect(parseOptionalIsoDate({ now: "2026-05-15T10:20:30Z" }, "now").error).toBeNull();+ expect(parseOptionalIsoDate({ now: "" }, "now")).toEqual({+ value: null,+ error: null,+ });+ });+});diff --git a/tests/cli/discipline-install.test.ts b/tests/cli/discipline-install.test.tsindex 9dc99d56..603d8bf2 100644--- a/tests/cli/discipline-install.test.ts+++ b/tests/cli/discipline-install.test.ts@@ -60,19 +60,13 @@ describe("o2b discipline install / uninstall", () => {expect(readJobs().jobs.length).toBe(1);// 3. Uninstall — job removed- const r3 = await runCli(- ["discipline", "uninstall", "--vault", vault],- { env },- );+ const r3 = await runCli(["discipline", "uninstall", "--vault", vault], { env });expect(r3.returncode).toBe(0);expect(r3.stdout).toContain("removed");expect(readJobs().jobs.length).toBe(0);// 4. Uninstall again — no-op, exits 0- const r4 = await runCli(- ["discipline", "uninstall", "--vault", vault],- { env },- );+ const r4 = await runCli(["discipline", "uninstall", "--vault", vault], { env });expect(r4.returncode).toBe(0);expect(r4.stdout).toContain("no-op");expect(readJobs().jobs.length).toBe(0);@@ -146,10 +140,7 @@ describe("o2b discipline install / uninstall", () => {test("install without --telegram-target exits 2 (no private chat id baked in)", async () => {const env = { OSB_HERMES_JOBS: jobsFile };- const r = await runCli(- ["discipline", "install", "--vault", vault],- { env },- );+ const r = await runCli(["discipline", "install", "--vault", vault], { env });expect(r.returncode).toBe(2);expect(r.stderr).toContain("--telegram-target is required");});@@ -169,15 +160,20 @@ describe("o2b discipline install / uninstall", () => {{ env },);await runCli(- ["discipline", "install", "--weekly", "--vault", vault, "--telegram-target", "telegram:-100123:42"],+ [+ "discipline",+ "install",+ "--weekly",+ "--vault",+ vault,+ "--telegram-target",+ "telegram:-100123:42",+ ],{ env },);expect(readJobs().jobs.length).toBe(2);- const r = await runCli(- ["discipline", "uninstall", "--vault", vault, "--weekly"],- { env },- );+ const r = await runCli(["discipline", "uninstall", "--vault", vault, "--weekly"], { env });expect(r.returncode).toBe(0);expect(r.stdout).toContain("removed");expect(readJobs().jobs.length).toBe(1);@@ -192,15 +188,20 @@ describe("o2b discipline install / uninstall", () => {{ env },);await runCli(- ["discipline", "install", "--weekly", "--vault", vault, "--telegram-target", "telegram:-100123:42"],+ [+ "discipline",+ "install",+ "--weekly",+ "--vault",+ vault,+ "--telegram-target",+ "telegram:-100123:42",+ ],{ env },);expect(readJobs().jobs.length).toBe(2);- const r = await runCli(- ["discipline", "uninstall", "--vault", vault],- { env },- );+ const r = await runCli(["discipline", "uninstall", "--vault", vault], { env });expect(r.returncode).toBe(0);expect(readJobs().jobs.length).toBe(0);});diff --git a/tests/cli/init-interactive.test.ts b/tests/cli/init-interactive.test.tsindex a5282c75..5dc0ad8d 100644--- a/tests/cli/init-interactive.test.ts+++ b/tests/cli/init-interactive.test.ts@@ -24,7 +24,9 @@ beforeEach(() => {home = mkdtempSync(join(tmpdir(), "osb-wizard-h-"));});afterEach(() => {- try { rmSync(home, { recursive: true, force: true }); } catch {}+ try {+ rmSync(home, { recursive: true, force: true });+ } catch {}});function scriptedReader(answers: string[]): WizardReader {@@ -43,10 +45,16 @@ function silentStreams() {const stdoutBuf: string[] = [];const stderrBuf: string[] = [];const stdout = new Writable({- write(chunk, _e, cb) { stdoutBuf.push(chunk.toString()); cb(); },+ write(chunk, _e, cb) {+ stdoutBuf.push(chunk.toString());+ cb();+ },});const stderr = new Writable({- write(chunk, _e, cb) { stderrBuf.push(chunk.toString()); cb(); },+ write(chunk, _e, cb) {+ stderrBuf.push(chunk.toString());+ cb();+ },});return {stdout: stdout as unknown as NodeJS.WriteStream,@@ -70,19 +78,22 @@ describe("init wizard", () => {const vaultPath = join(home, "vault");// ensure no candidate vault directory exists, so prompt 1 needs explicit pathconst answers = [- vaultPath, // vault path- "claude-vps", // agent name- "UTC", // timezone- "en", // language- "1,2", // pick targets 1 and 2 (whichever they are)- "y", // brain init- "n", // starter- "yes", // confirm+ vaultPath, // vault path+ "claude-vps", // agent name+ "UTC", // timezone+ "en", // language+ "1,2", // pick targets 1 and 2 (whichever they are)+ "y", // brain init+ "n", // starter+ "yes", // confirm];const { runner, calls } = recordingRunner();const { stdout, stderr } = silentStreams();const opts: WizardOpts = {- reader: scriptedReader(answers), stdout, stderr, runner,+ reader: scriptedReader(answers),+ stdout,+ stderr,+ runner,};const r = await runWizard(opts);expect(r.exitCode).toBe(0);@@ -117,15 +128,21 @@ describe("init wizard", () => {test("'no' at confirmation runs nothing", async () => {const vaultPath = join(home, "vault");const answers = [- vaultPath, "claude-vps", "UTC", "en",- "none", // no targets- "n", // no brain init- "no", // do not confirm+ vaultPath,+ "claude-vps",+ "UTC",+ "en",+ "none", // no targets+ "n", // no brain init+ "no", // do not confirm];const { runner, calls } = recordingRunner();const { stdout, stderr } = silentStreams();const opts: WizardOpts = {- reader: scriptedReader(answers), stdout, stderr, runner,+ reader: scriptedReader(answers),+ stdout,+ stderr,+ runner,};const r = await runWizard(opts);expect(r.exitCode).toBe(0);@@ -137,7 +154,7 @@ describe("init wizard", () => {const answers = [vaultPath,"claude-vps",- "Mars/Cydonia", // invalid IANA+ "Mars/Cydonia", // invalid IANA"Europe/Belgrade", // valid retry"en","none",@@ -147,7 +164,10 @@ describe("init wizard", () => {const { runner, calls } = recordingRunner();const { stdout, stderr, stdoutBuf } = silentStreams();const opts: WizardOpts = {- reader: scriptedReader(answers), stdout, stderr, runner,+ reader: scriptedReader(answers),+ stdout,+ stderr,+ runner,};const r = await runWizard(opts);expect(r.exitCode).toBe(0);@@ -157,14 +177,14 @@ describe("init wizard", () => {test("brain init with starter adds --starter flag", async () => {const vaultPath = join(home, "vault");- const answers = [- vaultPath, "claude-vps", "UTC", "en",- "none", "y", "y", "yes",- ];+ const answers = [vaultPath, "claude-vps", "UTC", "en", "none", "y", "y", "yes"];const { runner, calls } = recordingRunner();const { stdout, stderr } = silentStreams();const opts: WizardOpts = {- reader: scriptedReader(answers), stdout, stderr, runner,+ reader: scriptedReader(answers),+ stdout,+ stderr,+ runner,};const r = await runWizard(opts);expect(r.exitCode).toBe(0);@@ -178,7 +198,10 @@ describe("init wizard", () => {const runner: WizardRunner = async () => ({ exitCode: 1, stdout: "", stderr: "init failed" });const { stdout, stderr } = silentStreams();const opts: WizardOpts = {- reader: scriptedReader(answers), stdout, stderr, runner,+ reader: scriptedReader(answers),+ stdout,+ stderr,+ runner,};const r = await runWizard(opts);expect(r.exitCode).toBe(1);diff --git a/tests/cli/install-cli.test.ts b/tests/cli/install-cli.test.tsindex 1b0c5e89..dac46e01 100644--- a/tests/cli/install-cli.test.ts+++ b/tests/cli/install-cli.test.ts@@ -1,5 +1,13 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, lstatSync, mkdtempSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import {+ existsSync,+ lstatSync,+ mkdtempSync,+ readlinkSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -62,17 +70,15 @@ describe("uninstallCli", () => {symlinkSync(elsewhere, join(tmp, "o2b"));const result = uninstallCli(tmp);expect(result.errors).toEqual([]);- expect(result.outcomes.some(([n, msg]) => n === "o2b" && msg.includes("outside this repo"))).toBe(- true,- );+ expect(+ result.outcomes.some(([n, msg]) => n === "o2b" && msg.includes("outside this repo")),+ ).toBe(true);expect(existsSync(join(tmp, "o2b"))).toBe(true);});test("skips a link that doesn't exist", () => {const result = uninstallCli(tmp);expect(result.errors).toEqual([]);- expect(- result.outcomes.every(([_, msg]) => msg.startsWith("skipped:")),- ).toBe(true);+ expect(result.outcomes.every(([_, msg]) => msg.startsWith("skipped:"))).toBe(true);});});diff --git a/tests/cli/install-verb.test.ts b/tests/cli/install-verb.test.tsindex bebae3c2..1af93c7c 100644--- a/tests/cli/install-verb.test.ts+++ b/tests/cli/install-verb.test.ts@@ -21,14 +21,13 @@ beforeEach(() => {vault = mkdtempSync(join(tmpdir(), "osb-install-verb-v-"));home = mkdtempSync(join(tmpdir(), "osb-install-verb-h-"));configPath = join(home, "config.yaml");- writeFileSync(- configPath,- `vault: "${vault}"\nagent_name: "claude-vps"\ntimezone: "UTC"\n`,- );+ writeFileSync(configPath, `vault: "${vault}"\nagent_name: "claude-vps"\ntimezone: "UTC"\n`);});afterEach(() => {for (const p of [vault, home]) {- try { rmSync(p, { recursive: true, force: true }); } catch {}+ try {+ rmSync(p, { recursive: true, force: true });+ } catch {}}});@@ -80,10 +79,7 @@ describe("o2b install --target X (plan-only)", () => {describe("o2b install --target X --apply", () => {test("writes the cursor config file", async () => {- const r = await runCli(- ["install", "--target", "cursor", "--apply"],- { env: envBase() },- );+ const r = await runCli(["install", "--target", "cursor", "--apply"], { env: envBase() });expect(r.returncode).toBe(0);const cfgPath = join(home, ".cursor", "mcp.json");expect(existsSync(cfgPath)).toBe(true);@@ -111,10 +107,9 @@ describe("o2b install --target X --apply", () => {describe("o2b install --target generic", () => {test("--out <path> writes the JSON payload to that path", async () => {const outPath = join(home, "snippet.json");- const r = await runCli(- ["install", "--target", "generic", "--apply", "--out", outPath],- { env: envBase() },- );+ const r = await runCli(["install", "--target", "generic", "--apply", "--out", outPath], {+ env: envBase(),+ });expect(r.returncode).toBe(0);expect(existsSync(outPath)).toBe(true);const parsed = JSON.parse(readFileSync(outPath, "utf8"));diff --git a/tests/cli/mcp-scope-arg.test.ts b/tests/cli/mcp-scope-arg.test.tsindex 0392e417..c4582beb 100644--- a/tests/cli/mcp-scope-arg.test.ts+++ b/tests/cli/mcp-scope-arg.test.ts@@ -28,20 +28,29 @@ describe("o2b mcp --scope arg validation", () => {test("--scope writer starts the server and answers tools/list", async () => {const init = JSON.stringify({- jsonrpc: "2.0", id: 1, method: "initialize",+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",params: { protocolVersion: "2025-06-18", capabilities: {} },});const list = JSON.stringify({- jsonrpc: "2.0", id: 2, method: "tools/list", params: {},+ jsonrpc: "2.0",+ id: 2,+ method: "tools/list",+ params: {},+ });+ const res = await runCli(["mcp", "--scope", "writer"], {+ stdin: `${init}\n${list}\n`,+ env: { VAULT_DIR: tmp },});- const res = await runCli(- ["mcp", "--scope", "writer"],- { stdin: `${init}\n${list}\n`, env: { VAULT_DIR: tmp } },- );expect(res.returncode).toBe(0);- const lines = res.stdout.trim().split("\n").map((l) => JSON.parse(l));+ const lines = res.stdout+ .trim()+ .split("\n")+ .map((l) => JSON.parse(l));const names = (lines[1].result.tools as Array<{ name: string }>)- .map((t) => t.name).sort();+ .map((t) => t.name)+ .toSorted();expect(names).toEqual(["brain_apply_evidence","brain_context",diff --git a/tests/cli/mcp-writer-probe.test.ts b/tests/cli/mcp-writer-probe.test.tsindex d89ed969..4e038a5e 100644--- a/tests/cli/mcp-writer-probe.test.ts+++ b/tests/cli/mcp-writer-probe.test.ts@@ -10,20 +10,29 @@ describe("o2b mcp --writer-only alias", () => {try {tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-wo-"));const init = JSON.stringify({- jsonrpc: "2.0", id: 1, method: "initialize",+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",params: { protocolVersion: "2025-06-18", capabilities: {} },});const list = JSON.stringify({- jsonrpc: "2.0", id: 2, method: "tools/list", params: {},+ jsonrpc: "2.0",+ id: 2,+ method: "tools/list",+ params: {},+ });+ const res = await runCli(["mcp", "--writer-only"], {+ stdin: `${init}\n${list}\n`,+ env: { VAULT_DIR: tmp },});- const res = await runCli(- ["mcp", "--writer-only"],- { stdin: `${init}\n${list}\n`, env: { VAULT_DIR: tmp } },- );expect(res.returncode).toBe(0);- const lines = res.stdout.trim().split("\n").map((l) => JSON.parse(l));+ const lines = res.stdout+ .trim()+ .split("\n")+ .map((l) => JSON.parse(l));const names = (lines[1].result.tools as Array<{ name: string }>)- .map((t) => t.name).sort();+ .map((t) => t.name)+ .toSorted();expect(names).toEqual(["brain_apply_evidence","brain_context",@@ -36,10 +45,7 @@ describe("o2b mcp --writer-only alias", () => {});test("--writer-only with --scope full is rejected (exit 2)", async () => {- const res = await runCli(- ["mcp", "--writer-only", "--scope", "full"],- { stdin: "" },- );+ const res = await runCli(["mcp", "--writer-only", "--scope", "full"], { stdin: "" });expect(res.returncode).toBe(2);expect(res.stderr).toContain("--writer-only");});@@ -49,13 +55,15 @@ describe("o2b mcp --writer-only alias", () => {try {tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-wo2-"));const init = JSON.stringify({- jsonrpc: "2.0", id: 1, method: "initialize",+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",params: { protocolVersion: "2025-06-18", capabilities: {} },});- const res = await runCli(- ["mcp", "--writer-only", "--scope", "writer"],- { stdin: `${init}\n`, env: { VAULT_DIR: tmp } },- );+ const res = await runCli(["mcp", "--writer-only", "--scope", "writer"], {+ stdin: `${init}\n`,+ env: { VAULT_DIR: tmp },+ });expect(res.returncode).toBe(0);} finally {if (tmp) rmSync(tmp, { recursive: true, force: true });@@ -65,24 +73,25 @@ describe("o2b mcp --writer-only alias", () => {describe("o2b mcp --probe", () => {let tmp: string;- beforeAll(() => { tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-probe-")); });- afterAll(() => { rmSync(tmp, { recursive: true, force: true }); });+ beforeAll(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-probe-"));+ });+ afterAll(() => {+ rmSync(tmp, { recursive: true, force: true });+ });test("--probe with valid vault exits 0 with tool count", async () => {- const res = await runCli(- ["mcp", "--probe"],- { stdin: "", env: { VAULT_DIR: tmp } },- );+ const res = await runCli(["mcp", "--probe"], { stdin: "", env: { VAULT_DIR: tmp } });expect(res.returncode).toBe(0);expect(res.stdout).toContain("mcp probe ok");expect(res.stdout).toMatch(/\d+ tools/);});test("--probe --writer-only reports the writer-scope tool count", async () => {- const res = await runCli(- ["mcp", "--probe", "--writer-only"],- { stdin: "", env: { VAULT_DIR: tmp } },- );+ const res = await runCli(["mcp", "--probe", "--writer-only"], {+ stdin: "",+ env: { VAULT_DIR: tmp },+ });expect(res.returncode).toBe(0);expect(res.stdout).toContain("open-second-brain-writer");expect(res.stdout).toMatch(/[1-9]\d* tools/);diff --git a/tests/cli/pay-memory.test.ts b/tests/cli/pay-memory.test.tsindex cd39ebd9..0731099e 100644--- a/tests/cli/pay-memory.test.ts+++ b/tests/cli/pay-memory.test.ts@@ -31,10 +31,9 @@ afterEach(() => {describe("init-pay-memory", () => {test("creates the layout, policy, and reports the agent", async () => {- const r = await runCli(- ["init-pay-memory", "--vault", vault, "--agent", "hermes-vps-agent"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["init-pay-memory", "--vault", vault, "--agent", "hermes-vps-agent"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("pay-memory layout initialized:");expect(r.stdout).toContain("agent: hermes-vps-agent");@@ -104,18 +103,30 @@ describe("append-payment-receipt", () => {const r = await runCli(["append-payment-receipt",- "--vault", vault,- "--agent", "hermes-vps-agent",- "--service", "paysponge/fal",- "--status", "success",- "--reason", "Generate one original blog header image",- "--actual-amount", "0.05",- "--currency", "USDC",- "--result-ref", "https://fal-cdn.example/img.png",- "--result-note", `${PAY_MEMORY_ASSETS_REL}/blog-header.md`,- "--raw-output-file", rawFile,- "--date", "2026-05-10",- "--time", "17:20",+ "--vault",+ vault,+ "--agent",+ "hermes-vps-agent",+ "--service",+ "paysponge/fal",+ "--status",+ "success",+ "--reason",+ "Generate one original blog header image",+ "--actual-amount",+ "0.05",+ "--currency",+ "USDC",+ "--result-ref",+ "https://fal-cdn.example/img.png",+ "--result-note",+ `${PAY_MEMORY_ASSETS_REL}/blog-header.md`,+ "--raw-output-file",+ rawFile,+ "--date",+ "2026-05-10",+ "--time",+ "17:20",],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -135,14 +146,22 @@ describe("append-payment-receipt", () => {});const args = ["append-payment-receipt",- "--vault", vault,- "--agent", "h",- "--service", "x/y",- "--status", "success",- "--reason", "test",- "--slug", "fixed-slug",- "--date", "2026-05-10",- "--time", "00:00",+ "--vault",+ vault,+ "--agent",+ "h",+ "--service",+ "x/y",+ "--status",+ "success",+ "--reason",+ "test",+ "--slug",+ "fixed-slug",+ "--date",+ "2026-05-10",+ "--time",+ "00:00",];const first = await runCli(args, { env: { OPEN_SECOND_BRAIN_CONFIG: config } });expect(first.returncode).toBe(0);@@ -175,13 +194,20 @@ describe("capture-asset", () => {const r = await runCli(["capture-asset",- "--vault", vault,- "--title", "Blog Header: Pay Memory",- "--service", "paysponge/fal",- "--result-url", "https://fal-cdn.example/img.png",- "--source-receipt", `${PAY_MEMORY_ROOT_REL}/2026-05-10/fal-blog.md`,- "--prompt-file", promptFile,- "--used-in", `${PAY_MEMORY_DRAFTS_REL}/blog-post.md`,+ "--vault",+ vault,+ "--title",+ "Blog Header: Pay Memory",+ "--service",+ "paysponge/fal",+ "--result-url",+ "https://fal-cdn.example/img.png",+ "--source-receipt",+ `${PAY_MEMORY_ROOT_REL}/2026-05-10/fal-blog.md`,+ "--prompt-file",+ promptFile,+ "--used-in",+ `${PAY_MEMORY_DRAFTS_REL}/blog-post.md`,],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -204,16 +230,26 @@ describe("payment-report", () => {const r = await runCli(["append-payment-receipt",- "--vault", vault,- "--agent", "h",- "--service", slug.startsWith("fal") ? "paysponge/fal" : "alpha/translate",- "--status", "success",- "--reason", `reason-${slug}`,- "--actual-amount", "0.03",- "--currency", "USDC",- "--slug", slug,- "--date", "2026-05-10",- "--time", "17:20",+ "--vault",+ vault,+ "--agent",+ "h",+ "--service",+ slug.startsWith("fal") ? "paysponge/fal" : "alpha/translate",+ "--status",+ "success",+ "--reason",+ `reason-${slug}`,+ "--actual-amount",+ "0.03",+ "--currency",+ "USDC",+ "--slug",+ slug,+ "--date",+ "2026-05-10",+ "--time",+ "17:20",],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -222,10 +258,14 @@ describe("payment-report", () => {const report = await runCli(["payment-report",- "--vault", vault,- "--date", "2026-05-10",- "--title", "Demo Report",- "--task", "test task",+ "--vault",+ vault,+ "--date",+ "2026-05-10",+ "--title",+ "Demo Report",+ "--task",+ "test task",],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -244,10 +284,9 @@ describe("payment-report", () => {await runCli(["init-pay-memory", "--vault", vault], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});- const r = await runCli(- ["payment-report", "--vault", vault, "--date", "2026.05.10"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["payment-report", "--vault", vault, "--date", "2026.05.10"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(1);expect(r.stderr).toContain("YYYY-MM-DD");});@@ -299,12 +338,7 @@ describe("check-payment-policy", () => {"utf8",);const r = await runCli(- [- "check-payment-policy",- "--vault", vault,- "--service", "x/y",- "--expected-amount", "0.07",- ],+ ["check-payment-policy", "--vault", vault, "--service", "x/y", "--expected-amount", "0.07"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(3);@@ -336,12 +370,7 @@ describe("check-payment-policy", () => {"utf8",);const r = await runCli(- [- "check-payment-policy",- "--vault", vault,- "--service", "x/y",- "--expected-amount", " ",- ],+ ["check-payment-policy", "--vault", vault, "--service", "x/y", "--expected-amount", " "],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);// approval_required → exit 3 (missing-amount guard fires)@@ -358,12 +387,18 @@ describe("approval workflow (request → approve → consume)", () => {const req = await runCli(["request-payment-approval",- "--vault", vault,- "--service", "paysponge/fal",- "--reason", "header image",- "--expected-amount", "0.05",- "--currency", "USDC",- "--slug", "demo-1",+ "--vault",+ vault,+ "--service",+ "paysponge/fal",+ "--reason",+ "header image",+ "--expected-amount",+ "0.05",+ "--currency",+ "USDC",+ "--slug",+ "demo-1",],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -373,10 +408,14 @@ describe("approval workflow (request → approve → consume)", () => {const approve = await runCli(["approve-payment-request",- "--vault", vault,- "--id", "demo-1",- "--approved-by", "sergey",- "--note", "ok for demo",+ "--vault",+ vault,+ "--id",+ "demo-1",+ "--approved-by",+ "sergey",+ "--note",+ "ok for demo",],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -386,19 +425,19 @@ describe("approval workflow (request → approve → consume)", () => {const consume = await runCli(["consume-payment-request",- "--vault", vault,- "--id", "demo-1",- "--receipt", `${PAY_MEMORY_ROOT_REL}/2026-05-10/fal-1.md`,+ "--vault",+ vault,+ "--id",+ "demo-1",+ "--receipt",+ `${PAY_MEMORY_ROOT_REL}/2026-05-10/fal-1.md`,],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(consume.returncode).toBe(0);expect(consume.stdout).toContain("status: consumed");- const text = readFileSync(- join(vault, PAY_MEMORY_PENDING_REL, "demo-1.md"),- "utf8",- );+ const text = readFileSync(join(vault, PAY_MEMORY_PENDING_REL, "demo-1.md"), "utf8");expect(text).toContain("status: consumed");expect(text).toContain("approved_by: sergey");expect(text).toContain(`receipt: ${PAY_MEMORY_ROOT_REL}/2026-05-10/fal-1.md`);@@ -411,20 +450,28 @@ describe("approval workflow (request → approve → consume)", () => {await runCli(["request-payment-approval",- "--vault", vault,- "--service", "x/y",- "--reason", "test",- "--slug", "rej-1",+ "--vault",+ vault,+ "--service",+ "x/y",+ "--reason",+ "test",+ "--slug",+ "rej-1",],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);const reject = await runCli(["reject-payment-request",- "--vault", vault,- "--id", "rej-1",- "--rejected-by", "sergey",- "--reason", "no",+ "--vault",+ vault,+ "--id",+ "rej-1",+ "--rejected-by",+ "sergey",+ "--reason",+ "no",],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -445,10 +492,14 @@ describe("approval workflow (request → approve → consume)", () => {await runCli(["request-payment-approval",- "--vault", vault,- "--service", "x/y",- "--reason", `r-${slug}`,- "--slug", slug,+ "--vault",+ vault,+ "--service",+ "x/y",+ "--reason",+ `r-${slug}`,+ "--slug",+ slug,],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);@@ -457,10 +508,9 @@ describe("approval workflow (request → approve → consume)", () => {["approve-payment-request", "--vault", vault, "--id", "a", "--approved-by", "sergey"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);- const listPending = await runCli(- ["list-pending-payments", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const listPending = await runCli(["list-pending-payments", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });const pending = JSON.parse(listPending.stdout);expect(pending.length).toBe(1);expect(pending[0].id).toBe("b");@@ -471,17 +521,16 @@ describe("approval workflow (request → approve → consume)", () => {);const all = JSON.parse(listAll.stdout);expect(all.length).toBe(2);- expect(all.map((s: { id: string }) => s.id).sort()).toEqual(["a", "b"]);+ expect(all.map((s: { id: string }) => s.id).toSorted()).toEqual(["a", "b"]);});test("--status validates against the allowed set", async () => {await runCli(["init-pay-memory", "--vault", vault], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});- const r = await runCli(- ["list-pending-payments", "--vault", vault, "--status", "weird"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["list-pending-payments", "--vault", vault, "--status", "weird"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);expect(r.stderr).toContain("--status must be one of");});@@ -492,10 +541,9 @@ describe("payment-digest", () => {await runCli(["init-pay-memory", "--vault", vault], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});- const r = await runCli(- ["payment-digest", "--vault", vault, "--date", "2026-05-10"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["payment-digest", "--vault", vault, "--date", "2026-05-10"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout.trim()).toBe("[SILENT]");});@@ -507,22 +555,30 @@ describe("payment-digest", () => {await runCli(["append-payment-receipt",- "--vault", vault,- "--service", "paysponge/fal",- "--status", "success",- "--reason", "header",- "--actual-amount", "0.05",- "--currency", "USDC",- "--slug", "fal-1",- "--date", "2026-05-10",- "--time", "12:00",+ "--vault",+ vault,+ "--service",+ "paysponge/fal",+ "--status",+ "success",+ "--reason",+ "header",+ "--actual-amount",+ "0.05",+ "--currency",+ "USDC",+ "--slug",+ "fal-1",+ "--date",+ "2026-05-10",+ "--time",+ "12:00",],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);- const r = await runCli(- ["payment-digest", "--vault", vault, "--date", "2026-05-10"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["payment-digest", "--vault", vault, "--date", "2026-05-10"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("💳 Оплачено сервисов: **1**");expect(r.stdout).toContain("💰 Сумма: **0.05 USDC**");@@ -533,10 +589,9 @@ describe("payment-digest", () => {await runCli(["init-pay-memory", "--vault", vault], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});- const r = await runCli(- ["payment-digest", "--vault", vault, "--date", "2026-05-10", "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["payment-digest", "--vault", vault, "--date", "2026-05-10", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout);expect(payload.date).toBe("2026-05-10");diff --git a/tests/cli/search-cron-template.test.ts b/tests/cli/search-cron-template.test.tsindex 3976f74f..c925e25d 100644--- a/tests/cli/search-cron-template.test.ts+++ b/tests/cli/search-cron-template.test.ts@@ -78,9 +78,7 @@ describe("renderCronTemplate", () => {test("grep fallback emits when added, updated, or deleted are non-zero", () => {const body = renderCronTemplate("30m");- expect(body).toContain(- '"(added|updated|deleted)"[[:space:]]*:[[:space:]]*[1-9]',- );+ expect(body).toContain('"(added|updated|deleted)"[[:space:]]*:[[:space:]]*[1-9]');expect(body).not.toContain('"added": [^0]');});@@ -120,25 +118,20 @@ describe("o2b search reindex --cron-template (CLI)", () => {test("default 30m prints the template and writes nothing under tmp", async () => {await bootstrap();const before = readdirSync(tmp);- const r = await runCli(- ["search", "reindex", "--cron-template", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["search", "reindex", "--cron-template", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("*/30 * * * *");expect(r.stdout).toContain("osb-reindex.sh");// No new entries in tmp from the CLI itself.- expect(readdirSync(tmp).sort()).toEqual(before.sort());+ expect(readdirSync(tmp).toSorted()).toEqual(before.toSorted());});test("--interval 6h renders the 0 */6 cron expression", async () => {await bootstrap();const r = await runCli(- [- "search", "reindex", "--cron-template",- "--interval", "6h",- "--vault", vault,- ],+ ["search", "reindex", "--cron-template", "--interval", "6h", "--vault", vault],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);@@ -148,11 +141,7 @@ describe("o2b search reindex --cron-template (CLI)", () => {test("--interval garbage exits 1 with the parser error", async () => {await bootstrap();const r = await runCli(- [- "search", "reindex", "--cron-template",- "--interval", "garbage",- "--vault", vault,- ],+ ["search", "reindex", "--cron-template", "--interval", "garbage", "--vault", vault],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(1);diff --git a/tests/cli/search-property-cli.test.ts b/tests/cli/search-property-cli.test.tsindex 8beeded9..3e2647d2 100644--- a/tests/cli/search-property-cli.test.ts+++ b/tests/cli/search-property-cli.test.ts@@ -40,28 +40,25 @@ afterEach(() => {describe("o2b search --property", () => {test("malformed --property without '=' is rejected", async () => {- const r = await runCli(- ["search", "foo", "--property", "no-equals-here"],- { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },- );+ const r = await runCli(["search", "foo", "--property", "no-equals-here"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });expect(r.returncode).not.toBe(0);expect(r.stderr).toContain("--property must be KEY=VALUE");});test("--property KEY= rejects empty value", async () => {- const r = await runCli(- ["search", "foo", "--property", "type="],- { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },- );+ const r = await runCli(["search", "foo", "--property", "type="], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });expect(r.returncode).not.toBe(0);expect(r.stderr).toContain("KEY=VALUE");});test("--property =VALUE rejects empty key", async () => {- const r = await runCli(- ["search", "foo", "--property", "=decision"],- { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },- );+ const r = await runCli(["search", "foo", "--property", "=decision"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });expect(r.returncode).not.toBe(0);expect(r.stderr).toContain("KEY=VALUE");});diff --git a/tests/cli/search.test.ts b/tests/cli/search.test.tsindex bf2e450e..1c087474 100644--- a/tests/cli/search.test.ts+++ b/tests/cli/search.test.ts@@ -7,13 +7,7 @@*/import { afterEach, beforeEach, expect, test } from "bun:test";-import {- existsSync,- mkdirSync,- mkdtempSync,- rmSync,- writeFileSync,-} from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";diff --git a/tests/cli/status.test.ts b/tests/cli/status.test.tsindex 373eac49..85322afb 100644--- a/tests/cli/status.test.ts+++ b/tests/cli/status.test.ts@@ -7,13 +7,7 @@* `--json` keys.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -78,11 +72,8 @@ describe("o2b status — semantic hint (human output)", () => {test("hint present when configured key is whitespace-only", async () => {writeCfg(- [- "vault: /tmp/x",- 'search_semantic_enabled: "true"',- 'embedding_api_key: " "',- ].join("\n") + "\n",+ ["vault: /tmp/x", 'search_semantic_enabled: "true"', 'embedding_api_key: " "'].join("\n") ++ "\n",);const r = await runCli(["status", "--config", cfgPath], { env: ENV_CLEAN });expect(r.returncode).toBe(0);@@ -113,11 +104,9 @@ describe("o2b status — semantic fields (--json)", () => {test("--json semantic_hint is null when fully configured", async () => {writeCfg(- [- "vault: /tmp/x",- 'search_semantic_enabled: "true"',- 'embedding_api_key: "sk-test"',- ].join("\n") + "\n",+ ["vault: /tmp/x", 'search_semantic_enabled: "true"', 'embedding_api_key: "sk-test"'].join(+ "\n",+ ) + "\n",);const r = await runCli(["status", "--config", cfgPath, "--json"], {env: ENV_CLEAN,diff --git a/tests/cli/uninstall.test.ts b/tests/cli/uninstall.test.tsindex c1b02200..89325b2b 100644--- a/tests/cli/uninstall.test.ts+++ b/tests/cli/uninstall.test.ts@@ -282,6 +282,9 @@ describe("CLI uninstall", () => {describe("safe names", () => {test("only canonical Open Second Brain names", () => {- expect([...SAFE_CONFIG_DIR_NAMES].sort()).toEqual(["open-second-brain", "open_second_brain"]);+ expect([...SAFE_CONFIG_DIR_NAMES].toSorted()).toEqual([+ "open-second-brain",+ "open_second_brain",+ ]);});});diff --git a/tests/cli/vault.test.ts b/tests/cli/vault.test.tsindex 0705836b..21955149 100644--- a/tests/cli/vault.test.ts+++ b/tests/cli/vault.test.ts@@ -63,9 +63,9 @@ describe("o2b vault status", () => {expect(typeof payload.included.files).toBe("number");expect(typeof payload.included.dirs).toBe("number");expect(Array.isArray(payload.excluded.dirs)).toBe(true);- expect(payload.excluded.dirs.some(- (d: { rel_path: string }) => d.rel_path === ".obsidian",- )).toBe(true);+ expect(+ payload.excluded.dirs.some((d: { rel_path: string }) => d.rel_path === ".obsidian"),+ ).toBe(true);expect(Array.isArray(payload.rules)).toBe(true);});});@@ -74,10 +74,9 @@ describe("o2b vault inspect", () => {test("reports an included path that exists on disk (no suffix)", async () => {await bootstrap();writeFileSync(join(vault, "idea.md"), "x");- const r = await runCli(- ["vault", "inspect", "idea.md", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["vault", "inspect", "idea.md", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("status: included");expect(r.stdout).not.toContain("(not found on disk)");@@ -85,10 +84,9 @@ describe("o2b vault inspect", () => {test("reports an included path missing from disk with (not found on disk) suffix", async () => {await bootstrap();- const r = await runCli(- ["vault", "inspect", "hypothetical.md", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["vault", "inspect", "hypothetical.md", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);expect(r.stdout).toContain("status: included (not found on disk)");});@@ -96,13 +94,7 @@ describe("o2b vault inspect", () => {test("reports an excluded path with matched rule, source, and (not found) suffix when file is hypothetical", async () => {await bootstrap();const r = await runCli(- [- "vault",- "inspect",- ".obsidian/plugins/foo/note.md",- "--vault",- vault,- ],+ ["vault", "inspect", ".obsidian/plugins/foo/note.md", "--vault", vault],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);@@ -123,10 +115,9 @@ describe("o2b vault inspect", () => {test("path traversal exits 2", async () => {await bootstrap();- const r = await runCli(- ["vault", "inspect", "../outside", "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["vault", "inspect", "../outside", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(2);expect(r.stderr).toContain("traverse");});@@ -134,14 +125,7 @@ describe("o2b vault inspect", () => {test("--json shape exposes matched_rule, matched_at, exists_on_disk", async () => {await bootstrap();const r = await runCli(- [- "vault",- "inspect",- ".obsidian/plugins/foo/note.md",- "--vault",- vault,- "--json",- ],+ ["vault", "inspect", ".obsidian/plugins/foo/note.md", "--vault", vault, "--json"],{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },);expect(r.returncode).toBe(0);@@ -157,10 +141,9 @@ describe("o2b vault inspect", () => {test("--json on included path has matched_rule=null and exists_on_disk=true when file present", async () => {await bootstrap();writeFileSync(join(vault, "idea.md"), "x");- const r = await runCli(- ["vault", "inspect", "idea.md", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ const r = await runCli(["vault", "inspect", "idea.md", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const payload = JSON.parse(r.stdout);expect(payload.status).toBe("included");diff --git a/tests/core/brain.active.test.ts b/tests/core/brain.active.test.tsindex 5e42dbb3..ebbb9c88 100644--- a/tests/core/brain.active.test.ts+++ b/tests/core/brain.active.test.ts@@ -1,21 +1,12 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- existsSync,- mkdtempSync,- readFileSync,- rmSync,- statSync,-} from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { regenerateActive } from "../../src/core/brain/active.ts";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { brainActivePath, preferencePath } from "../../src/core/brain/paths.ts";-import {- moveToRetired,- writePreference,-} from "../../src/core/brain/preference.ts";+import { moveToRetired, writePreference } from "../../src/core/brain/preference.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";let vault: string;@@ -39,7 +30,11 @@ function readActive(): string {return readFileSync(brainActivePath(vault), "utf8");}-function seedConfirmed(slug: string, principle: string, confidence: "low" | "medium" | "high"): void {+function seedConfirmed(+ slug: string,+ principle: string,+ confidence: "low" | "medium" | "high",+): void {writePreference(vault, {slug,topic: slug,diff --git a/tests/core/brain.apply-evidence.test.ts b/tests/core/brain.apply-evidence.test.tsindex 71890570..ccf1f5b0 100644--- a/tests/core/brain.apply-evidence.test.ts+++ b/tests/core/brain.apply-evidence.test.ts@@ -205,7 +205,7 @@ describe("appendApplyEvidence — sanitisation (§7)", () => {artifact: "[[file]] token: abcdef",result: "applied",agent: "claude",- note: 'logged with api_key=hunter2 here',+ note: "logged with api_key=hunter2 here",},{ now: new Date("2026-05-15T10:00:00Z") },);diff --git a/tests/core/brain.backlinks.test.ts b/tests/core/brain.backlinks.test.tsindex 1e8382f7..1089be90 100644--- a/tests/core/brain.backlinks.test.ts+++ b/tests/core/brain.backlinks.test.ts@@ -3,10 +3,7 @@ import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- backlinkCount,- buildBacklinkIndex,-} from "../../src/core/brain/backlinks.ts";+import { backlinkCount, buildBacklinkIndex } from "../../src/core/brain/backlinks.ts";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { writePreference, moveToRetired } from "../../src/core/brain/preference.ts";import { writeSignal } from "../../src/core/brain/signal.ts";diff --git a/tests/core/brain.body-hygiene.test.ts b/tests/core/brain.body-hygiene.test.tsindex 6eae751d..9792f54d 100644--- a/tests/core/brain.body-hygiene.test.ts+++ b/tests/core/brain.body-hygiene.test.ts@@ -24,12 +24,7 @@ import { bootstrapBrain } from "../../src/core/brain/init.ts";import { dream } from "../../src/core/brain/dream.ts";import { moveToRetired, writePreference } from "../../src/core/brain/preference.ts";import { writeSignal } from "../../src/core/brain/signal.ts";-import {- brainDirs,- preferencePath,- retiredPath,- signalPath,-} from "../../src/core/brain/paths.ts";+import { brainDirs, preferencePath, retiredPath, signalPath } from "../../src/core/brain/paths.ts";let vault: string;@@ -53,10 +48,7 @@ describe("signal body — no placeholder Raw", () => {agent: "claude",principle: "Something",});- const content = readFileSync(- signalPath(vault, "2026-05-16", "no-raw-here"),- "utf8",- );+ const content = readFileSync(signalPath(vault, "2026-05-16", "no-raw-here"), "utf8");expect(content).not.toContain("## Raw");expect(content).not.toContain("_(not provided)_");});@@ -72,10 +64,7 @@ describe("signal body — no placeholder Raw", () => {principle: "Something",raw: "verbatim user quote",});- const content = readFileSync(- signalPath(vault, "2026-05-16", "with-raw"),- "utf8",- );+ const content = readFileSync(signalPath(vault, "2026-05-16", "with-raw"), "utf8");expect(content).toContain("## Raw");expect(content).toContain("verbatim user quote");});@@ -319,9 +308,7 @@ describe("§6 signal suppression", () => {expect(summary.suppressed.length).toBe(0);// A new pref is created (slug is suffixed because ret-scoped reserves// the bare slug, hence pref-scoped-2).- expect(summary.new_unconfirmed.some((id) => id.startsWith("pref-scoped"))).toBe(- true,- );+ expect(summary.new_unconfirmed.some((id) => id.startsWith("pref-scoped"))).toBe(true);const logPath = join(vault, "Brain", "log", "2026-05-16.md");const log = readFileSync(logPath, "utf8");expect(log).not.toContain("signal-suppressed");diff --git a/tests/core/brain.confidence-value.test.ts b/tests/core/brain.confidence-value.test.tsindex 05ac96d2..fa31132c 100644--- a/tests/core/brain.confidence-value.test.ts+++ b/tests/core/brain.confidence-value.test.ts@@ -7,10 +7,7 @@import { describe, expect, test } from "bun:test";-import {- computeConfidence,- type ConfidenceComputeResult,-} from "../../src/core/brain/dream.ts";+import { computeConfidence, type ConfidenceComputeResult } from "../../src/core/brain/dream.ts";import { DEFAULT_BRAIN_CONFIG } from "../../src/core/brain/policy.ts";const cfg = DEFAULT_BRAIN_CONFIG;@@ -37,20 +34,8 @@ describe("computeConfidence — numeric value", () => {});test("freshness decays linearly to 0 at retire.stale_evidence_days", () => {- const half = computeConfidence(- 10,- 0,- iso("2026-03-31"),- cfg,- NOW,- ).value;- const stale = computeConfidence(- 10,- 0,- iso("2026-02-14"),- cfg,- NOW,- ).value;+ const half = computeConfidence(10, 0, iso("2026-03-31"), cfg, NOW).value;+ const stale = computeConfidence(10, 0, iso("2026-02-14"), cfg, NOW).value;// 45 days vs 90 days at 90-day decay → 0.5x vs 0.0x freshness.expect(half).toBeGreaterThan(stale + 0.001);});@@ -97,7 +82,7 @@ describe("computeConfidence — numeric value", () => {expect(r1.band).toBe("medium");const tunedCfg = {...cfg,- confidence: { ...cfg.confidence, high_min: 0.5, medium_min: 0.30 },+ confidence: { ...cfg.confidence, high_min: 0.5, medium_min: 0.3 },};const r2 = computeConfidence(9, 0, iso("2026-05-15"), tunedCfg, NOW);expect(r2.band).toBe("high");diff --git a/tests/core/brain.digest.test.ts b/tests/core/brain.digest.test.tsindex 4ef83f7c..c2b4afe8 100644--- a/tests/core/brain.digest.test.ts+++ b/tests/core/brain.digest.test.ts@@ -14,10 +14,7 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- renderDigest,- type DigestJson,-} from "../../src/core/brain/digest.ts";+import { renderDigest, type DigestJson } from "../../src/core/brain/digest.ts";import { appendLogEvent } from "../../src/core/brain/log.ts";import { brainDirs } from "../../src/core/brain/paths.ts";import {@@ -118,10 +115,7 @@ describe("New (unconfirmed, in trial) section", () => {});test("omits unconfirmed prefs created outside the window", () => {- writePreference(- tmp,- basePref("old", { created_at: "2026-04-01T00:00:00Z" }),- );+ writePreference(tmp, basePref("old", { created_at: "2026-04-01T00:00:00Z" }));const res = renderDigest(tmp, { since: SINCE, until: UNTIL });expect(res.empty).toBe(true);expect(res.content).not.toMatch(/\[\[pref-old[\]|]/);@@ -244,10 +238,7 @@ describe("Markdown ↔ JSON parity", () => {describe("window filtering", () => {test("entries timestamped before `since` are excluded", () => {- writePreference(- tmp,- basePref("before-window", { created_at: "2026-04-01T00:00:00Z" }),- );+ writePreference(tmp, basePref("before-window", { created_at: "2026-04-01T00:00:00Z" }));writePreference(tmp, basePref("inside-window"));const res = renderDigest(tmp, { since: SINCE, until: UNTIL });expect(res.content).toContain("[[pref-inside-window|");@@ -256,10 +247,7 @@ describe("window filtering", () => {test("the upper bound is exclusive — until timestamp itself is dropped", () => {// created_at = until exactly → must be excluded.- writePreference(- tmp,- basePref("on-the-edge", { created_at: UNTIL.toISOString() }),- );+ writePreference(tmp, basePref("on-the-edge", { created_at: UNTIL.toISOString() }));const res = renderDigest(tmp, { since: SINCE, until: UNTIL });expect(res.empty).toBe(true);});@@ -328,14 +316,8 @@ describe("`empty` flag semantics", () => {test("default window is the last 24 hours when `since` is omitted", () => {const now = new Date("2026-05-14T20:00:00Z");- writePreference(- tmp,- basePref("recent", { created_at: "2026-05-14T15:00:00Z" }),- );- writePreference(- tmp,- basePref("old", { created_at: "2026-04-01T00:00:00Z" }),- );+ writePreference(tmp, basePref("recent", { created_at: "2026-05-14T15:00:00Z" }));+ writePreference(tmp, basePref("old", { created_at: "2026-04-01T00:00:00Z" }));const res = renderDigest(tmp, { until: now });expect(res.content).toContain("[[pref-recent|");expect(res.content).not.toMatch(/\[\[pref-old[\]|]/);diff --git a/tests/core/brain.doctor-trust-atoms.test.ts b/tests/core/brain.doctor-trust-atoms.test.tsindex 62c48059..213733ce 100644--- a/tests/core/brain.doctor-trust-atoms.test.ts+++ b/tests/core/brain.doctor-trust-atoms.test.ts@@ -11,10 +11,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { runDoctor } from "../../src/core/brain/doctor.ts";-import {- brainConfigPath,- brainDirs,-} from "../../src/core/brain/paths.ts";+import { brainConfigPath, brainDirs } from "../../src/core/brain/paths.ts";import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";diff --git a/tests/core/brain.doctor.test.ts b/tests/core/brain.doctor.test.tsindex d21eebf3..1564f532 100644--- a/tests/core/brain.doctor.test.ts+++ b/tests/core/brain.doctor.test.ts@@ -12,12 +12,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -115,9 +110,7 @@ describe("status-vs-folder mismatch", () => {);const res = runDoctor(tmp);expect(res.errors).toEqual([]);- expect(res.warnings.some((w) => w.code === "status-folder-mismatch")).toBe(- true,- );+ expect(res.warnings.some((w) => w.code === "status-folder-mismatch")).toBe(true);});});@@ -136,9 +129,7 @@ describe("broken wikilinks", () => {expect(res.errors).toEqual([]);expect(res.warnings.some(- (w) =>- w.code === "broken-wikilink" &&- w.message.includes("sig-never-existed"),+ (w) => w.code === "broken-wikilink" && w.message.includes("sig-never-existed"),),).toBe(true);});@@ -164,9 +155,7 @@ describe("broken wikilinks", () => {evidenced_by: ["[[sig-2026-05-13-alpha]]"],});const res = runDoctor(tmp);- expect(res.warnings.filter((w) => w.code === "broken-wikilink")).toEqual(- [],- );+ expect(res.warnings.filter((w) => w.code === "broken-wikilink")).toEqual([]);});});@@ -303,10 +292,7 @@ describe("schema_version", () => {);const res = runDoctor(tmp);expect(- res.errors.some(- (e) =>- e.code === "schema-version-unknown" || e.code === "config-invalid",- ),+ res.errors.some((e) => e.code === "schema-version-unknown" || e.code === "config-invalid"),).toBe(true);});});@@ -338,11 +324,9 @@ describe("required fields per kind", () => {"utf8",);const res = runDoctor(tmp);- expect(- res.errors.some(- (e) => e.code === "signal-invalid" && /topic/.test(e.message),- ),- ).toBe(true);+ expect(res.errors.some((e) => e.code === "signal-invalid" && /topic/.test(e.message))).toBe(+ true,+ );});});@@ -399,9 +383,7 @@ describe("retired entries", () => {);const res = runDoctor(tmp);expect(res.errors).toEqual([]);- expect(res.warnings.filter((w) => w.code === "broken-wikilink")).toEqual(- [],- );+ expect(res.warnings.filter((w) => w.code === "broken-wikilink")).toEqual([]);});});@@ -471,9 +453,7 @@ describe("duplicate-preferences lint", () => {applied_count: 3,});const res = runDoctor(tmp);- expect(- res.warnings.find((w) => w.code === "duplicate-preferences"),- ).toBeUndefined();+ expect(res.warnings.find((w) => w.code === "duplicate-preferences")).toBeUndefined();});});@@ -512,9 +492,7 @@ describe("low-evidence-confirmed lint", () => {});const now = new Date("2026-05-12T00:00:00Z"); // 2 days past confirmedconst res = runDoctor(tmp, { now });- expect(- res.warnings.find((w) => w.code === "low-evidence-confirmed"),- ).toBeUndefined();+ expect(res.warnings.find((w) => w.code === "low-evidence-confirmed")).toBeUndefined();});});@@ -556,9 +534,7 @@ describe("pinned-without-recent-evidence lint", () => {});const now = new Date("2026-05-15T00:00:00Z"); // 125 days past last evidenceconst res = runDoctor(tmp, { now });- expect(- res.warnings.find((w) => w.code === "pinned-without-recent-evidence"),- ).toBeDefined();+ expect(res.warnings.find((w) => w.code === "pinned-without-recent-evidence")).toBeDefined();});test("does NOT flag unpinned prefs", () => {@@ -577,9 +553,7 @@ describe("pinned-without-recent-evidence lint", () => {});const now = new Date("2026-05-15T00:00:00Z");const res = runDoctor(tmp, { now });- expect(- res.warnings.find((w) => w.code === "pinned-without-recent-evidence"),- ).toBeUndefined();+ expect(res.warnings.find((w) => w.code === "pinned-without-recent-evidence")).toBeUndefined();});});@@ -640,9 +614,7 @@ tags: [brain, brain/log]"utf8",);const res = runDoctor(tmp);- expect(- res.warnings.find((w) => w.code === "malformed-evidence-range"),- ).toBeUndefined();+ expect(res.warnings.find((w) => w.code === "malformed-evidence-range")).toBeUndefined();});});@@ -773,19 +745,12 @@ vault:`,);const res = runDoctor(tmp);- expect(- res.warnings.find((w) => w.code === "vault-ignore-missing-path"),- ).toBeUndefined();+ expect(res.warnings.find((w) => w.code === "vault-ignore-missing-path")).toBeUndefined();});test("does NOT warn when the vault block is absent (defaults source)", () => {- atomicWriteFileSync(- brainConfigPath(tmp),- `schema_version: 1\n`,- );+ atomicWriteFileSync(brainConfigPath(tmp), `schema_version: 1\n`);const res = runDoctor(tmp);- expect(- res.warnings.find((w) => w.code === "vault-ignore-missing-path"),- ).toBeUndefined();+ expect(res.warnings.find((w) => w.code === "vault-ignore-missing-path")).toBeUndefined();});});diff --git a/tests/core/brain.dream-guardrail.test.ts b/tests/core/brain.dream-guardrail.test.tsindex 925ce96b..eefa73ab 100644--- a/tests/core/brain.dream-guardrail.test.ts+++ b/tests/core/brain.dream-guardrail.test.ts@@ -77,10 +77,7 @@ describe("dream + self-approval guardrail (default config)", () => {describe("dream + self-approval guardrail (tighter config)", () => {test("3 signals from 1 agent: quarantined when min_distinct_agents=2", () => {- writeBrainCfg(- vault,- `guardrails:\n promotion_min_distinct_agents: 2\n`,- );+ writeBrainCfg(vault, `guardrails:\n promotion_min_distinct_agents: 2\n`);seedPositiveSignals(vault, 3, "agent-a");const res = dream(vault);expect(res.new_unconfirmed).toEqual([]);@@ -90,10 +87,7 @@ describe("dream + self-approval guardrail (tighter config)", () => {});test("cluster from two agents passes min_distinct_agents=2", () => {- writeBrainCfg(- vault,- `guardrails:\n promotion_min_distinct_agents: 2\n`,- );+ writeBrainCfg(vault, `guardrails:\n promotion_min_distinct_agents: 2\n`);seedPositiveSignals(vault, 2, "agent-a", "test-topic", 1);seedPositiveSignals(vault, 2, "agent-b", "test-topic", 1);const res = dream(vault);diff --git a/tests/core/brain.dream.non-primary.test.ts b/tests/core/brain.dream.non-primary.test.tsindex ab0d5f52..52175840 100644--- a/tests/core/brain.dream.non-primary.test.ts+++ b/tests/core/brain.dream.non-primary.test.ts@@ -14,20 +14,8 @@* lock that contract.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";-import {- mkdirSync,- mkdtempSync,- rmSync,- writeFileSync,- readFileSync,-} from "node:fs";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -103,8 +91,7 @@ describe("dream — non-primary warning channel", () => {setPrimaryAgent(vault, "hermes-vps");seedSignals();const r = dream(vault, { agentName: "hermes-vps", now: NOW });- expect(r.warnings.find((w) => w.code === "non-primary-dream-run"))- .toBeUndefined();+ expect(r.warnings.find((w) => w.code === "non-primary-dream-run")).toBeUndefined();});test("primary_agent: null never warns regardless of caller agent", () => {diff --git a/tests/core/brain.dream.test.ts b/tests/core/brain.dream.test.tsindex 9e0025e1..6971c8da 100644--- a/tests/core/brain.dream.test.ts+++ b/tests/core/brain.dream.test.ts@@ -1,12 +1,5 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- existsSync,- mkdtempSync,- readFileSync,- readdirSync,- rmSync,- writeFileSync,-} from "node:fs";+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -393,7 +386,12 @@ describe("dream — confidence formula at boundaries", () => {// pref.confidence. Default config (from policy.ts):// low_max_applied: 2, stale_evidence_days: 90,// medium_min: 0.40, high_min: 0.75.- function setupForConfidence(slug: string, applied: number, violated: number, fresh: boolean): void {+ function setupForConfidence(+ slug: string,+ applied: number,+ violated: number,+ fresh: boolean,+ ): void {writePreference(vault, {slug,topic: slug,@@ -493,19 +491,13 @@ describe("dream — idempotency and determinism", () => {const first = dream(vault, { now: new Date("2026-05-14T20:00:00Z") });expect(first.changed).toBe(true);- const logBefore = readFileSync(- join(brainDirs(vault).log, "2026-05-14.md"),- "utf8",- );+ const logBefore = readFileSync(join(brainDirs(vault).log, "2026-05-14.md"), "utf8");// Second run on a fresh `now` so the run_id would be different.const second = dream(vault, { now: new Date("2026-05-14T20:01:00Z") });expect(second.changed).toBe(false);- const logAfter = readFileSync(- join(brainDirs(vault).log, "2026-05-14.md"),- "utf8",- );+ const logAfter = readFileSync(join(brainDirs(vault).log, "2026-05-14.md"), "utf8");expect(logAfter).toBe(logBefore);});@@ -561,11 +553,9 @@ describe("dream — dryRun mode", () => {seedSignal({ topic: "dry", slug: "b", signal: "negative", date: "2026-05-14" });seedSignal({ topic: "dry", slug: "c", signal: "negative", date: "2026-05-14" });- const beforeInbox = listInboxActive().sort();- const beforePrefs = listPreferences().sort();- const beforeLog = existsSync(- join(brainDirs(vault).log, "2026-05-14.md"),- );+ const beforeInbox = listInboxActive().toSorted();+ const beforePrefs = listPreferences().toSorted();+ const beforeLog = existsSync(join(brainDirs(vault).log, "2026-05-14.md"));const res = dream(vault, {now: new Date("2026-05-14T20:00:00Z"),@@ -580,8 +570,8 @@ describe("dream — dryRun mode", () => {expect(res.log_path).toBeUndefined();// Nothing actually changed on disk.- expect(listInboxActive().sort()).toEqual(beforeInbox);- expect(listPreferences().sort()).toEqual(beforePrefs);+ expect(listInboxActive().toSorted()).toEqual(beforeInbox);+ expect(listPreferences().toSorted()).toEqual(beforePrefs);expect(existsSync(join(brainDirs(vault).log, "2026-05-14.md"))).toBe(beforeLog);});});diff --git a/tests/core/brain.init.test.ts b/tests/core/brain.init.test.tsindex c6301c61..bad07e11 100644--- a/tests/core/brain.init.test.ts+++ b/tests/core/brain.init.test.ts@@ -94,12 +94,8 @@ describe("bootstrapBrain — idempotent rerun", () => {// Brain-side: both files skipped, content intact.expect(second.skipped).toContain(join("Brain", "_brain.yaml"));expect(second.skipped).toContain(join("Brain", "_BRAIN.md"));- expect(readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8")).toBe(- "user: edited\n",- );- expect(readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8")).toBe(- "user manual edits\n",- );+ expect(readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8")).toBe("user: edited\n");+ expect(readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8")).toBe("user manual edits\n");// Nothing newly created or overwritten on the second run.expect(second.created.length).toBe(0);@@ -130,9 +126,7 @@ describe("bootstrapBrain — force overwrite", () => {expect(readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8")).toBe(DEFAULT_BRAIN_CONFIG_YAML,);- expect(- readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8"),- ).not.toBe("stale\n");+ expect(readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8")).not.toBe("stale\n");});});@@ -174,24 +168,22 @@ describe("bootstrapBrain — primary_agent option", () => {});test("empty-string primaryAgent throws (fail loud, not silent fallback)", () => {- expect(() =>- bootstrapBrain(vault, { configPath, primaryAgent: " " }),- ).toThrow(/primary_agent/);+ expect(() => bootstrapBrain(vault, { configPath, primaryAgent: " " })).toThrow(+ /primary_agent/,+ );});test("primaryAgent with a line break is rejected instead of corrupting YAML", () => {- expect(() =>- bootstrapBrain(vault, { configPath, primaryAgent: "agent\nsnapshots:" }),- ).toThrow(/disallowed character/);+ expect(() => bootstrapBrain(vault, { configPath, primaryAgent: "agent\nsnapshots:" })).toThrow(+ /disallowed character/,+ );});});describe("bootstrapBrain — missing machine config", () => {test("throws an error naming `o2b init` when the plugin config does not exist", () => {const missing = join(configHome, "does-not-exist.yaml");- expect(() => bootstrapBrain(vault, { configPath: missing })).toThrow(- /o2b init/,- );+ expect(() => bootstrapBrain(vault, { configPath: missing })).toThrow(/o2b init/);});test("error message includes the resolved config path", () => {@@ -215,10 +207,7 @@ describe("bootstrapBrain — _BRAIN.md compliance ceiling", () => {// ending in `\n` and one ending without it should both report the// user-visible line count.const lines = manual.split("\n");- const lineCount =- manual.endsWith("\n") && lines.length > 0- ? lines.length - 1- : lines.length;+ const lineCount = manual.endsWith("\n") && lines.length > 0 ? lines.length - 1 : lines.length;expect(lineCount).toBeLessThan(200);});});diff --git a/tests/core/brain.inline-rewrite.test.ts b/tests/core/brain.inline-rewrite.test.tsindex 865fcc7d..7760101c 100644--- a/tests/core/brain.inline-rewrite.test.ts+++ b/tests/core/brain.inline-rewrite.test.ts@@ -37,9 +37,7 @@ describe("rewriteMarkers (inline form)", () => {const markers = discoverMarkers(readFileSync(path, "utf8"));expect(markers.length).toBe(1);- await rewriteMarkers(path, [- { marker: markers[0]!, signalId: "sig-2026-05-16-t" },- ]);+ await rewriteMarkers(path, [{ marker: markers[0]!, signalId: "sig-2026-05-16-t" }]);const after = readFileSync(path, "utf8");expect(after).toMatch(@@ -50,14 +48,9 @@ describe("rewriteMarkers (inline form)", () => {});test("re-running discoverMarkers after rewrite returns zero matches", async () => {- const path = writeTmp(- "note.md",- "@osb feedback negative topic=t principle=p\n",- );+ const path = writeTmp("note.md", "@osb feedback negative topic=t principle=p\n");const first = discoverMarkers(readFileSync(path, "utf8"));- await rewriteMarkers(path, [- { marker: first[0]!, signalId: "sig-x" },- ]);+ await rewriteMarkers(path, [{ marker: first[0]!, signalId: "sig-x" }]);const second = discoverMarkers(readFileSync(path, "utf8"));expect(second.length).toBe(0);});@@ -82,9 +75,7 @@ describe("rewriteMarkers (block form)", () => {const markers = discoverMarkers(readFileSync(path, "utf8"));expect(markers.length).toBe(1);- await rewriteMarkers(path, [- { marker: markers[0]!, signalId: "sig-2026-05-16-t" },- ]);+ await rewriteMarkers(path, [{ marker: markers[0]!, signalId: "sig-2026-05-16-t" }]);const after = readFileSync(path, "utf8");expect(after).toMatch(/^```osb-checked$/m);@@ -99,20 +90,12 @@ describe("rewriteMarkers (block form)", () => {test("block rewrite is idempotent (re-run yields no new markers)", async () => {const path = writeTmp("note.md",- [- "```osb",- "kind: feedback",- "signal: positive",- "topic: t",- "principle: p",- "```",- "",- ].join("\n"),+ ["```osb", "kind: feedback", "signal: positive", "topic: t", "principle: p", "```", ""].join(+ "\n",+ ),);const first = discoverMarkers(readFileSync(path, "utf8"));- await rewriteMarkers(path, [- { marker: first[0]!, signalId: "sig-x" },- ]);+ await rewriteMarkers(path, [{ marker: first[0]!, signalId: "sig-x" }]);const second = discoverMarkers(readFileSync(path, "utf8"));expect(second.length).toBe(0);});diff --git a/tests/core/brain.inline-scan.test.ts b/tests/core/brain.inline-scan.test.tsindex 1f541f21..6d7e2ece 100644--- a/tests/core/brain.inline-scan.test.ts+++ b/tests/core/brain.inline-scan.test.ts@@ -5,14 +5,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- readFileSync,- readdirSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -61,15 +54,9 @@ function writeMd(rel: string, content: string): string {describe("scanInline empty notes.read_paths", () => {test("no notes config + no opts.paths -> scanInline does no work", async () => {// Override the beforeEach config to drop notes.read_paths entirely.- atomicWriteFileSync(- join(brainDirs(tmp).brain, "_brain.yaml"),- DEFAULT_BRAIN_CONFIG_YAML,- );+ atomicWriteFileSync(join(brainDirs(tmp).brain, "_brain.yaml"), DEFAULT_BRAIN_CONFIG_YAML);// Plant a marker in Daily/ — old behaviour would find it.- writeMd(- "Daily/2026-05-16.md",- "@osb feedback negative topic=should-be-skipped principle=p\n",- );+ writeMd("Daily/2026-05-16.md", "@osb feedback negative topic=should-be-skipped principle=p\n");const result = await scanInline(tmp, { agent: "test" });expect(result.scanned).toBe(0);expect(result.found).toBe(0);@@ -77,10 +64,7 @@ describe("scanInline empty notes.read_paths", () => {});test("opts.paths still overrides absent config (explicit > config)", async () => {- atomicWriteFileSync(- join(brainDirs(tmp).brain, "_brain.yaml"),- DEFAULT_BRAIN_CONFIG_YAML,- );+ atomicWriteFileSync(join(brainDirs(tmp).brain, "_brain.yaml"), DEFAULT_BRAIN_CONFIG_YAML);writeMd("Journal/2026-05-16.md","@osb feedback negative topic=explicit-override principle=p\n",@@ -98,14 +82,8 @@ describe("scanInline empty notes.read_paths", () => {join(brainDirs(tmp).brain, "_brain.yaml"),`${DEFAULT_BRAIN_CONFIG_YAML}\nnotes:\n read_paths:\n - Daily\n - Journal\n`,);- writeMd(- "Daily/2026-05-16.md",- "@osb feedback negative topic=daily-one principle=p\n",- );- writeMd(- "Journal/2026-05-16.md",- "@osb feedback negative topic=journal-one principle=p\n",- );+ writeMd("Daily/2026-05-16.md", "@osb feedback negative topic=daily-one principle=p\n");+ writeMd("Journal/2026-05-16.md", "@osb feedback negative topic=journal-one principle=p\n");const result = await scanInline(tmp, { agent: "test" });expect(result.found).toBe(2);expect(result.created).toBe(2);@@ -116,10 +94,7 @@ describe("scanInline empty notes.read_paths", () => {join(brainDirs(tmp).brain, "_brain.yaml"),`${DEFAULT_BRAIN_CONFIG_YAML}\nnotes:\n read_paths:\n - Daily\n - Missing\n`,);- writeMd(- "Daily/2026-05-16.md",- "@osb feedback negative topic=found-here principle=p\n",- );+ writeMd("Daily/2026-05-16.md", "@osb feedback negative topic=found-here principle=p\n");const result = await scanInline(tmp, { agent: "test" });expect(result.found).toBe(1);expect(result.errors.length).toBe(0);@@ -130,7 +105,7 @@ describe("scanInline", () => {test("finds an inline marker in Daily/ and creates a signal in inbox/", async () => {writeMd("Daily/2026-05-16.md",- "Note text\n@osb feedback negative topic=mocking principle=\"don't mock DB\"\n",+ 'Note text\n@osb feedback negative topic=mocking principle="don\'t mock DB"\n',);const result = await scanInline(tmp, { agent: "test" });expect(result.scanned).toBeGreaterThan(0);@@ -164,14 +139,13 @@ describe("scanInline", () => {);await scanInline(tmp, { agent: "test" });const after = readFileSync(notePath, "utf8");- expect(after).toMatch(/^@osb✓ \[\[sig-.*-rewrite\]\] feedback negative topic=rewrite principle=p$/m);+ expect(after).toMatch(+ /^@osb✓ \[\[sig-.*-rewrite\]\] feedback negative topic=rewrite principle=p$/m,+ );});test("is idempotent on second run (rewritten markers ignored)", async () => {- writeMd(- "Daily/2026-05-16.md",- "@osb feedback negative topic=idemp principle=p\n",- );+ writeMd("Daily/2026-05-16.md", "@osb feedback negative topic=idemp principle=p\n");const first = await scanInline(tmp, { agent: "test" });expect(first.created).toBe(1);@@ -251,9 +225,7 @@ describe("scanInline", () => {});expect(result.created).toBe(1);const inboxFiles = readdirSync(brainDirs(tmp).inbox).filter((n) => n.endsWith(".md"));- const content = inboxFiles.map((f) =>- readFileSync(join(brainDirs(tmp).inbox, f), "utf8"),- );+ const content = inboxFiles.map((f) => readFileSync(join(brainDirs(tmp).inbox, f), "utf8"));const joined = content.join("");expect(joined).toMatch(/topic: in-daily/);expect(joined).not.toMatch(/topic: in-projects/);@@ -290,10 +262,7 @@ describe("scanInline", () => {);// Build a marker preceded by 1.5 MiB of filler.const filler = "x".repeat(1_500_000);- writeMd(- "Big/huge.md",- `${filler}\n@osb feedback negative topic=huge principle=p\n`,- );+ writeMd("Big/huge.md", `${filler}\n@osb feedback negative topic=huge principle=p\n`);const result = await scanInline(tmp, { agent: "test" });expect(result.found).toBe(0);expect(result.errors.some((e) => e.message.includes("too large"))).toBe(true);@@ -316,10 +285,7 @@ describe("scanInline", () => {`@osb feedback negative topic=obsidian-leak principle="should not be captured"\n`,"utf8",);- writeMd(- "Daily/keep.md",- `@osb feedback negative topic=visible principle=p\n`,- );+ writeMd("Daily/keep.md", `@osb feedback negative topic=visible principle=p\n`);const result = await scanInline(tmp, { agent: "test" });expect(result.created).toBe(1);const inbox = readdirSync(brainDirs(tmp).inbox);@@ -359,9 +325,7 @@ describe("scanInline", () => {const result = await scanInline(tmp, { agent: "test" });expect(result.created).toBe(1);const inbox = readdirSync(brainDirs(tmp).inbox);- expect(- inbox.some((f) => f.includes("nested-brain-keep")),- ).toBe(true);+ expect(inbox.some((f) => f.includes("nested-brain-keep"))).toBe(true);});test("v0.10.9: vault.ignore_paths additions are respected", async () => {@@ -369,14 +333,8 @@ describe("scanInline", () => {join(brainDirs(tmp).brain, "_brain.yaml"),`schema_version: 1\nvault:\n ignore_paths:\n - Drafts\nnotes:\n read_paths:\n - Drafts\n - Daily\n`,);- writeMd(- "Drafts/x.md",- `@osb feedback negative topic=drafted principle=p\n`,- );- writeMd(- "Daily/d.md",- `@osb feedback negative topic=visible principle=p\n`,- );+ writeMd("Drafts/x.md", `@osb feedback negative topic=drafted principle=p\n`);+ writeMd("Daily/d.md", `@osb feedback negative topic=visible principle=p\n`);const result = await scanInline(tmp, { agent: "test" });expect(result.created).toBe(1);const inbox = readdirSync(brainDirs(tmp).inbox);diff --git a/tests/core/brain.inline.test.ts b/tests/core/brain.inline.test.tsindex 706234f5..4dea69f3 100644--- a/tests/core/brain.inline.test.ts+++ b/tests/core/brain.inline.test.ts@@ -48,10 +48,7 @@ describe("parseInlineMarker", () => {});test("accepts unquoted single-word values", () => {- const m = parseInlineMarker(- "@osb feedback positive topic=foo principle=bar scope=writing",- 1,- );+ const m = parseInlineMarker("@osb feedback positive topic=foo principle=bar scope=writing", 1);expect(m).not.toBeNull();if (m === null) return;expect(m.topic).toBe("foo");@@ -64,9 +61,7 @@ describe("parseInlineMarker", () => {});test("returns null when '@osb' is in the middle of a line", () => {- expect(- parseInlineMarker(`This is @osb feedback positive topic=t principle=p`, 1),- ).toBeNull();+ expect(parseInlineMarker(`This is @osb feedback positive topic=t principle=p`, 1)).toBeNull();});test("returns null when required field is missing", () => {@@ -77,16 +72,11 @@ describe("parseInlineMarker", () => {});test("returns null when signal value is not in the enum", () => {- expect(- parseInlineMarker(`@osb feedback maybe topic=t principle=p`, 1),- ).toBeNull();+ expect(parseInlineMarker(`@osb feedback maybe topic=t principle=p`, 1)).toBeNull();});test("accepts leading whitespace before '@osb'", () => {- const m = parseInlineMarker(- ` @osb feedback negative topic=t principle=p`,- 1,- );+ const m = parseInlineMarker(` @osb feedback negative topic=t principle=p`, 1);expect(m).not.toBeNull();});@@ -125,12 +115,7 @@ describe("parseBlockMarker", () => {});test("returns null on unknown kind", () => {- const body = [- "kind: lol",- "signal: negative",- "topic: t",- "principle: p",- ].join("\n");+ const body = ["kind: lol", "signal: negative", "topic: t", "principle: p"].join("\n");expect(parseBlockMarker(body, 1)).toBeNull();});@@ -157,11 +142,9 @@ describe("parseBlockMarker", () => {describe("discoverMarkers", () => {test("finds inline markers", () => {- const text = [- "Some note text",- "@osb feedback negative topic=t principle=p",- "More text",- ].join("\n");+ const text = ["Some note text", "@osb feedback negative topic=t principle=p", "More text"].join(+ "\n",+ );const markers = discoverMarkers(text);expect(markers.length).toBe(1);expect(markers[0]!.shape).toBe("inline");@@ -186,11 +169,7 @@ describe("discoverMarkers", () => {});test("ignores '@osb' inside non-osb fences (code samples in docs)", () => {- const text = [- "```python",- "@osb feedback negative topic=t principle=p",- "```",- ].join("\n");+ const text = ["```python", "@osb feedback negative topic=t principle=p", "```"].join("\n");expect(discoverMarkers(text).length).toBe(0);});diff --git a/tests/core/brain.log-jsonl-reader.test.ts b/tests/core/brain.log-jsonl-reader.test.tsindex 77cea310..70bc295a 100644--- a/tests/core/brain.log-jsonl-reader.test.ts+++ b/tests/core/brain.log-jsonl-reader.test.ts@@ -1,11 +1,5 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- existsSync,- mkdirSync,- mkdtempSync,- rmSync,- writeFileSync,-} from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -111,11 +105,7 @@ tags: [brain, brain/log]payload: { topic: "also-ok" },}),].join("\n");- writeFileSync(- logJsonlPath(tmp, "2026-05-19"),- lines + "\n",- "utf8",- );+ writeFileSync(logJsonlPath(tmp, "2026-05-19"), lines + "\n", "utf8");const res = readLogDay(tmp, "2026-05-19");expect(res.source).toBe("jsonl");@@ -140,11 +130,7 @@ tags: [brain, brain/log]payload: { topic: "ok" },}),].join("\n");- writeFileSync(- logJsonlPath(tmp, "2026-05-19"),- lines + "\n",- "utf8",- );+ writeFileSync(logJsonlPath(tmp, "2026-05-19"), lines + "\n", "utf8");const res = readLogDay(tmp, "2026-05-19");expect(res.entries).toHaveLength(1);@@ -168,11 +154,7 @@ tags: [brain, brain/log]payload: { topic: "ok" },}),].join("\n");- writeFileSync(- logJsonlPath(tmp, "2026-05-19"),- lines + "\n",- "utf8",- );+ writeFileSync(logJsonlPath(tmp, "2026-05-19"), lines + "\n", "utf8");const res = readLogDay(tmp, "2026-05-19");expect(res.entries).toHaveLength(1);@@ -194,11 +176,7 @@ tags: [brain, brain/log]"","",].join("\n");- writeFileSync(- logJsonlPath(tmp, "2026-05-19"),- lines,- "utf8",- );+ writeFileSync(logJsonlPath(tmp, "2026-05-19"), lines, "utf8");const res = readLogDay(tmp, "2026-05-19");expect(res.entries).toHaveLength(1);@@ -214,8 +192,6 @@ describe("readLogDay — invariants", () => {test("does not create files on a read", () => {readLogDay(tmp, "2026-05-19");expect(existsSync(logPath(tmp, "2026-05-19"))).toBe(false);- expect(- existsSync(logJsonlPath(tmp, "2026-05-19")),- ).toBe(false);+ expect(existsSync(logJsonlPath(tmp, "2026-05-19"))).toBe(false);});});diff --git a/tests/core/brain.log.test.ts b/tests/core/brain.log.test.tsindex 62efb9d1..95bcf097 100644--- a/tests/core/brain.log.test.ts+++ b/tests/core/brain.log.test.ts@@ -3,11 +3,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSyncimport { tmpdir } from "node:os";import { join } from "node:path";-import {- appendLogEvent,- parseLogDay,- type BrainLogEntry,-} from "../../src/core/brain/log.ts";+import { appendLogEvent, parseLogDay, type BrainLogEntry } from "../../src/core/brain/log.ts";import { brainDirs, logJsonlPath, logPath } from "../../src/core/brain/paths.ts";let tmp: string;@@ -155,7 +151,7 @@ describe("parseLogDay — malformed entry tolerance", () => {"- run_id: dream-2026-05-14-104200","- confirmed: 0","",- "## 11:00:00 NOT-A-VALID-HEADER", // broken header+ "## 11:00:00 NOT-A-VALID-HEADER", // broken header"- this: should be ignored","","## 12:00:00Z — apply-evidence",@@ -164,12 +160,12 @@ describe("parseLogDay — malformed entry tolerance", () => {"- agent: claude","- result: applied","",- "## 13:00:00Z — totally-bogus-kind", // unknown event kind+ "## 13:00:00Z — totally-bogus-kind", // unknown event kind"- foo: bar","","## 14:00:00Z — feedback","- signal: [[sig-x]]",- "garbage line that is not a bullet", // malformed bullet inside a valid block+ "garbage line that is not a bullet", // malformed bullet inside a valid block"- topic: foo",].join("\n");writeFileSync(path, content, "utf8");@@ -178,11 +174,7 @@ describe("parseLogDay — malformed entry tolerance", () => {// Only the three well-formed entries (dream, apply-evidence,// feedback) survive.expect(entries).toHaveLength(3);- expect(entries.map((e) => e.eventType)).toEqual([- "dream",- "apply-evidence",- "feedback",- ]);+ expect(entries.map((e) => e.eventType)).toEqual(["dream", "apply-evidence", "feedback"]);// The broken header and bogus kind both produce warnings; the// stray bullet does too.expect(warnings.length).toBeGreaterThanOrEqual(2);diff --git a/tests/core/brain.paths.test.ts b/tests/core/brain.paths.test.tsindex b0f3a391..565ad6da 100644--- a/tests/core/brain.paths.test.ts+++ b/tests/core/brain.paths.test.ts@@ -55,13 +55,7 @@ describe("path constructors", () => {join("/v", "Brain", "inbox", "sig-2026-05-14-no-internal-abbrev.md"),);expect(processedSignalPath("/v", "2026-05-14", "no-internal-abbrev")).toBe(- join(- "/v",- "Brain",- "inbox",- "processed",- "sig-2026-05-14-no-internal-abbrev.md",- ),+ join("/v", "Brain", "inbox", "processed", "sig-2026-05-14-no-internal-abbrev.md"),);});@@ -72,9 +66,7 @@ describe("path constructors", () => {expect(retiredPath("/v", "no-internal-abbrev")).toBe(join("/v", "Brain", "retired", "ret-no-internal-abbrev.md"),);- expect(logPath("/v", "2026-05-14")).toBe(- join("/v", "Brain", "log", "2026-05-14.md"),- );+ expect(logPath("/v", "2026-05-14")).toBe(join("/v", "Brain", "log", "2026-05-14.md"));expect(snapshotsDir("/v")).toBe(join("/v", "Brain", ".snapshots"));expect(snapshotPath("/v", "dream-2026-05-14-104200")).toBe(join("/v", "Brain", ".snapshots", "dream-2026-05-14-104200.tar.zst"),@@ -160,9 +152,7 @@ describe("validateIsoDate", () => {describe("validateRunId", () => {test("accepts dream run ids", () => {- expect(validateRunId("dream-2026-05-14-104200")).toBe(- "dream-2026-05-14-104200",- );+ expect(validateRunId("dream-2026-05-14-104200")).toBe("dream-2026-05-14-104200");});test("rejects empty / separators / traversal", () => {@@ -199,9 +189,7 @@ describe("path-safety", () => {describe("brainVaultRelative", () => {test("renders posix-style relative path", () => {const abs = join("/vault", "Brain", "preferences", "pref-x.md");- expect(brainVaultRelative(abs, "/vault")).toBe(- "Brain/preferences/pref-x.md",- );+ expect(brainVaultRelative(abs, "/vault")).toBe("Brain/preferences/pref-x.md");});});@@ -217,19 +205,13 @@ describe("allocateSlug — collision allocator", () => {});expect(result.slug).toBe("no-internal-abbrev");expect(result.suffix).toBeNull();- expect(result.path).toBe(- join(targetDir, "sig-2026-05-14-no-internal-abbrev.md"),- );+ expect(result.path).toBe(join(targetDir, "sig-2026-05-14-no-internal-abbrev.md"));});test("appends -2 on first collision", () => {const targetDir = join(tmp, "Brain", "inbox");mkdirSync(targetDir, { recursive: true });- writeFileSync(- join(targetDir, "sig-2026-05-14-no-internal-abbrev.md"),- "stub",- "utf8",- );+ writeFileSync(join(targetDir, "sig-2026-05-14-no-internal-abbrev.md"), "stub", "utf8");const result = allocateSlug({vault: tmp,@@ -239,24 +221,14 @@ describe("allocateSlug — collision allocator", () => {});expect(result.slug).toBe("no-internal-abbrev-2");expect(result.suffix).toBe(2);- expect(result.path).toBe(- join(targetDir, "sig-2026-05-14-no-internal-abbrev-2.md"),- );+ expect(result.path).toBe(join(targetDir, "sig-2026-05-14-no-internal-abbrev-2.md"));});test("appends -3 on second collision", () => {const targetDir = join(tmp, "Brain", "inbox");mkdirSync(targetDir, { recursive: true });- writeFileSync(- join(targetDir, "sig-2026-05-14-no-internal-abbrev.md"),- "stub",- "utf8",- );- writeFileSync(- join(targetDir, "sig-2026-05-14-no-internal-abbrev-2.md"),- "stub",- "utf8",- );+ writeFileSync(join(targetDir, "sig-2026-05-14-no-internal-abbrev.md"), "stub", "utf8");+ writeFileSync(join(targetDir, "sig-2026-05-14-no-internal-abbrev-2.md"), "stub", "utf8");const result = allocateSlug({vault: tmp,diff --git a/tests/core/brain.pin.test.ts b/tests/core/brain.pin.test.tsindex 10cbd3a2..6d7aa590 100644--- a/tests/core/brain.pin.test.ts+++ b/tests/core/brain.pin.test.ts@@ -5,10 +5,7 @@ import { join } from "node:path";import { isPinned, setPinned } from "../../src/core/brain/pin.ts";import { parseLogDay } from "../../src/core/brain/log.ts";-import {- parsePreference,- writePreference,-} from "../../src/core/brain/preference.ts";+import { parsePreference, writePreference } from "../../src/core/brain/preference.ts";import { BrainPreferenceNotFoundError } from "../../src/core/brain/apply-evidence.ts";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";@@ -141,9 +138,7 @@ describe("setPinned — body preservation", () => {describe("setPinned — error paths", () => {test("missing preference throws BrainPreferenceNotFoundError", () => {- expect(() => setPinned(vault, "does-not-exist", true)).toThrow(- BrainPreferenceNotFoundError,- );+ expect(() => setPinned(vault, "does-not-exist", true)).toThrow(BrainPreferenceNotFoundError);});test("empty pref_id throws", () => {@@ -178,9 +173,7 @@ describe("isPinned — accessor", () => {test("returns true when frontmatter explicitly sets pinned: true", () => {makePref("explicit-pinned", true);- const parsed = parsePreference(- `${vault}/Brain/preferences/pref-explicit-pinned.md`,- );+ const parsed = parsePreference(`${vault}/Brain/preferences/pref-explicit-pinned.md`);expect(isPinned(parsed)).toBe(true);});});diff --git a/tests/core/brain.policy.test.ts b/tests/core/brain.policy.test.tsindex 6b4a19a0..0f047229 100644--- a/tests/core/brain.policy.test.ts+++ b/tests/core/brain.policy.test.ts@@ -43,7 +43,7 @@ describe("DEFAULT_BRAIN_CONFIG", () => {expect(DEFAULT_BRAIN_CONFIG.dream.contradiction_window_days).toBe(14);expect(DEFAULT_BRAIN_CONFIG.retire.stale_evidence_days).toBe(90);expect(DEFAULT_BRAIN_CONFIG.confidence.low_max_applied).toBe(2);- expect(DEFAULT_BRAIN_CONFIG.confidence.medium_min).toBe(0.40);+ expect(DEFAULT_BRAIN_CONFIG.confidence.medium_min).toBe(0.4);expect(DEFAULT_BRAIN_CONFIG.confidence.high_min).toBe(0.75);expect(DEFAULT_BRAIN_CONFIG.snapshots.retention_count).toBe(10);});@@ -67,10 +67,7 @@ describe("DEFAULT_BRAIN_CONFIG", () => {describe("validateBrainConfig — happy path", () => {test("accepts the default config", () => {- const config = validateBrainConfig(- JSON.parse(JSON.stringify(DEFAULT_BRAIN_CONFIG)),- "<test>",- );+ const config = validateBrainConfig(JSON.parse(JSON.stringify(DEFAULT_BRAIN_CONFIG)), "<test>");expect(config.schema_version).toBe(1);expect(config.snapshots.retention_count).toBe(10);});@@ -79,7 +76,7 @@ describe("validateBrainConfig — happy path", () => {const config = validateBrainConfig({ schema_version: 1 }, "<test>");expect(config.dream.candidate_threshold).toBe(3);expect(config.retire.stale_evidence_days).toBe(90);- expect(config.confidence.medium_min).toBe(0.40);+ expect(config.confidence.medium_min).toBe(0.4);expect(config.snapshots.retention_count).toBe(10);});@@ -104,10 +101,7 @@ describe("validateBrainConfig — primary_agent", () => {});test("explicit null is accepted", () => {- const cfg = validateBrainConfig(- { schema_version: 1, primary_agent: null },- "<test>",- );+ const cfg = validateBrainConfig({ schema_version: 1, primary_agent: null }, "<test>");expect(cfg.primary_agent).toBeNull();});@@ -121,10 +115,7 @@ describe("validateBrainConfig — primary_agent", () => {test("empty string rejected with named field", () => {try {- validateBrainConfig(- { schema_version: 1, primary_agent: "" },- "<test>",- );+ validateBrainConfig({ schema_version: 1, primary_agent: "" }, "<test>");throw new Error("should have thrown");} catch (err) {expect(err).toBeInstanceOf(BrainConfigError);@@ -134,27 +125,21 @@ describe("validateBrainConfig — primary_agent", () => {test("whitespace-only string rejected", () => {expect(() =>- validateBrainConfig(- { schema_version: 1, primary_agent: " " },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, primary_agent: " " }, "<test>"),).toThrow(/primary_agent/);});test("non-string non-null rejected", () => {- expect(() =>- validateBrainConfig(- { schema_version: 1, primary_agent: 42 },- "<test>",- ),- ).toThrow(/primary_agent/);+ expect(() => validateBrainConfig({ schema_version: 1, primary_agent: 42 }, "<test>")).toThrow(+ /primary_agent/,+ );});});describe("formatPrimaryAgentYamlValue", () => {test("quotes strings so comment-like content round-trips", () => {const scalar = formatPrimaryAgentYamlValue("hermes lead # primary");- expect(scalar).toBe("\"hermes lead # primary\"");+ expect(scalar).toBe('"hermes lead # primary"');const cfg = validateBrainConfig(parseBrainYaml(`schema_version: 1\nprimary_agent: ${scalar}\n`),);@@ -162,18 +147,10 @@ describe("formatPrimaryAgentYamlValue", () => {});test("rejects values that would need escaping in the tiny YAML parser", () => {- expect(() => formatPrimaryAgentYamlValue("agent\nnext")).toThrow(- /disallowed character/,- );- expect(() => formatPrimaryAgentYamlValue("agent\rnext")).toThrow(- /disallowed character/,- );- expect(() => formatPrimaryAgentYamlValue("agent\\path")).toThrow(- /disallowed character/,- );- expect(() => formatPrimaryAgentYamlValue('agent "quoted"')).toThrow(- /disallowed character/,- );+ expect(() => formatPrimaryAgentYamlValue("agent\nnext")).toThrow(/disallowed character/);+ expect(() => formatPrimaryAgentYamlValue("agent\rnext")).toThrow(/disallowed character/);+ expect(() => formatPrimaryAgentYamlValue("agent\\path")).toThrow(/disallowed character/);+ expect(() => formatPrimaryAgentYamlValue('agent "quoted"')).toThrow(/disallowed character/);});});@@ -189,26 +166,17 @@ describe("validateBrainConfig — error cases", () => {});test("unsupported schema_version → error", () => {- expect(() =>- validateBrainConfig({ schema_version: 99 }, "<test>"),- ).toThrow(/schema_version/);+ expect(() => validateBrainConfig({ schema_version: 99 }, "<test>")).toThrow(/schema_version/);});test("non-integer schema_version → error", () => {- expect(() =>- validateBrainConfig({ schema_version: "1" }, "<test>"),- ).toThrow(/schema_version/);- expect(() =>- validateBrainConfig({ schema_version: 1.5 }, "<test>"),- ).toThrow(/schema_version/);+ expect(() => validateBrainConfig({ schema_version: "1" }, "<test>")).toThrow(/schema_version/);+ expect(() => validateBrainConfig({ schema_version: 1.5 }, "<test>")).toThrow(/schema_version/);});test("negative threshold → error naming the field", () => {try {- validateBrainConfig(- { schema_version: 1, dream: { candidate_threshold: -1 } },- "<test>",- );+ validateBrainConfig({ schema_version: 1, dream: { candidate_threshold: -1 } }, "<test>");throw new Error("should have thrown");} catch (err) {expect(err).toBeInstanceOf(BrainConfigError);@@ -218,40 +186,25 @@ describe("validateBrainConfig — error cases", () => {test("non-integer threshold → error", () => {expect(() =>- validateBrainConfig(- { schema_version: 1, dream: { candidate_threshold: 3.5 } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, dream: { candidate_threshold: 3.5 } }, "<test>"),).toThrow(/positive integer/);});test("zero candidate_threshold → error (must be positive)", () => {expect(() =>- validateBrainConfig(- { schema_version: 1, dream: { candidate_threshold: 0 } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, dream: { candidate_threshold: 0 } }, "<test>"),).toThrow(/positive integer/);});test("snapshots.retention_count must be positive integer", () => {expect(() =>- validateBrainConfig(- { schema_version: 1, snapshots: { retention_count: 0 } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, snapshots: { retention_count: 0 } }, "<test>"),).toThrow(/positive integer/);expect(() =>- validateBrainConfig(- { schema_version: 1, snapshots: { retention_count: -5 } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, snapshots: { retention_count: -5 } }, "<test>"),).toThrow(/positive integer/);expect(() =>- validateBrainConfig(- { schema_version: 1, snapshots: { retention_count: 1.5 } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, snapshots: { retention_count: 1.5 } }, "<test>"),).toThrow(/positive integer/);});@@ -262,9 +215,7 @@ describe("validateBrainConfig — error cases", () => {});test("non-object block → error", () => {- expect(() =>- validateBrainConfig({ schema_version: 1, dream: 5 }, "<test>"),- ).toThrow(/dream/);+ expect(() => validateBrainConfig({ schema_version: 1, dream: 5 }, "<test>")).toThrow(/dream/);});test("confidence.low_max_applied = 0 is allowed (non-negative)", () => {@@ -283,12 +234,8 @@ describe("validateBrainConfig — warnings (forward-compat)", () => {"<test>",);expect(result.warnings.length).toBe(2);- expect(result.warnings.map((w) => w.message).join("\n")).toContain(- "future_field",- );- expect(result.warnings.map((w) => w.message).join("\n")).toContain(- "another",- );+ expect(result.warnings.map((w) => w.message).join("\n")).toContain("future_field");+ expect(result.warnings.map((w) => w.message).join("\n")).toContain("another");expect(result.config.schema_version).toBe(1);});@@ -310,10 +257,7 @@ describe("validateBrainConfig — vault block (v0.10.9)", () => {test("vault block present without ignore_paths leaves vault undefined", () => {// Walker behaviour is identical to "absent block" (fall back to// defaults) — see design §4 table row 2.- const cfg = validateBrainConfig(- { schema_version: 1, vault: {} },- "<test>",- );+ const cfg = validateBrainConfig({ schema_version: 1, vault: {} }, "<test>");expect(cfg.vault).toBeUndefined();});@@ -325,18 +269,11 @@ describe("validateBrainConfig — vault block (v0.10.9)", () => {},"<test>",);- expect(cfg.vault?.ignore_paths).toEqual([- ".git",- "node_modules",- "Brain/.snapshots",- ]);+ expect(cfg.vault?.ignore_paths).toEqual([".git", "node_modules", "Brain/.snapshots"]);});test("vault.ignore_paths empty array honoured as explicit empty", () => {- const cfg = validateBrainConfig(- { schema_version: 1, vault: { ignore_paths: [] } },- "<test>",- );+ const cfg = validateBrainConfig({ schema_version: 1, vault: { ignore_paths: [] } }, "<test>");expect(cfg.vault?.ignore_paths).toEqual([]);});@@ -349,44 +286,30 @@ describe("validateBrainConfig — vault block (v0.10.9)", () => {});test("vault block not a map → BrainConfigError naming the field", () => {- expect(() =>- validateBrainConfig({ schema_version: 1, vault: 5 }, "<test>"),- ).toThrow(/vault/);+ expect(() => validateBrainConfig({ schema_version: 1, vault: 5 }, "<test>")).toThrow(/vault/);});test("vault.ignore_paths not an array → BrainConfigError", () => {expect(() =>- validateBrainConfig(- { schema_version: 1, vault: { ignore_paths: "not-a-list" } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, vault: { ignore_paths: "not-a-list" } }, "<test>"),).toThrow(/vault\.ignore_paths/);});test("non-string entry → BrainConfigError naming the index", () => {expect(() =>- validateBrainConfig(- { schema_version: 1, vault: { ignore_paths: [".git", 42] } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, vault: { ignore_paths: [".git", 42] } }, "<test>"),).toThrow(/vault\.ignore_paths\[1\]/);});test("empty-string entry rejected", () => {expect(() =>- validateBrainConfig(- { schema_version: 1, vault: { ignore_paths: [" "] } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, vault: { ignore_paths: [" "] } }, "<test>"),).toThrow(/non-empty/);});test("entry with newline is rejected", () => {expect(() =>- validateBrainConfig(- { schema_version: 1, vault: { ignore_paths: ["bad\nentry"] } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, vault: { ignore_paths: ["bad\nentry"] } }, "<test>"),).toThrow(/vault\.ignore_paths\[0\]/);});@@ -399,9 +322,7 @@ describe("validateBrainConfig — vault block (v0.10.9)", () => {"<test>",);expect(result.config.vault?.ignore_paths).toEqual([".git"]);- expect(- result.warnings.some((w) => w.message.includes("unknown_extra")),- ).toBe(true);+ expect(result.warnings.some((w) => w.message.includes("unknown_extra"))).toBe(true);});test("DEFAULT_BRAIN_CONFIG_YAML parses with the vault block populated", () => {@@ -429,16 +350,10 @@ describe("validateBrainConfig — vault block (v0.10.9)", () => {test("entry that normalises to empty (e.g. './' / '/') is rejected", () => {expect(() =>- validateBrainConfig(- { schema_version: 1, vault: { ignore_paths: ["./"] } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, vault: { ignore_paths: ["./"] } }, "<test>"),).toThrow(/vault\.ignore_paths\[0\].*empty/);expect(() =>- validateBrainConfig(- { schema_version: 1, vault: { ignore_paths: ["///"] } },- "<test>",- ),+ validateBrainConfig({ schema_version: 1, vault: { ignore_paths: ["///"] } }, "<test>"),).toThrow(/vault\.ignore_paths\[0\].*empty/);});@@ -460,10 +375,7 @@ describe("loadBrainConfig — filesystem integration", () => {});test("loadBrainConfigDetailed returns warnings + path", () => {- writeBrainYaml(- tmp,- `${DEFAULT_BRAIN_CONFIG_YAML}\nfuture_field: 1\n`,- );+ writeBrainYaml(tmp, `${DEFAULT_BRAIN_CONFIG_YAML}\nfuture_field: 1\n`);const result = loadBrainConfigDetailed(tmp);expect(result.path).toBe(join(tmp, "Brain", "_brain.yaml"));expect(result.warnings.length).toBe(1);@@ -532,16 +444,10 @@ describe("parseBrainYaml", () => {});test("rejects nested blocks deeper than one level", () => {- expect(() =>- parseBrainYaml(- `top:\n middle:\n leaf: 1\n`,- ),- ).toThrow(/deeper than one level/);+ expect(() => parseBrainYaml(`top:\n middle:\n leaf: 1\n`)).toThrow(/deeper than one level/);});test("rejects duplicate top-level key", () => {- expect(() =>- parseBrainYaml(`schema_version: 1\nschema_version: 2\n`),- ).toThrow(/duplicate/);+ expect(() => parseBrainYaml(`schema_version: 1\nschema_version: 2\n`)).toThrow(/duplicate/);});});diff --git a/tests/core/brain.preference.test.ts b/tests/core/brain.preference.test.tsindex 0ed9a581..4f377451 100644--- a/tests/core/brain.preference.test.ts+++ b/tests/core/brain.preference.test.ts@@ -1,12 +1,5 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- existsSync,- mkdirSync,- mkdtempSync,- readFileSync,- rmSync,- writeFileSync,-} from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -18,11 +11,7 @@ import {writePreference,type WritePreferenceInput,} from "../../src/core/brain/preference.ts";-import {- brainDirs,- preferencePath,- retiredPath,-} from "../../src/core/brain/paths.ts";+import { brainDirs, preferencePath, retiredPath } from "../../src/core/brain/paths.ts";let tmp: string;@@ -34,14 +23,11 @@ afterEach(() => {rmSync(tmp, { recursive: true, force: true });});-function basePrefInput(- overrides: Partial<WritePreferenceInput> = {},-): WritePreferenceInput {+function basePrefInput(overrides: Partial<WritePreferenceInput> = {}): WritePreferenceInput {return {slug: "no-internal-abbrev",topic: "no-internal-abbrev",- principle:- "Do not use internal abbreviations in user-facing copy unless explained first",+ principle: "Do not use internal abbreviations in user-facing copy unless explained first",created_at: "2026-05-14T10:42:00Z",unconfirmed_until: "2026-05-28T10:42:00Z",status: "unconfirmed",@@ -56,8 +42,7 @@ function basePrefInput(last_evidence_at: null,confidence: "low",pinned: false,- howToApply:- "Expand acronyms on first use in any user-facing copy.",+ howToApply: "Expand acronyms on first use in any user-facing copy.",...overrides,};}@@ -216,11 +201,7 @@ describe("moveToRetired", () => {retired_by: "[[Brain/log/2026-08-12]]",});const parsed = parseRetired(result.path);- expect(parsed.aliases).toEqual([- "pref-no-internal-abbrev",- "my-friendly-name",- "abbrev-rule",- ]);+ expect(parsed.aliases).toEqual(["pref-no-internal-abbrev", "my-friendly-name", "abbrev-rule"]);});});@@ -327,9 +308,7 @@ describe("status enum validation", () => {].join("\n");writeFileSync(path, content, "utf8");- expect(() => parsePreference(path)).toThrow(- /preference status must be one of/,- );+ expect(() => parsePreference(path)).toThrow(/preference status must be one of/);});});@@ -354,7 +333,16 @@ function writeRawRetired(tmp: string, slug: string, fmLines: ReadonlyArray<strinconst dirs = brainDirs(tmp);mkdirSync(dirs.retired, { recursive: true });const path = retiredPath(tmp, slug);- const content = ["---", ...fmLines, "---", "", "## Retired", "", "Reason: stale-no-evidence", ""].join("\n");+ const content = [+ "---",+ ...fmLines,+ "---",+ "",+ "## Retired",+ "",+ "Reason: stale-no-evidence",+ "",+ ].join("\n");writeFileSync(path, content, "utf8");return path;}@@ -496,10 +484,7 @@ describe("writePreference emits _-prefixed Group C fields (§24)", () => {describe("moveToRetired carries _-prefixed shape forward (§24)", () => {test("retired file uses new shape for Group C fields", () => {- const written = writePreference(- tmp,- basePrefInput({ status: "confirmed", applied_count: 3 }),- );+ const written = writePreference(tmp, basePrefInput({ status: "confirmed", applied_count: 3 }));const result = moveToRetired(tmp, written.path, "stale-no-evidence", {now: new Date("2026-08-12T05:00:00Z"),retired_by: "[[Brain/log/2026-08-12]]",diff --git a/tests/core/brain.query.test.ts b/tests/core/brain.query.test.tsindex 129a2527..64544f74 100644--- a/tests/core/brain.query.test.ts+++ b/tests/core/brain.query.test.ts@@ -17,10 +17,7 @@ import { join } from "node:path";import { brainDirs } from "../../src/core/brain/paths.ts";import { appendLogEvent } from "../../src/core/brain/log.ts";-import {- moveToRetired,- writePreference,-} from "../../src/core/brain/preference.ts";+import { moveToRetired, writePreference } from "../../src/core/brain/preference.ts";import { writeSignal } from "../../src/core/brain/signal.ts";import {BrainNotFoundError,@@ -60,10 +57,7 @@ function basePref(slug: string) {created_at: "2026-05-14T10:00:00Z",unconfirmed_until: "2026-05-28T10:00:00Z",status: "unconfirmed" as const,- evidenced_by: [- `[[sig-2026-05-13-${slug}]]`,- `[[sig-2026-05-14-${slug}]]`,- ],+ evidenced_by: [`[[sig-2026-05-13-${slug}]]`, `[[sig-2026-05-14-${slug}]]`],scope: "writing",confirmed_at: null,};@@ -145,12 +139,8 @@ describe("queryByPreference", () => {});test("throws BrainNotFoundError when no preference matches", () => {- expect(() => queryByPreference(tmp, "pref-nonexistent")).toThrow(- BrainNotFoundError,- );- expect(() => queryByPreference(tmp, "garbage")).toThrow(- BrainNotFoundError,- );+ expect(() => queryByPreference(tmp, "pref-nonexistent")).toThrow(BrainNotFoundError);+ expect(() => queryByPreference(tmp, "garbage")).toThrow(BrainNotFoundError);expect(() => queryByPreference(tmp, "")).toThrow(BrainNotFoundError);});@@ -160,16 +150,10 @@ describe("queryByPreference", () => {// could resolve outside the vault on a permissive filesystem. We// surface this as `BrainNotFoundError` so the caller sees the same// shape as any other unknown id.- expect(() => queryByPreference(tmp, "pref-../escape")).toThrow(- BrainNotFoundError,- );+ expect(() => queryByPreference(tmp, "pref-../escape")).toThrow(BrainNotFoundError);expect(() => queryByPreference(tmp, "pref-..")).toThrow(BrainNotFoundError);- expect(() => queryByPreference(tmp, "pref-with/slash")).toThrow(- BrainNotFoundError,- );- expect(() => queryByPreference(tmp, "ret-../escape")).toThrow(- BrainNotFoundError,- );+ expect(() => queryByPreference(tmp, "pref-with/slash")).toThrow(BrainNotFoundError);+ expect(() => queryByPreference(tmp, "ret-../escape")).toThrow(BrainNotFoundError);});test("preference without any applied evidence still resolves with empty `evidence` array", () => {@@ -235,10 +219,7 @@ describe("queryByTopic", () => {]);expect(res.preference?.id).toBe("pref-no-internal-abbrev");expect(res.all_log_events).toHaveLength(2);- expect(res.all_log_events.map((e) => e.eventType)).toEqual([- "promote",- "apply-evidence",- ]);+ expect(res.all_log_events.map((e) => e.eventType)).toEqual(["promote", "apply-evidence"]);});test("falls back to retired preference when no active one exists for the topic", () => {@@ -298,16 +279,11 @@ describe("queryByLogSince", () => {const res = queryByLogSince(tmp, new Date("2026-05-13T00:00:00Z"));expect(res).toHaveLength(2);- expect(res.map((e) => e.timestamp)).toEqual([- "2026-05-13T18:00:00Z",- "2026-05-14T14:00:00Z",- ]);+ expect(res.map((e) => e.timestamp)).toEqual(["2026-05-13T18:00:00Z", "2026-05-14T14:00:00Z"]);});test("invalid Date throws TypeError", () => {- expect(() =>- queryByLogSince(tmp, new Date("totally-not-a-date")),- ).toThrow(TypeError);+ expect(() => queryByLogSince(tmp, new Date("totally-not-a-date"))).toThrow(TypeError);});test("empty log returns empty array (no throw)", () => {diff --git a/tests/core/brain.sessions.hermes.test.ts b/tests/core/brain.sessions.hermes.test.tsindex cae56879..6c922f1e 100644--- a/tests/core/brain.sessions.hermes.test.ts+++ b/tests/core/brain.sessions.hermes.test.ts@@ -40,9 +40,7 @@ describe("hermesAdapter.detect", () => {test("requires 'tools' array on the meta line", () => {expect(hermesAdapter.detect('{"role":"session_meta"}')).toBe(false);- expect(- hermesAdapter.detect('{"role":"session_meta","tools":"not-an-array"}'),- ).toBe(false);+ expect(hermesAdapter.detect('{"role":"session_meta","tools":"not-an-array"}')).toBe(false);});});diff --git a/tests/core/brain.sessions.import.test.ts b/tests/core/brain.sessions.import.test.tsindex 00ad9dde..f0f2c551 100644--- a/tests/core/brain.sessions.import.test.ts+++ b/tests/core/brain.sessions.import.test.ts@@ -7,23 +7,14 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- readdirSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { brainDirs } from "../../src/core/brain/paths.ts";import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";-import {- importSession,- importSessionPath,-} from "../../src/core/brain/sessions/import.ts";+import { importSession, importSessionPath } from "../../src/core/brain/sessions/import.ts";import { SessionImportError } from "../../src/core/brain/sessions/types.ts";const CLAUDE = resolve("tests/fixtures/sessions/claude-minimal.jsonl");@@ -35,7 +26,15 @@ let tmp: string;beforeEach(() => {tmp = mkdtempSync(join(tmpdir(), "o2b-import-"));const dirs = brainDirs(tmp);- for (const d of [dirs.brain, dirs.inbox, dirs.processed, dirs.preferences, dirs.retired, dirs.log, dirs.snapshots]) {+ for (const d of [+ dirs.brain,+ dirs.inbox,+ dirs.processed,+ dirs.preferences,+ dirs.retired,+ dirs.log,+ dirs.snapshots,+ ]) {mkdirSync(d, { recursive: true });}atomicWriteFileSync(join(dirs.brain, "_brain.yaml"), DEFAULT_BRAIN_CONFIG_YAML);diff --git a/tests/core/brain.sessions.registry.test.ts b/tests/core/brain.sessions.registry.test.tsindex ad409fba..6d61d4c5 100644--- a/tests/core/brain.sessions.registry.test.ts+++ b/tests/core/brain.sessions.registry.test.ts@@ -25,7 +25,7 @@ function firstLine(path: string): string {describe("registry — single source of adapters", () => {test("exposes all three adapters", () => {- const ids = SESSION_ADAPTERS.map((a) => a.id).sort();+ const ids = SESSION_ADAPTERS.map((a) => a.id).toSorted();expect(ids).toEqual(["claude", "codex", "hermes"]);});diff --git a/tests/core/brain.set-primary.test.ts b/tests/core/brain.set-primary.test.tsindex b86258f6..95eb98be 100644--- a/tests/core/brain.set-primary.test.ts+++ b/tests/core/brain.set-primary.test.ts@@ -1,17 +1,5 @@-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";-import {- mkdirSync,- mkdtempSync,- readFileSync,- rmSync,- writeFileSync,-} from "node:fs";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -44,8 +32,7 @@ afterEach(() => {function readPrimary(): string | null {const text = readFileSync(brainConfigPath(vault), "utf8");- return validateBrainConfig(parseBrainYaml(text), brainConfigPath(vault))- .primary_agent;+ return validateBrainConfig(parseBrainYaml(text), brainConfigPath(vault)).primary_agent;}describe("setPrimaryAgent — happy path", () => {@@ -55,9 +42,7 @@ describe("setPrimaryAgent — happy path", () => {expect(r.next).toBe("hermes-vps");expect(r.changed).toBe(true);expect(readPrimary()).toBe("hermes-vps");- expect(readFileSync(brainConfigPath(vault), "utf8")).toMatch(- /^primary_agent: "hermes-vps"$/m,- );+ expect(readFileSync(brainConfigPath(vault), "utf8")).toMatch(/^primary_agent: "hermes-vps"$/m);});test("quotes values so inline-comment text round-trips", () => {@@ -104,8 +89,10 @@ describe("setPrimaryAgent — happy path", () => {test("preserves neighbouring blocks (dream/retire/confidence/snapshots)", () => {// Custom edit to a different block, then set primary.const cfgPath = brainConfigPath(vault);- const original = readFileSync(cfgPath, "utf8")- .replace(/^ candidate_threshold: 3$/m, " candidate_threshold: 5");+ const original = readFileSync(cfgPath, "utf8").replace(+ /^ candidate_threshold: 3$/m,+ " candidate_threshold: 5",+ );writeFileSync(cfgPath, original, "utf8");setPrimaryAgent(vault, "hermes-vps");@@ -130,9 +117,7 @@ describe("setPrimaryAgent — error cases", () => {});test("line breaks are rejected rather than written into YAML", () => {- expect(() => setPrimaryAgent(vault, "agent\nsnapshots:")).toThrow(- /disallowed character/,- );+ expect(() => setPrimaryAgent(vault, "agent\nsnapshots:")).toThrow(/disallowed character/);});test("rewritten file still validates against the schema", () => {@@ -159,8 +144,6 @@ describe("setPrimaryAgent — missing primary_agent line", () => {setPrimaryAgent(vault, "hermes-vps");const text = readFileSync(cfgPath, "utf8");expect(text).toMatch(/^primary_agent: "hermes-vps"$/m);- expect(text.indexOf("schema_version:")).toBeLessThan(- text.indexOf("primary_agent:"),- );+ expect(text.indexOf("schema_version:")).toBeLessThan(text.indexOf("primary_agent:"));});});diff --git a/tests/core/brain.signal.test.ts b/tests/core/brain.signal.test.tsindex 42fc7578..45168c23 100644--- a/tests/core/brain.signal.test.ts+++ b/tests/core/brain.signal.test.ts@@ -3,11 +3,7 @@ import { mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- parseSignal,- writeSignal,- type WriteSignalInput,-} from "../../src/core/brain/signal.ts";+import { parseSignal, writeSignal, type WriteSignalInput } from "../../src/core/brain/signal.ts";let tmp: string;@@ -55,9 +51,9 @@ describe("writeSignal — required field validation", () => {// field by composing a fresh object that omits it.const partial = { ...input } as Record<string, unknown>;delete partial[field as string];- expect(() =>- writeSignal(tmp, partial as unknown as WriteSignalInput),- ).toThrow(new RegExp(`signal missing field: ${String(field)}`));+ expect(() => writeSignal(tmp, partial as unknown as WriteSignalInput)).toThrow(+ new RegExp(`signal missing field: ${String(field)}`),+ );});}@@ -85,10 +81,7 @@ describe("writeSignal + parseSignal roundtrip", () => {expect(parsed.tags).toContain("brain/signal");expect(parsed.tags).toContain("brain/topic/no-internal-abbrev");expect(parsed.tags).toContain("brain/scope/writing");- expect(parsed.source).toEqual([- "[[Daily/2026.05.14]]",- "[[blog-header-draft]]",- ]);+ expect(parsed.source).toEqual(["[[Daily/2026.05.14]]", "[[blog-header-draft]]"]);expect(parsed.raw).toContain("Sergey pointed out");});@@ -119,10 +112,7 @@ describe("writeSignal + parseSignal roundtrip", () => {expect(normalize(firstBytes)).toBe(normalize(secondBytes));// And the parsed source array survives untouched.- expect(parsed.source).toEqual([- "[[Daily/2026.05.14]]",- "[[blog-header-draft]]",- ]);+ expect(parsed.source).toEqual(["[[Daily/2026.05.14]]", "[[blog-header-draft]]"]);});});@@ -133,10 +123,7 @@ describe("writeSignal — wikilink preservation", () => {});const first = writeSignal(tmp, input);const parsed = parseSignal(first.path);- expect(parsed.source).toEqual([- "[[Daily/2026.05.14]]",- "[[blog-header-draft]]",- ]);+ expect(parsed.source).toEqual(["[[Daily/2026.05.14]]", "[[blog-header-draft]]"]);// Write again to a different slug, then re-parse.const second = writeSignal(tmp, {@@ -145,10 +132,7 @@ describe("writeSignal — wikilink preservation", () => {source: [...parsed.source!],});const reparsed = parseSignal(second.path);- expect(reparsed.source).toEqual([- "[[Daily/2026.05.14]]",- "[[blog-header-draft]]",- ]);+ expect(reparsed.source).toEqual(["[[Daily/2026.05.14]]", "[[blog-header-draft]]"]);});test("file body actually contains the wikilink literally", () => {@@ -172,10 +156,13 @@ describe("extractRawSection (via parseSignal)", () => {"","Third line after a blank gap.",].join("\n");- const result = writeSignal(tmp, baseInput({- slug: "multi-line-raw",- raw: multiLine,- }));+ const result = writeSignal(+ tmp,+ baseInput({+ slug: "multi-line-raw",+ raw: multiLine,+ }),+ );const parsed = parseSignal(result.path);expect(parsed.raw).toBe(multiLine);});@@ -252,9 +239,9 @@ describe("writeSignal — sanitisation (§7)", () => {});test("rejects when sanitisation strips principle down to empty", () => {- expect(() =>- writeSignal(tmp, baseInput({ slug: "empty", principle: "\x00\x01\x07" })),- ).toThrow(/signal missing field: principle/);+ expect(() => writeSignal(tmp, baseInput({ slug: "empty", principle: "\x00\x01\x07" }))).toThrow(+ /signal missing field: principle/,+ );});});@@ -273,24 +260,20 @@ describe("writeSignal — capture-extension fields (§9/§16)", () => {);const raw = readFileSync(r.path, "utf8");expect(raw).toMatch(/^source_type: inline$/m);- expect(raw).toMatch(/^dedup_hash: deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef$/m);+ expect(raw).toMatch(+ /^dedup_hash: deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef$/m,+ );expect(raw).toMatch(/^session_ref: /m);});test("adds brain/source/<type> tag when source_type is 'inline'", () => {- const r = writeSignal(- tmp,- baseInput({ slug: "inline-tag", source_type: "inline" }),- );+ const r = writeSignal(tmp, baseInput({ slug: "inline-tag", source_type: "inline" }));const raw = readFileSync(r.path, "utf8");expect(raw).toMatch(/brain\/source\/inline/);});test("adds brain/source/<type> tag when source_type is 'session'", () => {- const r = writeSignal(- tmp,- baseInput({ slug: "session-tag", source_type: "session" }),- );+ const r = writeSignal(tmp, baseInput({ slug: "session-tag", source_type: "session" }));const raw = readFileSync(r.path, "utf8");expect(raw).toMatch(/brain\/source\/session/);});diff --git a/tests/core/brain.snapshot-diff.test.ts b/tests/core/brain.snapshot-diff.test.tsindex 80114b09..713b0b3c 100644--- a/tests/core/brain.snapshot-diff.test.ts+++ b/tests/core/brain.snapshot-diff.test.ts@@ -8,27 +8,13 @@* regressions visible without re-deriving the structured shape.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";-import {- mkdirSync,- mkdtempSync,- rmSync,- writeFileSync,-} from "node:fs";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { diffBrainTrees } from "../../src/core/brain/snapshot-diff.ts";-import {- renderDiffJson,- renderDiffMarkdown,-} from "../../src/core/brain/snapshot-diff-render.ts";+import { renderDiffJson, renderDiffMarkdown } from "../../src/core/brain/snapshot-diff-render.ts";let scratch: string;@@ -78,11 +64,7 @@ _violated_count: ${s.violated ?? 0}_last_evidence_at: null_confidence: ${s.confidence ?? "low"}_confidence_value: ${- s.confidence_value === undefined- ? 0- : s.confidence_value === null- ? "null"- : s.confidence_value+ s.confidence_value === undefined ? 0 : s.confidence_value === null ? "null" : s.confidence_value}pinned: ${s.pinned ?? false}---@@ -184,7 +166,7 @@ describe("diffBrainTrees — field-level modifications", () => {const change = d.modified[0]!;expect(change.entry.id).toBe("pref-rule");expect(change.bodyChanged).toBe(false);- const fieldNames = change.fields.map((f) => f.field).sort();+ const fieldNames = change.fields.map((f) => f.field).toSorted();expect(fieldNames).toEqual(["applied_count","confidence",@@ -227,12 +209,8 @@ describe("diffBrainTrees — ignored regions", () => {writeFileSync(join(a, ".snapshots", "x.tar.zst"), "old", "utf8");writeFileSync(join(b, ".snapshots", "y.tar.zst"), "new", "utf8");const d = diffBrainTrees(a, b);- expect(- d.added.find((e) => e.path.includes(".snapshots/")),- ).toBeUndefined();- expect(- d.removed.find((e) => e.path.includes(".snapshots/")),- ).toBeUndefined();+ expect(d.added.find((e) => e.path.includes(".snapshots/"))).toBeUndefined();+ expect(d.removed.find((e) => e.path.includes(".snapshots/"))).toBeUndefined();});test("symlinks are not followed (defense against malicious snapshot tarballs)", async () => {@@ -248,11 +226,7 @@ describe("diffBrainTrees — ignored regions", () => {symlinkSync(secret, join(b, "preferences", "pref-trojan.md"));const d = diffBrainTrees(a, b);// The symlink must not appear in any diff section.- const allEntries = [- ...d.added,- ...d.removed,- ...d.modified.map((c) => c.entry),- ];+ const allEntries = [...d.added, ...d.removed, ...d.modified.map((c) => c.entry)];expect(allEntries.find((e) => e.path.includes("pref-trojan"))).toBeUndefined();});});@@ -268,12 +242,7 @@ describe("diffBrainTrees — output ordering", () => {const d = diffBrainTrees(a, b);const addedKinds = d.added.map((e) => e.kind);// 'preference' < 'signal' alphabetically — preferences come first.- expect(addedKinds).toEqual([- "preference",- "preference",- "signal",- "signal",- ]);+ expect(addedKinds).toEqual(["preference", "preference", "signal", "signal"]);expect(d.added.map((e) => e.id)).toEqual(["pref-alpha","pref-zeta",diff --git a/tests/core/brain.snapshot.test.ts b/tests/core/brain.snapshot.test.tsindex 89c84a3c..59012553 100644--- a/tests/core/brain.snapshot.test.ts+++ b/tests/core/brain.snapshot.test.ts@@ -90,9 +90,7 @@ describe("createSnapshot", () => {expect(existsSync(extracted)).toBe(true);expect(existsSync(join(extracted, "_brain.yaml"))).toBe(true);expect(existsSync(join(extracted, "_BRAIN.md"))).toBe(true);- expect(- existsSync(join(extracted, "inbox", "sig-2026-05-14-foo.md")),- ).toBe(true);+ expect(existsSync(join(extracted, "inbox", "sig-2026-05-14-foo.md"))).toBe(true);expect(existsSync(join(extracted, "preferences", "pref-foo.md"))).toBe(true);// The .snapshots/ directory MUST NOT be inside the archive.expect(existsSync(join(extracted, ".snapshots"))).toBe(false);@@ -215,11 +213,7 @@ describe("pruneSnapshots", () => {test("removes sidecar manifest alongside the archive", () => {const labels = ["a", "b", "c"];- const ts = [- "2026-05-10T00:00:00Z",- "2026-05-11T00:00:00Z",- "2026-05-12T00:00:00Z",- ];+ const ts = ["2026-05-10T00:00:00Z", "2026-05-11T00:00:00Z", "2026-05-12T00:00:00Z"];for (let i = 0; i < labels.length; i++) {const runId = `dream-prune-${labels[i]}`;createSnapshot(vault, runId);diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.tsindex 782a6fd4..978a77e3 100644--- a/tests/core/brain.types.test.ts+++ b/tests/core/brain.types.test.ts@@ -191,7 +191,7 @@ describe("interface shape smoke (compile-time)", () => {retire: { stale_evidence_days: 90 },confidence: {low_max_applied: 2,- medium_min: 0.40,+ medium_min: 0.4,high_min: 0.75,},snapshots: { retention_count: 10 },diff --git a/tests/core/brain.wikilink.test.ts b/tests/core/brain.wikilink.test.tsindex 512ee82f..f5e766c6 100644Binary files a/tests/core/brain.wikilink.test.ts and b/tests/core/brain.wikilink.test.ts differdiff --git a/tests/core/brain/backlinks-anchor-alias.test.ts b/tests/core/brain/backlinks-anchor-alias.test.tsindex effdbd98..33d4a97d 100644--- a/tests/core/brain/backlinks-anchor-alias.test.ts+++ b/tests/core/brain/backlinks-anchor-alias.test.ts@@ -13,10 +13,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- buildBacklinkIndex,- type BacklinkRef,-} from "../../../src/core/brain/backlinks.ts";+import { buildBacklinkIndex, type BacklinkRef } from "../../../src/core/brain/backlinks.ts";import { bootstrapBrain } from "../../../src/core/brain/init.ts";describe("BacklinkRef atom shape (additive)", () => {@@ -138,7 +135,7 @@ describe("buildBacklinkIndex - anchor / block populated from body wikilinks", ()const idx = buildBacklinkIndex(vault);const refs = idx.get("bar") ?? [];expect(refs.length).toBe(2);- const anchors = refs.map((r) => r.targetAnchor).sort();+ const anchors = refs.map((r) => r.targetAnchor).toSorted();expect(anchors).toEqual(["Alpha", "Beta"]);});});diff --git a/tests/core/brain/claude-memory-manifest.test.ts b/tests/core/brain/claude-memory-manifest.test.tsindex 8da71d32..4ac10605 100644--- a/tests/core/brain/claude-memory-manifest.test.ts+++ b/tests/core/brain/claude-memory-manifest.test.ts@@ -3,7 +3,9 @@ import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import {- loadManifest, saveManifest, type ClaudeMemoryManifest,+ loadManifest,+ saveManifest,+ type ClaudeMemoryManifest,} from "../../../src/core/brain/claude-memory-manifest.ts";describe("claude-memory manifest", () => {diff --git a/tests/core/brain/claude-memory-plan.test.ts b/tests/core/brain/claude-memory-plan.test.tsindex 52264fc6..4066457a 100644--- a/tests/core/brain/claude-memory-plan.test.ts+++ b/tests/core/brain/claude-memory-plan.test.ts@@ -4,8 +4,12 @@ import { planAction } from "../../../src/core/brain/claude-memory-plan.ts";describe("planAction", () => {const make = (overrides: Partial<Parameters<typeof planAction>[0]>) =>planAction({- basename: "x.md", prefId: "pref-x", sha256: "h",- inManifest: null, prefExists: false, ...overrides,+ basename: "x.md",+ prefId: "pref-x",+ sha256: "h",+ inManifest: null,+ prefExists: false,+ ...overrides,});test("no manifest + no pref → CREATE", () => {diff --git a/tests/core/brain/claude-memory-render.test.ts b/tests/core/brain/claude-memory-render.test.tsindex 287cafbd..57ccbd3a 100644--- a/tests/core/brain/claude-memory-render.test.ts+++ b/tests/core/brain/claude-memory-render.test.ts@@ -20,7 +20,9 @@ describe("renderPreferenceFromMemory", () => {expect(out).toContain("scope: writing");expect(out).toContain("confidence: high");expect(out).toContain("_force_confirmed_via: claude-memory");- expect(out).toContain("_imported_from: \"/root/.claude/projects/-root/memory/feedback_no_em_dashes.md\"");+ expect(out).toContain(+ '_imported_from: "/root/.claude/projects/-root/memory/feedback_no_em_dashes.md"',+ );expect(out).toContain("Body text.");expect(out).toContain("**Why:**");expect(out).toContain("## Origin");@@ -29,9 +31,11 @@ describe("renderPreferenceFromMemory", () => {test("body scope marker overrides default writing scope", () => {const out = renderPreferenceFromMemory({- name: "x", description: "x",+ name: "x",+ description: "x",body: "First line.\nscope: testing\nrest.",- memoryPath: "/m.md", importedAt: "2026-05-18T10:00:00Z",+ memoryPath: "/m.md",+ importedAt: "2026-05-18T10:00:00Z",bodySha256: "a".repeat(64),});expect(out).toContain("scope: testing");@@ -48,15 +52,15 @@ describe("slugifyMemoryName", () => {});test("punctuation and spaces collapse to single dash", () => {- expect(- slugifyMemoryName("Phase-by-phase approval: don't conflate plan/code"),- ).toBe("phase-by-phase-approval-don-t-conflate-plan-code");+ expect(slugifyMemoryName("Phase-by-phase approval: don't conflate plan/code")).toBe(+ "phase-by-phase-approval-don-t-conflate-plan-code",+ );});test("em-dashes do not produce runs of dashes in the slug", () => {- expect(- slugifyMemoryName("Daily/ event log — append after every artifact"),- ).toBe("daily-event-log-append-after-every-artifact");+ expect(slugifyMemoryName("Daily/ event log — append after every artifact")).toBe(+ "daily-event-log-append-after-every-artifact",+ );});test("leading and trailing dashes are trimmed", () => {diff --git a/tests/core/brain/content-hash.test.ts b/tests/core/brain/content-hash.test.tsindex 71cc1104..07c3101e 100644--- a/tests/core/brain/content-hash.test.ts+++ b/tests/core/brain/content-hash.test.ts@@ -6,10 +6,7 @@import { describe, expect, test } from "bun:test";-import {- computeContentHash,- verifyContentHash,-} from "../../../src/core/brain/content-hash.ts";+import { computeContentHash, verifyContentHash } from "../../../src/core/brain/content-hash.ts";describe("computeContentHash", () => {test("returns a 64-char lowercase hex sha256 digest", () => {@@ -74,10 +71,9 @@ describe("verifyContentHash", () => {content_hash: "0".repeat(64),});expect(result.ok).toBe(false);- expect(result.expected).toBe(computeContentHash(- "altered principle after a hand edit",- "coding",- ));+ expect(result.expected).toBe(+ computeContentHash("altered principle after a hand edit", "coding"),+ );expect(result.observed).toBe("0".repeat(64));});diff --git a/tests/core/brain/context-pack.test.ts b/tests/core/brain/context-pack.test.tsindex 39b4dd30..79753b73 100644--- a/tests/core/brain/context-pack.test.ts+++ b/tests/core/brain/context-pack.test.ts@@ -20,14 +20,16 @@ function writePref(slug: string,fields: { topic: string; principle: string; tier?: string; created_at?: string },) {- const lines = ["---", `id: pref-${slug}`, `topic: ${fields.topic}`, `principle: ${fields.principle}`];+ const lines = [+ "---",+ `id: pref-${slug}`,+ `topic: ${fields.topic}`,+ `principle: ${fields.principle}`,+ ];if (fields.tier) lines.push(`tier: ${fields.tier}`);if (fields.created_at) lines.push(`created_at: ${fields.created_at}`);lines.push("---", "");- writeFileSync(- join(vault, "Brain", "preferences", `pref-${slug}.md`),- lines.join("\n"),- );+ writeFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`), lines.join("\n"));}describe("packContext", () => {diff --git a/tests/core/brain/digest-actions.test.ts b/tests/core/brain/digest-actions.test.tsindex a63ebda3..98cd0802 100644--- a/tests/core/brain/digest-actions.test.ts+++ b/tests/core/brain/digest-actions.test.ts@@ -6,12 +6,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -44,10 +39,7 @@ function writePref(slug: string, fields: Record<string, string>) {lines.push(`${key}: ${v}`);}lines.push("---", "");- writeFileSync(- join(vault, "Brain", "preferences", `pref-${slug}.md`),- lines.join("\n"),- );+ writeFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`), lines.join("\n"));}beforeEach(() => {diff --git a/tests/core/brain/digest-agent-summary.test.ts b/tests/core/brain/digest-agent-summary.test.tsindex 63c81284..d1658902 100644--- a/tests/core/brain/digest-agent-summary.test.ts+++ b/tests/core/brain/digest-agent-summary.test.ts@@ -5,10 +5,7 @@ import { join } from "node:path";import { computeAgentSummary } from "../../../src/core/brain/digest-agent-summary.ts";import { appendLogEvent } from "../../../src/core/brain/log.ts";-import {- BRAIN_LOG_EVENT_KIND,- BRAIN_APPLY_RESULT,-} from "../../../src/core/brain/types.ts";+import { BRAIN_LOG_EVENT_KIND, BRAIN_APPLY_RESULT } from "../../../src/core/brain/types.ts";let vault: string;@@ -20,7 +17,9 @@ beforeEach(() => {});afterEach(() => {- try { rmSync(vault, { recursive: true, force: true }); } catch {}+ try {+ rmSync(vault, { recursive: true, force: true });+ } catch {}});describe("computeAgentSummary", () => {diff --git a/tests/core/brain/digest-most-applied.test.ts b/tests/core/brain/digest-most-applied.test.tsindex 6826ad84..c4914584 100644--- a/tests/core/brain/digest-most-applied.test.ts+++ b/tests/core/brain/digest-most-applied.test.ts@@ -12,10 +12,7 @@ import { join } from "node:path";import { renderDigest } from "../../../src/core/brain/digest.ts";import { appendLogEvent } from "../../../src/core/brain/log.ts";-import {- BRAIN_APPLY_RESULT,- BRAIN_LOG_EVENT_KIND,-} from "../../../src/core/brain/types.ts";+import { BRAIN_APPLY_RESULT, BRAIN_LOG_EVENT_KIND } from "../../../src/core/brain/types.ts";let vault: string;@@ -51,7 +48,9 @@ body});afterEach(() => {- try { rmSync(vault, { recursive: true, force: true }); } catch {}+ try {+ rmSync(vault, { recursive: true, force: true });+ } catch {}});function writeBrainYaml(content: string): void {@@ -122,11 +121,11 @@ describe("digest most_applied block — custom config", () => {test("honours window_days / limit from _brain.yaml", () => {writeBrainYaml("schema_version: 1\n" +- "active:\n" +- " most_applied_window_days: 7\n" +- " most_applied_limit: 3\n",+ "active:\n" ++ " most_applied_window_days: 7\n" ++ " most_applied_limit: 3\n",);- seedApplied("2026-05-19T10:00:00Z", "[[pref-a]]"); // within 7d+ seedApplied("2026-05-19T10:00:00Z", "[[pref-a]]"); // within 7dconst result = renderDigest(vault, {format: "json",now: new Date("2026-05-20T12:00:00Z"),@@ -141,9 +140,9 @@ describe("digest most_applied block — custom config", () => {test("Markdown header reflects custom window", () => {writeBrainYaml("schema_version: 1\n" +- "active:\n" +- " most_applied_window_days: 14\n" +- " most_applied_limit: 5\n",+ "active:\n" ++ " most_applied_window_days: 14\n" ++ " most_applied_limit: 5\n",);seedApplied("2026-05-19T10:00:00Z", "[[pref-a]]");const result = renderDigest(vault, {diff --git a/tests/core/brain/doctor-drift.test.ts b/tests/core/brain/doctor-drift.test.tsindex 823a121d..23843b1b 100644--- a/tests/core/brain/doctor-drift.test.ts+++ b/tests/core/brain/doctor-drift.test.ts@@ -44,11 +44,7 @@ snapshots:`,"utf8",);- writeFileSync(- join(dirs.brain, "_BRAIN.md"),- "---\ntitle: Brain\n---\n",- "utf8",- );+ writeFileSync(join(dirs.brain, "_BRAIN.md"), "---\ntitle: Brain\n---\n", "utf8");});afterEach(() => {rmSync(vault, { recursive: true, force: true });@@ -96,9 +92,7 @@ describe("runDoctor content-hash drift detection", () => {const hash = computeContentHash(principle, undefined);writeConfirmedPref("clean", { principle, content_hash: hash });const result = runDoctor(vault);- const drift = result.warnings.filter(- (i) => i.code === "content-hash-drift",- );+ const drift = result.warnings.filter((i) => i.code === "content-hash-drift");expect(drift).toEqual([]);});@@ -111,9 +105,7 @@ describe("runDoctor content-hash drift detection", () => {content_hash: staleHash,});const result = runDoctor(vault);- const drift = result.warnings.filter(- (i) => i.code === "content-hash-drift",- );+ const drift = result.warnings.filter((i) => i.code === "content-hash-drift");expect(drift).toHaveLength(1);expect(drift[0]?.path).toBe(path);expect(drift[0]?.message).toContain("drift");@@ -125,9 +117,7 @@ describe("runDoctor content-hash drift detection", () => {// content_hash intentionally omitted});const result = runDoctor(vault);- const drift = result.warnings.filter(- (i) => i.code === "content-hash-drift",- );+ const drift = result.warnings.filter((i) => i.code === "content-hash-drift");expect(drift).toEqual([]);});@@ -141,9 +131,7 @@ describe("runDoctor content-hash drift detection", () => {content_hash: staleHash,});const result = runDoctor(vault);- const drift = result.warnings.filter(- (i) => i.code === "content-hash-drift",- );+ const drift = result.warnings.filter((i) => i.code === "content-hash-drift");expect(drift).toHaveLength(1);});});diff --git a/tests/core/brain/doctor-semantic.test.ts b/tests/core/brain/doctor-semantic.test.tsindex 1022867b..a23a2d5b 100644--- a/tests/core/brain/doctor-semantic.test.ts+++ b/tests/core/brain/doctor-semantic.test.ts@@ -91,12 +91,9 @@ describe("runDoctor semantic health", () => {test("a coherent vault produces no semantic warnings and a clean verdict", () => {const pos = sig("tdd-pos", BRAIN_SIGNAL_SIGN.positive, "write tests early");- confirmedPref(- "tdd-rule",- "testing-discipline",- "write unit tests before merging code",- [`[[${pos}]]`],- );+ confirmedPref("tdd-rule", "testing-discipline", "write unit tests before merging code", [+ `[[${pos}]]`,+ ]);const result = runDoctor(vault, { now: NOW });const semanticCodes = result.warningsdiff --git a/tests/core/brain/doctor-trust.test.ts b/tests/core/brain/doctor-trust.test.tsindex c7d5d034..2846d57b 100644--- a/tests/core/brain/doctor-trust.test.ts+++ b/tests/core/brain/doctor-trust.test.ts@@ -12,10 +12,7 @@ import { join } from "node:path";import { runDoctor } from "../../../src/core/brain/doctor.ts";import type { DreamRunSummary } from "../../../src/core/brain/dream.ts";-import {- brainConfigPath,- brainDirs,-} from "../../../src/core/brain/paths.ts";+import { brainConfigPath, brainDirs } from "../../../src/core/brain/paths.ts";import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";diff --git a/tests/core/brain/dream-content-hash-promotion.test.ts b/tests/core/brain/dream-content-hash-promotion.test.tsindex d4b5bcaf..fc5dc970 100644--- a/tests/core/brain/dream-content-hash-promotion.test.ts+++ b/tests/core/brain/dream-content-hash-promotion.test.ts@@ -11,11 +11,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdtempSync,- readFileSync,- rmSync,-} from "node:fs";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -89,8 +85,6 @@ describe("dream content_hash on promotion", () => {expect(text).toContain("_content_hash:");const parsed = parsePreference(path);expect(parsed.status).toBe("confirmed");- expect(parsed.content_hash).toBe(- computeContentHash(parsed.principle, parsed.scope),- );+ expect(parsed.content_hash).toBe(computeContentHash(parsed.principle, parsed.scope));});});diff --git a/tests/core/brain/dream-destructive-gate.test.ts b/tests/core/brain/dream-destructive-gate.test.tsindex b32a85e1..98a9c533 100644--- a/tests/core/brain/dream-destructive-gate.test.ts+++ b/tests/core/brain/dream-destructive-gate.test.ts@@ -16,10 +16,7 @@ import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- dream,- shouldGateRetireFromConfirmed,-} from "../../../src/core/brain/dream.ts";+import { dream, shouldGateRetireFromConfirmed } from "../../../src/core/brain/dream.ts";import { bootstrapBrain } from "../../../src/core/brain/init.ts";import {BRAIN_PREFERENCE_STATUS,@@ -51,29 +48,17 @@ const pref = (overrides: Partial<BrainPreference> = {}): BrainPreference => ({describe("shouldGateRetireFromConfirmed", () => {test("returns false when threshold is undefined (default-off)", () => {expect(- shouldGateRetireFromConfirmed(- pref(),- BRAIN_RETIRED_REASON.staleNoEvidence,- undefined,- ),+ shouldGateRetireFromConfirmed(pref(), BRAIN_RETIRED_REASON.staleNoEvidence, undefined),).toBe(false);});test("returns false when threshold is 0 or negative", () => {- expect(- shouldGateRetireFromConfirmed(- pref(),- BRAIN_RETIRED_REASON.staleNoEvidence,- 0,- ),- ).toBe(false);- expect(- shouldGateRetireFromConfirmed(- pref(),- BRAIN_RETIRED_REASON.staleNoEvidence,- -1,- ),- ).toBe(false);+ expect(shouldGateRetireFromConfirmed(pref(), BRAIN_RETIRED_REASON.staleNoEvidence, 0)).toBe(+ false,+ );+ expect(shouldGateRetireFromConfirmed(pref(), BRAIN_RETIRED_REASON.staleNoEvidence, -1)).toBe(+ false,+ );});test("returns true when confirmed + unpinned + evidence below threshold", () => {diff --git a/tests/core/brain/dream-workrun.test.ts b/tests/core/brain/dream-workrun.test.tsindex a688f225..7e6857ac 100644--- a/tests/core/brain/dream-workrun.test.ts+++ b/tests/core/brain/dream-workrun.test.ts@@ -14,14 +14,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- existsSync,- mkdirSync,- mkdtempSync,- readFileSync,- rmSync,- writeFileSync,-} from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -30,10 +23,7 @@ import {scanDanglingWorkruns,WORKRUN_PHASE,} from "../../../src/core/brain/dream-workrun.ts";-import {- dreamRunsDir,- dreamWorkrunPath,-} from "../../../src/core/brain/paths.ts";+import { dreamRunsDir, dreamWorkrunPath } from "../../../src/core/brain/paths.ts";let vault: string;@@ -151,7 +141,7 @@ describe("scanDanglingWorkruns", () => {const b = openWorkrun(vault, "dream-2026-05-27-200005");b.finalize();- const dangling = scanDanglingWorkruns(vault).sort();+ const dangling = scanDanglingWorkruns(vault).toSorted();expect(dangling).toEqual([a.path]);});diff --git a/tests/core/brain/explorer-deeplink.test.ts b/tests/core/brain/explorer-deeplink.test.tsindex 0bb96770..afcb4ddd 100644--- a/tests/core/brain/explorer-deeplink.test.ts+++ b/tests/core/brain/explorer-deeplink.test.ts@@ -3,7 +3,11 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { collectExplorerData, renderExportedHtml, __resetExplorerTemplateCacheForTests } from "../../../src/core/brain/explorer.ts";+import {+ collectExplorerData,+ renderExportedHtml,+ __resetExplorerTemplateCacheForTests,+} from "../../../src/core/brain/explorer.ts";let vault: string;@@ -15,7 +19,9 @@ beforeEach(() => {afterEach(() => {__resetExplorerTemplateCacheForTests();- try { rmSync(vault, { recursive: true, force: true }); } catch {}+ try {+ rmSync(vault, { recursive: true, force: true });+ } catch {}});describe("explorer deep-link", () => {diff --git a/tests/core/brain/explorer.test.ts b/tests/core/brain/explorer.test.tsindex 6601bd4b..c7eabade 100644--- a/tests/core/brain/explorer.test.ts+++ b/tests/core/brain/explorer.test.ts@@ -18,10 +18,7 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { basename, join } from "node:path";-import {- buildBacklinkIndex,- backlinkCount,-} from "../../../src/core/brain/backlinks.ts";+import { buildBacklinkIndex, backlinkCount } from "../../../src/core/brain/backlinks.ts";import {collectExplorerData,EXPLORER_SCHEMA_VERSION,@@ -87,7 +84,11 @@ describe("collectExplorerData", () => {test("nodes include confirmed, unconfirmed, quarantine, retired", () => {writePreference(vault,- basePref("conf", { status: BRAIN_PREFERENCE_STATUS.confirmed, applied_count: 5, confidence: BRAIN_CONFIDENCE.high }),+ basePref("conf", {+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ applied_count: 5,+ confidence: BRAIN_CONFIDENCE.high,+ }),);writePreference(vault,@@ -113,7 +114,7 @@ describe("collectExplorerData", () => {});const g = collectExplorerData(vault);- const ids = g.nodes.map((n) => n.id).sort();+ const ids = g.nodes.map((n) => n.id).toSorted();expect(ids).toEqual(["pref-conf", "pref-quar", "pref-trial", "ret-dead"]);const byId = new Map(g.nodes.map((n) => [n.id, n]));expect(byId.get("pref-conf")!.status).toBe("confirmed");@@ -149,9 +150,7 @@ describe("collectExplorerData", () => {const g = collectExplorerData(vault);const supersedesEdges = g.edges.filter((e) => e.kind === "supersedes");expect(supersedesEdges.length).toBeGreaterThanOrEqual(1);- const e = supersedesEdges.find(- (x) => x.source === "pref-new" && x.target === "ret-old",- );+ const e = supersedesEdges.find((x) => x.source === "pref-new" && x.target === "ret-old");expect(e).toBeDefined();});@@ -170,9 +169,7 @@ describe("collectExplorerData", () => {);const g = collectExplorerData(vault);const wlEdges = g.edges.filter((e) => e.kind === "wikilink");- const bToA = wlEdges.find(- (e) => e.source === "pref-b" && e.target === "pref-a",- );+ const bToA = wlEdges.find((e) => e.source === "pref-b" && e.target === "pref-a");expect(bToA).toBeDefined();// No edge to the signal — sig-foo is not in the node set.expect(g.edges.find((e) => e.target === "sig-foo")).toBeUndefined();@@ -213,14 +210,8 @@ describe("collectExplorerData", () => {writePreference(vault, basePref("target"));// Two sources, both reaching target via `evidenced_by` (the// canonical inter-pref reference field).- writePreference(- vault,- basePref("source1", { evidenced_by: ["[[pref-target]]"] }),- );- writePreference(- vault,- basePref("source2", { evidenced_by: ["[[pref-target]]"] }),- );+ writePreference(vault, basePref("source1", { evidenced_by: ["[[pref-target]]"] }));+ writePreference(vault, basePref("source2", { evidenced_by: ["[[pref-target]]"] }));const g = collectExplorerData(vault);const node = g.nodes.find((n) => n.id === "pref-target");const expected = backlinkCount(buildBacklinkIndex(vault), "pref-target");@@ -252,7 +243,7 @@ describe("collectExplorerData", () => {const kinds = g.nodes.map((n) => n.kind);expect(kinds).toEqual(["preference", "preference", "retired"]);const prefIds = g.nodes.filter((n) => n.kind === "preference").map((n) => n.id);- expect(prefIds).toEqual([...prefIds].sort());+ expect(prefIds).toEqual([...prefIds].toSorted());});});diff --git a/tests/core/brain/export.test.ts b/tests/core/brain/export.test.tsindex 92ef6c0f..d3ad9d94 100644--- a/tests/core/brain/export.test.ts+++ b/tests/core/brain/export.test.ts@@ -73,10 +73,7 @@ describe("exportPreferencesJson", () => {});test("mixed-status preferences are all included, retired/signal are excluded", () => {- writePreference(- vault,- basePref("alpha", { status: BRAIN_PREFERENCE_STATUS.confirmed }),- );+ writePreference(vault, basePref("alpha", { status: BRAIN_PREFERENCE_STATUS.confirmed }));writePreference(vault,basePref("beta", {@@ -106,18 +103,11 @@ describe("exportPreferencesJson", () => {);const out = exportPreferencesJson(vault);- expect(out.preferences.map((p) => p.id)).toEqual([- "pref-alpha",- "pref-beta",- "pref-gamma",- ]);+ expect(out.preferences.map((p) => p.id)).toEqual(["pref-alpha", "pref-beta", "pref-gamma"]);});test("row carries the canonical field set", () => {- writePreference(- vault,- basePref("alpha", { scope: "writing", pinned: true }),- );+ writePreference(vault, basePref("alpha", { scope: "writing", pinned: true }));const out = exportPreferencesJson(vault);const r = out.preferences[0]!;expect(r.id).toBe("pref-alpha");@@ -163,11 +153,7 @@ describe("exportPreferencesJson", () => {writePreference(vault, basePref("alpha"));writePreference(vault, basePref("mu"));const out = exportPreferencesJson(vault);- expect(out.preferences.map((p) => p.id)).toEqual([- "pref-alpha",- "pref-mu",- "pref-zeta",- ]);+ expect(out.preferences.map((p) => p.id)).toEqual(["pref-alpha", "pref-mu", "pref-zeta"]);});});@@ -183,10 +169,7 @@ describe("exportPreferencesLlmsTxt", () => {});test("mixed statuses render in fixed Confirmed → Unconfirmed → Quarantine order", () => {- writePreference(- vault,- basePref("alpha", { status: BRAIN_PREFERENCE_STATUS.confirmed }),- );+ writePreference(vault, basePref("alpha", { status: BRAIN_PREFERENCE_STATUS.confirmed }));writePreference(vault,basePref("beta", {@@ -194,10 +177,7 @@ describe("exportPreferencesLlmsTxt", () => {confirmed_at: null,}),);- writePreference(- vault,- basePref("gamma", { status: BRAIN_PREFERENCE_STATUS.quarantine }),- );+ writePreference(vault, basePref("gamma", { status: BRAIN_PREFERENCE_STATUS.quarantine }));const txt = exportPreferencesLlmsTxt(vault);const idxConfirmed = txt.indexOf("## Confirmed");const idxUnconfirmed = txt.indexOf("## Unconfirmed");@@ -219,9 +199,7 @@ describe("exportPreferencesLlmsTxt", () => {writePreference(vault, basePref("scoped", { scope: "writing" }));writePreference(vault, basePref("unscoped"));const txt = exportPreferencesLlmsTxt(vault);- expect(txt).toContain(- "- pref-scoped (topic: scoped, scope: writing): Principle for scoped",- );+ expect(txt).toContain("- pref-scoped (topic: scoped, scope: writing): Principle for scoped");expect(txt).toContain("- pref-unscoped (topic: unscoped): Principle for unscoped");});});diff --git a/tests/core/brain/health/concept-gap.test.ts b/tests/core/brain/health/concept-gap.test.tsindex 744d2c9f..4d755fb7 100644--- a/tests/core/brain/health/concept-gap.test.ts+++ b/tests/core/brain/health/concept-gap.test.ts@@ -30,11 +30,7 @@ describe("detectConceptGaps", () => {test("an entity covered by a preference topic is not a gap", () => {const gaps = detectConceptGaps(- [- "Kanban board needs grooming",- "the Kanban workflow is slow",- "review Kanban tasks weekly",- ],+ ["Kanban board needs grooming", "the Kanban workflow is slow", "review Kanban tasks weekly"],["kanban-grooming"],{ minFrequency: 3 },);@@ -55,29 +51,19 @@ describe("detectConceptGaps", () => {});test("lowercase function words are never entities", () => {- const gaps = detectConceptGaps(- ["use the tool", "use the result", "use the output"],- [],- { minFrequency: 3 },- );+ const gaps = detectConceptGaps(["use the tool", "use the result", "use the output"], [], {+ minFrequency: 3,+ });expect(gaps).toEqual([]);});test("an entity below the frequency threshold is not a gap", () => {- const gaps = detectConceptGaps(- ["Kanban once", "Kanban twice"],- [],- { minFrequency: 3 },- );+ const gaps = detectConceptGaps(["Kanban once", "Kanban twice"], [], { minFrequency: 3 });expect(gaps).toEqual([]);});test("repeats within one principle count once (document frequency)", () => {- const gaps = detectConceptGaps(- ["Kanban Kanban Kanban Kanban"],- [],- { minFrequency: 2 },- );+ const gaps = detectConceptGaps(["Kanban Kanban Kanban Kanban"], [], { minFrequency: 2 });expect(gaps).toEqual([]);});@@ -94,11 +80,9 @@ describe("detectConceptGaps", () => {});test("is language-agnostic", () => {- const gaps = detectConceptGaps(- ["Бэклог растёт", "Бэклог завис", "разгрести Бэклог"],- [],- { minFrequency: 3 },- );+ const gaps = detectConceptGaps(["Бэклог растёт", "Бэклог завис", "разгрести Бэклог"], [], {+ minFrequency: 3,+ });expect(gaps).toEqual([{ term: "бэклог", frequency: 3 }]);});});diff --git a/tests/core/brain/health/contradiction.test.ts b/tests/core/brain/health/contradiction.test.tsindex 16453150..872b0b3e 100644--- a/tests/core/brain/health/contradiction.test.ts+++ b/tests/core/brain/health/contradiction.test.ts@@ -9,10 +9,7 @@import { describe, expect, test } from "bun:test";-import {- BRAIN_PREFERENCE_STATUS,- BRAIN_SIGNAL_SIGN,-} from "../../../../src/core/brain/types.ts";+import { BRAIN_PREFERENCE_STATUS, BRAIN_SIGNAL_SIGN } from "../../../../src/core/brain/types.ts";import {detectContradictions,type PreferenceForContradiction,diff --git a/tests/core/brain/health/reconcile.test.ts b/tests/core/brain/health/reconcile.test.tsindex 9d196d48..1cda237d 100644--- a/tests/core/brain/health/reconcile.test.ts+++ b/tests/core/brain/health/reconcile.test.ts@@ -13,10 +13,7 @@import { describe, expect, test } from "bun:test";-import {- BRAIN_PREFERENCE_STATUS,- BRAIN_SIGNAL_SIGN,-} from "../../../../src/core/brain/types.ts";+import { BRAIN_PREFERENCE_STATUS, BRAIN_SIGNAL_SIGN } from "../../../../src/core/brain/types.ts";import {reconcileSemanticHealth,type PreferenceForHealth,@@ -24,7 +21,9 @@ import {const NOW = new Date("2026-05-27T00:00:00Z");-function pref(over: Partial<PreferenceForHealth> & Pick<PreferenceForHealth, "id">): PreferenceForHealth {+function pref(+ over: Partial<PreferenceForHealth> & Pick<PreferenceForHealth, "id">,+): PreferenceForHealth {return {status: BRAIN_PREFERENCE_STATUS.confirmed,scope: "coding",diff --git a/tests/core/brain/health/remediation.test.ts b/tests/core/brain/health/remediation.test.tsindex e589c40e..50d40555 100644--- a/tests/core/brain/health/remediation.test.ts+++ b/tests/core/brain/health/remediation.test.ts@@ -63,11 +63,8 @@ describe("planRemediation", () => {const plan = planRemediation(allFindings, { stepCap: 10 });const auto = plan.steps.filter((s) => s.classification === "auto-safe");const review = plan.steps.filter((s) => s.classification === "needs-review");- expect(auto.map((s) => s.code)).toEqual([- "content-hash-drift",- "content-hash-drift",- ]);- expect(review.map((s) => s.code).sort()).toEqual([+ expect(auto.map((s) => s.code)).toEqual(["content-hash-drift", "content-hash-drift"]);+ expect(review.map((s) => s.code).toSorted()).toEqual(["concept-gap","contradictory-preferences","stale-claim",@@ -117,7 +114,12 @@ describe("applyRemediation", () => {writeDriftedPref("a-drift");writeDriftedPref("b-drift");const plan = planRemediation(- { driftedSlugs: ["a-drift", "b-drift"], contradictions: [], staleClaims: [], conceptGaps: [] },+ {+ driftedSlugs: ["a-drift", "b-drift"],+ contradictions: [],+ staleClaims: [],+ conceptGaps: [],+ },{ stepCap: 1 },);const outcome = applyRemediation(vault, plan, { dryRun: false });diff --git a/tests/core/brain/health/stale-claim.test.ts b/tests/core/brain/health/stale-claim.test.tsindex e67c443f..43be1428 100644--- a/tests/core/brain/health/stale-claim.test.ts+++ b/tests/core/brain/health/stale-claim.test.ts@@ -47,10 +47,10 @@ describe("detectStaleClaims", () => {});test("skips preferences with no evidence date", () => {- const stale = detectStaleClaims(- [pref({ id: "pref-none", last_evidence_at: null })],- { maxAgeDays: 90, now: NOW },- );+ const stale = detectStaleClaims([pref({ id: "pref-none", last_evidence_at: null })], {+ maxAgeDays: 90,+ now: NOW,+ });expect(stale).toEqual([]);});@@ -81,9 +81,7 @@ describe("detectStaleClaims", () => {[pref({ id: "pref-dateonly", last_evidence_at: "2026-01-01" })],{ maxAgeDays: 90, now: NOW },);- expect(stale).toEqual([- { id: "pref-dateonly", lastEvidenceAt: "2026-01-01", ageDays: 146 },- ]);+ expect(stale).toEqual([{ id: "pref-dateonly", lastEvidenceAt: "2026-01-01", ageDays: 146 }]);});test("orders findings by age descending", () => {diff --git a/tests/core/brain/import-claude-memory-conflict.test.ts b/tests/core/brain/import-claude-memory-conflict.test.tsindex 7f14cc5a..76b50b24 100644--- a/tests/core/brain/import-claude-memory-conflict.test.ts+++ b/tests/core/brain/import-claude-memory-conflict.test.ts@@ -51,7 +51,12 @@ describe("CONFLICT path", () => {"---\nname: rule-c\ndescription: x.\nmetadata:\n type: feedback\n---\n\nb.\n","utf8",);- const res = importClaudeMemory({ vault, memoryDir: mem, mode: "dry-run", allowArbitraryMemoryPath: true });+ const res = importClaudeMemory({+ vault,+ memoryDir: mem,+ mode: "dry-run",+ allowArbitraryMemoryPath: true,+ });expect(res.conflicts.length).toBe(1);expect(res.conflicts[0]?.prefId).toBe("pref-rule-c");diff --git a/tests/core/brain/import-claude-memory-orchestrator.test.ts b/tests/core/brain/import-claude-memory-orchestrator.test.tsindex ecce3100..e785b1ed 100644--- a/tests/core/brain/import-claude-memory-orchestrator.test.ts+++ b/tests/core/brain/import-claude-memory-orchestrator.test.ts@@ -38,10 +38,13 @@ describe("importClaudeMemory", () => {const vault = setupVault();const mem = setupMemory();const res = importClaudeMemory({- vault, memoryDir: mem, mode: "dry-run", allowArbitraryMemoryPath: true,+ vault,+ memoryDir: mem,+ mode: "dry-run",+ allowArbitraryMemoryPath: true,});- expect(res.plans.map((p) => p.action).sort()).toEqual(["CREATE", "CREATE"]);- expect(res.skipped.length).toBe(1); // user_who.md; MEMORY.md is filtered earlier+ expect(res.plans.map((p) => p.action).toSorted()).toEqual(["CREATE", "CREATE"]);+ expect(res.skipped.length).toBe(1); // user_who.md; MEMORY.md is filtered earlierexpect(existsSync(join(vault, "Brain", "preferences", "pref-rule-a.md"))).toBe(false);rmSync(vault, { recursive: true });rmSync(mem, { recursive: true });@@ -51,14 +54,19 @@ describe("importClaudeMemory", () => {const vault = setupVault();const mem = setupMemory();const res = importClaudeMemory({- vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true,+ vault,+ memoryDir: mem,+ mode: "apply",+ allowArbitraryMemoryPath: true,now: new Date("2026-05-18T10:00:00Z"),});expect(res.applied.length).toBe(2);expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-a.md"))).toBe(true);expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-b.md"))).toBe(true);- const manifest = JSON.parse(readFileSync(join(vault, "Brain", ".imports", "claude-memory.json"), "utf8"));- expect(Object.keys(manifest.imports).sort()).toEqual(["feedback_a.md", "feedback_b.md"]);+ const manifest = JSON.parse(+ readFileSync(join(vault, "Brain", ".imports", "claude-memory.json"), "utf8"),+ );+ expect(Object.keys(manifest.imports).toSorted()).toEqual(["feedback_a.md", "feedback_b.md"]);const log = readFileSync(join(vault, "Brain", "log", res.localDate + ".md"), "utf8");expect(log).toContain("import-claude-memory");expect(log).toContain("created: 2");@@ -71,7 +79,12 @@ describe("importClaudeMemory", () => {const mem = setupMemory();importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true });const before = readFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "utf8");- const res2 = importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true });+ const res2 = importClaudeMemory({+ vault,+ memoryDir: mem,+ mode: "apply",+ allowArbitraryMemoryPath: true,+ });expect(res2.applied.length).toBe(0);expect(res2.skippedUnchanged.length).toBe(2);const after = readFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "utf8");diff --git a/tests/core/brain/import-claude-memory-preserve-evidence.test.ts b/tests/core/brain/import-claude-memory-preserve-evidence.test.tsindex f672e315..1f14202b 100644--- a/tests/core/brain/import-claude-memory-preserve-evidence.test.ts+++ b/tests/core/brain/import-claude-memory-preserve-evidence.test.ts@@ -16,7 +16,13 @@ describe("UPDATE preserves accumulated evidence", () => {"---\nname: rule-x\ndescription: V1.\nmetadata:\n type: feedback\n---\n\nBody v1.\n","utf8",);- importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true, now: new Date("2026-05-19T10:00:00Z") });+ importClaudeMemory({+ vault,+ memoryDir: mem,+ mode: "apply",+ allowArbitraryMemoryPath: true,+ now: new Date("2026-05-19T10:00:00Z"),+ });// Simulate accumulated evidence.const prefPath = join(vault, "Brain", "preferences", "pref-rule-x.md");@@ -34,14 +40,20 @@ describe("UPDATE preserves accumulated evidence", () => {"---\nname: rule-x\ndescription: V2.\nmetadata:\n type: feedback\n---\n\nBody v2.\n","utf8",);- importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true, now: new Date("2026-05-19T10:00:01Z") });+ importClaudeMemory({+ vault,+ memoryDir: mem,+ mode: "apply",+ allowArbitraryMemoryPath: true,+ now: new Date("2026-05-19T10:00:01Z"),+ });const after = readFileSync(prefPath, "utf8");expect(after).toContain("_applied_count: 7");expect(after).toContain("_violated_count: 2");expect(after).toContain("_evidenced_by: ['[[a.md]]', '[[b.md]]']");expect(after).toContain("pinned: true");- expect(after).toContain("principle: \"V2.\"");+ expect(after).toContain('principle: "V2."');expect(after).toContain("Body v2.");rmSync(vault, { recursive: true });diff --git a/tests/core/brain/link-graph/alias-index.test.ts b/tests/core/brain/link-graph/alias-index.test.tsindex d6b7798f..5702d8ed 100644--- a/tests/core/brain/link-graph/alias-index.test.ts+++ b/tests/core/brain/link-graph/alias-index.test.ts@@ -10,12 +10,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -25,17 +20,11 @@ import { bootstrapBrain } from "../../../../src/core/brain/init.ts";let vault: string;function writePref(slug: string, body: string): void {- writeFileSync(- join(vault, "Brain", "preferences", `${slug}.md`),- `${body}\n`,- );+ writeFileSync(join(vault, "Brain", "preferences", `${slug}.md`), `${body}\n`);}function writeRetired(slug: string, body: string): void {- writeFileSync(- join(vault, "Brain", "retired", `${slug}.md`),- `${body}\n`,- );+ writeFileSync(join(vault, "Brain", "retired", `${slug}.md`), `${body}\n`);}beforeEach(() => {@@ -145,9 +134,7 @@ describe("buildAliasIndex - normalisation", () => {const idx = buildAliasIndex(vault);// Lookup with composed form should hit (NFC normalises both// sides).- expect(idx.get(composed.normalize("NFC").toLowerCase())).toBe(- "pref-cafe",- );+ expect(idx.get(composed.normalize("NFC").toLowerCase())).toBe("pref-cafe");});test("trims whitespace from alias entries", () => {@@ -238,14 +225,9 @@ describe("buildAliasIndex - collision handling", () => {);writePref("pref-bar",- [- "---",- "kind: preference",- "topic: bar",- "status: confirmed",- "principle: y",- "---",- ].join("\n"),+ ["---", "kind: preference", "topic: bar", "status: confirmed", "principle: y", "---"].join(+ "\n",+ ),);const idx = buildAliasIndex(vault);expect(idx.get("pref-bar")).toBeUndefined();@@ -262,14 +244,9 @@ describe("buildAliasIndex - degenerate inputs", () => {test("artifact without aliases is skipped", () => {writePref("pref-noalias",- [- "---",- "kind: preference",- "topic: x",- "status: confirmed",- "principle: y",- "---",- ].join("\n"),+ ["---", "kind: preference", "topic: x", "status: confirmed", "principle: y", "---"].join(+ "\n",+ ),);const idx = buildAliasIndex(vault);expect(idx.size).toBe(0);@@ -293,13 +270,7 @@ describe("buildAliasIndex - degenerate inputs", () => {});test("malformed frontmatter row is silently skipped", () => {- writePref(- "pref-bad",- [- "no frontmatter here",- "just body content",- ].join("\n"),- );+ writePref("pref-bad", ["no frontmatter here", "just body content"].join("\n"));writePref("pref-good",[diff --git a/tests/core/brain/link-graph/concept-cluster.test.ts b/tests/core/brain/link-graph/concept-cluster.test.tsindex 2d6e26c3..86c5a14b 100644--- a/tests/core/brain/link-graph/concept-cluster.test.ts+++ b/tests/core/brain/link-graph/concept-cluster.test.ts@@ -9,12 +9,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -143,7 +138,7 @@ describe("buildConceptCluster - linkers", () => {);const r = buildConceptCluster(vault, "pref-tgt");expect(r.linkers.length).toBe(2);- const sources = r.linkers.map((l: { source: string }) => l.source).sort();+ const sources = r.linkers.map((l: { source: string }) => l.source).toSorted();expect(sources).toEqual(["pref-a", "pref-b"]);});diff --git a/tests/core/brain/link-graph/moc-audit.test.ts b/tests/core/brain/link-graph/moc-audit.test.tsindex de269949..5a3428c0 100644--- a/tests/core/brain/link-graph/moc-audit.test.ts+++ b/tests/core/brain/link-graph/moc-audit.test.ts@@ -9,12 +9,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -100,9 +95,21 @@ describe("auditMoc - bucket classification", () => {// Hub references pref-popular. Two other prefs also reference pref-popular.// Body of pref-popular is long.const longBody = "Long body content. ".repeat(20);- writePref("pref-popular", { kind: "preference", topic: "p", status: "confirmed", principle: "p" }, longBody);- writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" }, "Refers to [[pref-popular]].");- writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" }, "Also [[pref-popular]].");+ writePref(+ "pref-popular",+ { kind: "preference", topic: "p", status: "confirmed", principle: "p" },+ longBody,+ );+ writePref(+ "pref-a",+ { kind: "preference", topic: "a", status: "confirmed", principle: "p" },+ "Refers to [[pref-popular]].",+ );+ writePref(+ "pref-b",+ { kind: "preference", topic: "b", status: "confirmed", principle: "p" },+ "Also [[pref-popular]].",+ );writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });@@ -117,7 +124,11 @@ describe("auditMoc - bucket classification", () => {});test("fragile: cluster member with only one backlink and short body", () => {- writePref("pref-thin", { kind: "preference", topic: "t", status: "confirmed", principle: "p" }, "short");+ writePref(+ "pref-thin",+ { kind: "preference", topic: "t", status: "confirmed", principle: "p" },+ "short",+ );writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" });writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" });writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });@@ -152,8 +163,16 @@ describe("auditMoc - bucket classification", () => {test("suggested-next: highest-leverage candidate-missing (most mentions across cluster)", () => {// pref-popular-missing referenced from hub + 2 cluster members.// pref-rare-missing referenced from hub only.- writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" }, "see [[pref-popular-missing]]");- writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" }, "again [[pref-popular-missing]]");+ writePref(+ "pref-a",+ { kind: "preference", topic: "a", status: "confirmed", principle: "p" },+ "see [[pref-popular-missing]]",+ );+ writePref(+ "pref-b",+ { kind: "preference", topic: "b", status: "confirmed", principle: "p" },+ "again [[pref-popular-missing]]",+ );writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });diff --git a/tests/core/brain/link-graph/unlinked-mentions.test.ts b/tests/core/brain/link-graph/unlinked-mentions.test.tsindex 7e40e842..078ffafc 100644--- a/tests/core/brain/link-graph/unlinked-mentions.test.ts+++ b/tests/core/brain/link-graph/unlinked-mentions.test.ts@@ -8,12 +8,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- 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/core/brain/lint-consolidate.test.ts b/tests/core/brain/lint-consolidate.test.tsindex 6553a784..c20ae575 100644--- a/tests/core/brain/lint-consolidate.test.ts+++ b/tests/core/brain/lint-consolidate.test.ts@@ -1,11 +1,5 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- readFileSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -27,20 +21,14 @@ function writePref(slug: string, fields: Record<string, string>) {const lines = ["---", `id: pref-${slug}`];for (const [k, v] of Object.entries(fields)) lines.push(`${k}: ${v}`);lines.push("---", "");- writeFileSync(- join(vault, "Brain", "preferences", `pref-${slug}.md`),- lines.join("\n"),- );+ writeFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`), lines.join("\n"));}describe("lintConsolidate — fix-merged-link", () => {test("rewrites wikilinks pointing at a secondary", () => {writePref("canon", { topic: "x", principle: "y" });writePref("dup", { topic: "x", principle: "y", merged_into: "pref-canon" });- writeFileSync(- join(vault, "Brain", "log", "2026-05-25.md"),- "saw [[pref-dup]] today\n",- );+ writeFileSync(join(vault, "Brain", "log", "2026-05-25.md"), "saw [[pref-dup]] today\n");const dry = lintConsolidate(vault, { apply: false });expect(dry.fixes.length).toBe(1);@@ -48,16 +36,16 @@ describe("lintConsolidate — fix-merged-link", () => {expect(dry.fixes[0]!.to).toBe("pref-canon");expect(dry.applied).toBe(false);// dry-run does not write- expect(- readFileSync(join(vault, "Brain", "log", "2026-05-25.md"), "utf8"),- ).toContain("[[pref-dup]]");+ expect(readFileSync(join(vault, "Brain", "log", "2026-05-25.md"), "utf8")).toContain(+ "[[pref-dup]]",+ );const apply = lintConsolidate(vault, { apply: true });expect(apply.applied).toBe(true);expect(apply.filesWritten).toBeGreaterThan(0);- expect(- readFileSync(join(vault, "Brain", "log", "2026-05-25.md"), "utf8"),- ).toContain("[[pref-canon]]");+ expect(readFileSync(join(vault, "Brain", "log", "2026-05-25.md"), "utf8")).toContain(+ "[[pref-canon]]",+ );});test("preserves wikilink aliases and anchors when rewriting", () => {@@ -68,10 +56,7 @@ describe("lintConsolidate — fix-merged-link", () => {"[[pref-dup|the rule]] and [[pref-dup#section]]\n",);lintConsolidate(vault, { apply: true });- const content = readFileSync(- join(vault, "Brain", "log", "2026-05-25.md"),- "utf8",- );+ const content = readFileSync(join(vault, "Brain", "log", "2026-05-25.md"), "utf8");expect(content).toContain("[[pref-canon|the rule]]");expect(content).toContain("[[pref-canon#section]]");});@@ -85,10 +70,7 @@ describe("lintConsolidate — fix-merged-link", () => {);const report = lintConsolidate(vault, { apply: true });expect(report.fixes.length).toBe(1);- const content = readFileSync(- join(vault, "Brain", "log", "2026-05-25.md"),- "utf8",- );+ const content = readFileSync(join(vault, "Brain", "log", "2026-05-25.md"), "utf8");expect(content).toContain("[[pref-canon]]");expect(content).toContain("[[pref-dup-extra]]");expect(content).toContain("[[pref-duplicate]]");@@ -143,10 +125,7 @@ describe("lintConsolidate — demote-stale-stable", () => {apply: true,now: new Date("2026-05-25T00:00:00Z"),});- const yaml = readFileSync(- join(vault, "Brain", "preferences", "pref-old.md"),- "utf8",- );+ const yaml = readFileSync(join(vault, "Brain", "preferences", "pref-old.md"), "utf8");expect(yaml).toContain("_lifecycle: draft");expect(yaml).not.toContain("_lifecycle: stable");});diff --git a/tests/core/brain/manifest.test.ts b/tests/core/brain/manifest.test.tsindex 0177c063..66e75ad7 100644--- a/tests/core/brain/manifest.test.ts+++ b/tests/core/brain/manifest.test.ts@@ -13,13 +13,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- rmSync,- symlinkSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -65,10 +59,7 @@ describe("buildManifest", () => {writeFileSync(join(brain, "preferences", "pref-b.md"), "beta\n");writeFileSync(join(brain, "preferences", "pref-a.md"), "alpha\n");const m = buildManifest(brain);- expect(Object.keys(m.files)).toEqual([- "preferences/pref-a.md",- "preferences/pref-b.md",- ]);+ expect(Object.keys(m.files)).toEqual(["preferences/pref-a.md", "preferences/pref-b.md"]);expect(m.files["preferences/pref-a.md"]!.size).toBe(6);expect(m.files["preferences/pref-a.md"]!.sha256).toMatch(/^[0-9a-f]{64}$/);// sha256("alpha\n") == "31c0c4dee7f8eeeb27ff4f64ff5a7a9d97a6b6f49ad22082f6c12f9f0c5b9d27" → guard via length only.@@ -108,15 +99,13 @@ describe("buildManifest", () => {writeFileSync(join(brain, "_brain.yaml"), "schema_version: 1\n");writeFileSync(join(brain, "_BRAIN.md"), "# manual\n");const m = buildManifest(brain);- expect(Object.keys(m.files).sort()).toEqual(["_BRAIN.md", "_brain.yaml"]);+ expect(Object.keys(m.files).toSorted()).toEqual(["_BRAIN.md", "_brain.yaml"]);});});describe("diffManifests", () => {- function fakeManifest(- files: Record<string, { sha: string; size: number }>,- ): BrainManifest {- const sortedKeys = Object.keys(files).sort();+ function fakeManifest(files: Record<string, { sha: string; size: number }>): BrainManifest {+ const sortedKeys = Object.keys(files).toSorted();const out: Record<string, { readonly sha256: string; readonly size: number }> = {};for (const k of sortedKeys) {out[k] = Object.freeze({ sha256: files[k]!.sha, size: files[k]!.size });@@ -192,9 +181,7 @@ describe("diffManifests", () => {describe("sidecar I/O", () => {test("manifestSidecarPath lands inside Brain/.snapshots/", () => {- expect(manifestSidecarPath(vault, "abc")).toBe(- join(brain, ".snapshots", "abc.manifest.json"),- );+ expect(manifestSidecarPath(vault, "abc")).toBe(join(brain, ".snapshots", "abc.manifest.json"));});test("read of missing path → null (no throw)", () => {diff --git a/tests/core/brain/merge-candidates.test.ts b/tests/core/brain/merge-candidates.test.tsindex 8a450d3f..1cc98ae3 100644--- a/tests/core/brain/merge-candidates.test.ts+++ b/tests/core/brain/merge-candidates.test.ts@@ -16,10 +16,7 @@ import {MERGE_SUGGESTION_LIMIT,} from "../../../src/core/brain/merge-candidates.ts";import { writePreference } from "../../../src/core/brain/preference.ts";-import {- BRAIN_CONFIDENCE,- BRAIN_PREFERENCE_STATUS,-} from "../../../src/core/brain/types.ts";+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";let vault: string;@@ -54,8 +51,7 @@ function makePref(opts: MakePrefOpts): void {unconfirmed_until: "2026-05-08T00:00:00Z",status,evidenced_by: [`[[sig-2026-05-01-${opts.slug}]]`],- confirmed_at:- status === BRAIN_PREFERENCE_STATUS.unconfirmed ? null : "2026-05-02T00:00:00Z",+ confirmed_at: status === BRAIN_PREFERENCE_STATUS.unconfirmed ? null : "2026-05-02T00:00:00Z",applied_count: 1,violated_count: 0,last_evidence_at: "2026-05-02T00:00:00Z",@@ -85,9 +81,7 @@ describe("findMergeCandidates", () => {expect(out.length).toBe(1);expect(out[0]!.topic).toBe("commits");expect(out[0]!.scope).toBeNull();- expect(out[0]!.jaccard).toBeGreaterThanOrEqual(- JACCARD_MERGE_SUGGEST_THRESHOLD,- );+ expect(out[0]!.jaccard).toBeGreaterThanOrEqual(JACCARD_MERGE_SUGGEST_THRESHOLD);// Ids stored as lexicographically smaller / larger.expect(out[0]!.a < out[0]!.b).toBe(true);});diff --git a/tests/core/brain/merge.test.ts b/tests/core/brain/merge.test.tsindex 10869c72..46e8ff11 100644--- a/tests/core/brain/merge.test.ts+++ b/tests/core/brain/merge.test.ts@@ -9,22 +9,13 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- existsSync,- mkdirSync,- mkdtempSync,- readFileSync,- rmSync,-} from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { regenerateActiveQuiet } from "../../../src/core/brain/active.ts";import { parseLogDay } from "../../../src/core/brain/log.ts";-import {- BrainMergeError,- mergePreferences,-} from "../../../src/core/brain/merge.ts";+import { BrainMergeError, mergePreferences } from "../../../src/core/brain/merge.ts";import {parsePreference,parseRetired,@@ -77,9 +68,9 @@ function basePref(describe("mergePreferences — guards", () => {test("rejects when keep id equals drop id", () => {writePreference(vault, basePref("a"));- expect(() =>- mergePreferences(vault, "pref-a", "pref-a", { now: NOW }),- ).toThrow(BrainMergeError);+ expect(() => mergePreferences(vault, "pref-a", "pref-a", { now: NOW })).toThrow(+ BrainMergeError,+ );});test("rejects when keep is missing", () => {@@ -161,9 +152,7 @@ describe("mergePreferences — guards", () => {test("accepts when both are pinned", () => {writePreference(vault, basePref("a", { pinned: true }));writePreference(vault, basePref("b", { pinned: true }));- expect(() =>- mergePreferences(vault, "pref-a", "pref-b", { now: NOW }),- ).not.toThrow();+ expect(() => mergePreferences(vault, "pref-a", "pref-b", { now: NOW })).not.toThrow();});});@@ -235,9 +224,7 @@ describe("mergePreferences — happy path", () => {// summary counters.const day = NOW.toISOString().slice(0, 10);const { entries } = parseLogDay(vault, day);- const merges = entries.filter(- (e) => e.eventType === BRAIN_LOG_EVENT_KIND.merge,- );+ const merges = entries.filter((e) => e.eventType === BRAIN_LOG_EVENT_KIND.merge);expect(merges.length).toBe(1);const body = merges[0]!.body;expect(String(body["keep"])).toContain("pref-keep");@@ -254,34 +241,23 @@ describe("mergePreferences — happy path", () => {test("dryRun returns plan but writes nothing", () => {writePreference(vault, basePref("keep"));writePreference(vault, basePref("drop"));- const before = readFileSync(- join(vault, "Brain", "preferences", "pref-keep.md"),- "utf8",- );+ const before = readFileSync(join(vault, "Brain", "preferences", "pref-keep.md"), "utf8");const plan = mergePreferences(vault, "pref-keep", "pref-drop", {now: NOW,dryRun: true,});expect(plan.applied_sum).toBe(2);// Disk unchanged.- expect(- readFileSync(join(vault, "Brain", "preferences", "pref-keep.md"), "utf8"),- ).toBe(before);- expect(- existsSync(join(vault, "Brain", "preferences", "pref-drop.md")),- ).toBe(true);- expect(- existsSync(join(vault, "Brain", "retired", "ret-drop.md")),- ).toBe(false);+ expect(readFileSync(join(vault, "Brain", "preferences", "pref-keep.md"), "utf8")).toBe(before);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-drop.md"))).toBe(true);+ expect(existsSync(join(vault, "Brain", "retired", "ret-drop.md"))).toBe(false);});test("preserves keep.pinned across merge", () => {writePreference(vault, basePref("keep", { pinned: true }));writePreference(vault, basePref("drop", { pinned: true }));mergePreferences(vault, "pref-keep", "pref-drop", { now: NOW });- const keep = parsePreference(- join(vault, "Brain", "preferences", "pref-keep.md"),- );+ const keep = parsePreference(join(vault, "Brain", "preferences", "pref-keep.md"));expect(keep.pinned).toBe(true);});});diff --git a/tests/core/brain/most-applied.test.ts b/tests/core/brain/most-applied.test.tsindex 01de561e..cfa3699f 100644--- a/tests/core/brain/most-applied.test.ts+++ b/tests/core/brain/most-applied.test.ts@@ -26,10 +26,7 @@ import {* placeholders so the value satisfies the interface without dragging* unrelated test-shape concerns into this file.*/-function buildPref(- id: string,- overrides: Partial<BrainPreference> = {},-): BrainPreference {+function buildPref(id: string, overrides: Partial<BrainPreference> = {}): BrainPreference {const base: BrainPreference = {kind: "brain-preference",id,@@ -147,11 +144,7 @@ describe("computeMostApplied", () => {[buildPref("pref-a"), buildPref("pref-b"), buildPref("pref-c")],{ now },);- expect(result.map((r) => r.preference.id)).toEqual([- "pref-a",- "pref-b",- "pref-c",- ]);+ expect(result.map((r) => r.preference.id)).toEqual(["pref-a", "pref-b", "pref-c"]);expect(result[0]!.applied_30d).toBe(2);});@@ -174,11 +167,7 @@ describe("computeMostApplied", () => {// bare id before the count lookup. Same shape `normaliseWikilinkTarget`// already strips on the read side.const now = new Date("2026-05-20T00:00:00Z");- seedApplied(- vault,- "2026-05-15T10:00:00Z",- "[[pref-a|principle title with spaces]]",- );+ seedApplied(vault, "2026-05-15T10:00:00Z", "[[pref-a|principle title with spaces]]");const result = computeMostApplied(vault, [buildPref("pref-a")], { now });expect(result.length).toBe(1);expect(result[0]!.applied_30d).toBe(1);@@ -225,7 +214,7 @@ describe("computeMostApplied", () => {test("windowDays: 365 includes events from one year ago", () => {const now = new Date("2026-05-20T00:00:00Z");- seedApplied(vault, "2025-06-01T00:00:00Z", "[[pref-a]]"); // ~354 days ago+ seedApplied(vault, "2025-06-01T00:00:00Z", "[[pref-a]]"); // ~354 days agoconst result = computeMostApplied(vault, [buildPref("pref-a")], { now, windowDays: 365 });expect(result.length).toBe(1);});@@ -247,8 +236,8 @@ describe("computeMostApplied", () => {test("default windowDays still 30 when option omitted", () => {const now = new Date("2026-05-20T00:00:00Z");- seedApplied(vault, "2026-05-15T00:00:00Z", "[[pref-a]]"); // 5d ago- seedApplied(vault, "2026-04-10T00:00:00Z", "[[pref-a]]"); // 40d ago — excluded+ seedApplied(vault, "2026-05-15T00:00:00Z", "[[pref-a]]"); // 5d ago+ seedApplied(vault, "2026-04-10T00:00:00Z", "[[pref-a]]"); // 40d ago — excludedconst result = computeMostApplied(vault, [buildPref("pref-a")], { now });expect(result[0]!.applied_30d).toBe(1);});diff --git a/tests/core/brain/note.test.ts b/tests/core/brain/note.test.tsindex a8901caa..afe7914a 100644--- a/tests/core/brain/note.test.ts+++ b/tests/core/brain/note.test.ts@@ -70,9 +70,9 @@ describe("appendBrainNote", () => {});test("rejects whitespace-only text", () => {- expect(() =>- appendBrainNote({ vault, text: " ", agent: "tester", now: new Date() }),- ).toThrow(/text is required/);+ expect(() => appendBrainNote({ vault, text: " ", agent: "tester", now: new Date() })).toThrow(+ /text is required/,+ );});test("rejects text that becomes empty after sanitising", () => {diff --git a/tests/core/brain/notes-config.test.ts b/tests/core/brain/notes-config.test.tsindex 6fd4cdbd..026e64fe 100644--- a/tests/core/brain/notes-config.test.ts+++ b/tests/core/brain/notes-config.test.ts@@ -44,9 +44,7 @@ describe("notes config block", () => {});test("present with a single read_path", () => {- const { config } = validate(- HEAD + `notes:\n read_paths:\n - Daily\n`,- );+ const { config } = validate(HEAD + `notes:\n read_paths:\n - Daily\n`);expect(config.notes).toEqual({ read_paths: ["Daily"] });expect(resolveNotes(config).read_paths).toEqual(["Daily"]);});@@ -60,11 +58,7 @@ describe("notes config block", () => {` - Journal/Weekly\n` +` - Notes\n`,);- expect(resolveNotes(config).read_paths).toEqual([- "Daily",- "Journal/Weekly",- "Notes",- ]);+ expect(resolveNotes(config).read_paths).toEqual(["Daily", "Journal/Weekly", "Notes"]);});test("explicit empty array preserves the empty-list intent", () => {@@ -74,65 +68,48 @@ describe("notes config block", () => {});test("rejects non-mapping notes", () => {- expect(() => validate(HEAD + `notes: Daily\n`)).toThrow(- BrainConfigError,- );+ expect(() => validate(HEAD + `notes: Daily\n`)).toThrow(BrainConfigError);});test("rejects non-array read_paths", () => {- expect(() =>- validate(HEAD + `notes:\n read_paths: Daily\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `notes:\n read_paths: Daily\n`)).toThrow(BrainConfigError);});test("rejects non-string entries", () => {- expect(() =>- validate(HEAD + `notes:\n read_paths:\n - 42\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `notes:\n read_paths:\n - 42\n`)).toThrow(BrainConfigError);});test("rejects empty / whitespace-only string entries", () => {- expect(() =>- validate(HEAD + `notes:\n read_paths:\n - ""\n`),- ).toThrow(BrainConfigError);- expect(() =>- validate(HEAD + `notes:\n read_paths:\n - " "\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `notes:\n read_paths:\n - ""\n`)).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `notes:\n read_paths:\n - " "\n`)).toThrow(BrainConfigError);});test("rejects absolute paths", () => {- expect(() =>- validate(HEAD + `notes:\n read_paths:\n - /etc/daily\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `notes:\n read_paths:\n - /etc/daily\n`)).toThrow(+ BrainConfigError,+ );});test("rejects parent-traversal", () => {- expect(() =>- validate(HEAD + `notes:\n read_paths:\n - ../escape\n`),- ).toThrow(BrainConfigError);- expect(() =>- validate(HEAD + `notes:\n read_paths:\n - Daily/../etc\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `notes:\n read_paths:\n - ../escape\n`)).toThrow(+ BrainConfigError,+ );+ expect(() => validate(HEAD + `notes:\n read_paths:\n - Daily/../etc\n`)).toThrow(+ BrainConfigError,+ );});test("trims surrounding whitespace on each entry", () => {- const { config } = validate(- HEAD + `notes:\n read_paths:\n - " Daily "\n`,- );+ const { config } = validate(HEAD + `notes:\n read_paths:\n - " Daily "\n`);expect(resolveNotes(config).read_paths).toEqual(["Daily"]);});test("unknown sub-keys emit a forward-compat warning, not an error", () => {const { config, warnings } = validate(- HEAD +- `notes:\n` +- ` read_paths:\n - Daily\n` +- ` future_field: hello\n`,+ HEAD + `notes:\n` + ` read_paths:\n - Daily\n` + ` future_field: hello\n`,);expect(config.notes).toEqual({ read_paths: ["Daily"] });- expect(- warnings.some((w) => w.message.includes("notes.future_field")),- ).toBe(true);+ expect(warnings.some((w) => w.message.includes("notes.future_field"))).toBe(true);});test("resolveNotes returns frozen output", () => {diff --git a/tests/core/brain/page-dedup.test.ts b/tests/core/brain/page-dedup.test.tsindex 79dbdcf0..fdbbbd8b 100644--- a/tests/core/brain/page-dedup.test.ts+++ b/tests/core/brain/page-dedup.test.ts@@ -1,11 +1,5 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- readFileSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -32,7 +26,12 @@ function writePref(fields: { topic: string; principle: string; created_at?: string; merged_into?: string },): string {const path = join(vault, "Brain", "preferences", `pref-${slug}.md`);- const lines = ["---", `id: pref-${slug}`, `topic: ${fields.topic}`, `principle: ${fields.principle}`];+ const lines = [+ "---",+ `id: pref-${slug}`,+ `topic: ${fields.topic}`,+ `principle: ${fields.principle}`,+ ];if (fields.created_at) lines.push(`created_at: ${fields.created_at}`);if (fields.merged_into) lines.push(`merged_into: ${fields.merged_into}`);lines.push("---", "");@@ -91,10 +90,7 @@ describe("findDuplicateCandidates", () => {writePref("c", { topic: "x", principle: "alpha" });const report = findDuplicateCandidates(vault);expect(report.candidates.length).toBe(1);- expect(report.candidates[0]!.pages.map((p) => p.id).sort()).toEqual([- "pref-a",- "pref-c",- ]);+ expect(report.candidates[0]!.pages.map((p) => p.id).toSorted()).toEqual(["pref-a", "pref-c"]);});});@@ -109,10 +105,7 @@ describe("patchWikilinks", () => {test("rewrites aliased and anchored wikilinks", () => {const log = join(vault, "Brain", "log", "2026-05-25.md");- writeFileSync(- log,- "[[pref-old|the rule]] and [[pref-old#section]] and [[pref-old]]\n",- );+ writeFileSync(log, "[[pref-old|the rule]] and [[pref-old#section]] and [[pref-old]]\n");const touched = patchWikilinks(vault, "pref-old", "pref-new");expect(touched).toBe(1);const content = readFileSync(log, "utf8");@@ -143,10 +136,7 @@ describe("patchWikilinks", () => {// the patcher's regex defends this; pin it explicitly so a// future regex rewrite cannot regress the case.const log = join(vault, "Brain", "log", "2026-05-25.md");- writeFileSync(- log,- "matches [[pref-old]] and skips [[pref-old-extra]] and [[pref-older]]\n",- );+ writeFileSync(log, "matches [[pref-old]] and skips [[pref-old-extra]] and [[pref-older]]\n");const touched = patchWikilinks(vault, "pref-old", "pref-new");expect(touched).toBe(1);const content = readFileSync(log, "utf8");diff --git a/tests/core/brain/page-meta/confidence.test.ts b/tests/core/brain/page-meta/confidence.test.tsindex 56397e46..d8d8fdd5 100644--- a/tests/core/brain/page-meta/confidence.test.ts+++ b/tests/core/brain/page-meta/confidence.test.ts@@ -37,8 +37,6 @@ describe("readConfidence", () => {});test("modern shape wins over legacy", () => {- expect(readConfidence({ _confidence: "high", confidence: "low" })).toBe(- "high",- );+ expect(readConfidence({ _confidence: "high", confidence: "low" })).toBe("high");});});diff --git a/tests/core/brain/page-meta/lifecycle.test.ts b/tests/core/brain/page-meta/lifecycle.test.tsindex ed2db53b..a8196b81 100644--- a/tests/core/brain/page-meta/lifecycle.test.ts+++ b/tests/core/brain/page-meta/lifecycle.test.ts@@ -11,7 +11,7 @@ import {describe("PAGE_LIFECYCLE", () => {test("enumerates exactly the six documented values", () => {- expect(Object.values(PAGE_LIFECYCLE).sort()).toEqual([+ expect(Object.values(PAGE_LIFECYCLE).toSorted()).toEqual(["archived","deprecated","disputed",@@ -56,9 +56,7 @@ describe("readLifecycle", () => {});test("modern shape wins over legacy", () => {- expect(- readLifecycle({ _lifecycle: "verified", lifecycle: "draft" }),- ).toBe("verified");+ expect(readLifecycle({ _lifecycle: "verified", lifecycle: "draft" })).toBe("verified");});});diff --git a/tests/core/brain/page-meta/page-id.test.ts b/tests/core/brain/page-meta/page-id.test.tsindex 5a4ca901..8ab1857f 100644--- a/tests/core/brain/page-meta/page-id.test.ts+++ b/tests/core/brain/page-meta/page-id.test.ts@@ -96,7 +96,9 @@ describe("resolveCanonicalId", () => {const target = i + 1 < n ? `pref-p${i + 1}` : undefined;writePref(`p${i}`,- target ? { topic: "x", principle: "y", merged_into: target } : { topic: "x", principle: "y" },+ target+ ? { topic: "x", principle: "y", merged_into: target }+ : { topic: "x", principle: "y" },);}try {diff --git a/tests/core/brain/page-meta/tier.test.ts b/tests/core/brain/page-meta/tier.test.tsindex 629927f7..f30b2be0 100644--- a/tests/core/brain/page-meta/tier.test.ts+++ b/tests/core/brain/page-meta/tier.test.ts@@ -10,11 +10,7 @@ import {describe("PAGE_TIER", () => {test("exposes exactly three tiers", () => {- expect(Object.values(PAGE_TIER).sort()).toEqual([- "core",- "peripheral",- "supporting",- ]);+ expect(Object.values(PAGE_TIER).toSorted()).toEqual(["core", "peripheral", "supporting"]);});test("default is supporting", () => {diff --git a/tests/core/brain/policy-active.test.ts b/tests/core/brain/policy-active.test.tsindex d8663eaa..7caa8af7 100644--- a/tests/core/brain/policy-active.test.ts+++ b/tests/core/brain/policy-active.test.ts@@ -23,10 +23,7 @@ describe("active.most_applied_* config block", () => {test("present with values → loaded into BrainMostAppliedConfig", () => {const { config } = validate(- HEAD +- `active:\n` +- ` most_applied_window_days: 7\n` +- ` most_applied_limit: 3\n`,+ HEAD + `active:\n` + ` most_applied_window_days: 7\n` + ` most_applied_limit: 3\n`,);expect(config.active?.most_applied?.window_days).toBe(7);expect(config.active?.most_applied?.limit).toBe(3);@@ -40,64 +37,48 @@ describe("active.most_applied_* config block", () => {test("window_days: 0 rejected", () => {expect(() =>- validate(- HEAD + `active:\n most_applied_window_days: 0\n most_applied_limit: 5\n`,- ),+ validate(HEAD + `active:\n most_applied_window_days: 0\n most_applied_limit: 5\n`),).toThrow(BrainConfigError);});test("window_days: 366 rejected", () => {expect(() =>- validate(- HEAD + `active:\n most_applied_window_days: 366\n most_applied_limit: 5\n`,- ),+ validate(HEAD + `active:\n most_applied_window_days: 366\n most_applied_limit: 5\n`),).toThrow(BrainConfigError);});test("limit: 0 rejected", () => {expect(() =>- validate(- HEAD + `active:\n most_applied_window_days: 30\n most_applied_limit: 0\n`,- ),+ validate(HEAD + `active:\n most_applied_window_days: 30\n most_applied_limit: 0\n`),).toThrow(BrainConfigError);});test("limit: 51 rejected", () => {expect(() =>- validate(- HEAD + `active:\n most_applied_window_days: 30\n most_applied_limit: 51\n`,- ),+ validate(HEAD + `active:\n most_applied_window_days: 30\n most_applied_limit: 51\n`),).toThrow(BrainConfigError);});test("non-integer window_days rejected", () => {expect(() =>- validate(- HEAD + `active:\n most_applied_window_days: 30.5\n most_applied_limit: 10\n`,- ),+ validate(HEAD + `active:\n most_applied_window_days: 30.5\n most_applied_limit: 10\n`),).toThrow(BrainConfigError);});test("string window_days rejected", () => {- expect(() =>- validate(- HEAD + `active:\n most_applied_window_days: "thirty"\n`,- ),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `active:\n most_applied_window_days: "thirty"\n`)).toThrow(+ BrainConfigError,+ );});test("only window_days set → limit defaults to 10", () => {- const { config } = validate(- HEAD + `active:\n most_applied_window_days: 14\n`,- );+ const { config } = validate(HEAD + `active:\n most_applied_window_days: 14\n`);expect(config.active?.most_applied?.window_days).toBe(14);expect(config.active?.most_applied?.limit).toBe(10);});test("only limit set → window_days defaults to 30", () => {- const { config } = validate(- HEAD + `active:\n most_applied_limit: 3\n`,- );+ const { config } = validate(HEAD + `active:\n most_applied_limit: 3\n`);expect(config.active?.most_applied?.window_days).toBe(30);expect(config.active?.most_applied?.limit).toBe(3);});diff --git a/tests/core/brain/policy-discipline.test.ts b/tests/core/brain/policy-discipline.test.tsindex 4f10a4e6..b12bd05a 100644--- a/tests/core/brain/policy-discipline.test.ts+++ b/tests/core/brain/policy-discipline.test.ts@@ -23,13 +23,13 @@ describe("discipline_report config", () => {test("populated section is parsed verbatim", () => {const v = vaultWith("schema_version: 1\n" +- "discipline_report:\n" +- " enabled: true\n" +- " timezone: Europe/Belgrade\n" +- " watched_paths:\n" +- " - /srv/projects/foo\n" +- " known_agents:\n" +- " - '@claude-vps-agent'\n",+ "discipline_report:\n" ++ " enabled: true\n" ++ " timezone: Europe/Belgrade\n" ++ " watched_paths:\n" ++ " - /srv/projects/foo\n" ++ " known_agents:\n" ++ " - '@claude-vps-agent'\n",);const cfg = loadBrainConfig(v);expect(cfg.discipline_report).toEqual({diff --git a/tests/core/brain/policy-guardrails.test.ts b/tests/core/brain/policy-guardrails.test.tsindex df04faa9..84b24878 100644--- a/tests/core/brain/policy-guardrails.test.ts+++ b/tests/core/brain/policy-guardrails.test.ts@@ -54,9 +54,7 @@ describe("guardrails config block", () => {});test("partial block → missing fields fall back to defaults via resolveGuardrails", () => {- const { config } = validate(- HEAD + `guardrails:\n promotion_min_signals: 5\n`,- );+ const { config } = validate(HEAD + `guardrails:\n promotion_min_signals: 5\n`);expect(config.guardrails?.promotion_min_signals).toBe(5);const resolved = resolveGuardrails(config);expect(resolved.promotion_min_signals).toBe(5);@@ -69,67 +67,59 @@ describe("guardrails config block", () => {});test("promotion_min_signals: 0 rejected", () => {- expect(() =>- validate(HEAD + `guardrails:\n promotion_min_signals: 0\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `guardrails:\n promotion_min_signals: 0\n`)).toThrow(+ BrainConfigError,+ );});test("promotion_min_signals: negative rejected", () => {- expect(() =>- validate(HEAD + `guardrails:\n promotion_min_signals: -1\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `guardrails:\n promotion_min_signals: -1\n`)).toThrow(+ BrainConfigError,+ );});test("promotion_min_signals: non-integer rejected", () => {- expect(() =>- validate(HEAD + `guardrails:\n promotion_min_signals: 2.5\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `guardrails:\n promotion_min_signals: 2.5\n`)).toThrow(+ BrainConfigError,+ );});test("promotion_min_distinct_agents: 0 rejected", () => {- expect(() =>- validate(HEAD + `guardrails:\n promotion_min_distinct_agents: 0\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `guardrails:\n promotion_min_distinct_agents: 0\n`)).toThrow(+ BrainConfigError,+ );});test("promotion_min_age_days: 0 accepted (means disabled)", () => {- const { config } = validate(- HEAD + `guardrails:\n promotion_min_age_days: 0\n`,- );+ const { config } = validate(HEAD + `guardrails:\n promotion_min_age_days: 0\n`);expect(config.guardrails?.promotion_min_age_days).toBe(0);});test("promotion_min_age_days: negative rejected", () => {- expect(() =>- validate(HEAD + `guardrails:\n promotion_min_age_days: -1\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `guardrails:\n promotion_min_age_days: -1\n`)).toThrow(+ BrainConfigError,+ );});test("instruction_file_max_lines: 0 rejected", () => {- expect(() =>- validate(HEAD + `guardrails:\n instruction_file_max_lines: 0\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `guardrails:\n instruction_file_max_lines: 0\n`)).toThrow(+ BrainConfigError,+ );});test("instruction_file_max_lines: extreme upper bound 10000 accepted", () => {- const { config } = validate(- HEAD + `guardrails:\n instruction_file_max_lines: 10000\n`,- );+ const { config } = validate(HEAD + `guardrails:\n instruction_file_max_lines: 10000\n`);expect(config.guardrails?.instruction_file_max_lines).toBe(10000);});test("instruction_file_max_lines: above hard ceiling rejected", () => {- expect(() =>- validate(- HEAD + `guardrails:\n instruction_file_max_lines: 100000\n`,- ),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `guardrails:\n instruction_file_max_lines: 100000\n`)).toThrow(+ BrainConfigError,+ );});test("non-object guardrails block rejected", () => {- expect(() =>- validate(HEAD + `guardrails: "nope"\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `guardrails: "nope"\n`)).toThrow(BrainConfigError);});test("unknown sub-key warns but does not throw", () => {diff --git a/tests/core/brain/preference-collision.test.ts b/tests/core/brain/preference-collision.test.tsindex a5a91cac..286471cd 100644--- a/tests/core/brain/preference-collision.test.ts+++ b/tests/core/brain/preference-collision.test.ts@@ -11,10 +11,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { computeContentHash } from "../../../src/core/brain/content-hash.ts";-import {- brainDirs,- preferencePath,-} from "../../../src/core/brain/paths.ts";+import { brainDirs, preferencePath } from "../../../src/core/brain/paths.ts";import { writePreference } from "../../../src/core/brain/preference.ts";import {BRAIN_COLLISION_KIND,@@ -24,9 +21,7 @@ import {noUnsafeShrink,writePreferenceTxn,} from "../../../src/core/brain/preference-txn.ts";-import {- BRAIN_PREFERENCE_STATUS,-} from "../../../src/core/brain/types.ts";+import { BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";let vault: string;@@ -71,12 +66,9 @@ describe("expectRevision", () => {writePreferenceTxn(vault, baseInput({ revision: 5 }), [], {});let caught: unknown;try {- writePreferenceTxn(- vault,- baseInput({ revision: 6 }),- [expectRevision(2)],- { overwrite: true },- );+ writePreferenceTxn(vault, baseInput({ revision: 6 }), [expectRevision(2)], {+ overwrite: true,+ });} catch (err) {caught = err;}@@ -93,8 +85,7 @@ describe("expectRevision", () => {vault,baseInput({revision: 1,- principle:- "edited principle text after the no-revision baseline",+ principle: "edited principle text after the no-revision baseline",}),[expectRevision(0)],{ overwrite: true },@@ -112,9 +103,7 @@ describe("noUnsafeShrink", () => {[noUnsafeShrink(0.5)],{},);- expect(- require("node:fs").existsSync(preferencePath(vault, "fresh")),- ).toBe(true);+ expect(require("node:fs").existsSync(preferencePath(vault, "fresh"))).toBe(true);});test("passes when new principle is the same length or longer", () => {@@ -134,12 +123,9 @@ describe("noUnsafeShrink", () => {writePreferenceTxn(vault, baseInput({}), [], {});let caught: unknown;try {- writePreferenceTxn(- vault,- baseInput({ principle: "tiny" }),- [noUnsafeShrink(0.5)],- { overwrite: true },- );+ writePreferenceTxn(vault, baseInput({ principle: "tiny" }), [noUnsafeShrink(0.5)], {+ overwrite: true,+ });} catch (err) {caught = err;}@@ -151,12 +137,9 @@ describe("noUnsafeShrink", () => {const r = writePreferenceTxn(vault, baseInput({}), [], {});const before = readFileSync(r.path, "utf8");try {- writePreferenceTxn(- vault,- baseInput({ principle: "x" }),- [noUnsafeShrink(0.5)],- { overwrite: true },- );+ writePreferenceTxn(vault, baseInput({ principle: "x" }), [noUnsafeShrink(0.5)], {+ overwrite: true,+ });} catch {// expected}@@ -248,14 +231,9 @@ describe("noDuplicateWriteWithin", () => {describe("BRAIN_COLLISION_KIND completeness", () => {test("all four discriminants are covered by either lock acquire or an expectation factory", () => {// Sanity assertion - guards against silent renames of the kind table.- const expected = [- "DuplicateWrite",- "SourceLock",- "StaleUpdate",- "UnsafeShrink",- ] as const;- const actual = [...Object.values(BRAIN_COLLISION_KIND)].sort();- const expectedSorted = [...expected].sort();+ const expected = ["DuplicateWrite", "SourceLock", "StaleUpdate", "UnsafeShrink"] as const;+ const actual = Object.values(BRAIN_COLLISION_KIND).toSorted();+ const expectedSorted = [...expected].toSorted();expect(actual).toEqual(expectedSorted);});});diff --git a/tests/core/brain/preference-integrity-fields.test.ts b/tests/core/brain/preference-integrity-fields.test.tsindex d50c2b94..4d07a52b 100644--- a/tests/core/brain/preference-integrity-fields.test.ts+++ b/tests/core/brain/preference-integrity-fields.test.ts@@ -22,10 +22,7 @@ import {writePreference,type WritePreferenceInput,} from "../../../src/core/brain/preference.ts";-import {- BRAIN_CONFIDENCE,- BRAIN_PREFERENCE_STATUS,-} from "../../../src/core/brain/types.ts";+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";let vault: string;@@ -63,19 +60,13 @@ describe("writePreference - _revision emission", () => {});test("emits the supplied revision when caller provides one", () => {- const res = writePreference(- vault,- basePref("rev-supplied", { revision: 7 }),- );+ const res = writePreference(vault, basePref("rev-supplied", { revision: 7 }));const text = readFileSync(res.path, "utf8");expect(text).toContain("_revision: 7");});test("parsePreference reads _revision back as a number", () => {- const res = writePreference(- vault,- basePref("rev-roundtrip", { revision: 12 }),- );+ const res = writePreference(vault, basePref("rev-roundtrip", { revision: 12 }));const parsed = parsePreference(res.path);expect(parsed.revision).toBe(12);});diff --git a/tests/core/brain/preference-lifecycle.test.ts b/tests/core/brain/preference-lifecycle.test.tsindex 69206938..2647f586 100644--- a/tests/core/brain/preference-lifecycle.test.ts+++ b/tests/core/brain/preference-lifecycle.test.ts@@ -17,10 +17,7 @@ import {} from "../../../src/core/brain/preference.ts";import { readLifecycle } from "../../../src/core/brain/page-meta/lifecycle.ts";import { parseFrontmatter } from "../../../src/core/vault.ts";-import {- BRAIN_CONFIDENCE,- BRAIN_PREFERENCE_STATUS,-} from "../../../src/core/brain/types.ts";+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";let vault: string;@@ -90,16 +87,9 @@ describe("writePreference — _lifecycle emission", () => {});test("byte-identical second write when lifecycle is supplied both times", () => {- const res = writePreference(- vault,- basePref("idem-mod", { lifecycle: "verified" }),- );+ const res = writePreference(vault, basePref("idem-mod", { lifecycle: "verified" }));const first = readFileSync(res.path, "utf8");- writePreference(- vault,- basePref("idem-mod", { lifecycle: "verified" }),- { overwrite: true },- );+ writePreference(vault, basePref("idem-mod", { lifecycle: "verified" }), { overwrite: true });const second = readFileSync(res.path, "utf8");expect(second).toBe(first);});diff --git a/tests/core/brain/preference-txn-history.test.ts b/tests/core/brain/preference-txn-history.test.tsindex 3ba5467e..ced3380c 100644--- a/tests/core/brain/preference-txn-history.test.ts+++ b/tests/core/brain/preference-txn-history.test.ts@@ -12,10 +12,7 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- brainDirs,- preferenceHistoryPath,-} from "../../../src/core/brain/paths.ts";+import { brainDirs, preferenceHistoryPath } from "../../../src/core/brain/paths.ts";import { writePreferenceTxn } from "../../../src/core/brain/preference-txn.ts";import { readEditHistory } from "../../../src/core/brain/health/edit-history.ts";import { BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";@@ -51,7 +48,7 @@ describe("writePreferenceTxn edit-history", () => {test("first write seeds the trail from current state", () => {writePreferenceTxn(vault, baseInput(), [], {}, history);const entries = readEditHistory(vault, "test-rule");- const fields = entries.map((e) => e.field).sort();+ const fields = entries.map((e) => e.field).toSorted();expect(fields).toEqual(["principle", "status"]);const principle = entries.find((e) => e.field === "principle")!;expect(principle.revision).toBe(1);diff --git a/tests/core/brain/preference-txn.test.ts b/tests/core/brain/preference-txn.test.tsindex 13800e60..fac8dea8 100644--- a/tests/core/brain/preference-txn.test.ts+++ b/tests/core/brain/preference-txn.test.ts@@ -10,10 +10,7 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- brainDirs,- preferencePath,-} from "../../../src/core/brain/paths.ts";+import { brainDirs, preferencePath } from "../../../src/core/brain/paths.ts";import { parsePreference } from "../../../src/core/brain/preference.ts";import {BrainCollisionError,@@ -62,10 +59,7 @@ describe("BRAIN_COLLISION_KIND", () => {describe("BrainCollisionError", () => {test("kind field is preserved on instances", () => {- const err = new BrainCollisionError(- BRAIN_COLLISION_KIND.staleUpdate,- "test message",- );+ const err = new BrainCollisionError(BRAIN_COLLISION_KIND.staleUpdate, "test message");expect(err).toBeInstanceOf(Error);expect(err.kind).toBe("StaleUpdate");expect(err.name).toBe("BrainCollisionError");@@ -112,10 +106,7 @@ describe("writePreferenceTxn", () => {};const fail: WritePreferenceExpectation = () => {calls.push("fail");- throw new BrainCollisionError(- BRAIN_COLLISION_KIND.staleUpdate,- "deliberate failure",- );+ throw new BrainCollisionError(BRAIN_COLLISION_KIND.staleUpdate, "deliberate failure");};const never: WritePreferenceExpectation = () => {calls.push("never");@@ -143,20 +134,14 @@ describe("writePreferenceTxn", () => {test("releases the lock even when an expectation throws", () => {writePreferenceTxn(vault, baseInput({ slug: "release-rule" }), [], {});const failingExpectation: WritePreferenceExpectation = () => {- throw new BrainCollisionError(- BRAIN_COLLISION_KIND.duplicateWrite,- "blocked",- );+ throw new BrainCollisionError(BRAIN_COLLISION_KIND.duplicateWrite, "blocked");};let caught: unknown;try {- writePreferenceTxn(- vault,- baseInput({ slug: "release-rule" }),- [failingExpectation],- { overwrite: true },- );+ writePreferenceTxn(vault, baseInput({ slug: "release-rule" }), [failingExpectation], {+ overwrite: true,+ });} catch (err) {caught = err;}@@ -167,12 +152,9 @@ describe("writePreferenceTxn", () => {expect(existsSync(lockPath)).toBe(false);// A follow-up write with empty expectations must succeed.- const ok = writePreferenceTxn(- vault,- baseInput({ slug: "release-rule" }),- [],- { overwrite: true },- );+ const ok = writePreferenceTxn(vault, baseInput({ slug: "release-rule" }), [], {+ overwrite: true,+ });expect(existsSync(ok.path)).toBe(true);});diff --git a/tests/core/brain/protect.test.ts b/tests/core/brain/protect.test.tsindex 8bf05d58..3ef102f4 100644--- a/tests/core/brain/protect.test.ts+++ b/tests/core/brain/protect.test.ts@@ -1,11 +1,5 @@import { afterEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- readFileSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -69,7 +63,7 @@ describe("buildProtectRules", () => {const rules = buildProtectRules("/v");const denyPaths = Array.from(new Set(rules.filter((r) => r.kind === "deny").map((r) => r.path)),- ).sort();+ ).toSorted();expect(denyPaths).toEqual(["/v/Brain/.snapshots/**","/v/Brain/_brain.yaml",@@ -84,22 +78,14 @@ describe("renderClaudeCode", () => {test("emits a snippet with deny + allow arrays and a manifest", () => {const rules = buildProtectRules("/vault");const out = renderClaudeCode(rules, "/vault");- expect(out.snippet.permissions.deny).toContain(- "Write(/vault/Brain/preferences/**)",- );- expect(out.snippet.permissions.deny).toContain(- "Edit(/vault/Brain/preferences/**)",- );- expect(out.snippet.permissions.allow).toEqual([- "Write(/vault/Brain/inbox/**)",- ]);+ expect(out.snippet.permissions.deny).toContain("Write(/vault/Brain/preferences/**)");+ expect(out.snippet.permissions.deny).toContain("Edit(/vault/Brain/preferences/**)");+ expect(out.snippet.permissions.allow).toEqual(["Write(/vault/Brain/inbox/**)"]);expect(out.manifest.schema_version).toBe(PROTECT_SCHEMA_VERSION);expect(out.manifest.target).toBe("claudecode");expect(out.manifest.vault).toBe("/vault");expect(out.manifest.owned_deny).toHaveLength(10);- expect(out.manifest.owned_allow).toEqual([- "Write(/vault/Brain/inbox/**)",- ]);+ expect(out.manifest.owned_allow).toEqual(["Write(/vault/Brain/inbox/**)"]);});});@@ -164,26 +150,16 @@ describe("applyProtect claudecode", () => {const vault = mkVault();const r = applyProtect({ target: "claudecode", vault });expect(r.changed).toBe(true);- const settings = JSON.parse(- readFileSync(join(vault, ".claude", "settings.json"), "utf8"),- );- expect(settings.permissions.deny).toContain(- `Write(${vault}/Brain/preferences/**)`,- );+ const settings = JSON.parse(readFileSync(join(vault, ".claude", "settings.json"), "utf8"));+ expect(settings.permissions.deny).toContain(`Write(${vault}/Brain/preferences/**)`);});test("idempotent: second apply produces byte-identical settings", () => {const vault = mkVault();applyProtect({ target: "claudecode", vault });- const first = readFileSync(- join(vault, ".claude", "settings.json"),- "utf8",- );+ const first = readFileSync(join(vault, ".claude", "settings.json"), "utf8");applyProtect({ target: "claudecode", vault });- const second = readFileSync(- join(vault, ".claude", "settings.json"),- "utf8",- );+ const second = readFileSync(join(vault, ".claude", "settings.json"), "utf8");expect(second).toBe(first);});@@ -192,27 +168,18 @@ describe("applyProtect claudecode", () => {mkdirSync(join(vault, ".claude"), { recursive: true });writeFileSync(join(vault, ".claude", "settings.json"),- JSON.stringify(- { permissions: { deny: ["Bash(rm -rf /)"], allow: [] } },- null,- 2,- ) + "\n",+ JSON.stringify({ permissions: { deny: ["Bash(rm -rf /)"], allow: [] } }, null, 2) + "\n",);applyProtect({ target: "claudecode", vault });- const settings = JSON.parse(- readFileSync(join(vault, ".claude", "settings.json"), "utf8"),- );+ const settings = JSON.parse(readFileSync(join(vault, ".claude", "settings.json"), "utf8"));expect(settings.permissions.deny).toContain("Bash(rm -rf /)");- expect(settings.permissions.deny).toContain(- `Write(${vault}/Brain/preferences/**)`,- );+ expect(settings.permissions.deny).toContain(`Write(${vault}/Brain/preferences/**)`);});test("apply against unbootstrapped vault throws", () => {const dir = mkdtempSync(join(tmpdir(), "osb-noinit-"));tmpRoots.push(dir);- expect(() => applyProtect({ target: "claudecode", vault: dir }))- .toThrow(BrainProtectError);+ expect(() => applyProtect({ target: "claudecode", vault: dir })).toThrow(BrainProtectError);});});@@ -220,20 +187,14 @@ describe("unprotect claudecode", () => {test("round-trip restores settings.json to pre-protect content", () => {const vault = mkVault();mkdirSync(join(vault, ".claude"), { recursive: true });- const userSettings = JSON.stringify(- { permissions: { deny: ["Bash(rm -rf /)"], allow: [] } },- null,- 2,- ) + "\n";+ const userSettings =+ JSON.stringify({ permissions: { deny: ["Bash(rm -rf /)"], allow: [] } }, null, 2) + "\n";writeFileSync(join(vault, ".claude", "settings.json"), userSettings);applyProtect({ target: "claudecode", vault });unprotect({ target: "claudecode", vault });- const after = readFileSync(- join(vault, ".claude", "settings.json"),- "utf8",- );+ const after = readFileSync(join(vault, ".claude", "settings.json"), "utf8");expect(after).toBe(userSettings);});@@ -249,10 +210,7 @@ describe("applyProtect codex", () => {const vault = mkVault();const r = applyProtect({ target: "codex", vault, __homeOverride: home });expect(r.changed).toBe(true);- const config = readFileSync(- join(home, ".codex", "config.toml"),- "utf8",- );+ const config = readFileSync(join(home, ".codex", "config.toml"), "utf8");expect(config).toContain("# >>> open-second-brain managed >>>");expect(config).toContain("[permissions.osb_protected.filesystem]");expect(config).toContain(`"${vault}/Brain/preferences/**" = "none"`);@@ -262,15 +220,9 @@ describe("applyProtect codex", () => {const home = mkHome();const vault = mkVault();applyProtect({ target: "codex", vault, __homeOverride: home });- const first = readFileSync(- join(home, ".codex", "config.toml"),- "utf8",- );+ const first = readFileSync(join(home, ".codex", "config.toml"), "utf8");applyProtect({ target: "codex", vault, __homeOverride: home });- const second = readFileSync(- join(home, ".codex", "config.toml"),- "utf8",- );+ const second = readFileSync(join(home, ".codex", "config.toml"), "utf8");expect(second).toBe(first);});@@ -281,10 +233,7 @@ describe("applyProtect codex", () => {const userToml = '# user content\nmodel = "gpt-5.5"\n';writeFileSync(join(home, ".codex", "config.toml"), userToml);applyProtect({ target: "codex", vault, __homeOverride: home });- const after = readFileSync(- join(home, ".codex", "config.toml"),- "utf8",- );+ const after = readFileSync(join(home, ".codex", "config.toml"), "utf8");expect(after.startsWith(userToml)).toBe(true);expect(after).toContain("# >>> open-second-brain managed >>>");});@@ -305,14 +254,13 @@ describe("applyProtect codex", () => {);applyProtect({ target: "codex", vault, __homeOverride: home });- const after = readFileSync(- join(home, ".codex", "config.toml"),- "utf8",+ const after = readFileSync(join(home, ".codex", "config.toml"), "utf8");+ expect(after.indexOf('default_permissions = "osb_protected"')).toBeLessThan(+ after.indexOf('[plugins."open-second-brain@open-second-brain"]'),+ );+ expect(after.indexOf("[permissions.osb_protected.filesystem]")).toBeLessThan(+ after.indexOf('[plugins."open-second-brain@open-second-brain"]'),);- expect(after.indexOf('default_permissions = "osb_protected"'))- .toBeLessThan(after.indexOf('[plugins."open-second-brain@open-second-brain"]'));- expect(after.indexOf("[permissions.osb_protected.filesystem]"))- .toBeLessThan(after.indexOf('[plugins."open-second-brain@open-second-brain"]'));});test("applying a second vault preserves the first vault's entries", () => {@@ -322,10 +270,7 @@ describe("applyProtect codex", () => {applyProtect({ target: "codex", vault: vaultA, __homeOverride: home });applyProtect({ target: "codex", vault: vaultB, __homeOverride: home });- const config = readFileSync(- join(home, ".codex", "config.toml"),- "utf8",- );+ const config = readFileSync(join(home, ".codex", "config.toml"), "utf8");expect(config).toContain(`"${vaultA}/Brain/preferences/**" = "none"`);expect(config).toContain(`"${vaultB}/Brain/preferences/**" = "none"`);});@@ -340,10 +285,7 @@ describe("unprotect codex", () => {writeFileSync(join(home, ".codex", "config.toml"), userToml);applyProtect({ target: "codex", vault, __homeOverride: home });unprotect({ target: "codex", vault, __homeOverride: home });- const after = readFileSync(- join(home, ".codex", "config.toml"),- "utf8",- );+ const after = readFileSync(join(home, ".codex", "config.toml"), "utf8");expect(after).toBe(userToml);});@@ -355,10 +297,7 @@ describe("unprotect codex", () => {applyProtect({ target: "codex", vault: vaultB, __homeOverride: home });unprotect({ target: "codex", vault: vaultA, __homeOverride: home });- const after = readFileSync(- join(home, ".codex", "config.toml"),- "utf8",- );+ const after = readFileSync(join(home, ".codex", "config.toml"), "utf8");expect(after).not.toContain(`${vaultA}/Brain/preferences/**`);expect(after).toContain(`${vaultB}/Brain/preferences/**`);expect(after).toContain("# >>> open-second-brain managed >>>");@@ -379,6 +318,6 @@ describe("printSnippet", () => {test("codex prints the fenced TOML block", () => {const out = printSnippet({ target: "codex", vault: "/v" });expect(out.body).toContain("# >>> open-second-brain managed >>>");- expect(out.body).toContain('[permissions.osb_protected.filesystem]');+ expect(out.body).toContain("[permissions.osb_protected.filesystem]");});});diff --git a/tests/core/brain/sign.test.ts b/tests/core/brain/sign.test.tsindex 4bad673f..2a311431 100644--- a/tests/core/brain/sign.test.ts+++ b/tests/core/brain/sign.test.ts@@ -62,9 +62,7 @@ describe("dominantSignOf", () => {});test("ignores wikilinks that do not resolve in the map", () => {- expect(dominantSignOf(["[[sig-c]]", "[[sig-missing]]"], byId)).toBe(- BRAIN_SIGNAL_SIGN.negative,- );+ expect(dominantSignOf(["[[sig-c]]", "[[sig-missing]]"], byId)).toBe(BRAIN_SIGNAL_SIGN.negative);});test("returns unknown when no cited signal resolves", () => {diff --git a/tests/core/brain/similarity.test.ts b/tests/core/brain/similarity.test.tsindex 82466166..090507a0 100644--- a/tests/core/brain/similarity.test.ts+++ b/tests/core/brain/similarity.test.ts@@ -12,9 +12,7 @@ import { jaccard, tokenise } from "../../../src/core/brain/similarity.ts";describe("tokenise", () => {test("lowercases and splits on punctuation", () => {- const tokens = tokenise(- "Use imperative voice; describe what the commit DOES",- );+ const tokens = tokenise("Use imperative voice; describe what the commit DOES");expect(tokens.has("use")).toBe(true);expect(tokens.has("imperative")).toBe(true);expect(tokens.has("does")).toBe(true);@@ -56,8 +54,6 @@ describe("jaccard", () => {});test("partial overlap → |intersection| / |union|", () => {- expect(- jaccard(new Set(["a", "b", "c"]), new Set(["b", "c", "d"])),- ).toBeCloseTo(2 / 4, 5);+ expect(jaccard(new Set(["a", "b", "c"]), new Set(["b", "c", "d"]))).toBeCloseTo(2 / 4, 5);});});diff --git a/tests/core/brain/starter.test.ts b/tests/core/brain/starter.test.tsindex 4b30aae2..a1af7f66 100644--- a/tests/core/brain/starter.test.ts+++ b/tests/core/brain/starter.test.ts@@ -1,11 +1,5 @@import { afterEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- readdirSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -34,8 +28,8 @@ function withRegisteredConfig(): { vault: string; config: string } {writeFileSync(config,[- 'kind: open-second-brain-config',- 'schema_version: 1',+ "kind: open-second-brain-config",+ "schema_version: 1",`vault: ${JSON.stringify(vault)}`,'agent_name: "starter-test-agent"',"",@@ -90,10 +84,7 @@ describe("copyStarterBundle", () => {for (const sub of ["preferences", "retired", "inbox", "log"]) {mkdirSync(join(vault, "Brain", sub), { recursive: true });}- writeFileSync(- join(vault, "Brain", "log", "2026-05-01.md"),- "---\ndate: 2026-05-01\n---\n",- );+ writeFileSync(join(vault, "Brain", "log", "2026-05-01.md"), "---\ndate: 2026-05-01\n---\n");expect(() => copyStarterBundle(vault)).toThrow(BrainStarterError);});@@ -113,9 +104,7 @@ describe("copyStarterBundle", () => {);const result = copyStarterBundle(vault, { starterPath: custom });expect(result.copied).toHaveLength(1);- expect(readdirSync(join(vault, "Brain", "preferences"))).toEqual([- "pref-x.md",- ]);+ expect(readdirSync(join(vault, "Brain", "preferences"))).toEqual(["pref-x.md"]);});test("rejects a starter path that does not exist", () => {@@ -140,11 +129,12 @@ describe("bootstrapBrain --starter", () => {});// 2 baseline file entries (_brain.yaml, _BRAIN.md) plus 18 from// the starter bundle.- const starterEntries = r.created.filter((p) =>- p.startsWith("Brain/preferences/")- || p.startsWith("Brain/retired/")- || p.startsWith("Brain/inbox/")- || p.startsWith("Brain/log/"),+ const starterEntries = r.created.filter(+ (p) =>+ p.startsWith("Brain/preferences/") ||+ p.startsWith("Brain/retired/") ||+ p.startsWith("Brain/inbox/") ||+ p.startsWith("Brain/log/"),);expect(starterEntries).toHaveLength(18);diff --git a/tests/core/brain/sync-lockfile.test.ts b/tests/core/brain/sync-lockfile.test.tsindex 9fa27f55..afb5f171 100644--- a/tests/core/brain/sync-lockfile.test.ts+++ b/tests/core/brain/sync-lockfile.test.ts@@ -10,10 +10,7 @@ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- acquireLockSync,- scanStaleLocks,-} from "../../../src/core/brain/sync-lockfile.ts";+import { acquireLockSync, scanStaleLocks } from "../../../src/core/brain/sync-lockfile.ts";let tmpRoot: string;@@ -103,7 +100,7 @@ describe("scanStaleLocks", () => {require("node:fs").mkdirSync(subDir, { recursive: true });writeFileSync(b + ".lock", "");- const found = scanStaleLocks(tmpRoot).sort();+ const found = scanStaleLocks(tmpRoot).toSorted();expect(found).toContain(a + ".lock");expect(found).toContain(b + ".lock");diff --git a/tests/core/brain/templates.test.ts b/tests/core/brain/templates.test.tsindex 7ae8ff76..ec05df30 100644--- a/tests/core/brain/templates.test.ts+++ b/tests/core/brain/templates.test.ts@@ -10,10 +10,7 @@import { describe, expect, test } from "bun:test";-import {- buildSubstitutions,- renderTemplate,-} from "../../../src/core/brain/templates.ts";+import { buildSubstitutions, renderTemplate } from "../../../src/core/brain/templates.ts";describe("renderTemplate", () => {test("replaces a single placeholder verbatim", () => {@@ -26,12 +23,9 @@ describe("renderTemplate", () => {["vault_name", "alpha"],["schema_version", "1"],]);- expect(- renderTemplate(- "vault {{vault_name}} schema {{schema_version}}",- subs,- ),- ).toBe("vault alpha schema 1");+ expect(renderTemplate("vault {{vault_name}} schema {{schema_version}}", subs)).toBe(+ "vault alpha schema 1",+ );});test("preserves literal $& / $1 in substitution values (regression: CR on PR #21)", () => {@@ -47,9 +41,7 @@ describe("renderTemplate", () => {];for (const [input, expected] of cases) {const subs = new Map([["vault_name", input]]);- expect(renderTemplate("name={{vault_name}}", subs)).toBe(- `name=${expected}`,- );+ expect(renderTemplate("name={{vault_name}}", subs)).toBe(`name=${expected}`);}});diff --git a/tests/core/brain/temporal/belief-evolution.test.ts b/tests/core/brain/temporal/belief-evolution.test.tsindex 25366205..d1c6dedc 100644--- a/tests/core/brain/temporal/belief-evolution.test.ts+++ b/tests/core/brain/temporal/belief-evolution.test.ts@@ -29,15 +29,9 @@ interface FixtureEvent {readonly body: Record<string, string | ReadonlyArray<string>>;}-function writeJsonl(- vault: string,- date: string,- events: ReadonlyArray<FixtureEvent>,-): void {+function writeJsonl(vault: string, date: string, events: ReadonlyArray<FixtureEvent>): void {const lines = events- .map((e) =>- JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),- )+ .map((e) => JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body })).join("\n");writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");}@@ -91,11 +85,7 @@ describe("buildBeliefEvolution by prefId", () => {]);const idx = buildTimelineIndex(VAULT, {});const evo = buildBeliefEvolution(idx, VAULT, { prefId: "pref-foo" });- expect(evo.transitions.map((t) => t.kind)).toEqual([- "creation",- "promotion",- "retirement",- ]);+ expect(evo.transitions.map((t) => t.kind)).toEqual(["creation", "promotion", "retirement"]);expect(evo.transitions[0]!.at).toBe("2026-05-01T08:00:00Z");expect(evo.transitions[2]!.at).toBe("2026-05-20T08:00:00Z");});@@ -172,7 +162,7 @@ describe("buildBeliefEvolution by prefId", () => {// once even though the supersedes-chain loops.const evo = buildBeliefEvolution(idx, VAULT, { prefId: "pref-a" });expect(evo.retirements.length).toBe(2);- const ids = evo.retirements.map((r) => r.prefId).sort();+ const ids = evo.retirements.map((r) => r.prefId).toSorted();expect(ids).toEqual(["ret-a", "ret-b"]);});diff --git a/tests/core/brain/temporal/bi-temporal-atoms.test.ts b/tests/core/brain/temporal/bi-temporal-atoms.test.tsindex 1f660074..ec992590 100644--- a/tests/core/brain/temporal/bi-temporal-atoms.test.ts+++ b/tests/core/brain/temporal/bi-temporal-atoms.test.ts@@ -17,14 +17,8 @@ import {parseBrainYaml,validateBrainConfigDetailed,} from "../../../../src/core/brain/policy.ts";-import {- BRAIN_TEMPORAL_DEFAULTS,- resolveTemporal,-} from "../../../../src/core/brain/policy.ts";-import type {- TemporalEvent,- TimelineIndex,-} from "../../../../src/core/brain/temporal/types.ts";+import { BRAIN_TEMPORAL_DEFAULTS, resolveTemporal } from "../../../../src/core/brain/policy.ts";+import type { TemporalEvent, TimelineIndex } from "../../../../src/core/brain/temporal/types.ts";function validate(yaml: string) {return validateBrainConfigDetailed(parseBrainYaml(yaml), "<test>");@@ -74,111 +68,78 @@ describe("temporal config block", () => {});test("partial block - missing fields fall back to defaults", () => {- const { config } = validate(- HEAD + `temporal:\n stale_pref_days: 60\n`,- );+ const { config } = validate(HEAD + `temporal:\n stale_pref_days: 60\n`);expect(config.temporal?.stale_pref_days).toBe(60);const resolved = resolveTemporal(config);expect(resolved.stale_pref_days).toBe(60);- expect(resolved.stale_signal_days).toBe(- BRAIN_TEMPORAL_DEFAULTS.stale_signal_days,- );- expect(resolved.weekly_start_dow).toBe(- BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow,- );+ expect(resolved.stale_signal_days).toBe(BRAIN_TEMPORAL_DEFAULTS.stale_signal_days);+ expect(resolved.weekly_start_dow).toBe(BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow);});test("stale_pref_days: 0 rejected", () => {- expect(() =>- validate(HEAD + `temporal:\n stale_pref_days: 0\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `temporal:\n stale_pref_days: 0\n`)).toThrow(BrainConfigError);});test("stale_pref_days: negative rejected", () => {- expect(() =>- validate(HEAD + `temporal:\n stale_pref_days: -1\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `temporal:\n stale_pref_days: -1\n`)).toThrow(BrainConfigError);});test("stale_pref_days: non-integer rejected", () => {- expect(() =>- validate(HEAD + `temporal:\n stale_pref_days: 2.5\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `temporal:\n stale_pref_days: 2.5\n`)).toThrow(BrainConfigError);});test("stale_signal_days: 0 rejected", () => {- expect(() =>- validate(HEAD + `temporal:\n stale_signal_days: 0\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `temporal:\n stale_signal_days: 0\n`)).toThrow(BrainConfigError);});test("stale_log_days: 0 rejected", () => {- expect(() =>- validate(HEAD + `temporal:\n stale_log_days: 0\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `temporal:\n stale_log_days: 0\n`)).toThrow(BrainConfigError);});test("weekly_start_dow: 0 rejected (must be 1..7 ISO-8601)", () => {- expect(() =>- validate(HEAD + `temporal:\n weekly_start_dow: 0\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `temporal:\n weekly_start_dow: 0\n`)).toThrow(BrainConfigError);});test("weekly_start_dow: 8 rejected (must be 1..7 ISO-8601)", () => {- expect(() =>- validate(HEAD + `temporal:\n weekly_start_dow: 8\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `temporal:\n weekly_start_dow: 8\n`)).toThrow(BrainConfigError);});test("weekly_start_dow: non-integer rejected", () => {- expect(() =>- validate(HEAD + `temporal:\n weekly_start_dow: 3.5\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `temporal:\n weekly_start_dow: 3.5\n`)).toThrow(BrainConfigError);});test("daily_window_offset_hours: -23 accepted (lower bound)", () => {- const { config } = validate(- HEAD + `temporal:\n daily_window_offset_hours: -23\n`,- );+ const { config } = validate(HEAD + `temporal:\n daily_window_offset_hours: -23\n`);expect(config.temporal?.daily_window_offset_hours).toBe(-23);});test("daily_window_offset_hours: 23 accepted (upper bound)", () => {- const { config } = validate(- HEAD + `temporal:\n daily_window_offset_hours: 23\n`,- );+ const { config } = validate(HEAD + `temporal:\n daily_window_offset_hours: 23\n`);expect(config.temporal?.daily_window_offset_hours).toBe(23);});test("daily_window_offset_hours: -24 rejected (out of range)", () => {- expect(() =>- validate(HEAD + `temporal:\n daily_window_offset_hours: -24\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `temporal:\n daily_window_offset_hours: -24\n`)).toThrow(+ BrainConfigError,+ );});test("daily_window_offset_hours: 24 rejected (out of range)", () => {- expect(() =>- validate(HEAD + `temporal:\n daily_window_offset_hours: 24\n`),- ).toThrow(BrainConfigError);+ expect(() => validate(HEAD + `temporal:\n daily_window_offset_hours: 24\n`)).toThrow(+ BrainConfigError,+ );});test("non-object temporal block rejected", () => {- expect(() => validate(HEAD + `temporal: "nope"\n`)).toThrow(- BrainConfigError,- );+ expect(() => validate(HEAD + `temporal: "nope"\n`)).toThrow(BrainConfigError);});test("unknown sub-key warns but does not throw", () => {const { config, warnings } = validate(- HEAD +- `temporal:\n stale_pref_days: 90\n unknown_slot: 7\n`,+ HEAD + `temporal:\n stale_pref_days: 90\n unknown_slot: 7\n`,);expect(config.temporal?.stale_pref_days).toBe(90);- expect(- warnings.some((w) =>- w.message.includes("temporal.unknown_slot"),- ),- ).toBe(true);+ expect(warnings.some((w) => w.message.includes("temporal.unknown_slot"))).toBe(true);});});diff --git a/tests/core/brain/temporal/build-index.test.ts b/tests/core/brain/temporal/build-index.test.tsindex 5da78e73..5501c0bd 100644--- a/tests/core/brain/temporal/build-index.test.ts+++ b/tests/core/brain/temporal/build-index.test.ts@@ -40,15 +40,9 @@ interface FixtureEvent {readonly body: Record<string, string | ReadonlyArray<string>>;}-function writeJsonlDay(- vault: string,- date: string,- events: ReadonlyArray<FixtureEvent>,-): void {+function writeJsonlDay(vault: string, date: string, events: ReadonlyArray<FixtureEvent>): void {const lines = events- .map((e) =>- JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),- )+ .map((e) => JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body })).join("\n");writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");}@@ -185,11 +179,7 @@ describe("buildTimelineIndex", () => {},]);const idx = buildTimelineIndex(VAULT, {});- expect(idx.events.map((e) => e.text)).toEqual([- "noon-19",- "afternoon-20",- "morning-21",- ]);+ expect(idx.events.map((e) => e.text)).toEqual(["noon-19", "afternoon-20", "morning-21"]);});test("window since/until: inclusive lower, exclusive upper", () => {@@ -222,10 +212,7 @@ describe("buildTimelineIndex", () => {until: "2026-05-21T00:00:00Z",});// lower-boundary included, upper-boundary excluded.- expect(idx.events.map((e) => e.text)).toEqual([- "lower-boundary",- "inside",- ]);+ expect(idx.events.map((e) => e.text)).toEqual(["lower-boundary", "inside"]);});test("window since/until accept bare ISO date (interpreted as T00:00:00Z)", () => {diff --git a/tests/core/brain/temporal/daily-brief.test.ts b/tests/core/brain/temporal/daily-brief.test.tsindex 321428a9..d72d40e9 100644--- a/tests/core/brain/temporal/daily-brief.test.ts+++ b/tests/core/brain/temporal/daily-brief.test.ts@@ -30,15 +30,9 @@ interface FixtureEvent {readonly body: Record<string, string | ReadonlyArray<string>>;}-function writeJsonl(- vault: string,- date: string,- events: ReadonlyArray<FixtureEvent>,-): void {+function writeJsonl(vault: string, date: string, events: ReadonlyArray<FixtureEvent>): void {const lines = events- .map((e) =>- JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),- )+ .map((e) => JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body })).join("\n");writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");}@@ -133,7 +127,7 @@ describe("buildDailyBrief", () => {const idx = buildTimelineIndex(VAULT, {});const brief = buildDailyBrief(idx, VAULT, "2026-05-25");expect(brief.statusTransitions.length).toBe(3);- const kinds = brief.statusTransitions.map((t) => t.kind).sort();+ const kinds = brief.statusTransitions.map((t) => t.kind).toSorted();expect(kinds).toEqual(["creation", "promotion", "retirement"]);});diff --git a/tests/core/brain/temporal/select-events.test.ts b/tests/core/brain/temporal/select-events.test.tsindex 501a404d..8a41a59a 100644--- a/tests/core/brain/temporal/select-events.test.ts+++ b/tests/core/brain/temporal/select-events.test.ts@@ -28,15 +28,9 @@ interface FixtureEvent {readonly body: Record<string, string | ReadonlyArray<string>>;}-function writeJsonlDay(- vault: string,- date: string,- events: ReadonlyArray<FixtureEvent>,-): void {+function writeJsonlDay(vault: string, date: string, events: ReadonlyArray<FixtureEvent>): void {const lines = events- .map((e) =>- JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),- )+ .map((e) => JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body })).join("\n");writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");}diff --git a/tests/core/brain/temporal/stale-watch.test.ts b/tests/core/brain/temporal/stale-watch.test.tsindex 776c626d..ee11f9f6 100644--- a/tests/core/brain/temporal/stale-watch.test.ts+++ b/tests/core/brain/temporal/stale-watch.test.ts@@ -98,16 +98,8 @@ describe("findStaleEntries", () => {});test("log file stale when mtime older than stale_log_days", () => {- writeFileMtime(- join(VAULT, "Brain", "log", "2025-08-01.jsonl"),- "",- "2025-08-01T00:00:00Z",- );- writeFileMtime(- join(VAULT, "Brain", "log", "2026-05-20.jsonl"),- "",- "2026-05-20T00:00:00Z",- );+ writeFileMtime(join(VAULT, "Brain", "log", "2025-08-01.jsonl"), "", "2025-08-01T00:00:00Z");+ writeFileMtime(join(VAULT, "Brain", "log", "2026-05-20.jsonl"), "", "2026-05-20T00:00:00Z");const idx = buildTimelineIndex(VAULT, {});const out = findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, {now: NOW,diff --git a/tests/core/brain/temporal/weekly-brief.test.ts b/tests/core/brain/temporal/weekly-brief.test.tsindex 7a9b2346..75912d6a 100644--- a/tests/core/brain/temporal/weekly-brief.test.ts+++ b/tests/core/brain/temporal/weekly-brief.test.ts@@ -28,15 +28,9 @@ interface FixtureEvent {readonly body: Record<string, string | ReadonlyArray<string>>;}-function writeJsonl(- vault: string,- date: string,- events: ReadonlyArray<FixtureEvent>,-): void {+function writeJsonl(vault: string, date: string, events: ReadonlyArray<FixtureEvent>): void {const lines = events- .map((e) =>- JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),- )+ .map((e) => JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body })).join("\n");writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");}@@ -49,12 +43,7 @@ beforeEach(() => {describe("buildWeeklySynthesis", () => {test("empty window - frozen empty-counts envelope", () => {const idx = buildTimelineIndex(VAULT, {});- const brief = buildWeeklySynthesis(- idx,- VAULT,- "2026-05-25",- BRAIN_TEMPORAL_DEFAULTS,- );+ const brief = buildWeeklySynthesis(idx, VAULT, "2026-05-25", BRAIN_TEMPORAL_DEFAULTS);expect(brief.windowEnd).toBe("2026-05-25T00:00:00Z");expect(brief.retired.length).toBe(0);expect(brief.contradictions.length).toBe(0);@@ -63,12 +52,7 @@ describe("buildWeeklySynthesis", () => {test("window covers exactly 7 days back from weekEnd", () => {const idx = buildTimelineIndex(VAULT, {});- const brief = buildWeeklySynthesis(- idx,- VAULT,- "2026-05-25",- BRAIN_TEMPORAL_DEFAULTS,- );+ const brief = buildWeeklySynthesis(idx, VAULT, "2026-05-25", BRAIN_TEMPORAL_DEFAULTS);expect(brief.windowEnd).toBe("2026-05-25T00:00:00Z");expect(brief.windowStart).toBe("2026-05-18T00:00:00Z");});@@ -107,15 +91,10 @@ describe("buildWeeklySynthesis", () => {},]);const idx = buildTimelineIndex(VAULT, {});- const brief = buildWeeklySynthesis(- idx,- VAULT,- "2026-05-25",- BRAIN_TEMPORAL_DEFAULTS,- );+ const brief = buildWeeklySynthesis(idx, VAULT, "2026-05-25", BRAIN_TEMPORAL_DEFAULTS);expect(brief.contradictions.length).toBe(2);// signal-suppressed contributes one; apply-evidence violated one.- const kinds = brief.contradictions.map((c) => c.kind).sort();+ const kinds = brief.contradictions.map((c) => c.kind).toSorted();expect(kinds).toEqual(["evidence-violated", "signal-suppressed"]);});@@ -131,12 +110,7 @@ describe("buildWeeklySynthesis", () => {},]);const idx = buildTimelineIndex(VAULT, {});- const brief = buildWeeklySynthesis(- idx,- VAULT,- "2026-05-25",- BRAIN_TEMPORAL_DEFAULTS,- );+ const brief = buildWeeklySynthesis(idx, VAULT, "2026-05-25", BRAIN_TEMPORAL_DEFAULTS);expect(brief.retired.length).toBe(1);expect(brief.retired[0]!.prefId).toBe("ret-foo");});@@ -167,12 +141,7 @@ describe("buildWeeklySynthesis", () => {},]);const idx = buildTimelineIndex(VAULT, {});- const brief = buildWeeklySynthesis(- idx,- VAULT,- "2026-05-25",- BRAIN_TEMPORAL_DEFAULTS,- );+ const brief = buildWeeklySynthesis(idx, VAULT, "2026-05-25", BRAIN_TEMPORAL_DEFAULTS);expect(brief.vaultDelta.newFeedback).toBe(1);expect(brief.vaultDelta.evidenceApplied).toBe(1);});diff --git a/tests/core/brain/text/tokenizer.test.ts b/tests/core/brain/text/tokenizer.test.tsindex c0dce2fa..52997440 100644--- a/tests/core/brain/text/tokenizer.test.ts+++ b/tests/core/brain/text/tokenizer.test.ts@@ -24,17 +24,17 @@ describe("estimateTokens", () => {// No script is special-cased: the formula must hold for every// input, regardless of which scripts it mixes.const samples = [- "Hello", // Latin ASCII- "café au lait", // Latin extended (NFC)- "Тест", // Cyrillic- "テスト", // Hiragana / Katakana- "안녕하세요", // Hangul- "مرحبا", // Arabic- "สวัสดี", // Thai (with combining marks)- "नमस्ते", // Devanagari (Hindi)- "アイウ", // Halfwidth katakana- "🦊🚀", // Emoji- "Hello テスト مرحبا 🦊", // Mixed+ "Hello", // Latin ASCII+ "café au lait", // Latin extended (NFC)+ "Тест", // Cyrillic+ "テスト", // Hiragana / Katakana+ "안녕하세요", // Hangul+ "مرحبا", // Arabic+ "สวัสดี", // Thai (with combining marks)+ "नमस्ते", // Devanagari (Hindi)+ "アイウ", // Halfwidth katakana+ "🦊🚀", // Emoji+ "Hello テスト مرحبا 🦊", // Mixed];for (const s of samples) {expect(estimateTokens(s)).toBe(Math.ceil(utf8Len(s) / 4));diff --git a/tests/core/brain/token-footprint.test.ts b/tests/core/brain/token-footprint.test.tsindex 50484983..4dcb3f10 100644--- a/tests/core/brain/token-footprint.test.ts+++ b/tests/core/brain/token-footprint.test.ts@@ -31,26 +31,11 @@ describe("computeTokenFootprint", () => {});test("counts preferences, retired, inbox, processed, log buckets", () => {- writeFileSync(- join(vault, "Brain", "preferences", "pref-a.md"),- "alpha beta gamma\n",- );- writeFileSync(- join(vault, "Brain", "retired", "ret-b.md"),- "delta epsilon\n",- );- writeFileSync(- join(vault, "Brain", "inbox", "sig-c.md"),- "zeta eta theta iota\n",- );- writeFileSync(- join(vault, "Brain", "inbox", "processed", "sig-d.md"),- "kappa lambda\n",- );- writeFileSync(- join(vault, "Brain", "log", "2026-05-25.md"),- "mu nu xi omicron\n",- );+ writeFileSync(join(vault, "Brain", "preferences", "pref-a.md"), "alpha beta gamma\n");+ writeFileSync(join(vault, "Brain", "retired", "ret-b.md"), "delta epsilon\n");+ writeFileSync(join(vault, "Brain", "inbox", "sig-c.md"), "zeta eta theta iota\n");+ writeFileSync(join(vault, "Brain", "inbox", "processed", "sig-d.md"), "kappa lambda\n");+ writeFileSync(join(vault, "Brain", "log", "2026-05-25.md"), "mu nu xi omicron\n");const r = computeTokenFootprint(vault);expect(r.files).toBe(5);const names = r.byCategory.map((c) => c.name);@@ -67,14 +52,8 @@ describe("computeTokenFootprint", () => {// would naturally recurse into it. The processed bucket counts// those files separately, so the total must equal the sum of// both buckets exactly.- writeFileSync(- join(vault, "Brain", "inbox", "sig-a.md"),- "alpha beta gamma\n",- );- writeFileSync(- join(vault, "Brain", "inbox", "processed", "sig-b.md"),- "delta epsilon zeta\n",- );+ writeFileSync(join(vault, "Brain", "inbox", "sig-a.md"), "alpha beta gamma\n");+ writeFileSync(join(vault, "Brain", "inbox", "processed", "sig-b.md"), "delta epsilon zeta\n");const r = computeTokenFootprint(vault);const inbox = r.byCategory.find((c) => c.name === "inbox")!.tokens;const processed = r.byCategory.find((c) => c.name === "processed")!.tokens;@@ -82,10 +61,7 @@ describe("computeTokenFootprint", () => {});test("exceeded flag flips when total crosses the threshold", () => {- writeFileSync(- join(vault, "Brain", "preferences", "pref-big.md"),- "word ".repeat(50),- );+ writeFileSync(join(vault, "Brain", "preferences", "pref-big.md"), "word ".repeat(50));const r = computeTokenFootprint(vault, { warnThreshold: 1 });expect(r.exceeded).toBe(true);});diff --git a/tests/core/brain/trust/check-role-permission.test.ts b/tests/core/brain/trust/check-role-permission.test.tsindex 5bbf1df3..d85e0f49 100644--- a/tests/core/brain/trust/check-role-permission.test.ts+++ b/tests/core/brain/trust/check-role-permission.test.ts@@ -1,17 +1,11 @@import { describe, expect, test } from "bun:test";-import {- BRAIN_OPERATIONS,- BRAIN_ROLES,-} from "../../../../src/core/brain/trust/role.ts";+import { BRAIN_OPERATIONS, BRAIN_ROLES } from "../../../../src/core/brain/trust/role.ts";import { checkRolePermission } from "../../../../src/core/brain/trust/check-role-permission.ts";describe("checkRolePermission - allowed paths", () => {test("writer may write inbox feedback", () => {- const r = checkRolePermission(- BRAIN_ROLES.writer,- BRAIN_OPERATIONS.feedback_write,- );+ const r = checkRolePermission(BRAIN_ROLES.writer, BRAIN_OPERATIONS.feedback_write);expect(r.allowed).toBe(true);});@@ -42,18 +36,12 @@ describe("checkRolePermission - allowed paths", () => {});test("applier may record evidence", () => {- const r = checkRolePermission(- BRAIN_ROLES.applier,- BRAIN_OPERATIONS.evidence_record,- );+ const r = checkRolePermission(BRAIN_ROLES.applier, BRAIN_OPERATIONS.evidence_record);expect(r.allowed).toBe(true);});test("applier may append narrative log", () => {- const r = checkRolePermission(- BRAIN_ROLES.applier,- BRAIN_OPERATIONS.log_append,- );+ const r = checkRolePermission(BRAIN_ROLES.applier, BRAIN_OPERATIONS.log_append);expect(r.allowed).toBe(true);});});@@ -69,26 +57,17 @@ describe("checkRolePermission - forbidden paths", () => {});test("writer must not retire a preference", () => {- const r = checkRolePermission(- BRAIN_ROLES.writer,- BRAIN_OPERATIONS.preference_retire,- );+ const r = checkRolePermission(BRAIN_ROLES.writer, BRAIN_OPERATIONS.preference_retire);expect(r.allowed).toBe(false);});test("dreamer must not write inbox feedback", () => {- const r = checkRolePermission(- BRAIN_ROLES.dreamer,- BRAIN_OPERATIONS.feedback_write,- );+ const r = checkRolePermission(BRAIN_ROLES.dreamer, BRAIN_OPERATIONS.feedback_write);expect(r.allowed).toBe(false);});test("dreamer must not record evidence", () => {- const r = checkRolePermission(- BRAIN_ROLES.dreamer,- BRAIN_OPERATIONS.evidence_record,- );+ const r = checkRolePermission(BRAIN_ROLES.dreamer, BRAIN_OPERATIONS.evidence_record);expect(r.allowed).toBe(false);});@@ -120,10 +99,7 @@ describe("checkRolePermission - forbidden paths", () => {});test("applier must not retire a preference", () => {- const r = checkRolePermission(- BRAIN_ROLES.applier,- BRAIN_OPERATIONS.preference_retire,- );+ const r = checkRolePermission(BRAIN_ROLES.applier, BRAIN_OPERATIONS.preference_retire);expect(r.allowed).toBe(false);});@@ -137,10 +113,7 @@ describe("checkRolePermission - forbidden paths", () => {describe("checkRolePermission - structural invariants", () => {test("returned object is frozen", () => {- const r = checkRolePermission(- BRAIN_ROLES.writer,- BRAIN_OPERATIONS.feedback_write,- );+ const r = checkRolePermission(BRAIN_ROLES.writer, BRAIN_OPERATIONS.feedback_write);expect(Object.isFrozen(r)).toBe(true);});});diff --git a/tests/core/brain/trust/compute-verification-delta.test.ts b/tests/core/brain/trust/compute-verification-delta.test.tsindex 806274ce..3fcce3f8 100644--- a/tests/core/brain/trust/compute-verification-delta.test.ts+++ b/tests/core/brain/trust/compute-verification-delta.test.ts@@ -64,10 +64,7 @@ describe("computeVerificationDelta", () => {confidence: "high",});- const r = computeVerificationDelta(- vault,- emptyDream({ confirmed: ["pref-test-rule"] }),- );+ const r = computeVerificationDelta(vault, emptyDream({ confirmed: ["pref-test-rule"] }));expect(r.summary.confirmed).toBe(1);expect(r.summary.drift).toBe(0);expect(r.entries).toHaveLength(1);@@ -91,19 +88,13 @@ describe("computeVerificationDelta", () => {confidence: "low",});- const r = computeVerificationDelta(- vault,- emptyDream({ confirmed: ["pref-no-evidence"] }),- );+ const r = computeVerificationDelta(vault, emptyDream({ confirmed: ["pref-no-evidence"] }));expect(r.summary.drift).toBe(1);expect(r.entries[0]?.state).toBe("drift");});test("missing_evidence: dream cites pref id that no longer exists on disk", () => {- const r = computeVerificationDelta(- vault,- emptyDream({ confirmed: ["pref-ghost-id"] }),- );+ const r = computeVerificationDelta(vault, emptyDream({ confirmed: ["pref-ghost-id"] }));expect(r.summary.missing_evidence).toBe(1);expect(r.entries[0]?.state).toBe("missing_evidence");expect(r.entries[0]?.id).toBe("pref-ghost-id");@@ -162,10 +153,7 @@ describe("computeVerificationDelta - regression + path contract", () => {status: "unconfirmed",evidenced_by: ["[[sig-z]]"],});- const r = computeVerificationDelta(- vault,- emptyDream({ confirmed: ["pref-claim-mismatch"] }),- );+ const r = computeVerificationDelta(vault, emptyDream({ confirmed: ["pref-claim-mismatch"] }));expect(r.summary.drift).toBe(1);expect(r.entries[0]?.state).toBe("drift");expect(r.entries[0]?.note).toMatch(/on-disk status is 'unconfirmed'/);@@ -184,10 +172,7 @@ describe("computeVerificationDelta - regression + path contract", () => {applied_count: 1,last_evidence_at: "2026-05-22T00:00:00Z",});- const r = computeVerificationDelta(- vault,- emptyDream({ confirmed: ["pref-path-shape"] }),- );+ const r = computeVerificationDelta(vault, emptyDream({ confirmed: ["pref-path-shape"] }));const path = r.entries[0]?.path ?? "";// Vault-relative path: starts with `Brain/preferences/`, never// with `/tmp/...` or any other absolute host directory.@@ -197,10 +182,7 @@ describe("computeVerificationDelta - regression + path contract", () => {test("malformed slug surfaces as missing_evidence, not a thrown error", () => {// Slug with characters rejected by validateSlug (uppercase, spaces).- const r = computeVerificationDelta(- vault,- emptyDream({ confirmed: ["pref-Invalid Slug!"] }),- );+ const r = computeVerificationDelta(vault, emptyDream({ confirmed: ["pref-Invalid Slug!"] }));expect(r.summary.missing_evidence).toBe(1);expect(r.entries[0]?.state).toBe("missing_evidence");});diff --git a/tests/core/brain/trust/instruction-file-ceiling.test.ts b/tests/core/brain/trust/instruction-file-ceiling.test.tsindex bed28ca0..99d31895 100644--- a/tests/core/brain/trust/instruction-file-ceiling.test.ts+++ b/tests/core/brain/trust/instruction-file-ceiling.test.ts@@ -40,7 +40,7 @@ describe("checkInstructionFileCeiling", () => {writeFileSync(join(vault, "AGENTS.md"), "x\n".repeat(250));writeFileSync(join(vault, "GEMINI.md"), "y\n".repeat(250));const r = checkInstructionFileCeiling(vault, { maxLines: 200 });- const paths = [...r].map((w) => w.path).sort();+ const paths = [...r].map((w) => w.path).toSorted();expect(paths).toEqual(["AGENTS.md", "GEMINI.md"]);});diff --git a/tests/core/brain/trust/role.test.ts b/tests/core/brain/trust/role.test.tsindex 697c364e..2d7369a0 100644--- a/tests/core/brain/trust/role.test.ts+++ b/tests/core/brain/trust/role.test.ts@@ -9,7 +9,7 @@ import {describe("BRAIN_ROLES", () => {test("enumerates exactly the four documented roles", () => {- expect(Object.values(BRAIN_ROLES).sort()).toEqual([+ expect(Object.values(BRAIN_ROLES).toSorted()).toEqual(["applier","dreamer","unknown",@@ -34,7 +34,7 @@ describe("BRAIN_ROLES", () => {describe("BRAIN_OPERATIONS", () => {test("enumerates exactly the six documented operations", () => {- expect(Object.values(BRAIN_OPERATIONS).sort()).toEqual([+ expect(Object.values(BRAIN_OPERATIONS).toSorted()).toEqual(["evidence_record","feedback_write","log_append",diff --git a/tests/core/brain/trust/self-approval-guardrail.test.ts b/tests/core/brain/trust/self-approval-guardrail.test.tsindex 28521d6b..9f49983a 100644--- a/tests/core/brain/trust/self-approval-guardrail.test.ts+++ b/tests/core/brain/trust/self-approval-guardrail.test.ts@@ -7,10 +7,7 @@ describe("applySelfApprovalGuardrail - default config", () => {const cfg = BRAIN_GUARDRAIL_DEFAULTS;test("promotes when all thresholds met (defaults)", () => {- const r = applySelfApprovalGuardrail(- { signal_count: 2, distinct_agents: 1, age_days: 0 },- cfg,- );+ const r = applySelfApprovalGuardrail({ signal_count: 2, distinct_agents: 1, age_days: 0 }, cfg);expect(r.decision).toBe("promote");expect(r.failed_gates).toEqual([]);});@@ -28,10 +25,7 @@ describe("applySelfApprovalGuardrail - default config", () => {});test("default min_age_days: 0 means the age gate never fails", () => {- const r = applySelfApprovalGuardrail(- { signal_count: 5, distinct_agents: 1, age_days: 0 },- cfg,- );+ const r = applySelfApprovalGuardrail({ signal_count: 5, distinct_agents: 1, age_days: 0 }, cfg);expect(r.decision).toBe("promote");});});@@ -55,10 +49,7 @@ describe("applySelfApprovalGuardrail - tighter config", () => {...BRAIN_GUARDRAIL_DEFAULTS,promotion_min_age_days: 7,};- const r = applySelfApprovalGuardrail(- { signal_count: 5, distinct_agents: 2, age_days: 3 },- cfg,- );+ const r = applySelfApprovalGuardrail({ signal_count: 5, distinct_agents: 2, age_days: 3 }, cfg);expect(r.decision).toBe("quarantine");expect(r.failed_gates).toContain("min_age_days");});@@ -70,12 +61,9 @@ describe("applySelfApprovalGuardrail - tighter config", () => {promotion_min_distinct_agents: 3,promotion_min_age_days: 10,};- const r = applySelfApprovalGuardrail(- { signal_count: 1, distinct_agents: 1, age_days: 0 },- cfg,- );+ const r = applySelfApprovalGuardrail({ signal_count: 1, distinct_agents: 1, age_days: 0 }, cfg);expect(r.decision).toBe("quarantine");- expect([...r.failed_gates].sort()).toEqual([+ expect([...r.failed_gates].toSorted()).toEqual(["min_age_days","min_distinct_agents","min_signals",diff --git a/tests/core/brain/upgrade.test.ts b/tests/core/brain/upgrade.test.tsindex a1966888..38788f37 100644--- a/tests/core/brain/upgrade.test.ts+++ b/tests/core/brain/upgrade.test.ts@@ -10,21 +10,12 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- existsSync,- mkdtempSync,- readFileSync,- rmSync,-} from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { bootstrapBrain } from "../../../src/core/brain/init.ts";-import {- applyUpgrade,- mergeBrainYaml,- planUpgrade,-} from "../../../src/core/brain/upgrade.ts";+import { applyUpgrade, mergeBrainYaml, planUpgrade } from "../../../src/core/brain/upgrade.ts";import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";import { brainConfigPath, brainManualPath } from "../../../src/core/brain/paths.ts";import { listSnapshots } from "../../../src/core/brain/snapshot.ts";@@ -87,9 +78,7 @@ dream:expect(merged).toContain("snapshots:");expect(merged).toContain("retention_count: 10");// Existing keys must remain at their original spot.- expect(merged.indexOf("schema_version: 1")).toBeLessThan(- merged.indexOf("retire:"),- );+ expect(merged.indexOf("schema_version: 1")).toBeLessThan(merged.indexOf("retire:"));expect(merged.indexOf("dream:")).toBeLessThan(merged.indexOf("retire:"));});@@ -162,10 +151,7 @@ describe("planUpgrade", () => {test("file ordering is _brain.yaml, _BRAIN.md", () => {const plan = planUpgrade(vault);- expect(plan.files.map((f) => f.path)).toEqual([- "Brain/_brain.yaml",- "Brain/_BRAIN.md",- ]);+ expect(plan.files.map((f) => f.path)).toEqual(["Brain/_brain.yaml", "Brain/_BRAIN.md"]);});test("missing snapshots section in _brain.yaml → update with appended block", () => {@@ -215,7 +201,6 @@ describe("planUpgrade", () => {expect(manualPlan.before).toBe("stale operator copy\n");expect(manualPlan.after).toContain("Brain");});-});describe("applyUpgrade", () => {@@ -236,9 +221,7 @@ describe("applyUpgrade", () => {const snaps = listSnapshots(vault);expect(snaps.some((s) => s.run_id === res.run_id)).toBe(true);// The live file is now the canonical template body.- expect(readFileSync(brainManualPath(vault), "utf8")).not.toBe(- "stale operator copy\n",- );+ expect(readFileSync(brainManualPath(vault), "utf8")).not.toBe("stale operator copy\n");// Idempotent re-run: plan is now empty.const res2 = applyUpgrade(vault, { agent: "claude-vps-agent" });expect(res2.files_updated).toEqual([]);@@ -262,9 +245,7 @@ describe("applyUpgrade", () => {test("malformed _brain.yaml refuses to apply (no snapshot taken)", () => {atomicWriteFileSync(brainConfigPath(vault), "not: a valid: brain yaml\n");const before = listSnapshots(vault).length;- expect(() => applyUpgrade(vault, { agent: "claude" })).toThrow(- /upgrade aborted/,- );+ expect(() => applyUpgrade(vault, { agent: "claude" })).toThrow(/upgrade aborted/);expect(listSnapshots(vault).length).toBe(before);});diff --git a/tests/core/config.test.ts b/tests/core/config.test.tsindex cb9abb5f..2fd7b190 100644--- a/tests/core/config.test.ts+++ b/tests/core/config.test.ts@@ -12,6 +12,7 @@ import {resolveTimezone,resolveVault,setConfigValue,+ validateTimezoneName,} from "../../src/core/config.ts";let tmp: string;@@ -60,7 +61,7 @@ describe("parseSimpleYaml", () => {});test("strips surrounding quotes", () => {- const data = parseSimpleYaml('vault: "/path"\nname: \'X\'\n');+ const data = parseSimpleYaml("vault: \"/path\"\nname: 'X'\n");expect(data["vault"]).toBe("/path");expect(data["name"]).toBe("X");});@@ -199,6 +200,13 @@ describe("resolveAgentName", () => {});describe("resolveTimezone", () => {+ test("validates IANA timezone names", () => {+ expect(validateTimezoneName("UTC")).toEqual({ ok: true, error: null });+ const invalid = validateTimezoneName("Not/A/Real/Zone");+ expect(invalid.ok).toBe(false);+ expect(invalid.error).toBeString();+ });+test("returns null when nothing configured", () => {expect(resolveTimezone(join(tmp, "missing.yaml"))).toBeNull();});diff --git a/tests/core/discipline/transcripts.test.ts b/tests/core/discipline/transcripts.test.tsindex 9589cdc8..9c81085a 100644--- a/tests/core/discipline/transcripts.test.ts+++ b/tests/core/discipline/transcripts.test.ts@@ -18,7 +18,9 @@ beforeEach(() => {home = mkdtempSync(join(tmpdir(), "osb-transcripts-h-"));});afterEach(() => {- try { rmSync(home, { recursive: true, force: true }); } catch {}+ try {+ rmSync(home, { recursive: true, force: true });+ } catch {}});const DAY_START = new Date("2026-05-19T00:00:00Z").getTime();@@ -115,10 +117,12 @@ describe("collectTranscriptActivity aggregator", () => {writeWithMtime(join(wdir, "state.vscdb"), "x", IN_DAY);const out = collectTranscriptActivity({- dayStartMs: DAY_START, dayEndMs: DAY_END, home,+ dayStartMs: DAY_START,+ dayEndMs: DAY_END,+ home,});expect(out.totalFiles).toBe(4);- expect(out.byRuntime.map((b) => `${b.runtime}=${b.fileCount}`).sort()).toEqual([+ expect(out.byRuntime.map((b) => `${b.runtime}=${b.fileCount}`).toSorted()).toEqual(["claudecode=1","codex=2","cursor=1",@@ -127,7 +131,9 @@ describe("collectTranscriptActivity aggregator", () => {test("totalFiles is zero when no runtime found anything", () => {const out = collectTranscriptActivity({- dayStartMs: DAY_START, dayEndMs: DAY_END, home,+ dayStartMs: DAY_START,+ dayEndMs: DAY_END,+ home,});expect(out.totalFiles).toBe(0);});diff --git a/tests/core/fs-atomic.test.ts b/tests/core/fs-atomic.test.tsindex 1c611b63..c129d60b 100644--- a/tests/core/fs-atomic.test.ts+++ b/tests/core/fs-atomic.test.ts@@ -3,10 +3,7 @@ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSyimport { tmpdir } from "node:os";import { join } from "node:path";-import {- atomicCreateFileSyncExclusive,- atomicWriteFileSync,-} from "../../src/core/fs-atomic.ts";+import { atomicCreateFileSyncExclusive, atomicWriteFileSync } from "../../src/core/fs-atomic.ts";let tmp: string;diff --git a/tests/core/identity-reminder.test.ts b/tests/core/identity-reminder.test.tsindex ba05888a..fd3f5ab7 100644--- a/tests/core/identity-reminder.test.ts+++ b/tests/core/identity-reminder.test.ts@@ -115,16 +115,12 @@ describe("buildReminder env-based resolution", () => {test("env O2B_TARGET=openclaw resolves to openclaw template", () => {process.env.O2B_TARGET = "openclaw";- expect(buildReminder("test-agent")).toContain(- "OpenClaw has no session boundary",- );+ expect(buildReminder("test-agent")).toContain("OpenClaw has no session boundary");});test("explicit target beats env", () => {process.env.O2B_TARGET = "openclaw";- expect(buildReminder("test-agent", "hermes")).toContain(- "Hermes turns are short",- );+ expect(buildReminder("test-agent", "hermes")).toContain("Hermes turns are short");});test("unknown env value falls back to common template", () => {diff --git a/tests/core/install/adapters/aider.test.ts b/tests/core/install/adapters/aider.test.tsindex 6b78f8b7..674b3148 100644--- a/tests/core/install/adapters/aider.test.ts+++ b/tests/core/install/adapters/aider.test.ts@@ -30,7 +30,9 @@ beforeEach(() => {});afterEach(() => {for (const p of [vault, home]) {- try { rmSync(p, { recursive: true, force: true }); } catch {}+ try {+ rmSync(p, { recursive: true, force: true });+ } catch {}}});@@ -39,9 +41,14 @@ function env(now = new Date("2026-05-20T12:00:00.000Z"), envVars: Record<string,}function applyOpts(overrides: Record<string, unknown> = {}) {- const sink = new Writable({ write(_c, _e, cb) { cb(); } });+ const sink = new Writable({+ write(_c, _e, cb) {+ cb();+ },+ });return {- dryRun: false, force: false,+ dryRun: false,+ force: false,stdout: sink as unknown as NodeJS.WriteStream,stderr: sink as unknown as NodeJS.WriteStream,...overrides,@@ -87,8 +94,7 @@ describe("aider adapter", () => {});test("preserves user-authored config above and below the managed block", () => {- const userConf =- "# user config\nmodel: gpt-4o-mini\nedit-format: diff\n";+ const userConf = "# user config\nmodel: gpt-4o-mini\nedit-format: diff\n";writeFileSync(aiderConfPath(), userConf);aiderAdapter.apply(aiderAdapter.plan(payload, env()), payload, env(), applyOpts());const conf = readFileSync(aiderConfPath(), "utf8");@@ -160,6 +166,8 @@ describe("aider adapter", () => {const e = env(new Date(), { AIDER_CONFIG: customConf });aiderAdapter.apply(aiderAdapter.plan(payload, e), payload, e, applyOpts());expect(existsSync(customConf)).toBe(true);- try { rmSync(custom, { recursive: true, force: true }); } catch {}+ try {+ rmSync(custom, { recursive: true, force: true });+ } catch {}});});diff --git a/tests/core/install/adapters/copilot-cli.test.ts b/tests/core/install/adapters/copilot-cli.test.tsindex ed94d8d4..f1812ff4 100644--- a/tests/core/install/adapters/copilot-cli.test.ts+++ b/tests/core/install/adapters/copilot-cli.test.ts@@ -1,7 +1,5 @@import { describe, expect, test, beforeEach, afterEach } from "bun:test";-import {- mkdtempSync, rmSync, existsSync, readFileSync, mkdirSync, writeFileSync,-} from "node:fs";+import { mkdtempSync, rmSync, existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { Writable } from "node:stream";@@ -27,7 +25,9 @@ beforeEach(() => {afterEach(() => {resetCopilotRunner();for (const p of [vault, home]) {- try { rmSync(p, { recursive: true, force: true }); } catch {}+ try {+ rmSync(p, { recursive: true, force: true });+ } catch {}}});@@ -42,12 +42,20 @@ function env() {}function applyOpts() {- const stdout = new Writable({ write(_c, _e, cb) { cb(); } });+ const stdout = new Writable({+ write(_c, _e, cb) {+ cb();+ },+ });const stderr = new Writable({- write(chunk, _e, cb) { stderrBuf.push(chunk.toString()); cb(); },+ write(chunk, _e, cb) {+ stderrBuf.push(chunk.toString());+ cb();+ },});return {- dryRun: false, force: false,+ dryRun: false,+ force: false,stdout: stdout as unknown as NodeJS.WriteStream,stderr: stderr as unknown as NodeJS.WriteStream,};@@ -89,7 +97,9 @@ describe("copilot-cli adapter — fallback to JSON file", () => {test("uses file fallback when CLI absent", () => {const runner: CopilotRunner = {available: () => false,- run: () => { throw new Error("should not run"); },+ run: () => {+ throw new Error("should not run");+ },list: () => ({ ok: false, names: [] }),};setCopilotRunner(runner);@@ -140,7 +150,9 @@ describe("copilot-cli adapter — verify", () => {test("verify ok when fallback file has both keys", () => {const runner: CopilotRunner = {available: () => false,- run: () => { throw new Error("nope"); },+ run: () => {+ throw new Error("nope");+ },list: () => ({ ok: false, names: [] }),};setCopilotRunner(runner);@@ -152,7 +164,9 @@ describe("copilot-cli adapter — verify", () => {test("verify drift when fallback file payload was changed", () => {const runner: CopilotRunner = {available: () => false,- run: () => { throw new Error("nope"); },+ run: () => {+ throw new Error("nope");+ },list: () => ({ ok: false, names: [] }),};setCopilotRunner(runner);@@ -203,7 +217,9 @@ describe("copilot-cli adapter — uninstall", () => {test("uninstall via fallback file removes both keys", () => {const runner: CopilotRunner = {available: () => false,- run: () => { throw new Error("nope"); },+ run: () => {+ throw new Error("nope");+ },list: () => ({ ok: false, names: [] }),};setCopilotRunner(runner);diff --git a/tests/core/install/adapters/cursor.test.ts b/tests/core/install/adapters/cursor.test.tsindex 71f83d43..412c7fae 100644--- a/tests/core/install/adapters/cursor.test.ts+++ b/tests/core/install/adapters/cursor.test.ts@@ -30,8 +30,12 @@ beforeEach(() => {});afterEach(() => {- try { rmSync(vault, { recursive: true, force: true }); } catch {}- try { rmSync(home, { recursive: true, force: true }); } catch {}+ try {+ rmSync(vault, { recursive: true, force: true });+ } catch {}+ try {+ rmSync(home, { recursive: true, force: true });+ } catch {}});function makeEnv(now = new Date("2026-05-20T12:00:00.000Z")) {@@ -46,24 +50,33 @@ function makeEnv(now = new Date("2026-05-20T12:00:00.000Z")) {function makeStreams() {const stdout = new Writable({- write(chunk, _enc, cb) { stdoutBuf.push(chunk.toString()); cb(); },+ write(chunk, _enc, cb) {+ stdoutBuf.push(chunk.toString());+ cb();+ },});const stderr = new Writable({- write(chunk, _enc, cb) { stderrBuf.push(chunk.toString()); cb(); },+ write(chunk, _enc, cb) {+ stderrBuf.push(chunk.toString());+ cb();+ },});return { stdout, stderr };}function payload() {return buildPayload({- vault, agent_name: "claude-vps", timezone: "UTC",+ vault,+ agent_name: "claude-vps",+ timezone: "UTC",});}function applyOpts(overrides: Record<string, unknown> = {}) {const { stdout, stderr } = makeStreams();return {- dryRun: false, force: false,+ dryRun: false,+ force: false,stdout: stdout as unknown as NodeJS.WriteStream,stderr: stderr as unknown as NodeJS.WriteStream,...overrides,@@ -110,8 +123,10 @@ describe("cursor adapter", () => {test("apply preserves unrelated mcpServers keys", () => {mkdirSync(join(home, ".cursor"), { recursive: true });- writeFileSync(cursorConfigPath(),- JSON.stringify({ mcpServers: { other: { command: "x", args: [] } } }, null, 2) + "\n");+ writeFileSync(+ cursorConfigPath(),+ JSON.stringify({ mcpServers: { other: { command: "x", args: [] } } }, null, 2) + "\n",+ );const p = payload();const plan = cursorAdapter.plan(p, makeEnv());cursorAdapter.apply(plan, p, makeEnv(), applyOpts());@@ -165,8 +180,10 @@ describe("cursor adapter", () => {test("uninstall removes both OSB keys, preserves user key, drops manifest entry", () => {mkdirSync(join(home, ".cursor"), { recursive: true });- writeFileSync(cursorConfigPath(),- JSON.stringify({ mcpServers: { other: { command: "x", args: [] } } }, null, 2) + "\n");+ writeFileSync(+ cursorConfigPath(),+ JSON.stringify({ mcpServers: { other: { command: "x", args: [] } } }, null, 2) + "\n",+ );const p = payload();cursorAdapter.apply(cursorAdapter.plan(p, makeEnv()), p, makeEnv(), applyOpts());cursorAdapter.uninstall(makeEnv(), applyOpts());@@ -179,8 +196,14 @@ describe("cursor adapter", () => {test("uninstall without manifest entry throws manifest-missing", () => {mkdirSync(join(home, ".cursor"), { recursive: true });- writeFileSync(cursorConfigPath(),- JSON.stringify({ mcpServers: { "open-second-brain": { command: "o2b", args: ["mcp"] } } }, null, 2) + "\n");+ writeFileSync(+ cursorConfigPath(),+ JSON.stringify(+ { mcpServers: { "open-second-brain": { command: "o2b", args: ["mcp"] } } },+ null,+ 2,+ ) + "\n",+ );try {cursorAdapter.uninstall(makeEnv(), applyOpts());expect.unreachable("should have thrown");@@ -192,10 +215,17 @@ describe("cursor adapter", () => {test("uninstall --force-from-snippet works without manifest", () => {mkdirSync(join(home, ".cursor"), { recursive: true });- writeFileSync(cursorConfigPath(),- JSON.stringify({ mcpServers: { "open-second-brain": { command: "o2b", args: ["mcp"] } } }, null, 2) + "\n");- expect(() => cursorAdapter.uninstall(makeEnv(), applyOpts({ fromSnippet: true })))- .not.toThrow();+ writeFileSync(+ cursorConfigPath(),+ JSON.stringify(+ { mcpServers: { "open-second-brain": { command: "o2b", args: ["mcp"] } } },+ null,+ 2,+ ) + "\n",+ );+ expect(() =>+ cursorAdapter.uninstall(makeEnv(), applyOpts({ fromSnippet: true })),+ ).not.toThrow();const parsed = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));expect(parsed.mcpServers["open-second-brain"]).toBeUndefined();});diff --git a/tests/core/install/adapters/generic.test.ts b/tests/core/install/adapters/generic.test.tsindex a3534b36..a8765ee8 100644--- a/tests/core/install/adapters/generic.test.ts+++ b/tests/core/install/adapters/generic.test.ts@@ -22,29 +22,45 @@ beforeEach(() => {stdoutBuf = [];stderrBuf = [];stdout = new Writable({- write(chunk, _enc, cb) { stdoutBuf.push(chunk.toString()); cb(); },+ write(chunk, _enc, cb) {+ stdoutBuf.push(chunk.toString());+ cb();+ },});stderr = new Writable({- write(chunk, _enc, cb) { stderrBuf.push(chunk.toString()); cb(); },+ write(chunk, _enc, cb) {+ stderrBuf.push(chunk.toString());+ cb();+ },});env = {- vault, home, cwd: home,- env: {}, now: new Date("2026-05-20T12:00:00.000Z"),+ vault,+ home,+ cwd: home,+ env: {},+ now: new Date("2026-05-20T12:00:00.000Z"),};});afterEach(() => {- try { rmSync(vault, { recursive: true, force: true }); } catch {}- try { rmSync(home, { recursive: true, force: true }); } catch {}+ try {+ rmSync(vault, { recursive: true, force: true });+ } catch {}+ try {+ rmSync(home, { recursive: true, force: true });+ } catch {}});const payload = buildPayload({- vault: "/home/u/vault", agent_name: "a", timezone: "UTC",+ vault: "/home/u/vault",+ agent_name: "a",+ timezone: "UTC",});function applyOpts(extra: Partial<Parameters<typeof genericAdapter.apply>[3]> = {}) {return {- dryRun: false, force: false,+ dryRun: false,+ force: false,stdout: stdout as unknown as NodeJS.WriteStream,stderr: stderr as unknown as NodeJS.WriteStream,...extra,@@ -101,7 +117,7 @@ describe("generic adapter", () => {const out = stdoutBuf.join("");expect(out).toContain("mcpServers:");expect(out).toContain("open-second-brain:");- expect(() => JSON.parse(out)).toThrow(); // not JSON+ expect(() => JSON.parse(out)).toThrow(); // not JSON});test("apply dryRun does not write the output file", () => {diff --git a/tests/core/install/adapters/json-mcp-smoke.test.ts b/tests/core/install/adapters/json-mcp-smoke.test.tsindex ad8ad8b2..4541783d 100644--- a/tests/core/install/adapters/json-mcp-smoke.test.ts+++ b/tests/core/install/adapters/json-mcp-smoke.test.ts@@ -27,13 +27,19 @@ beforeEach(() => {home = mkdtempSync(join(tmpdir(), "osb-jsonmcp-h-"));});afterEach(() => {- try { rmSync(vault, { recursive: true, force: true }); } catch {}- try { rmSync(home, { recursive: true, force: true }); } catch {}+ try {+ rmSync(vault, { recursive: true, force: true });+ } catch {}+ try {+ rmSync(home, { recursive: true, force: true });+ } catch {}});function env(extraEnv: Record<string, string> = {}) {return {- vault, home, cwd: home,+ vault,+ home,+ cwd: home,// verify() rebuilds the canonical payload from these env vars; they// must match the values passed to buildPayload() below or every// smoke check would report drift.@@ -43,9 +49,14 @@ function env(extraEnv: Record<string, string> = {}) {}function applyOpts() {- const sink = new Writable({ write(_c, _e, cb) { cb(); } });+ const sink = new Writable({+ write(_c, _e, cb) {+ cb();+ },+ });return {- dryRun: false, force: false,+ dryRun: false,+ force: false,stdout: sink as unknown as NodeJS.WriteStream,stderr: sink as unknown as NodeJS.WriteStream,};@@ -65,7 +76,9 @@ describe("opencode adapter — config path resolution", () => {const xdg = mkdtempSync(join(tmpdir(), "osb-xdg-"));const r = opencodeAdapter.detect(env({ XDG_CONFIG_HOME: xdg }));expect(r.configPath).toBe(join(xdg, "opencode", "mcp.json"));- try { rmSync(xdg, { recursive: true, force: true }); } catch {}+ try {+ rmSync(xdg, { recursive: true, force: true });+ } catch {}});test("install + uninstall round-trip", () => {diff --git a/tests/core/install/adapters/pi.test.ts b/tests/core/install/adapters/pi.test.tsindex 0c7cd7b4..fd24bf3b 100644--- a/tests/core/install/adapters/pi.test.ts+++ b/tests/core/install/adapters/pi.test.ts@@ -34,7 +34,9 @@ beforeEach(() => {afterEach(() => {for (const p of [vault, home, pluginRoot]) {- try { rmSync(p, { recursive: true, force: true }); } catch {}+ try {+ rmSync(p, { recursive: true, force: true });+ } catch {}}});@@ -43,9 +45,14 @@ function env() {}function applyOpts(overrides: Record<string, unknown> = {}) {- const sink = new Writable({ write(_c, _e, cb) { cb(); } });+ const sink = new Writable({+ write(_c, _e, cb) {+ cb();+ },+ });return {- dryRun: false, force: false,+ dryRun: false,+ force: false,stdout: sink as unknown as NodeJS.WriteStream,stderr: sink as unknown as NodeJS.WriteStream,piSkillSource: skillSource,@@ -118,9 +125,16 @@ describe("pi adapter", () => {test("piSkillDir override changes target location", () => {const altDir = mkdtempSync(join(tmpdir(), "osb-pi-alt-"));- piAdapter.apply(piAdapter.plan(payload, env()), payload, env(), applyOpts({ piSkillDir: altDir }));+ piAdapter.apply(+ piAdapter.plan(payload, env()),+ payload,+ env(),+ applyOpts({ piSkillDir: altDir }),+ );expect(lstatSync(join(altDir, "brain-memory")).isSymbolicLink()).toBe(true);- try { rmSync(altDir, { recursive: true, force: true }); } catch {}+ try {+ rmSync(altDir, { recursive: true, force: true });+ } catch {}});test("uninstall removes the symlink only, leaves source alone", () => {diff --git a/tests/core/install/json-merge.test.ts b/tests/core/install/json-merge.test.tsindex 813ae536..317cb9d5 100644--- a/tests/core/install/json-merge.test.ts+++ b/tests/core/install/json-merge.test.ts@@ -74,7 +74,9 @@ describe("mergeMcpServers", () => {const out = mergeMcpServers(before, OSB_PAYLOAD);const parsed = JSON.parse(out);expect(parsed.mcpServers["open-second-brain"].args).toEqual([- "mcp", "--vault", "/home/u/vault",+ "mcp",+ "--vault",+ "/home/u/vault",]);});diff --git a/tests/core/install/manifest.test.ts b/tests/core/install/manifest.test.tsindex 268dc203..bb986a07 100644--- a/tests/core/install/manifest.test.ts+++ b/tests/core/install/manifest.test.ts@@ -15,7 +15,9 @@ beforeEach(() => {vault = mkdtempSync(join(tmpdir(), "osb-manifest-"));});afterEach(() => {- try { rmSync(vault, { recursive: true, force: true }); } catch {}+ try {+ rmSync(vault, { recursive: true, force: true });+ } catch {}});describe("install manifest sidecar", () => {@@ -102,10 +104,7 @@ describe("install manifest sidecar", () => {test("readManifest rejects unknown schema_version", () => {mkdirSync(join(vault, ".open-second-brain"), { recursive: true });- writeFileSync(- manifestPath(vault),- JSON.stringify({ schema_version: 999, installs: {} }),- );+ writeFileSync(manifestPath(vault), JSON.stringify({ schema_version: 999, installs: {} }));expect(() => readManifest(vault)).toThrow(/schema_version/);});diff --git a/tests/core/install/payload.test.ts b/tests/core/install/payload.test.tsindex be638279..960dcbbb 100644--- a/tests/core/install/payload.test.ts+++ b/tests/core/install/payload.test.ts@@ -16,7 +16,9 @@ describe("buildPayload", () => {test("includes env when agent_name + timezone present", () => {const { full, writer } = buildPayload({- vault: "/v", agent_name: "a", timezone: "UTC",+ vault: "/v",+ agent_name: "a",+ timezone: "UTC",});expect(full.env).toEqual({ VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" });expect(writer.env).toEqual({ VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" });@@ -38,10 +40,12 @@ describe("buildPayload", () => {});test("throws PayloadError on missing vault", () => {- expect(() => buildPayload({ vault: "", agent_name: null, timezone: null }))- .toThrow(PayloadError);- expect(() => buildPayload({ vault: null as unknown as string, agent_name: null, timezone: null }))- .toThrow(PayloadError);+ expect(() => buildPayload({ vault: "", agent_name: null, timezone: null })).toThrow(+ PayloadError,+ );+ expect(() =>+ buildPayload({ vault: null as unknown as string, agent_name: null, timezone: null }),+ ).toThrow(PayloadError);});test("writer args carry --writer-only before --vault", () => {diff --git a/tests/core/install/registry.test.ts b/tests/core/install/registry.test.tsindex c954659b..86ed4a5c 100644--- a/tests/core/install/registry.test.ts+++ b/tests/core/install/registry.test.ts@@ -78,7 +78,7 @@ describe("install registry", () => {reg.register(makeFakeAdapter("a"));reg.register(makeFakeAdapter("b"));const out = reg.detectAll(makeEnv());- expect(out.map((d) => d.target).sort()).toEqual(["a", "b"]);+ expect(out.map((d) => d.target).toSorted()).toEqual(["a", "b"]);});test("list returns adapters in registration order", () => {diff --git a/tests/core/install/types.test.ts b/tests/core/install/types.test.tsindex ca02122f..3d4f817b 100644--- a/tests/core/install/types.test.ts+++ b/tests/core/install/types.test.ts@@ -9,25 +9,13 @@ import {describe("install types", () => {test("ADAPTER_STATUSES covers the four documented states", () => {expect(new Set(ADAPTER_STATUSES)).toEqual(- new Set([- "not-installed",- "installed",- "drift",- "unsupported-on-this-platform",- ]),+ new Set(["not-installed", "installed", "drift", "unsupported-on-this-platform"]),);});test("INSTALL_STEP_KINDS covers the six operation kinds", () => {expect(new Set(INSTALL_STEP_KINDS)).toEqual(- new Set([- "json-merge",- "managed-block",- "subprocess",- "file-copy",- "symlink",- "print",- ]),+ new Set(["json-merge", "managed-block", "subprocess", "file-copy", "symlink", "print"]),);});diff --git a/tests/core/install/update.test.ts b/tests/core/install/update.test.tsindex 2392df92..83991ac2 100644--- a/tests/core/install/update.test.ts+++ b/tests/core/install/update.test.ts@@ -26,8 +26,12 @@ beforeEach(() => {});afterEach(() => {- try { rmSync(vault, { recursive: true, force: true }); } catch {}- try { rmSync(home, { recursive: true, force: true }); } catch {}+ try {+ rmSync(vault, { recursive: true, force: true });+ } catch {}+ try {+ rmSync(home, { recursive: true, force: true });+ } catch {}});function makeEnv(): InstallEnv {diff --git a/tests/core/path-constants.test.ts b/tests/core/path-constants.test.tsindex 1a02d7df..fead403f 100644--- a/tests/core/path-constants.test.ts+++ b/tests/core/path-constants.test.ts@@ -30,29 +30,15 @@ describe("BRAIN_ROOT_REL", () => {describe("PAY_MEMORY_*_REL constants", () => {test("compose under BRAIN_ROOT_REL so a Brain rename cascades", () => {expect(PAY_MEMORY_ROOT_REL).toBe(posix.join(BRAIN_ROOT_REL, "payments"));- expect(PAY_MEMORY_POLICIES_REL).toBe(- posix.join(PAY_MEMORY_ROOT_REL, "policies"),- );- expect(PAY_MEMORY_ASSETS_REL).toBe(- posix.join(PAY_MEMORY_ROOT_REL, "assets"),- );- expect(PAY_MEMORY_DRAFTS_REL).toBe(- posix.join(PAY_MEMORY_ROOT_REL, "drafts"),- );- expect(PAY_MEMORY_REPORTS_REL).toBe(- posix.join(PAY_MEMORY_ROOT_REL, "reports"),- );- expect(PAY_MEMORY_PENDING_REL).toBe(- posix.join(PAY_MEMORY_ROOT_REL, "_pending"),- );+ expect(PAY_MEMORY_POLICIES_REL).toBe(posix.join(PAY_MEMORY_ROOT_REL, "policies"));+ expect(PAY_MEMORY_ASSETS_REL).toBe(posix.join(PAY_MEMORY_ROOT_REL, "assets"));+ expect(PAY_MEMORY_DRAFTS_REL).toBe(posix.join(PAY_MEMORY_ROOT_REL, "drafts"));+ expect(PAY_MEMORY_REPORTS_REL).toBe(posix.join(PAY_MEMORY_ROOT_REL, "reports"));+ expect(PAY_MEMORY_PENDING_REL).toBe(posix.join(PAY_MEMORY_ROOT_REL, "_pending"));});test("spending policy file constants compose under policies", () => {- expect(PAY_MEMORY_SPENDING_MD_REL).toBe(- posix.join(PAY_MEMORY_POLICIES_REL, "spending.md"),- );- expect(PAY_MEMORY_SPENDING_JSON_REL).toBe(- posix.join(PAY_MEMORY_POLICIES_REL, "spending.json"),- );+ expect(PAY_MEMORY_SPENDING_MD_REL).toBe(posix.join(PAY_MEMORY_POLICIES_REL, "spending.md"));+ expect(PAY_MEMORY_SPENDING_JSON_REL).toBe(posix.join(PAY_MEMORY_POLICIES_REL, "spending.json"));});});diff --git a/tests/core/path-safety.test.ts b/tests/core/path-safety.test.tsindex 60484e28..ff3e6cfd 100644--- a/tests/core/path-safety.test.ts+++ b/tests/core/path-safety.test.ts@@ -27,9 +27,7 @@ describe("ensureInsideVault", () => {// Without using `path.sep`, the naive `startsWith(vault + "/")` check// would happily admit `/v-evil/...` because `/v-evil` starts with `/v`// when concatenated. The fixed implementation rejects it.- expect(() => ensureInsideVault(join(SIBLING, "x.md"), VAULT)).toThrow(- /escapes vault/,- );+ expect(() => ensureInsideVault(join(SIBLING, "x.md"), VAULT)).toThrow(/escapes vault/);});test("rejects paths that resolve outside the vault", () => {@@ -80,9 +78,9 @@ describe("ensureInsideVault — realpath / symlink escape", () => {// No symlink involved; just a fresh slug on a real vault. realpath// protection should not crash on a path component that doesn't exist// yet (the writer creates it after this check passes).- expect(- ensureInsideVault(join(vault, "Notes", "payments", "2026-05-10", "x.md"), vault),- ).toBe(join(vault, "Notes", "payments", "2026-05-10", "x.md"));+ expect(ensureInsideVault(join(vault, "Notes", "payments", "2026-05-10", "x.md"), vault)).toBe(+ join(vault, "Notes", "payments", "2026-05-10", "x.md"),+ );});});diff --git a/tests/core/pay-memory.approval.test.ts b/tests/core/pay-memory.approval.test.tsindex 43777d58..ab2fe29b 100644--- a/tests/core/pay-memory.approval.test.ts+++ b/tests/core/pay-memory.approval.test.ts@@ -142,9 +142,9 @@ describe("state transitions", () => {test("approve then consume requires the approved state", async () => {writePendingRequest(tmp, { ...baseInput, slug: "t-3" });- await expect(- consumePendingRequest(tmp, "t-3", { receiptPath: "x" }),- ).rejects.toThrow(/cannot transition request t-3 from pending to consumed/);+ await expect(consumePendingRequest(tmp, "t-3", { receiptPath: "x" })).rejects.toThrow(+ /cannot transition request t-3 from pending to consumed/,+ );await approvePendingRequest(tmp, "t-3", { approvedBy: "sergey" });const out = await consumePendingRequest(tmp, "t-3", {receiptPath: `${PAY_MEMORY_ROOT_REL}/2026-05-10/x.md`,@@ -157,22 +157,18 @@ describe("state transitions", () => {test("rejected and consumed are terminal", async () => {writePendingRequest(tmp, { ...baseInput, slug: "t-4" });await rejectPendingRequest(tmp, "t-4", { rejectedBy: "sergey" });- await expect(- approvePendingRequest(tmp, "t-4", { approvedBy: "x" }),- ).rejects.toThrow();+ await expect(approvePendingRequest(tmp, "t-4", { approvedBy: "x" })).rejects.toThrow();writePendingRequest(tmp, { ...baseInput, slug: "t-5" });await approvePendingRequest(tmp, "t-5", { approvedBy: "sergey" });await consumePendingRequest(tmp, "t-5", { receiptPath: "x" });- await expect(- consumePendingRequest(tmp, "t-5", { receiptPath: "y" }),- ).rejects.toThrow();+ await expect(consumePendingRequest(tmp, "t-5", { receiptPath: "y" })).rejects.toThrow();});test("transitioning a non-existent request throws", async () => {- await expect(- approvePendingRequest(tmp, "nope", { approvedBy: "x" }),- ).rejects.toThrow(/not found/);+ await expect(approvePendingRequest(tmp, "nope", { approvedBy: "x" })).rejects.toThrow(+ /not found/,+ );});test("concurrent approve+reject on the same id: exactly one transition wins", async () => {@@ -204,7 +200,7 @@ describe("listPendingRequests", () => {const pending = listPendingRequests(tmp);expect(pending.map((s) => s.id)).toEqual(["p-1"]);const all = listPendingRequests(tmp, { status: "all" });- expect(all.map((s) => s.id).sort()).toEqual(["p-1", "p-2"]);+ expect(all.map((s) => s.id).toSorted()).toEqual(["p-1", "p-2"]);const rejected = listPendingRequests(tmp, { status: "rejected" });expect(rejected.map((s) => s.id)).toEqual(["p-2"]);});diff --git a/tests/core/pay-memory.asset.test.ts b/tests/core/pay-memory.asset.test.tsindex 4bb0cbf3..c3342f59 100644--- a/tests/core/pay-memory.asset.test.ts+++ b/tests/core/pay-memory.asset.test.ts@@ -6,7 +6,6 @@ import { join } from "node:path";import { parseFrontmatter } from "../../src/core/vault.ts";import { writeAsset } from "../../src/core/pay-memory/asset.ts";-let tmp: string;beforeEach(() => {diff --git a/tests/core/pay-memory.digest.test.ts b/tests/core/pay-memory.digest.test.tsindex c437aacd..29dc5b07 100644--- a/tests/core/pay-memory.digest.test.ts+++ b/tests/core/pay-memory.digest.test.ts@@ -10,7 +10,6 @@ import {} from "../../src/core/pay-memory/digest.ts";import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";-let tmp: string;beforeEach(() => {@@ -40,16 +39,27 @@ describe("buildPaymentDigest", () => {test("counts unique services and sums same-currency amounts", () => {writeReceipt(tmp, {- ...baseInput, service: "paysponge/fal", slug: "f1",- actualAmount: "0.05", currency: "USDC",+ ...baseInput,+ service: "paysponge/fal",+ slug: "f1",+ actualAmount: "0.05",+ currency: "USDC",});writeReceipt(tmp, {- ...baseInput, service: "paysponge/fal", slug: "f2",- actualAmount: "0.02", currency: "USDC", reason: "demo-2",+ ...baseInput,+ service: "paysponge/fal",+ slug: "f2",+ actualAmount: "0.02",+ currency: "USDC",+ reason: "demo-2",});writeReceipt(tmp, {- ...baseInput, service: "alpha/translate", slug: "a1",- actualAmount: "0.01", currency: "USDC", reason: "demo-3",+ ...baseInput,+ service: "alpha/translate",+ slug: "a1",+ actualAmount: "0.01",+ currency: "USDC",+ reason: "demo-3",});const d = buildPaymentDigest(tmp, { date: "2026-05-10" });expect(d.receipts).toBe(3);@@ -60,12 +70,19 @@ describe("buildPaymentDigest", () => {test("totalAmount=null when receipts mix currencies", () => {writeReceipt(tmp, {- ...baseInput, service: "x/y", slug: "u1",- actualAmount: "0.05", currency: "USDC",+ ...baseInput,+ service: "x/y",+ slug: "u1",+ actualAmount: "0.05",+ currency: "USDC",});writeReceipt(tmp, {- ...baseInput, service: "x/y", slug: "u2",- actualAmount: "1.0", currency: "EUR", reason: "demo-2",+ ...baseInput,+ service: "x/y",+ slug: "u2",+ actualAmount: "1.0",+ currency: "EUR",+ reason: "demo-2",});const d = buildPaymentDigest(tmp, { date: "2026-05-10" });expect(d.receipts).toBe(2);@@ -96,14 +113,16 @@ describe("renderPaymentDigestTelegram", () => {expect(text).toContain("💳 Оплачено сервисов: **2**");expect(text).toContain("💰 Сумма: **0.08 USDC**");expect(text).toContain("📁 Файлы чеков: **3**");- expect(text).toContain(- "🔗 Отчёт: `Brain/payments/reports/payment-report-2026-05-10.md`",- );+ expect(text).toContain("🔗 Отчёт: `Brain/payments/reports/payment-report-2026-05-10.md`");});test("emits [SILENT] when receipts == 0 in default mode", () => {const text = renderPaymentDigestTelegram({- date: "x", services: 0, receipts: 0, totalAmount: null, currency: null,+ date: "x",+ services: 0,+ receipts: 0,+ totalAmount: null,+ currency: null,});expect(text).toBe(DIGEST_SILENT_TOKEN);});@@ -126,14 +145,22 @@ describe("renderPaymentDigestTelegram", () => {test("trims trailing zeros in amount formatting", () => {const text = renderPaymentDigestTelegram({- date: "x", services: 1, receipts: 1, totalAmount: 0.5, currency: "USDC",+ date: "x",+ services: 1,+ receipts: 1,+ totalAmount: 0.5,+ currency: "USDC",});expect(text).toContain("💰 Сумма: **0.5 USDC**");});test("falls back to dash when totalAmount is null but receipts > 0", () => {const text = renderPaymentDigestTelegram({- date: "x", services: 1, receipts: 1, totalAmount: null, currency: null,+ date: "x",+ services: 1,+ receipts: 1,+ totalAmount: null,+ currency: null,});expect(text).toContain("💰 Сумма: **—**");});diff --git a/tests/core/pay-memory.paths.test.ts b/tests/core/pay-memory.paths.test.tsindex 0039c3ee..e9285994 100644--- a/tests/core/pay-memory.paths.test.ts+++ b/tests/core/pay-memory.paths.test.ts@@ -42,9 +42,7 @@ describe("payMemoryDirs", () => {});test("paymentsDateDir validates date", () => {- expect(paymentsDateDir("/v", "2026-05-10")).toBe(- join("/v", PAY_MEMORY_ROOT_REL, "2026-05-10"),- );+ expect(paymentsDateDir("/v", "2026-05-10")).toBe(join("/v", PAY_MEMORY_ROOT_REL, "2026-05-10"));expect(() => paymentsDateDir("/v", "2026.05.10")).toThrow();expect(() => paymentsDateDir("/v", "10-05-2026")).toThrow();});@@ -154,23 +152,15 @@ describe("isoTimestampZ", () => {// of the tz-aware path is that 09:00 is not just relabelled `09:00Z`// (the bug the v0.8.0 review flagged) but actually shifted by the// zone's offset.- expect(isoTimestampZ("2026-05-10", "09:00", "Asia/Tokyo")).toBe(- "2026-05-10T00:00:00Z",- );+ expect(isoTimestampZ("2026-05-10", "09:00", "Asia/Tokyo")).toBe("2026-05-10T00:00:00Z");// Day rollover: 06:00 Tokyo = 21:00 UTC the previous day.- expect(isoTimestampZ("2026-05-10", "06:00", "Asia/Tokyo")).toBe(- "2026-05-09T21:00:00Z",- );+ expect(isoTimestampZ("2026-05-10", "06:00", "Asia/Tokyo")).toBe("2026-05-09T21:00:00Z");});test("uses the offset that was in effect for that specific instant (DST aware)", () => {// Belgrade is UTC+1 in winter, UTC+2 in summer. Same wall-clock,// different real UTC depending on the date.- expect(isoTimestampZ("2026-01-15", "12:00", "Europe/Belgrade")).toBe(- "2026-01-15T11:00:00Z",- );- expect(isoTimestampZ("2026-07-15", "12:00", "Europe/Belgrade")).toBe(- "2026-07-15T10:00:00Z",- );+ expect(isoTimestampZ("2026-01-15", "12:00", "Europe/Belgrade")).toBe("2026-01-15T11:00:00Z");+ expect(isoTimestampZ("2026-07-15", "12:00", "Europe/Belgrade")).toBe("2026-07-15T10:00:00Z");});});diff --git a/tests/core/pay-memory.policy-rules.test.ts b/tests/core/pay-memory.policy-rules.test.tsindex 67f4d1ca..4668c4a3 100644--- a/tests/core/pay-memory.policy-rules.test.ts+++ b/tests/core/pay-memory.policy-rules.test.ts@@ -140,7 +140,7 @@ describe("evaluatePolicy", () => {// approval threshold can be bypassed by simply not stating the cost.for (const rule of [{ max_single_call: 0.05 },- { max_total_per_day: 0.10 },+ { max_total_per_day: 0.1 },{ require_approval_above: 0.03 },] as const) {const d = evaluatePolicy(diff --git a/tests/core/pay-memory.receipt.test.ts b/tests/core/pay-memory.receipt.test.tsindex b454de41..095bcca6 100644--- a/tests/core/pay-memory.receipt.test.ts+++ b/tests/core/pay-memory.receipt.test.ts@@ -6,7 +6,6 @@ import { join } from "node:path";import { parseFrontmatter } from "../../src/core/vault.ts";import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";-let tmp: string;beforeEach(() => {@@ -70,7 +69,7 @@ describe("writeReceipt", () => {paymentProof: "5G3...sig",resultRef: "https://fal-cdn.example/abc.png",resultNote: "Brain/payments/assets/blog-header.md",- rawOutput: "{\"ok\": true}",+ rawOutput: '{"ok": true}',});const [meta, body] = parseFrontmatter(out.path);expect(meta["category"]).toBe("media_generation");@@ -97,7 +96,7 @@ describe("writeReceipt", () => {test("redacts secrets in raw_output before writing", () => {const raw = ["request: GET /v1/foo",- 'Authorization: Bearer eyJhbGciOi.SECRET',+ "Authorization: Bearer eyJhbGciOi.SECRET",'response: {"api_key": "sk_live_abc", "ok": true}',].join("\n");const out = writeReceipt(tmp, { ...baseInput, rawOutput: raw });diff --git a/tests/core/pay-memory.redactor.test.ts b/tests/core/pay-memory.redactor.test.tsindex 673e2197..c1aa527c 100644--- a/tests/core/pay-memory.redactor.test.ts+++ b/tests/core/pay-memory.redactor.test.ts@@ -21,9 +21,7 @@ describe("redactRawOutput", () => {expect(redactRawOutput('{"api_key": "abc", "name": "ok"}')).toBe('{"api_key": "***REDACTED***", "name": "ok"}',);- expect(redactRawOutput('{"token":"long.signed.value"}')).toBe(- '{"token":"***REDACTED***"}',- );+ expect(redactRawOutput('{"token":"long.signed.value"}')).toBe('{"token":"***REDACTED***"}');});test("redacts Authorization: Bearer headers and preserves the `Bearer` prefix", () => {@@ -70,9 +68,7 @@ describe("redactRawOutput", () => {test("redacts password / credential / session_token assignments", () => {expect(redactRawOutput("password: hunter2")).toBe("password: ***REDACTED***");expect(redactRawOutput("PASSWD=somepw123")).toBe("PASSWD=***REDACTED***");- expect(redactRawOutput('{"credential": "abc"}')).toBe(- '{"credential": "***REDACTED***"}',- );+ expect(redactRawOutput('{"credential": "abc"}')).toBe('{"credential": "***REDACTED***"}');expect(redactRawOutput("session_token: eyJ.session.value")).toBe("session_token: ***REDACTED***",);diff --git a/tests/core/pay-memory.report.test.ts b/tests/core/pay-memory.report.test.tsindex 70cdeb5f..f6cb1c90 100644--- a/tests/core/pay-memory.report.test.ts+++ b/tests/core/pay-memory.report.test.ts@@ -4,13 +4,9 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { parseFrontmatter } from "../../src/core/vault.ts";-import {- aggregateReceipts,- writeReport,-} from "../../src/core/pay-memory/report.ts";+import { aggregateReceipts, writeReport } from "../../src/core/pay-memory/report.ts";import { writeReceipt } from "../../src/core/pay-memory/receipt.ts";-let tmp: string;beforeEach(() => {@@ -65,11 +61,7 @@ describe("aggregateReceipts", () => {writeReceipt(tmp, { ...baseReceipt, slug: "real-1" });const dir = join(tmp, "Brain", "payments", "2026-05-10");mkdirSync(dir, { recursive: true });- writeFileSync(- join(dir, "stray.md"),- "---\ntype: note\n---\n\nNot a receipt.\n",- "utf8",- );+ writeFileSync(join(dir, "stray.md"), "---\ntype: note\n---\n\nNot a receipt.\n", "utf8");writeFileSync(join(dir, "no-frontmatter.md"), "Just a note.\n", "utf8");const summaries = aggregateReceipts(tmp, "2026-05-10");expect(summaries.length).toBe(1);diff --git a/tests/core/redactor.test.ts b/tests/core/redactor.test.tsindex a602c3f4..f5e3b6d1 100644--- a/tests/core/redactor.test.ts+++ b/tests/core/redactor.test.ts@@ -1,10 +1,6 @@import { describe, expect, test } from "bun:test";-import {- normaliseTextField,- redactRawOutput,- sanitiseTextField,-} from "../../src/core/redactor.ts";+import { normaliseTextField, redactRawOutput, sanitiseTextField } from "../../src/core/redactor.ts";describe("redactRawOutput (cross-module backward compat)", () => {test("masks api_key in env-style assignment", () => {@@ -44,9 +40,7 @@ describe("normaliseTextField", () => {test("singleLine collapses \\n / \\r / \\t runs to single space", () => {const input = "a\n\nb\tc\r\nd";- expect(normaliseTextField(input, { maxLen: 100, singleLine: true })).toBe(- "a b c d",- );+ expect(normaliseTextField(input, { maxLen: 100, singleLine: true })).toBe("a b c d");});test("non-singleLine normalises CRLF/CR to LF", () => {diff --git a/tests/core/search/check-recommendations.test.ts b/tests/core/search/check-recommendations.test.tsindex 7cf40d25..871909d0 100644--- a/tests/core/search/check-recommendations.test.ts+++ b/tests/core/search/check-recommendations.test.ts@@ -52,12 +52,8 @@ test("semantic enabled, no key → recipe mentions the env var and the provider"semantic: { enabled: true, apiKey: null, model: "text-embedding-3-small" },});const r = await indexCheck(cfg);- expect(- r.recommendations.some((s) => s.includes("OPEN_SECOND_BRAIN_EMBEDDING_KEY")),- ).toBe(true);- expect(- r.recommendations.some((s) => s.includes("text-embedding-3-small")),- ).toBe(true);+ expect(r.recommendations.some((s) => s.includes("OPEN_SECOND_BRAIN_EMBEDDING_KEY"))).toBe(true);+ expect(r.recommendations.some((s) => s.includes("text-embedding-3-small"))).toBe(true);});test("vec unavailable on Darwin → brew sqlite recipe", async () => {@@ -74,9 +70,7 @@ test("vec unavailable on Darwin → brew sqlite recipe", async () => {// host. The Darwin recommendation only appears when vec didn't// load — assert conditional on the report's own field.if (r.vecExtension === "unavailable") {- expect(- r.recommendations.some((s) => s.includes("brew install sqlite")),- ).toBe(true);+ expect(r.recommendations.some((s) => s.includes("brew install sqlite"))).toBe(true);}});@@ -89,12 +83,8 @@ test("vec unavailable on Linux → bun pm hint, no brew mention", async () => {});const r = await indexCheck(cfg);if (r.vecExtension === "unavailable") {- expect(- r.recommendations.some((s) => s.includes("bun pm ls")),- ).toBe(true);- expect(- r.recommendations.every((s) => !s.includes("brew install")),- ).toBe(true);+ expect(r.recommendations.some((s) => s.includes("bun pm ls"))).toBe(true);+ expect(r.recommendations.every((s) => !s.includes("brew install"))).toBe(true);}});diff --git a/tests/core/search/embeddings.test.ts b/tests/core/search/embeddings.test.tsindex a8f9ac1e..d18770db 100644--- a/tests/core/search/embeddings.test.ts+++ b/tests/core/search/embeddings.test.ts@@ -55,10 +55,10 @@ test("embed() preserves input order across batches", async () => {test("embed() sorts response.data by `index` even if server returns shuffled", async () => {server.setHandler((req) => {- const body = (req.body as { input: string[]; model: string });+ const body = req.body as { input: string[]; model: string };const indices = body.input.map((_, i) => i);// Shuffle: reverse.- const shuffled = [...indices].reverse();+ const shuffled = [...indices].toReversed();const data = shuffled.map((origIdx) => {const text = body.input[origIdx]!;const v = [text.length, origIdx, 1, 1];diff --git a/tests/core/search/fts.test.ts b/tests/core/search/fts.test.tsindex f84f6127..fe4f477c 100644--- a/tests/core/search/fts.test.ts+++ b/tests/core/search/fts.test.ts@@ -130,4 +130,3 @@ test("runFtsQuery survives FTS5-operator-like queries safely", async () => {expect(hits.length).toBeGreaterThan(0);await store.close();});-diff --git a/tests/core/search/indexer.embeddings.test.ts b/tests/core/search/indexer.embeddings.test.tsindex d1f7b0df..b9a9db11 100644--- a/tests/core/search/indexer.embeddings.test.ts+++ b/tests/core/search/indexer.embeddings.test.ts@@ -5,6 +5,7 @@ import { Store } from "../../../src/core/search/store.ts";import { SearchError } from "../../../src/core/search/types.ts";import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";let vault: string;let dbPath: string;@@ -43,6 +44,7 @@ function semanticConfig(model = "fake-model", dim = 4) {}test("index --embeddings populates chunk_vec for new chunks", async () => {+ if (!sqliteVecLoadable()) return;writeMd(vault, "a.md", "# A\n\nFirst note about something.");writeMd(vault, "b.md", "# B\n\nSecond note discussing things.");const cfg = semanticConfig();@@ -57,6 +59,7 @@ test("index --embeddings populates chunk_vec for new chunks", async () => {});test("unchanged files do NOT trigger re-embedding on the next run", async () => {+ if (!sqliteVecLoadable()) return;writeMd(vault, "a.md", "# A\n\nHello.");const cfg = semanticConfig();await indexVault(cfg, { embeddings: true });@@ -68,12 +71,17 @@ test("unchanged files do NOT trigger re-embedding on the next run", async () =>});test("changing the embedding model drops embeddings and the next index repopulates", async () => {+ if (!sqliteVecLoadable()) return;writeMd(vault, "a.md", "# A\n\nHello.");- const first = await indexVault(semanticConfig("modelA", 4), { embeddings: true });+ const first = await indexVault(semanticConfig("modelA", 4), {+ embeddings: true,+ });expect(first.embeddingsComputed).toBeGreaterThan(0);const before = server.callCount();- const second = await indexVault(semanticConfig("modelB", 4), { embeddings: true });+ const second = await indexVault(semanticConfig("modelB", 4), {+ embeddings: true,+ });// All chunks re-embedded under the new model.expect(second.embeddingsComputed).toBeGreaterThan(0);expect(server.callCount()).toBeGreaterThan(before);@@ -129,7 +137,9 @@ test("onFile callback fires for every classification", async () => {writeMd(vault, "new.md", "# C");const events: Array<{ kind: string; path: string }> = [];- await indexVault(cfg, { onFile: (e) => events.push({ kind: e.kind, path: e.path }) });+ await indexVault(cfg, {+ onFile: (e) => events.push({ kind: e.kind, path: e.path }),+ });const kinds = new Set(events.map((e) => e.kind));expect(kinds.has("added")).toBe(true);diff --git a/tests/core/search/indexer.test.ts b/tests/core/search/indexer.test.tsindex 32a8da59..149cb720 100644--- a/tests/core/search/indexer.test.ts+++ b/tests/core/search/indexer.test.ts@@ -2,7 +2,12 @@ import { test, expect, beforeEach, afterEach } from "bun:test";import { existsSync, rmSync, utimesSync, writeFileSync } from "node:fs";import { join } from "node:path";-import { indexVault, reindexVault, indexStatus, indexCheck } from "../../../src/core/search/indexer.ts";+import {+ indexVault,+ reindexVault,+ indexStatus,+ indexCheck,+} from "../../../src/core/search/indexer.ts";import { Store } from "../../../src/core/search/store.ts";import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";@@ -51,7 +56,9 @@ test("modifying a file produces an `updated` event and replaces chunks", async (utimesSync(abs, t, t);const events: Array<{ path: string; kind: string }> = [];- const stats = await indexVault(cfg, { onFile: (e) => events.push({ path: e.path, kind: e.kind }) });+ const stats = await indexVault(cfg, {+ onFile: (e) => events.push({ path: e.path, kind: e.kind }),+ });expect(stats.updated).toBe(1);expect(events.find((e) => e.path === "x.md")?.kind).toBe("updated");@@ -184,4 +191,3 @@ test("mtime+size fastpath skips read; hash fallback detects same-content touch",expect(second.updated).toBe(0);expect(second.added).toBe(0);});-diff --git a/tests/core/search/property-filter.test.ts b/tests/core/search/property-filter.test.tsindex b423fe7d..8aae23d8 100644--- a/tests/core/search/property-filter.test.ts+++ b/tests/core/search/property-filter.test.ts@@ -46,26 +46,18 @@ describe("filterByProperties - shape", () => {describe("filterByProperties - single-key filter", () => {test("scalar match: type=decision", () => {- const r = filterByProperties(- ROWS,- new Map([["type", ["decision"]]]),- reader,- );- expect(r.map((x) => x.path).sort()).toEqual(["a.md", "b.md"]);+ const r = filterByProperties(ROWS, new Map([["type", ["decision"]]]), reader);+ expect(r.map((x) => x.path).toSorted()).toEqual(["a.md", "b.md"]);});test("multi-value filter (OR within key): status=open|closed", () => {- const r = filterByProperties(- ROWS,- new Map([["status", ["open", "closed"]]]),- reader,- );- expect(r.map((x) => x.path).sort()).toEqual(["a.md", "b.md", "c.md"]);+ const r = filterByProperties(ROWS, new Map([["status", ["open", "closed"]]]), reader);+ expect(r.map((x) => x.path).toSorted()).toEqual(["a.md", "b.md", "c.md"]);});test("array frontmatter value intersects requested set: tags=urgent", () => {const r = filterByProperties(ROWS, new Map([["tags", ["urgent"]]]), reader);- expect(r.map((x) => x.path).sort()).toEqual(["a.md", "c.md"]);+ expect(r.map((x) => x.path).toSorted()).toEqual(["a.md", "c.md"]);});});@@ -99,7 +91,7 @@ describe("filterByProperties - missing keys + null frontmatter", () => {test("missing key in row's frontmatter excludes the row", () => {const r = filterByProperties(ROWS, new Map([["tags", ["urgent"]]]), reader);// d.md has no `tags`, should be dropped.- expect(r.map((x) => x.path).sort()).toEqual(["a.md", "c.md"]);+ expect(r.map((x) => x.path).toSorted()).toEqual(["a.md", "c.md"]);});test("frontmatter reader returning null excludes the row", () => {diff --git a/tests/core/search/ranker-entity-boost.test.ts b/tests/core/search/ranker-entity-boost.test.tsindex bb9ae1cb..c88918e6 100644--- a/tests/core/search/ranker-entity-boost.test.ts+++ b/tests/core/search/ranker-entity-boost.test.ts@@ -8,10 +8,7 @@import { test, expect } from "bun:test";import { rankResults } from "../../../src/core/search/ranker.ts";-import type {- KeywordHit,- HydratedChunk,-} from "../../../src/core/search/store.ts";+import type { KeywordHit, HydratedChunk } from "../../../src/core/search/store.ts";function hyd(chunkId: number, docId: number): HydratedChunk {return Object.freeze({diff --git a/tests/core/search/ranker-reasons.test.ts b/tests/core/search/ranker-reasons.test.tsindex 3682a326..07cfc39b 100644--- a/tests/core/search/ranker-reasons.test.ts+++ b/tests/core/search/ranker-reasons.test.ts@@ -7,11 +7,7 @@import { test, expect } from "bun:test";import { rankResults } from "../../../src/core/search/ranker.ts";-import type {- KeywordHit,- SemanticHit,- HydratedChunk,-} from "../../../src/core/search/store.ts";+import type { KeywordHit, SemanticHit, HydratedChunk } from "../../../src/core/search/store.ts";function hyd(chunkId: number, docId: number, mtime: number): HydratedChunk {return Object.freeze({diff --git a/tests/core/search/ranker-tier.test.ts b/tests/core/search/ranker-tier.test.tsindex 895d0b66..14ab5de8 100644--- a/tests/core/search/ranker-tier.test.ts+++ b/tests/core/search/ranker-tier.test.ts@@ -9,17 +9,9 @@import { test, expect } from "bun:test";import { rankResults } from "../../../src/core/search/ranker.ts";-import type {- KeywordHit,- SemanticHit,- HydratedChunk,-} from "../../../src/core/search/store.ts";+import type { KeywordHit, SemanticHit, HydratedChunk } from "../../../src/core/search/store.ts";-function hyd(- chunkId: number,- docId: number,- mtime: number,-): HydratedChunk {+function hyd(chunkId: number, docId: number, mtime: number): HydratedChunk {return Object.freeze({chunkId,documentId: docId,@@ -35,9 +27,7 @@ function hyd(const NOW = 1_750_000_000_000;const OLD = NOW / 1000 - 365 * 24 * 3600;-function rank(- tierByDoc?: ReadonlyMap<number, "core" | "supporting" | "peripheral">,-) {+function rank(tierByDoc?: ReadonlyMap<number, "core" | "supporting" | "peripheral">) {// Varied bm25 values produce a non-degenerate normalized spread// (min-max ≠ 0) so the tier multiplier has headroom below clamp01.// Lower keyword weight keeps the weighted product comfortablydiff --git a/tests/core/search/ranker.test.ts b/tests/core/search/ranker.test.tsindex 7fd79a30..27bf5fe3 100644--- a/tests/core/search/ranker.test.ts+++ b/tests/core/search/ranker.test.ts@@ -17,7 +17,7 @@ function hyd(chunkId: number, docId: number, mtime: number): HydratedChunk {const NOW = 1_750_000_000_000; // msconst RECENT_MTIME = NOW / 1000 - 3 * 24 * 3600; // 3 days ago in unix seconds → 0.05 recency-const OLD_MTIME = NOW / 1000 - 365 * 24 * 3600; // >90d → 0 recency+const OLD_MTIME = NOW / 1000 - 365 * 24 * 3600; // >90d → 0 recencytest("union of keyword + semantic produces hybrid scoring", () => {const kw: KeywordHit[] = [diff --git a/tests/core/search/schema.test.ts b/tests/core/search/schema.test.tsindex d18f55f4..b8e4d466 100644--- a/tests/core/search/schema.test.ts+++ b/tests/core/search/schema.test.ts@@ -89,10 +89,9 @@ test("applyMigrations throws SCHEMA_MISMATCH if db is newer than binary", () =>const db = new Database(dbPath);applyMigrations(db);// Simulate a future version.- db.run(- "UPDATE index_state SET value = ? WHERE key = 'schema_version'",- [String(LATEST_SCHEMA_VERSION + 7)],- );+ db.run("UPDATE index_state SET value = ? WHERE key = 'schema_version'", [+ String(LATEST_SCHEMA_VERSION + 7),+ ]);let err: SearchError | null = null;try {@@ -127,7 +126,9 @@ test("ensureVecTable + dropVecTable round-trip", () => {expect(tables.has("chunk_vec")).toBe(true);// Insert a vector.- db.run("INSERT INTO chunk_vec(rowid, embedding) VALUES (1, ?)", [JSON.stringify([0.1, 0.2, 0.3, 0.4])]);+ db.run("INSERT INTO chunk_vec(rowid, embedding) VALUES (1, ?)", [+ JSON.stringify([0.1, 0.2, 0.3, 0.4]),+ ]);const row = db.query<{ c: number }, []>("SELECT count(*) AS c FROM chunk_vec").get();expect(row?.c).toBe(1);diff --git a/tests/core/search/search.test.ts b/tests/core/search/search.test.tsindex 93dbfa75..d0dc0da1 100644--- a/tests/core/search/search.test.ts+++ b/tests/core/search/search.test.ts@@ -5,6 +5,7 @@ import { search } from "../../../src/core/search/search.ts";import { SearchError } from "../../../src/core/search/types.ts";import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";let vault: string;let dbPath: string;@@ -85,7 +86,11 @@ test("path_prefix filter scopes results", async () => {await indexVault(cfg);const all = await search(cfg, { query: "quick", limit: 5 });expect(all.results.length).toBe(1);- const scoped = await search(cfg, { query: "quick", limit: 5, pathPrefix: "Other/" });+ const scoped = await search(cfg, {+ query: "quick",+ limit: 5,+ pathPrefix: "Other/",+ });expect(scoped.results.length).toBe(0);});@@ -126,6 +131,7 @@ test("missing index throws INDEX_MISSING", async () => {});test("hybrid search combines keyword and semantic when both contribute", async () => {+ if (!sqliteVecLoadable()) return;writeMd(vault, "A/foo.md", "alpha beta gamma");writeMd(vault, "A/bar.md", "delta epsilon zeta");const cfg = semanticConfig();diff --git a/tests/core/search/store-entities.test.ts b/tests/core/search/store-entities.test.tsindex 14def238..086a831d 100644--- a/tests/core/search/store-entities.test.ts+++ b/tests/core/search/store-entities.test.ts@@ -27,7 +27,13 @@ async function open() {}async function seedChunk(store: Store): Promise<number> {- const doc = store.upsertDocument({ path: "a.md", title: "A", contentHash: "h", mtime: 1, size: 1 });+ const doc = store.upsertDocument({+ path: "a.md",+ title: "A",+ contentHash: "h",+ mtime: 1,+ size: 1,+ });const ids = store.replaceChunks(doc, [{ chunkIndex: 0, content: "body", contentHash: "c0", startLine: 1, endLine: 1, tokenCount: 1 },]);diff --git a/tests/core/search/store-outbound-links.test.ts b/tests/core/search/store-outbound-links.test.tsindex 92e973d1..9507cd3a 100644--- a/tests/core/search/store-outbound-links.test.ts+++ b/tests/core/search/store-outbound-links.test.ts@@ -24,18 +24,64 @@ async function seed() {mode: "write",loadVec: false,});- const a = store.upsertDocument({ path: "a.md", title: "A", contentHash: "ha", mtime: 1, size: 1 });- const b = store.upsertDocument({ path: "b.md", title: "B", contentHash: "hb", mtime: 1, size: 1 });- const c = store.upsertDocument({ path: "c.md", title: "C", contentHash: "hc", mtime: 1, size: 1 });+ const a = store.upsertDocument({+ path: "a.md",+ title: "A",+ contentHash: "ha",+ mtime: 1,+ size: 1,+ });+ const b = store.upsertDocument({+ path: "b.md",+ title: "B",+ contentHash: "hb",+ mtime: 1,+ size: 1,+ });+ const c = store.upsertDocument({+ path: "c.md",+ title: "C",+ contentHash: "hc",+ mtime: 1,+ size: 1,+ });const aChunks = store.replaceChunks(a, [- { chunkIndex: 0, content: "alpha head", contentHash: "a0", startLine: 1, endLine: 1, tokenCount: 2 },- { chunkIndex: 1, content: "alpha tail", contentHash: "a1", startLine: 2, endLine: 2, tokenCount: 2 },+ {+ chunkIndex: 0,+ content: "alpha head",+ contentHash: "a0",+ startLine: 1,+ endLine: 1,+ tokenCount: 2,+ },+ {+ chunkIndex: 1,+ content: "alpha tail",+ contentHash: "a1",+ startLine: 2,+ endLine: 2,+ tokenCount: 2,+ },]);store.replaceChunks(b, [- { chunkIndex: 0, content: "beta body", contentHash: "b0", startLine: 1, endLine: 1, tokenCount: 2 },+ {+ chunkIndex: 0,+ content: "beta body",+ contentHash: "b0",+ startLine: 1,+ endLine: 1,+ tokenCount: 2,+ },]);store.replaceChunks(c, [- { chunkIndex: 0, content: "gamma body", contentHash: "c0", startLine: 1, endLine: 1, tokenCount: 2 },+ {+ chunkIndex: 0,+ content: "gamma body",+ contentHash: "c0",+ startLine: 1,+ endLine: 1,+ tokenCount: 2,+ },]);// a -> b (wikilink), a -> c (markdown_link), a -> a (self, must be ignored),// a -> #tag (tag, must be ignored for traversal).@@ -52,8 +98,8 @@ async function seed() {test("outboundLinkTargets returns resolved wikilink/markdown targets, excluding self and tags", async () => {const { store, a, b, c } = await seed();const map = store.outboundLinkTargets([a]);- const targets = (map.get(a) ?? []).slice().sort((x, y) => x - y);- expect(targets).toEqual([b, c].sort((x, y) => x - y));+ const targets = (map.get(a) ?? []).slice().toSorted((x, y) => x - y);+ expect(targets).toEqual([b, c].toSorted((x, y) => x - y));await store.close();});diff --git a/tests/core/search/store.test.ts b/tests/core/search/store.test.tsindex 63d2e9e5..3442cb90 100644--- a/tests/core/search/store.test.ts+++ b/tests/core/search/store.test.ts@@ -5,7 +5,10 @@ import { join } from "node:path";import { Store } from "../../../src/core/search/store.ts";import { SearchError } from "../../../src/core/search/types.ts";-import type { ResolvedSearchConfig, ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";+import type {+ ResolvedSearchConfig,+ ResolvedEmbeddingConfig,+} from "../../../src/core/search/types.ts";let tmp: string;let dbPath: string;@@ -32,7 +35,7 @@ function makeConfig(overrides?: Partial<ResolvedSearchConfig>): ResolvedSearchCosemanticWeight: 0.4,semantic,recall: Object.freeze({ mmrLambda: 0.7, maxHops: 1, hopDecay: 0.5, maxExpansionPerHit: 3 }),- ...(overrides ?? {}),+ ...overrides,});}@@ -142,10 +145,24 @@ test("replaceChunks twice replaces all old chunks", async () => {size: 1,});store.replaceChunks(docId, [- { chunkIndex: 0, content: "alpha bravo", contentHash: "c0", startLine: 1, endLine: 1, tokenCount: 2 },+ {+ chunkIndex: 0,+ content: "alpha bravo",+ contentHash: "c0",+ startLine: 1,+ endLine: 1,+ tokenCount: 2,+ },]);store.replaceChunks(docId, [- { chunkIndex: 0, content: "charlie delta", contentHash: "c1", startLine: 1, endLine: 1, tokenCount: 2 },+ {+ chunkIndex: 0,+ content: "charlie delta",+ contentHash: "c1",+ startLine: 1,+ endLine: 1,+ tokenCount: 2,+ },]);expect(store.keywordTopK("alpha", { limit: 5 }).length).toBe(0);expect(store.keywordTopK("charlie", { limit: 5 }).length).toBe(1);@@ -163,7 +180,14 @@ test("deleteDocument cascades to chunks and FTS", async () => {size: 1,});store.replaceChunks(docId, [- { chunkIndex: 0, content: "doomed content", contentHash: "c", startLine: 1, endLine: 1, tokenCount: 2 },+ {+ chunkIndex: 0,+ content: "doomed content",+ contentHash: "c",+ startLine: 1,+ endLine: 1,+ tokenCount: 2,+ },]);expect(store.keywordTopK("doomed", { limit: 5 }).length).toBe(1);@@ -175,13 +199,39 @@ test("deleteDocument cascades to chunks and FTS", async () => {test("path-prefix filter constrains keywordTopK", async () => {const store = await Store.open(makeConfig(), { mode: "write", loadVec: false });- const d1 = store.upsertDocument({ path: "A/foo.md", title: null, contentHash: "h", mtime: 0, size: 1 });- const d2 = store.upsertDocument({ path: "B/bar.md", title: null, contentHash: "h", mtime: 0, size: 1 });+ const d1 = store.upsertDocument({+ path: "A/foo.md",+ title: null,+ contentHash: "h",+ mtime: 0,+ size: 1,+ });+ const d2 = store.upsertDocument({+ path: "B/bar.md",+ title: null,+ contentHash: "h",+ mtime: 0,+ size: 1,+ });store.replaceChunks(d1, [- { chunkIndex: 0, content: "alpha alpha alpha", contentHash: "c", startLine: 1, endLine: 1, tokenCount: 3 },+ {+ chunkIndex: 0,+ content: "alpha alpha alpha",+ contentHash: "c",+ startLine: 1,+ endLine: 1,+ tokenCount: 3,+ },]);store.replaceChunks(d2, [- { chunkIndex: 0, content: "alpha bravo", contentHash: "c", startLine: 1, endLine: 1, tokenCount: 2 },+ {+ chunkIndex: 0,+ content: "alpha bravo",+ contentHash: "c",+ startLine: 1,+ endLine: 1,+ tokenCount: 2,+ },]);const hitsA = store.keywordTopK("alpha", { limit: 10, pathPrefix: "A/" });expect(hitsA.length).toBe(1);@@ -191,13 +241,39 @@ test("path-prefix filter constrains keywordTopK", async () => {test("path-prefix filter treats SQL wildcard characters literally", async () => {const store = await Store.open(makeConfig(), { mode: "write", loadVec: false });- const literal = store.upsertDocument({ path: "A_/foo.md", title: null, contentHash: "h1", mtime: 0, size: 1 });- const wildcardMatch = store.upsertDocument({ path: "AB/bar.md", title: null, contentHash: "h2", mtime: 0, size: 1 });+ const literal = store.upsertDocument({+ path: "A_/foo.md",+ title: null,+ contentHash: "h1",+ mtime: 0,+ size: 1,+ });+ const wildcardMatch = store.upsertDocument({+ path: "AB/bar.md",+ title: null,+ contentHash: "h2",+ mtime: 0,+ size: 1,+ });store.replaceChunks(literal, [- { chunkIndex: 0, content: "alpha literal", contentHash: "c1", startLine: 1, endLine: 1, tokenCount: 2 },+ {+ chunkIndex: 0,+ content: "alpha literal",+ contentHash: "c1",+ startLine: 1,+ endLine: 1,+ tokenCount: 2,+ },]);store.replaceChunks(wildcardMatch, [- { chunkIndex: 0, content: "alpha wildcard", contentHash: "c2", startLine: 1, endLine: 1, tokenCount: 2 },+ {+ chunkIndex: 0,+ content: "alpha wildcard",+ contentHash: "c2",+ startLine: 1,+ endLine: 1,+ tokenCount: 2,+ },]);const hits = store.keywordTopK("alpha", { limit: 10, pathPrefix: "A_/" });expect(hits.map((h) => h.documentId)).toEqual([literal]);@@ -206,7 +282,13 @@ test("path-prefix filter treats SQL wildcard characters literally", async () =>test("counts() reflects documents/chunks", async () => {const store = await Store.open(makeConfig(), { mode: "write", loadVec: false });- const d = store.upsertDocument({ path: "a.md", title: null, contentHash: "h", mtime: 0, size: 1 });+ const d = store.upsertDocument({+ path: "a.md",+ title: null,+ contentHash: "h",+ mtime: 0,+ size: 1,+ });store.replaceChunks(d, [{ chunkIndex: 0, content: "one", contentHash: "c0", startLine: 1, endLine: 1, tokenCount: 1 },{ chunkIndex: 1, content: "two", contentHash: "c1", startLine: 2, endLine: 2, tokenCount: 1 },@@ -252,9 +334,7 @@ test("ensureEmbeddingModel sets state on first call and clears on change", asynctest("vecUpsert without sqlite-vec throws VEC_EXTENSION_UNAVAILABLE", async () => {const store = await Store.open(makeConfig(), { mode: "write", loadVec: false });- expect(() =>- store.vecUpsert(1, [0.1, 0.2, 0.3], "m", 3, "h"),- ).toThrow(/sqlite-vec/);+ expect(() => store.vecUpsert(1, [0.1, 0.2, 0.3], "m", 3, "h")).toThrow(/sqlite-vec/);await store.close();});diff --git a/tests/core/search/store.vec.test.ts b/tests/core/search/store.vec.test.tsindex e8456c7f..daf798fe 100644--- a/tests/core/search/store.vec.test.ts+++ b/tests/core/search/store.vec.test.ts@@ -4,12 +4,20 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { Store } from "../../../src/core/search/store.ts";-import type { ResolvedSearchConfig, ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";+import type {+ ResolvedSearchConfig,+ ResolvedEmbeddingConfig,+} from "../../../src/core/search/types.ts";+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";let tmp: string;let dbPath: string;-function semanticConfig(model: string, dim: number, overrides?: Partial<ResolvedSearchConfig>): ResolvedSearchConfig {+function semanticConfig(+ model: string,+ dim: number,+ overrides?: Partial<ResolvedSearchConfig>,+): ResolvedSearchConfig {const semantic: ResolvedEmbeddingConfig = Object.freeze({enabled: true,provider: "openai-compat",@@ -30,8 +38,13 @@ function semanticConfig(model: string, dim: number, overrides?: Partial<ResolvedkeywordWeight: 0.6,semanticWeight: 0.4,semantic,- recall: Object.freeze({ mmrLambda: 0.7, maxHops: 1, hopDecay: 0.5, maxExpansionPerHit: 3 }),- ...(overrides ?? {}),+ recall: Object.freeze({+ mmrLambda: 0.7,+ maxHops: 1,+ hopDecay: 0.5,+ maxExpansionPerHit: 3,+ }),+ ...overrides,});}@@ -44,15 +57,6 @@ afterEach(() => {rmSync(tmp, { recursive: true, force: true });});-function vecAvailable(): boolean {- try {- require("sqlite-vec");- return true;- } catch {- return false;- }-}-function unit(values: number[]): number[] {const norm = Math.hypot(...values);if (norm === 0) return values;@@ -60,7 +64,7 @@ function unit(values: number[]): number[] {}test("vec round-trip when sqlite-vec is loaded", async () => {- if (!vecAvailable()) return;+ if (!sqliteVecLoadable()) return;const store = await Store.open(semanticConfig("m1", 4), { mode: "write" });expect(store.vecLoaded()).toBe(true);@@ -72,8 +76,22 @@ test("vec round-trip when sqlite-vec is loaded", async () => {size: 1,});const [c0, c1] = store.replaceChunks(docId, [- { chunkIndex: 0, content: "alpha", contentHash: "h0", startLine: 1, endLine: 1, tokenCount: 1 },- { chunkIndex: 1, content: "bravo", contentHash: "h1", startLine: 2, endLine: 2, tokenCount: 1 },+ {+ chunkIndex: 0,+ content: "alpha",+ contentHash: "h0",+ startLine: 1,+ endLine: 1,+ tokenCount: 1,+ },+ {+ chunkIndex: 1,+ content: "bravo",+ contentHash: "h1",+ startLine: 2,+ endLine: 2,+ tokenCount: 1,+ },]);store.vecUpsert(c0!, unit([1, 0, 0, 0]), "m1", 4, "eh0");@@ -89,7 +107,7 @@ test("vec round-trip when sqlite-vec is loaded", async () => {});test("deleting a document leaves zero rows in chunk_vec/chunk_vec_map", async () => {- if (!vecAvailable()) return;+ if (!sqliteVecLoadable()) return;const store = await Store.open(semanticConfig("m1", 4), { mode: "write" });const docId = store.upsertDocument({path: "vec/b.md",@@ -99,8 +117,22 @@ test("deleting a document leaves zero rows in chunk_vec/chunk_vec_map", async ()size: 1,});const [c0, c1] = store.replaceChunks(docId, [- { chunkIndex: 0, content: "x", contentHash: "h0", startLine: 1, endLine: 1, tokenCount: 1 },- { chunkIndex: 1, content: "y", contentHash: "h1", startLine: 2, endLine: 2, tokenCount: 1 },+ {+ chunkIndex: 0,+ content: "x",+ contentHash: "h0",+ startLine: 1,+ endLine: 1,+ tokenCount: 1,+ },+ {+ chunkIndex: 1,+ content: "y",+ contentHash: "h1",+ startLine: 2,+ endLine: 2,+ tokenCount: 1,+ },]);store.vecUpsert(c0!, unit([1, 0, 0, 0]), "m1", 4, "eh0");store.vecUpsert(c1!, unit([0, 1, 0, 0]), "m1", 4, "eh1");@@ -120,7 +152,7 @@ test("deleting a document leaves zero rows in chunk_vec/chunk_vec_map", async ()});test("ensureEmbeddingModel drops chunk_vec when dimension changes", async () => {- if (!vecAvailable()) return;+ if (!sqliteVecLoadable()) return;const store = await Store.open(semanticConfig("m1", 4), { mode: "write" });// Touch the vec table to confirm it exists.@@ -146,7 +178,7 @@ test("ensureEmbeddingModel drops chunk_vec when dimension changes", async () =>});test("dimension mismatch is rejected on vecUpsert", async () => {- if (!vecAvailable()) return;+ if (!sqliteVecLoadable()) return;const store = await Store.open(semanticConfig("m1", 4), { mode: "write" });const docId = store.upsertDocument({path: "z.md",@@ -156,7 +188,14 @@ test("dimension mismatch is rejected on vecUpsert", async () => {size: 1,});const [c0] = store.replaceChunks(docId, [- { chunkIndex: 0, content: "x", contentHash: "h", startLine: 1, endLine: 1, tokenCount: 1 },+ {+ chunkIndex: 0,+ content: "x",+ contentHash: "h",+ startLine: 1,+ endLine: 1,+ tokenCount: 1,+ },]);expect(() => store.vecUpsert(c0!, [0.1, 0.2, 0.3], "m1", 4, "eh")).toThrow(/dimension/);await store.close();diff --git a/tests/core/search/traversal.test.ts b/tests/core/search/traversal.test.tsindex bf151991..1fc72362 100644--- a/tests/core/search/traversal.test.ts+++ b/tests/core/search/traversal.test.ts@@ -130,6 +130,6 @@ test("results stay sorted by score descending after expansion", () => {OPTS,);const scores = out.map((r) => r.score);- const sorted = [...scores].sort((a, b) => b - a);+ const sorted = [...scores].toSorted((a, b) => b - a);expect(scores).toEqual(sorted);});diff --git a/tests/core/search/walker.test.ts b/tests/core/search/walker.test.tsindex 345b5cfe..c2dfc205 100644--- a/tests/core/search/walker.test.ts+++ b/tests/core/search/walker.test.ts@@ -4,7 +4,12 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { walkVault } from "../../../src/core/search/walker.ts";-import { createTempVault, writeMd, writeSymlink, makeConfig } from "../../helpers/search-fixtures.ts";+import {+ createTempVault,+ writeMd,+ writeSymlink,+ makeConfig,+} from "../../helpers/search-fixtures.ts";let vault: string;let cleanup: () => void;@@ -22,7 +27,7 @@ afterEach(() => {function collect(cfg: ReturnType<typeof makeConfig>): string[] {const out: string[] = [];for (const f of walkVault(cfg)) out.push(f.relPath);- return out.sort();+ return out.toSorted();}test("returns *.md files relative to vault, POSIX paths", () => {diff --git a/tests/core/validate.test.ts b/tests/core/validate.test.tsnew file mode 100644index 00000000..c4955c4d--- /dev/null+++ b/tests/core/validate.test.ts@@ -0,0 +1,46 @@+import { describe, expect, test } from "bun:test";++import { parseOptionalFiniteNumberInput } from "../../src/core/validate.ts";++describe("parseOptionalFiniteNumberInput", () => {+ test("treats absent and blank values as not provided", () => {+ expect(parseOptionalFiniteNumberInput(undefined)).toEqual({+ value: null,+ error: null,+ });+ expect(parseOptionalFiniteNumberInput(null)).toEqual({+ value: null,+ error: null,+ });+ expect(parseOptionalFiniteNumberInput(" ")).toEqual({+ value: null,+ error: null,+ });+ });++ test("accepts finite numbers and numeric strings", () => {+ expect(parseOptionalFiniteNumberInput(0.05)).toEqual({+ value: 0.05,+ error: null,+ });+ expect(parseOptionalFiniteNumberInput(" 0.05 ")).toEqual({+ value: 0.05,+ error: null,+ });+ });++ test("classifies non-finite numbers separately from bad shapes", () => {+ expect(parseOptionalFiniteNumberInput(Number.NaN)).toEqual({+ value: null,+ error: "finite-number",+ });+ expect(parseOptionalFiniteNumberInput("abc")).toEqual({+ value: null,+ error: "number-or-numeric-string",+ });+ expect(parseOptionalFiniteNumberInput(true)).toEqual({+ value: null,+ error: "number-or-numeric-string",+ });+ });+});diff --git a/tests/core/vault-scope.test.ts b/tests/core/vault-scope.test.tsindex 841f4213..4f633434 100644--- a/tests/core/vault-scope.test.ts+++ b/tests/core/vault-scope.test.ts@@ -215,9 +215,7 @@ test("walkVaultScope: counts included files+dirs and reports excluded subtree onexpect(obsidianHit).toBeTruthy();expect(obsidianHit?.rule.raw).toBe(".obsidian");// Subtree descendants must NOT be reported separately.- expect(- walk.excludedDirs.filter((d) => d.relPath.startsWith(".obsidian/")),- ).toHaveLength(0);+ expect(walk.excludedDirs.filter((d) => d.relPath.startsWith(".obsidian/"))).toHaveLength(0);});test("walkVaultScope: file-level rule excludes a single file but not the parent", () => {diff --git a/tests/core/vault.test.ts b/tests/core/vault.test.tsindex 9d70bf96..e89c1621 100644--- a/tests/core/vault.test.ts+++ b/tests/core/vault.test.ts@@ -24,10 +24,7 @@ afterEach(() => {describe("parseFrontmatter", () => {test("extracts simple key/value fields", () => {const path = join(tmp, "note.md");- writeFileSync(- path,- "---\ntitle: Hello World\ntags: test, example\n---\n\nBody text.\n",- );+ writeFileSync(path, "---\ntitle: Hello World\ntags: test, example\n---\n\nBody text.\n");const [meta, body] = parseFrontmatter(path);expect(meta["title"]).toBe("Hello World");expect(meta["tags"]).toBe("test, example");diff --git a/tests/discipline/activity-git.test.ts b/tests/discipline/activity-git.test.tsindex 5b378b89..d4fc1b00 100644--- a/tests/discipline/activity-git.test.ts+++ b/tests/discipline/activity-git.test.ts@@ -13,14 +13,20 @@ beforeAll(() => {execSync("git init -q -b main", { cwd: repo });execSync("git config user.email t@t && git config user.name t", { cwd: repo });writeFileSync(join(repo, "a.txt"), "hello\n");- execSync("git add a.txt && git commit -q -m c1 --date=2026-05-17T10:00:00Z",- { cwd: repo, env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T10:00:00Z" } });+ execSync("git add a.txt && git commit -q -m c1 --date=2026-05-17T10:00:00Z", {+ cwd: repo,+ env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T10:00:00Z" },+ });writeFileSync(join(repo, "a.txt"), "hello\nworld\n");- execSync("git add a.txt && git commit -q -m c2 --date=2026-05-17T20:00:00Z",- { cwd: repo, env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T20:00:00Z" } });+ execSync("git add a.txt && git commit -q -m c2 --date=2026-05-17T20:00:00Z", {+ cwd: repo,+ env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T20:00:00Z" },+ });writeFileSync(join(repo, "b.txt"), "x\n");- execSync("git add b.txt && git commit -q -m c3 --date=2026-05-18T10:00:00Z",- { cwd: repo, env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-18T10:00:00Z" } });+ execSync("git add b.txt && git commit -q -m c3 --date=2026-05-18T10:00:00Z", {+ cwd: repo,+ env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-18T10:00:00Z" },+ });});afterAll(() => rmSync(repo, { recursive: true, force: true }));diff --git a/tests/discipline/activity-mtime.test.ts b/tests/discipline/activity-mtime.test.tsindex 4101d062..2dbd8cb5 100644--- a/tests/discipline/activity-mtime.test.ts+++ b/tests/discipline/activity-mtime.test.ts@@ -1,7 +1,5 @@import { describe, expect, test } from "bun:test";-import {- mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";diff --git a/tests/discipline/decision.test.ts b/tests/discipline/decision.test.tsindex 6564fd4c..9ef77c0a 100644--- a/tests/discipline/decision.test.ts+++ b/tests/discipline/decision.test.ts@@ -18,16 +18,21 @@ describe("decideStatus", () => {total: 4,} as any;const noActivity = {- repo: [], nonRepo: [], vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ repo: [],+ nonRepo: [],+ vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },} as any;const someRepoActivity = {- ...noActivity, repo: [{ path: "/a", git: { commits: 2, filesChanged: 1, insertions: 1, deletions: 0 } }],+ ...noActivity,+ repo: [{ path: "/a", git: { commits: 2, filesChanged: 1, insertions: 1, deletions: 0 } }],};const someMtimeActivity = {- ...noActivity, nonRepo: [{ path: "/b", modifiedFiles: 5 }],+ ...noActivity,+ nonRepo: [{ path: "/b", modifiedFiles: 5 }],};const someVaultDelta = {- ...noActivity, vaultDelta: { newSignals: 0, newPreferences: 1, newRetired: 0, total: 1 },+ ...noActivity,+ vaultDelta: { newSignals: 0, newPreferences: 1, newRetired: 0, total: 1 },};test("0 events + 0 activity → info", () => {diff --git a/tests/discipline/log-counts.test.ts b/tests/discipline/log-counts.test.tsindex 14eec23b..ea033b87 100644--- a/tests/discipline/log-counts.test.ts+++ b/tests/discipline/log-counts.test.ts@@ -27,10 +27,7 @@ describe("countBrainEvents", () => {"## 11:00:00Z — promote\n- agent: @claude-vps-agent\n- promoted: 0\n\n" +"## 12:00:00Z — rollback\n- run_id: x\n";const v = vaultWithLog(body);- const out = countBrainEvents(v, "2026-05-17", [- "@claude-vps-agent",- "@codex-vps-agent",- ]);+ const out = countBrainEvents(v, "2026-05-17", ["@claude-vps-agent", "@codex-vps-agent"]);expect(out.byAgent["@claude-vps-agent"]).toEqual({feedback: 1,apply_evidence: 1,@@ -51,8 +48,7 @@ describe("countBrainEvents", () => {});test("agent missing from known_agents shows under unknownAgents", () => {- const body =- "## 08:00:00Z — feedback\n- agent: @stranger\n- topic: foo\n\n";+ const body = "## 08:00:00Z — feedback\n- agent: @stranger\n- topic: foo\n\n";const v = vaultWithLog(body);const out = countBrainEvents(v, "2026-05-17", ["@claude-vps-agent"]);expect(out.byAgent["@claude-vps-agent"]).toEqual({@@ -138,8 +134,7 @@ describe("countBrainEvents", () => {test("falls back to markdown for historical pre-v0.10.8 days", () => {// Pure-markdown fixture (no JSONL sidecar) - simulates a day from// before the JSONL writer existed.- const body =- "## 09:00:00Z — feedback\n- agent: @a-legacy\n- topic: old\n";+ const body = "## 09:00:00Z — feedback\n- agent: @a-legacy\n- topic: old\n";const v = vaultWithLog(body);const out = countBrainEvents(v, "2026-05-17", ["@a-legacy"]);expect(out.byAgent["@a-legacy"]!.feedback).toBe(1);diff --git a/tests/discipline/render.test.ts b/tests/discipline/render.test.tsindex f5d9a4ba..904a105c 100644--- a/tests/discipline/render.test.ts+++ b/tests/discipline/render.test.ts@@ -16,7 +16,12 @@ describe("renderReport", () => {total: 6,},activity: {- repo: [{ path: "/srv/projects/foo", git: { commits: 4, filesChanged: 27, insertions: 312, deletions: 148 } }],+ repo: [+ {+ path: "/srv/projects/foo",+ git: { commits: 4, filesChanged: 27, insertions: 312, deletions: 148 },+ },+ ],nonRepo: [],vaultDelta: { newSignals: 1, newPreferences: 0, newRetired: 0, total: 1 },},@@ -38,7 +43,11 @@ describe("renderReport", () => {localDate: "2026-05-17",timezone: "UTC",status: "alert",- events: { byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } }, unknownAgents: [], total: 0 },+ events: {+ byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } },+ unknownAgents: [],+ total: 0,+ },activity: {repo: [{ path: "/x", git: { commits: 3, filesChanged: 5, insertions: 10, deletions: 2 } }],nonRepo: [],@@ -55,7 +64,11 @@ describe("renderReport", () => {localDate: "2026-05-17",timezone: "UTC",status: "alert",- events: { byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } }, unknownAgents: [], total: 0 },+ events: {+ byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } },+ unknownAgents: [],+ total: 0,+ },activity: {repo: [{ path: "/x", git: { commits: 3, filesChanged: 5, insertions: 10, deletions: 2 } }],nonRepo: [],@@ -79,15 +92,17 @@ describe("renderReport", () => {localDate: "2026-05-17",timezone: "UTC",status: "alert",- events: { byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } }, unknownAgents: [], total: 0 },+ events: {+ byAgent: { "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 } },+ unknownAgents: [],+ total: 0,+ },activity: {repo: [{ path: "/x", git: { commits: 1, filesChanged: 1, insertions: 1, deletions: 0 } }],nonRepo: [],vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },transcripts: {- byRuntime: [- { runtime: "claudecode", fileCount: 0, agentHint: "claude-vps-agent" },- ],+ byRuntime: [{ runtime: "claudecode", fileCount: 0, agentHint: "claude-vps-agent" }],totalFiles: 0,},},diff --git a/tests/discipline/report.test.ts b/tests/discipline/report.test.tsindex a8116fc5..1ab2fa6f 100644--- a/tests/discipline/report.test.ts+++ b/tests/discipline/report.test.ts@@ -13,9 +13,11 @@ describe("runDisciplineReport", () => {writeFileSync(join(vault, "Brain", "_brain.yaml"),"schema_version: 1\ndiscipline_report:\n" +- " enabled: true\n timezone: UTC\n" +- " watched_paths:\n - " + vault + "/repo\n" +- " known_agents:\n - '@claude-vps-agent'\n",+ " enabled: true\n timezone: UTC\n" ++ " watched_paths:\n - " ++ vault ++ "/repo\n" ++ " known_agents:\n - '@claude-vps-agent'\n","utf8",);@@ -26,7 +28,11 @@ describe("runDisciplineReport", () => {writeFileSync(join(repo, "a.txt"), "hi\n");execSync("git add . && git commit -q -m c1", {cwd: repo,- env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T10:00:00Z", GIT_AUTHOR_DATE: "2026-05-17T10:00:00Z" },+ env: {+ ...process.env,+ GIT_COMMITTER_DATE: "2026-05-17T10:00:00Z",+ GIT_AUTHOR_DATE: "2026-05-17T10:00:00Z",+ },});const res = runDisciplineReport({diff --git a/tests/e2e/brain-capture-and-fields.test.ts b/tests/e2e/brain-capture-and-fields.test.tsindex d23c4fec..6a65b038 100644--- a/tests/e2e/brain-capture-and-fields.test.ts+++ b/tests/e2e/brain-capture-and-fields.test.ts@@ -13,14 +13,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdirSync,- mkdtempSync,- readFileSync,- readdirSync,- rmSync,- writeFileSync,-} from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";@@ -60,7 +53,7 @@ describe("capture + migration end-to-end", () => {["# Daily notes","",- "@osb feedback negative topic=e2e-inline principle=\"no e2e shortcuts\"",+ '@osb feedback negative topic=e2e-inline principle="no e2e shortcuts"',"",].join("\n"),"utf8",@@ -88,21 +81,17 @@ describe("capture + migration end-to-end", () => {const inlineSigs = readdirSync(inbox).filter((n) => n.startsWith("sig-"));expect(inlineSigs.length).toBe(1);// The .obsidian marker MUST NOT have produced a signal.- expect(- inlineSigs.some((n) => n.includes("e2e-obsidian-leak")),- ).toBe(false);+ expect(inlineSigs.some((n) => n.includes("e2e-obsidian-leak"))).toBe(false);// Step 4: import-session adds an independent signal from the// claude fixture (topic=mocking, distinct from e2e-inline).const fixturePath = resolve("tests/fixtures/sessions/claude-minimal.jsonl");- r = await runCli(- ["brain", "import-session", fixturePath, "--vault", vault],- { env: { OPEN_SECOND_BRAIN_CONFIG: config } },- );+ r = await runCli(["brain", "import-session", fixturePath, "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });expect(r.returncode).toBe(0);const sigsAfterImport = readdirSync(inbox).filter((n) => n.startsWith("sig-"));expect(sigsAfterImport.length).toBeGreaterThan(inlineSigs.length);-}, 60_000);});diff --git a/tests/e2e/v0.10.10-pull-channels.test.ts b/tests/e2e/v0.10.10-pull-channels.test.tsindex 41661250..0bea47a4 100644--- a/tests/e2e/v0.10.10-pull-channels.test.ts+++ b/tests/e2e/v0.10.10-pull-channels.test.ts@@ -17,20 +17,12 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import {- mkdtempSync,- readFileSync,- rmSync,-} from "node:fs";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { runCli } from "../helpers/run-cli.ts";-import {- JSONRPC_VERSION,- MCPServer,- PROTOCOL_VERSION,-} from "../../src/mcp/index.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";let tmp: string;let vault: string;@@ -62,10 +54,9 @@ describe("v0.10.10 pull-channels e2e", () => {// 2. CLI mirror of brain_note lands one event in Brain/log/<today>.md// plus the JSONL sidecar, with the configured identity.- r = await runCli(- ["brain", "note", "v0.10.10 released", "--vault", vault, "--json"],- { env: { OPEN_SECOND_BRAIN_CONFIG: config, VAULT_AGENT_NAME: "" } },- );+ r = await runCli(["brain", "note", "v0.10.10 released", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config, VAULT_AGENT_NAME: "" },+ });expect(r.returncode).toBe(0);const noteResult = JSON.parse(r.stdout);expect(noteResult.agent).toBe("tester");diff --git a/tests/helpers/fake-http.ts b/tests/helpers/fake-http.tsindex 4c0069dc..a46003fe 100644--- a/tests/helpers/fake-http.ts+++ b/tests/helpers/fake-http.ts@@ -7,7 +7,6 @@* `toBeCloseTo` checks stay stable).*/-export interface FakeRequest {readonly method: string;readonly path: string;@@ -22,7 +21,10 @@ export interface FakeResponseSpec {delayMs?: number;}-type Handler = (req: FakeRequest, callIndex: number) => FakeResponseSpec | Promise<FakeResponseSpec>;+type Handler = (+ req: FakeRequest,+ callIndex: number,+) => FakeResponseSpec | Promise<FakeResponseSpec>;export interface FakeHttp {url: string;@@ -72,13 +74,10 @@ export async function startFakeHttp(): Promise<FakeHttp> {if (resp.delayMs && resp.delayMs > 0) {await new Promise<void>((r) => setTimeout(r, resp.delayMs));}- return new Response(- resp.body === undefined ? "" : JSON.stringify(resp.body),- {- status: resp.status ?? 200,- headers: { "content-type": "application/json", ...(resp.headers ?? {}) },- },- );+ return new Response(resp.body === undefined ? "" : JSON.stringify(resp.body), {+ status: resp.status ?? 200,+ headers: { "content-type": "application/json", ...resp.headers },+ });},});diff --git a/tests/helpers/fixtures.ts b/tests/helpers/fixtures.tsindex f4c94867..fee58059 100644--- a/tests/helpers/fixtures.ts+++ b/tests/helpers/fixtures.ts@@ -6,10 +6,7 @@import { mkdirSync, writeFileSync } from "node:fs";import { join } from "node:path";-import {- BRAIN_MANUAL_FILE,- BRAIN_ROOT_REL,-} from "../../src/core/brain/paths.ts";+import { BRAIN_MANUAL_FILE, BRAIN_ROOT_REL } from "../../src/core/brain/paths.ts";export function createSandboxVault(root: string, name = "Sandbox Brain"): string {const vault = join(root, "sandbox-vault");diff --git a/tests/helpers/search-fixtures.ts b/tests/helpers/search-fixtures.tsindex 696ec41f..73b728b2 100644--- a/tests/helpers/search-fixtures.ts+++ b/tests/helpers/search-fixtures.ts@@ -11,10 +11,7 @@ import {DEFAULT_VAULT_IGNORE_PATHS,type VaultIgnoreRule,} from "../../src/core/vault-scope/defaults.ts";-import type {- ResolvedSearchConfig,- ResolvedEmbeddingConfig,-} from "../../src/core/search/types.ts";+import type { ResolvedSearchConfig, ResolvedEmbeddingConfig } from "../../src/core/search/types.ts";export function createTempVault(prefix: string): {vault: string;@@ -72,7 +69,7 @@ export function makeConfig(opts: {});const semantic: ResolvedEmbeddingConfig = Object.freeze({...baseSemantic,- ...(opts.semantic ?? {}),+ ...opts.semantic,});const paths = opts.ignorePaths ?? DEFAULT_VAULT_IGNORE_PATHS;const ignoreRules: ReadonlyArray<VaultIgnoreRule> = Object.freeze(diff --git a/tests/helpers/sqlite-vec.ts b/tests/helpers/sqlite-vec.tsnew file mode 100644index 00000000..c835d578--- /dev/null+++ b/tests/helpers/sqlite-vec.ts@@ -0,0 +1,21 @@+import { Database } from "bun:sqlite";++let cachedLoadable: boolean | null = null;++export function sqliteVecLoadable(): boolean {+ if (cachedLoadable !== null) return cachedLoadable;++ const db = new Database(":memory:");+ try {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const vec = require("sqlite-vec") as { getLoadablePath(): string };+ db.loadExtension(vec.getLoadablePath());+ db.query("SELECT vec_version()").get();+ cachedLoadable = true;+ } catch {+ cachedLoadable = false;+ } finally {+ db.close();+ }+ return cachedLoadable;+}diff --git a/tests/hooks/active-inject.test.ts b/tests/hooks/active-inject.test.tsindex bd3e4d50..e9f31828 100644--- a/tests/hooks/active-inject.test.ts+++ b/tests/hooks/active-inject.test.ts@@ -32,10 +32,7 @@ interface RunResult {readonly exit: number;}-async function runHook(- payload: unknown,- env: Record<string, string> = {},-): Promise<RunResult> {+async function runHook(payload: unknown, env: Record<string, string> = {}): Promise<RunResult> {// Bun.spawn env replaces (does not merge with) process.env when// provided. We explicitly forward PATH so `bun run` can resolve its// own toolchain on $PATH-only systems.@@ -102,10 +99,7 @@ describe("active-inject hook", () => {});test("stays silent when Brain/active.md does not exist", async () => {- const r = await runHook(- { hook_event_name: "SessionStart" },- { VAULT_DIR: vault },- );+ const r = await runHook({ hook_event_name: "SessionStart" }, { VAULT_DIR: vault });expect(r.exit).toBe(0);expect(r.stdout).toBe("");});@@ -118,9 +112,7 @@ describe("active-inject hook", () => {});test("stays silent on empty payload", async () => {- writeActive(- "---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\nbody\n",- );+ writeActive("---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\nbody\n");const proc = Bun.spawn(["bun", "run", HOOK], {stdin: "pipe",stdout: "pipe",@@ -146,10 +138,7 @@ describe("active-inject hook", () => {test("stays silent when active.md is empty whitespace only", async () => {writeActive(" \n \n");- const r = await runHook(- { hook_event_name: "SessionStart" },- { VAULT_DIR: vault },- );+ const r = await runHook({ hook_event_name: "SessionStart" }, { VAULT_DIR: vault });expect(r.exit).toBe(0);expect(r.stdout).toBe("");});diff --git a/tests/hooks/detect.test.ts b/tests/hooks/detect.test.tsindex 932c8a04..e536f259 100644--- a/tests/hooks/detect.test.ts+++ b/tests/hooks/detect.test.ts@@ -8,12 +8,9 @@ import {} from "../../hooks/lib/detect.ts";describe("isArtifactToolName", () => {- test.each([["Write"], ["Edit"], ["MultiEdit"], ["apply_patch"]])(- "%s is an artifact",- (name) => {- expect(isArtifactToolName(name)).toBe(true);- },- );+ test.each([["Write"], ["Edit"], ["MultiEdit"], ["apply_patch"]])("%s is an artifact", (name) => {+ expect(isArtifactToolName(name)).toBe(true);+ });test.each([["Bash"], ["Read"], ["Grep"], ["event_log_append"], ["second_brain_status"]])("%s is NOT an artifact",@@ -31,9 +28,7 @@ describe("isBrainEventToolName", () => {test("recognises `brain_feedback` (bare and decorated)", () => {expect(isBrainEventToolName("brain_feedback")).toBe(true);expect(- isBrainEventToolName(- "mcp__plugin_open-second-brain_open-second-brain__brain_feedback",- ),+ isBrainEventToolName("mcp__plugin_open-second-brain_open-second-brain__brain_feedback"),).toBe(true);expect(isBrainEventToolName("mcp__open-second-brain__brain_feedback")).toBe(true);});@@ -41,27 +36,21 @@ describe("isBrainEventToolName", () => {test("recognises `brain_apply_evidence` (bare and decorated)", () => {expect(isBrainEventToolName("brain_apply_evidence")).toBe(true);expect(- isBrainEventToolName(- "mcp__plugin_open-second-brain_open-second-brain__brain_apply_evidence",- ),+ isBrainEventToolName("mcp__plugin_open-second-brain_open-second-brain__brain_apply_evidence"),).toBe(true);});test("recognises `brain_note` (bare and decorated) — §32B", () => {expect(isBrainEventToolName("brain_note")).toBe(true);expect(- isBrainEventToolName(- "mcp__plugin_open-second-brain_open-second-brain-writer__brain_note",- ),+ isBrainEventToolName("mcp__plugin_open-second-brain_open-second-brain-writer__brain_note"),).toBe(true);});test("event_log_append no longer counts as a brain event — §32", () => {expect(isBrainEventToolName("event_log_append")).toBe(false);expect(- isBrainEventToolName(- "mcp__plugin_open-second-brain_open-second-brain__event_log_append",- ),+ isBrainEventToolName("mcp__plugin_open-second-brain_open-second-brain__event_log_append"),).toBe(false);expect(isBrainEventToolName("mcp__open-second-brain__event_log_append")).toBe(false);});@@ -112,10 +101,7 @@ describe("summarizeTurn", () => {});test("artifact + bash `vault-log` (deprecated, §32) does NOT clear guardrail", () => {- const s = summarizeTurn(- [{ name: "Write" }, { name: "Bash" }],- ["vault-log 'noted finding'"],- );+ const s = summarizeTurn([{ name: "Write" }, { name: "Bash" }], ["vault-log 'noted finding'"]);expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });});@@ -132,10 +118,7 @@ describe("summarizeTurn", () => {// does not append anything to the daily log. Regression guard// against an earlier, looser needle list that incorrectly// treated `o2b mcp` as a log call.- const s = summarizeTurn(- [{ name: "Write" }, { name: "Bash" }],- ["o2b mcp --vault /tmp/vault"],- );+ const s = summarizeTurn([{ name: "Write" }, { name: "Bash" }], ["o2b mcp --vault /tmp/vault"]);expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });});@@ -159,10 +142,7 @@ describe("summarizeTurn", () => {});test("artifact + `brain_apply_evidence` MCP call clears guardrail", () => {- const s = summarizeTurn([- { name: "apply_patch" },- { name: "brain_apply_evidence" },- ]);+ const s = summarizeTurn([{ name: "apply_patch" }, { name: "brain_apply_evidence" }]);expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });});@@ -202,7 +182,7 @@ describe("summarizeTurn", () => {test("echoing `o2b brain note` text does NOT clear guardrail", () => {const s = summarizeTurn([{ name: "Write" }, { name: "Bash" }],- ['echo \'o2b brain note "not executed"\''],+ ["echo 'o2b brain note \"not executed\"'"],);expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });});@@ -268,8 +248,7 @@ describe("detectHookRuntime", () => {test("Claude Code transcript path → claudecode", () => {expect(detectHookRuntime({- transcript_path:- "/Users/x/.claude/projects/-srv/projects/foo/abc.jsonl",+ transcript_path: "/Users/x/.claude/projects/-srv/projects/foo/abc.jsonl",}),).toBe("claudecode");});@@ -297,8 +276,7 @@ describe("detectHookRuntime", () => {detectHookRuntime({tool_name: "apply_patch",tool_input: {- input:- "*** Begin Patch\n*** Update File: /tmp/x\n*** End Patch",+ input: "*** Begin Patch\n*** Update File: /tmp/x\n*** End Patch",},}),).toBe("codex");diff --git a/tests/hooks/post-write-reminder.test.ts b/tests/hooks/post-write-reminder.test.tsindex 5803e301..52d982f7 100644--- a/tests/hooks/post-write-reminder.test.ts+++ b/tests/hooks/post-write-reminder.test.ts@@ -69,9 +69,7 @@ describe("post-write-reminder hook", () => {expect(r.exit).toBe(0);const out = JSON.parse(r.stdout);expect(out.hookSpecificOutput.additionalContext).toContain("apply_patch");- expect(out.hookSpecificOutput.additionalContext).toContain(- "/srv/projects/x/src/index.ts",- );+ expect(out.hookSpecificOutput.additionalContext).toContain("/srv/projects/x/src/index.ts");});test("stays silent when Claude's tool_response reports an error", async () => {@@ -128,14 +126,11 @@ describe("post-write-reminder hook", () => {});expect(r.exit).toBe(0);const out = JSON.parse(r.stdout);- expect(out.hookSpecificOutput.additionalContext).toContain(- "Claude Code session",- );+ expect(out.hookSpecificOutput.additionalContext).toContain("Claude Code session");});test("Codex apply_patch shape triggers the codex cadence line", async () => {- const patch =- "*** Begin Patch\n*** Update File: /tmp/x\n*** End Patch\n";+ const patch = "*** Begin Patch\n*** Update File: /tmp/x\n*** End Patch\n";const r = await runHook({hook_event_name: "PostToolUse",tool_name: "apply_patch",diff --git a/tests/hooks/stop-log-guardrail.test.ts b/tests/hooks/stop-log-guardrail.test.tsindex b87f22f3..7a4bf0d1 100644--- a/tests/hooks/stop-log-guardrail.test.ts+++ b/tests/hooks/stop-log-guardrail.test.ts@@ -179,8 +179,7 @@ describe("stop-log-guardrail hook", () => {id: "toolu_b",name: "Bash",input: {- command:- "o2b brain feedback --topic x --signal positive --principle p",+ command: "o2b brain feedback --topic x --signal positive --principle p",},},],@@ -231,10 +230,9 @@ describe("stop-log-guardrail hook", () => {const transcript_path = writeTranscript([ccUser("add a file"),ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),- ccAssistantToolUse(- "mcp__plugin_open-second-brain_open-second-brain__event_log_append",- { message: "added /tmp/x.md" },- ),+ ccAssistantToolUse("mcp__plugin_open-second-brain_open-second-brain__event_log_append", {+ message: "added /tmp/x.md",+ }),]);const r = await runHook({hook_event_name: "Stop",@@ -271,19 +269,13 @@ describe("stop-log-guardrail hook", () => {test("Claude Code transcript path adds the claudecode cadence line", async () => {// Reuse the per-test `tmp` so afterEach cleans this up too.- const transcript_path = join(- tmp,- ".claude",- "projects",- "session.jsonl",- );+ const transcript_path = join(tmp, ".claude", "projects", "session.jsonl");mkdirSync(dirname(transcript_path), { recursive: true });writeFileSync(transcript_path,- [- ccUser("write something"),- ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),- ].join("\n") + "\n",+ [ccUser("write something"), ccAssistantToolUse("Write", { file_path: "/tmp/x.md" })].join(+ "\n",+ ) + "\n",);const r = await runHook({hook_event_name: "Stop",@@ -297,12 +289,7 @@ describe("stop-log-guardrail hook", () => {test("Codex transcript path adds the codex cadence line", async () => {// Reuse the per-test `tmp` so afterEach cleans this up too.- const transcript_path = join(- tmp,- ".codex",- "sessions",- "session.jsonl",- );+ const transcript_path = join(tmp, ".codex", "sessions", "session.jsonl");mkdirSync(dirname(transcript_path), { recursive: true });writeFileSync(transcript_path,diff --git a/tests/hooks/transcript.test.ts b/tests/hooks/transcript.test.tsindex aa2c8465..22438f56 100644--- a/tests/hooks/transcript.test.ts+++ b/tests/hooks/transcript.test.ts@@ -88,9 +88,9 @@ describe("detectFormat", () => {// permission-mode, attachment. They have `type` and `sessionId`// but no `message.role`. Detection must keep scanning so a real// user/assistant line drives the decision.- expect(- detectFormat(JSON.stringify({ type: "queue-operation", sessionId: "abc" })),- ).toBe("unknown");+ expect(detectFormat(JSON.stringify({ type: "queue-operation", sessionId: "abc" }))).toBe(+ "unknown",+ );expect(detectFormat(JSON.stringify({ type: "permission-mode", permissionMode: "default" })),).toBe("unknown");diff --git a/tests/mcp/brain-context-vault-instruction.test.ts b/tests/mcp/brain-context-vault-instruction.test.tsindex fcd120de..b44b5397 100644--- a/tests/mcp/brain-context-vault-instruction.test.ts+++ b/tests/mcp/brain-context-vault-instruction.test.ts@@ -6,22 +6,12 @@* stay byte-identical.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- JSONRPC_VERSION,- MCPServer,- PROTOCOL_VERSION,-} from "../../src/mcp/index.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";let tmp: string;@@ -40,12 +30,7 @@ beforeEach(() => {writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-vault-instr-cfg-"));configPath = join(configHome, "config.yaml");- for (const k of [- "VAULT_AGENT_NAME",- "VAULT_TIMEZONE",- "VAULT_DIR",- "OPEN_SECOND_BRAIN_CONFIG",- ]) {+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {savedEnv[k] = process.env[k];delete process.env[k];}@@ -98,10 +83,7 @@ describe("brain_context envelope vault_instruction extension (v0.10.17)", () =>});test("present VAULT.md: envelope includes path + content + lines", async () => {- writeFileSync(- join(vault, "VAULT.md"),- "# Project context\n\nI work on Open Second Brain.\n",- );+ writeFileSync(join(vault, "VAULT.md"), "# Project context\n\nI work on Open Second Brain.\n");const server = new MCPServer({ vault, configPath });await initialize(server);const out = await callContext(server);diff --git a/tests/mcp/brain-context.test.ts b/tests/mcp/brain-context.test.tsindex d64d3d2b..19b253d4 100644--- a/tests/mcp/brain-context.test.ts+++ b/tests/mcp/brain-context.test.ts@@ -10,28 +10,12 @@* tools/call → handler`) so registration drift is caught here too.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";-import {- existsSync,- mkdtempSync,- readFileSync,- rmSync,- unlinkSync,-} from "node:fs";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync, unlinkSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- JSONRPC_VERSION,- MCPServer,- PROTOCOL_VERSION,-} from "../../src/mcp/index.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { buildToolTable } from "../../src/mcp/tools.ts";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { brainActivePath } from "../../src/core/brain/paths.ts";@@ -49,12 +33,7 @@ beforeEach(() => {vault = join(tmp, "vault");configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-brain-context-cfg-"));configPath = join(configHome, "config.yaml");- for (const k of [- "VAULT_AGENT_NAME",- "VAULT_TIMEZONE",- "VAULT_DIR",- "OPEN_SECOND_BRAIN_CONFIG",- ]) {+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {savedEnv[k] = process.env[k];delete process.env[k];}@@ -112,9 +91,11 @@ describe("brain_context tool registration", () => {});test("writer scope still hosts the three Brain writers", () => {- const names = buildToolTable("writer").map((t) => t.name).sort();+ const names = buildToolTable("writer")+ .map((t) => t.name)+ .toSorted();expect(names).toEqual(- ["brain_apply_evidence", "brain_context", "brain_feedback", "brain_note"].sort(),+ ["brain_apply_evidence", "brain_context", "brain_feedback", "brain_note"].toSorted(),);});});diff --git a/tests/mcp/brain-health.test.ts b/tests/mcp/brain-health.test.tsindex 8b09ea9b..efeb04e7 100644--- a/tests/mcp/brain-health.test.ts+++ b/tests/mcp/brain-health.test.ts@@ -52,12 +52,20 @@ async function initialize(server: MCPServer): Promise<void> {jsonrpc: JSONRPC_VERSION,id: 1,method: "initialize",- params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "health-test", version: "0" } },+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "health-test", version: "0" },+ },});await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });}-async function callTool(server: MCPServer, name: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {+async function callTool(+ server: MCPServer,+ name: string,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {const r = (await server.handleRequest({jsonrpc: JSONRPC_VERSION,id: 9,@@ -80,23 +88,41 @@ describe("brain_health MCP tool", () => {test("contradictory preferences surface with an investigate verdict", async () => {const pos = writeSignal(vault, {- topic: "indentation", signal: BRAIN_SIGNAL_SIGN.positive, agent: "t",- principle: "use tabs", created_at: "2026-05-01T00:00:00Z", date: "2026-05-01", slug: "tabs-pos",+ topic: "indentation",+ signal: BRAIN_SIGNAL_SIGN.positive,+ agent: "t",+ principle: "use tabs",+ created_at: "2026-05-01T00:00:00Z",+ date: "2026-05-01",+ slug: "tabs-pos",}).id;const neg = writeSignal(vault, {- topic: "indentation", signal: BRAIN_SIGNAL_SIGN.negative, agent: "t",- principle: "use spaces", created_at: "2026-05-01T00:00:00Z", date: "2026-05-01", slug: "tabs-neg",+ topic: "indentation",+ signal: BRAIN_SIGNAL_SIGN.negative,+ agent: "t",+ principle: "use spaces",+ created_at: "2026-05-01T00:00:00Z",+ date: "2026-05-01",+ slug: "tabs-neg",}).id;for (const [slug, principle, ev] of [["tabs-rule", "always indent source with tabs not spaces", pos],["spaces-rule", "never indent source with tabs always spaces", neg],] as const) {- writePreference(vault, {- slug, topic: slug, principle,- created_at: "2026-05-01T00:00:00Z", unconfirmed_until: "2026-05-08T00:00:00Z",- confirmed_at: "2026-05-08T00:00:00Z", status: BRAIN_PREFERENCE_STATUS.confirmed,- evidenced_by: [`[[${ev}]]`],- }, { overwrite: true });+ writePreference(+ vault,+ {+ slug,+ topic: slug,+ principle,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ confirmed_at: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[${ev}]]`],+ },+ { overwrite: true },+ );}const server = new MCPServer({ vault, configPath });await initialize(server);diff --git a/tests/mcp/brain-trust-mcp-fields.test.ts b/tests/mcp/brain-trust-mcp-fields.test.tsindex da746bec..680999ef 100644--- a/tests/mcp/brain-trust-mcp-fields.test.ts+++ b/tests/mcp/brain-trust-mcp-fields.test.ts@@ -6,22 +6,12 @@* silently drops it.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- JSONRPC_VERSION,- MCPServer,- PROTOCOL_VERSION,-} from "../../src/mcp/index.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";let tmp: string;@@ -40,12 +30,7 @@ beforeEach(() => {writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-trust-fields-cfg-"));configPath = join(configHome, "config.yaml");- for (const k of [- "VAULT_AGENT_NAME",- "VAULT_TIMEZONE",- "VAULT_DIR",- "OPEN_SECOND_BRAIN_CONFIG",- ]) {+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {savedEnv[k] = process.env[k];delete process.env[k];}diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.tsindex 8588eb88..cc711611 100644--- a/tests/mcp/brain.test.ts+++ b/tests/mcp/brain.test.ts@@ -12,36 +12,15 @@* tool's own `now` argument.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";-import {- existsSync,- mkdtempSync,- readFileSync,- readdirSync,- rmSync,-} from "node:fs";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- JSONRPC_VERSION,- MCPServer,- PROTOCOL_VERSION,-} from "../../src/mcp/index.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { buildToolTable } from "../../src/mcp/tools.ts";import { bootstrapBrain } from "../../src/core/brain/init.ts";-import {- brainDirs,- logJsonlPath,- logPath,- preferencePath,-} from "../../src/core/brain/paths.ts";+import { brainDirs, logJsonlPath, logPath, preferencePath } from "../../src/core/brain/paths.ts";import { writeSignal } from "../../src/core/brain/signal.ts";import { writePreference } from "../../src/core/brain/preference.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";@@ -58,12 +37,7 @@ beforeEach(() => {vault = join(tmp, "vault");configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-brain-cfg-"));configPath = join(configHome, "config.yaml");- for (const k of [- "VAULT_AGENT_NAME",- "VAULT_TIMEZONE",- "VAULT_DIR",- "OPEN_SECOND_BRAIN_CONFIG",- ]) {+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {savedEnv[k] = process.env[k];delete process.env[k];}@@ -160,8 +134,7 @@ describe("brain_feedback tool schema", () => {}>;const feedback = tools.find((t) => t.name === "brain_feedback");expect(feedback).toBeDefined();- const fcDesc =- feedback!.inputSchema.properties?.["force_confirmed"]?.description ?? "";+ const fcDesc = feedback!.inputSchema.properties?.["force_confirmed"]?.description ?? "";// The handler ALWAYS writes the inbox signal; with force_confirmed// it additionally materialises a confirmed preference. The earlier// "instead of an inbox signal" wording was incorrect.@@ -307,12 +280,8 @@ describe("brain_dream", () => {const server = makeServer();await initialize(server);const dirs = brainDirs(vault);- const inboxBefore = readdirSync(dirs.inbox).filter((n) =>- n.endsWith(".md"),- ).length;- const prefsBefore = readdirSync(dirs.preferences).filter((n) =>- n.endsWith(".md"),- ).length;+ const inboxBefore = readdirSync(dirs.inbox).filter((n) => n.endsWith(".md")).length;+ const prefsBefore = readdirSync(dirs.preferences).filter((n) => n.endsWith(".md")).length;const r = await call(server, "brain_dream", {dry_run: true,@@ -322,12 +291,8 @@ describe("brain_dream", () => {expect(r.result.structuredContent.dry_run).toBe(true);// Files unchanged on disk after a dry-run.- const inboxAfter = readdirSync(dirs.inbox).filter((n) =>- n.endsWith(".md"),- ).length;- const prefsAfter = readdirSync(dirs.preferences).filter((n) =>- n.endsWith(".md"),- ).length;+ const inboxAfter = readdirSync(dirs.inbox).filter((n) => n.endsWith(".md")).length;+ const prefsAfter = readdirSync(dirs.preferences).filter((n) => n.endsWith(".md")).length;expect(inboxAfter).toBe(inboxBefore);expect(prefsAfter).toBe(prefsBefore);});@@ -703,10 +668,7 @@ describe("brain_backlinks", () => {// brain_note (§32B, v0.10.8)// ----------------------------------------------------------------------------function logFilesForLoggedAt(- vaultDir: string,- loggedAt: string,-): { md: string; jsonl: string } {+function logFilesForLoggedAt(vaultDir: string, loggedAt: string): { md: string; jsonl: string } {// Derive the date from the tool's own `logged_at` payload instead// of `new Date()`. This avoids a flake if the test happens to cross// `00:00:00Z` between the `brain_note` call and the file lookup.diff --git a/tests/mcp/context-pack-tool.test.ts b/tests/mcp/context-pack-tool.test.tsindex 14f88588..b7c95338 100644--- a/tests/mcp/context-pack-tool.test.ts+++ b/tests/mcp/context-pack-tool.test.ts@@ -4,22 +4,12 @@* the JSON-RPC round-trip shape.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- JSONRPC_VERSION,- MCPServer,- PROTOCOL_VERSION,-} from "../../src/mcp/index.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { buildToolTable } from "../../src/mcp/tools.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";@@ -35,12 +25,7 @@ beforeEach(() => {mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-context-pack-cfg-"));configPath = join(configHome, "config.yaml");- for (const k of [- "VAULT_AGENT_NAME",- "VAULT_TIMEZONE",- "VAULT_DIR",- "OPEN_SECOND_BRAIN_CONFIG",- ]) {+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {savedEnv[k] = process.env[k];delete process.env[k];}diff --git a/tests/mcp/link-graph-mcp-fields.test.ts b/tests/mcp/link-graph-mcp-fields.test.tsindex cccd20bc..cc230883 100644--- a/tests/mcp/link-graph-mcp-fields.test.ts+++ b/tests/mcp/link-graph-mcp-fields.test.ts@@ -7,22 +7,12 @@* - brain_unlinked_mentions*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- JSONRPC_VERSION,- MCPServer,- PROTOCOL_VERSION,-} from "../../src/mcp/index.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { buildToolTable } from "../../src/mcp/tools.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";@@ -42,12 +32,7 @@ beforeEach(() => {writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-link-graph-cfg-"));configPath = join(configHome, "config.yaml");- for (const k of [- "VAULT_AGENT_NAME",- "VAULT_TIMEZONE",- "VAULT_DIR",- "OPEN_SECOND_BRAIN_CONFIG",- ]) {+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {savedEnv[k] = process.env[k];delete process.env[k];}@@ -86,13 +71,19 @@ async function callTool(name: string,args: Record<string, unknown>,id = 9,-): Promise<{ result?: { content: ReadonlyArray<{ type: string; text: string }> }; error?: { code: number; message: string } }> {+): Promise<{+ result?: { content: ReadonlyArray<{ type: string; text: string }> };+ error?: { code: number; message: string };+}> {return server.handleRequest({jsonrpc: JSONRPC_VERSION,id,method: "tools/call",params: { name, arguments: args },- }) as Promise<{ result?: { content: ReadonlyArray<{ type: string; text: string }> }; error?: { code: number; message: string } }>;+ }) as Promise<{+ result?: { content: ReadonlyArray<{ type: string; text: string }> };+ error?: { code: number; message: string };+ }>;}const DERIVED_KEYS = new Set([@@ -108,11 +99,7 @@ const DERIVED_KEYS = new Set(["confirmed_at",]);-function writePref(- slug: string,- frontmatter: Record<string, string>,- body = "",-): void {+function writePref(slug: string, frontmatter: Record<string, string>, body = ""): void {const lines = ["---"];for (const [k, v] of Object.entries(frontmatter)) {const key = DERIVED_KEYS.has(k) ? `_${k}` : k;@@ -148,11 +135,36 @@ describe("brain_moc_audit registration", () => {describe("brain_moc_audit round trip", () => {test("returns bucketed envelope for a qualifying hub", async () => {- writePref("pref-a", { kind: "preference", topic: "a", status: "confirmed", principle: "p" });- writePref("pref-b", { kind: "preference", topic: "b", status: "confirmed", principle: "p" });- writePref("pref-c", { kind: "preference", topic: "c", status: "confirmed", principle: "p" });- writePref("pref-d", { kind: "preference", topic: "d", status: "confirmed", principle: "p" });- writePref("pref-e", { kind: "preference", topic: "e", status: "confirmed", principle: "p" });+ writePref("pref-a", {+ kind: "preference",+ topic: "a",+ status: "confirmed",+ principle: "p",+ });+ writePref("pref-b", {+ kind: "preference",+ topic: "b",+ status: "confirmed",+ principle: "p",+ });+ writePref("pref-c", {+ kind: "preference",+ topic: "c",+ status: "confirmed",+ principle: "p",+ });+ writePref("pref-d", {+ kind: "preference",+ topic: "d",+ status: "confirmed",+ principle: "p",+ });+ writePref("pref-e", {+ kind: "preference",+ topic: "e",+ status: "confirmed",+ principle: "p",+ });writePref("pref-hub",{ kind: "preference", topic: "hub", status: "confirmed", principle: "p" },@@ -165,9 +177,7 @@ describe("brain_moc_audit round trip", () => {expect(out["hub_id"]).toBe("pref-hub");expect(out["outbound_count"]).toBe(6);expect(- (out["candidate_missing"] as Array<{ id: string }>).some(- (c) => c.id === "pref-missing",- ),+ (out["candidate_missing"] as Array<{ id: string }>).some((c) => c.id === "pref-missing"),).toBe(true);});@@ -255,36 +265,25 @@ describe("brain_concept_synthesis round trip", () => {expect(out["unlinked_mentions"].length).toBe(1);});- test("rejects empty id with INVALID_PARAMS", async () => {- const server = new MCPServer({ vault, configPath });- await initialize(server);- const r = await callTool(server, "brain_concept_synthesis", { id: "" });- expect(r.error?.code).toBe(-32602);- });-- test("rejects non-boolean include_unlinked", async () => {+ test("rejects invalid concept synthesis arguments with INVALID_PARAMS", async () => {const server = new MCPServer({ vault, configPath });await initialize(server);- const r = await callTool(server, "brain_concept_synthesis", {- id: "pref-x",- include_unlinked: "yes",- });- expect(r.error?.code).toBe(-32602);+ for (const args of [{ id: "" }, { id: "pref-x", include_unlinked: "yes" }]) {+ const r = await callTool(server, "brain_concept_synthesis", args);+ expect(r.error?.code).toBe(-32602);+ }});});describe("brain_unlinked_mentions round trip", () => {test("returns mention list for matching prose", async () => {- writePref(- "pref-target",- {- kind: "preference",- topic: "t",- status: "confirmed",- principle: "p",- title: "Subject Line",- },- );+ writePref("pref-target", {+ kind: "preference",+ topic: "t",+ status: "confirmed",+ principle: "p",+ title: "Subject Line",+ });writePref("pref-linker",{@@ -318,30 +317,16 @@ describe("brain_unlinked_mentions round trip", () => {expect(out["mentions"]).toEqual([]);});- test("rejects empty id with INVALID_PARAMS", async () => {- const server = new MCPServer({ vault, configPath });- await initialize(server);- const r = await callTool(server, "brain_unlinked_mentions", { id: "" });- expect(r.error?.code).toBe(-32602);- });-- test("rejects negative limit with INVALID_PARAMS", async () => {- const server = new MCPServer({ vault, configPath });- await initialize(server);- const r = await callTool(server, "brain_unlinked_mentions", {- id: "pref-foo",- limit: -1,- });- expect(r.error?.code).toBe(-32602);- });-- test("rejects non-numeric limit with INVALID_PARAMS", async () => {+ test("rejects invalid unlinked mention arguments with INVALID_PARAMS", async () => {const server = new MCPServer({ vault, configPath });await initialize(server);- const r = await callTool(server, "brain_unlinked_mentions", {- id: "pref-foo",- limit: "many",- });- expect(r.error?.code).toBe(-32602);+ for (const args of [+ { id: "" },+ { id: "pref-foo", limit: -1 },+ { id: "pref-foo", limit: "many" },+ ]) {+ const r = await callTool(server, "brain_unlinked_mentions", args);+ expect(r.error?.code).toBe(-32602);+ }});});diff --git a/tests/mcp/mcp-json.test.ts b/tests/mcp/mcp-json.test.tsindex 4370bd22..634b0427 100644--- a/tests/mcp/mcp-json.test.ts+++ b/tests/mcp/mcp-json.test.ts@@ -11,7 +11,7 @@ const MCP_JSON_PATH = resolve(HERE, "..", "..", ".mcp.json");describe(".mcp.json shipped with the plugin", () => {const file = JSON.parse(readFileSync(MCP_JSON_PATH, "utf8"));test("declares both open-second-brain and -writer entries", () => {- expect(Object.keys(file.mcpServers).sort()).toEqual([+ expect(Object.keys(file.mcpServers).toSorted()).toEqual(["open-second-brain","open-second-brain-writer",]);diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex f0f9b06d..69213e92 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -48,7 +48,12 @@ async function initialize(server: MCPServer) {return r;}-async function callTool(server: MCPServer, name: string, args: Record<string, unknown> = {}, id = 99) {+async function callTool(+ server: MCPServer,+ name: string,+ args: Record<string, unknown> = {},+ id = 99,+) {return server.handleRequest({jsonrpc: JSONRPC_VERSION,id,@@ -116,7 +121,11 @@ describe("handshake", () => {jsonrpc: JSONRPC_VERSION,id: 1,method: "initialize",- params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "old", version: "0" } },+ params: {+ protocolVersion: "2024-11-05",+ capabilities: {},+ clientInfo: { name: "old", version: "0" },+ },})) as any;expect(r.result.protocolVersion).toBe("2024-11-05");});@@ -255,9 +264,7 @@ describe("tool calls", () => {expect(s.vault.ignore_source).toBeDefined();expect(["_brain.yaml", "defaults"]).toContain(s.vault.ignore_source);expect(Array.isArray(s.vault.rules)).toBe(true);- expect(s.vault.rules.some(- (r: { raw: string }) => r.raw === ".obsidian",- )).toBe(true);+ expect(s.vault.rules.some((r: { raw: string }) => r.raw === ".obsidian")).toBe(true);expect(typeof s.vault.included.files).toBe("number");expect(typeof s.vault.included.dirs).toBe("number");expect(typeof s.vault.excluded.dirs).toBe("number");@@ -311,7 +318,10 @@ describe("tool calls", () => {const vault = createSandboxVault(tmp);const server = new MCPServer({ vault });await initialize(server);- const r = (await callTool(server, "second_brain_query", { pattern: "Sandbox", limit: 5 })) as any;+ const r = (await callTool(server, "second_brain_query", {+ pattern: "Sandbox",+ limit: 5,+ })) as any;const s = r.result.structuredContent;expect(s.limit).toBe(5);expect(s.total_pages).toBeGreaterThanOrEqual(1);@@ -431,21 +441,29 @@ describe("serveStdioFromString respects scope+name", () => {test("writer scope filters tools/list response", async () => {const ctx = { vault: "/tmp/x", configPath: null, repoRoot: null };const initReq = JSON.stringify({- jsonrpc: "2.0", id: 1, method: "initialize",+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",params: { protocolVersion: "2025-06-18", capabilities: {} },});const listReq = JSON.stringify({- jsonrpc: "2.0", id: 2, method: "tools/list", params: {},+ jsonrpc: "2.0",+ id: 2,+ method: "tools/list",+ params: {},});- const out = await serveStdioFromString(- ctx,- `${initReq}\n${listReq}\n`,- { scope: "writer", serverName: "open-second-brain-writer" },- );- const lines = out.trim().split("\n").map((l) => JSON.parse(l));+ const out = await serveStdioFromString(ctx, `${initReq}\n${listReq}\n`, {+ scope: "writer",+ serverName: "open-second-brain-writer",+ });+ const lines = out+ .trim()+ .split("\n")+ .map((l) => JSON.parse(l));expect(lines[0].result.serverInfo.name).toBe("open-second-brain-writer");const toolNames = (lines[1].result.tools as Array<{ name: string }>)- .map((t) => t.name).sort();+ .map((t) => t.name)+ .toSorted();expect(toolNames).toEqual(["brain_apply_evidence","brain_context",diff --git a/tests/mcp/operator-summary-tool.test.ts b/tests/mcp/operator-summary-tool.test.tsindex b4ba595e..e4f4267f 100644--- a/tests/mcp/operator-summary-tool.test.ts+++ b/tests/mcp/operator-summary-tool.test.ts@@ -4,22 +4,12 @@* round-trip shape.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- JSONRPC_VERSION,- MCPServer,- PROTOCOL_VERSION,-} from "../../src/mcp/index.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { buildToolTable } from "../../src/mcp/tools.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";@@ -39,12 +29,7 @@ beforeEach(() => {writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-op-summary-cfg-"));configPath = join(configHome, "config.yaml");- for (const k of [- "VAULT_AGENT_NAME",- "VAULT_TIMEZONE",- "VAULT_DIR",- "OPEN_SECOND_BRAIN_CONFIG",- ]) {+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {savedEnv[k] = process.env[k];delete process.env[k];}@@ -120,54 +105,32 @@ describe("brain_operator_summary tool - round trip", () => {const server = new MCPServer({ vault, configPath });await initialize(server);const out = await callSummary(server, {});- const ifWarn = out["instruction_file_warnings"] as Array<{ path: string; lines: number }>;+ const ifWarn = out["instruction_file_warnings"] as Array<{+ path: string;+ lines: number;+ }>;expect(ifWarn).toHaveLength(1);expect(ifWarn[0]?.path).toBe("CLAUDE.md");});- test("rejects negative top_actions via INVALID_PARAMS", async () => {+ test("rejects invalid summary arguments via INVALID_PARAMS", async () => {const server = new MCPServer({ vault, configPath });await initialize(server);- const r = (await server.handleRequest({- jsonrpc: JSONRPC_VERSION,- id: 11,- method: "tools/call",- params: { name: "brain_operator_summary", arguments: { top_actions: -1 } },- })) as { error?: { code: number; message: string } };- expect(r.error).toBeDefined();- // JSON-RPC INVALID_PARAMS = -32602. Assert the specific code so- // the test fails on the wrong failure mode (e.g. INTERNAL_ERROR- // smuggled through).- expect(r.error?.code).toBe(-32602);- });-- test("rejects malformed top_actions string via INVALID_PARAMS", async () => {- const server = new MCPServer({ vault, configPath });- await initialize(server);- const r = (await server.handleRequest({- jsonrpc: JSONRPC_VERSION,- id: 12,- method: "tools/call",- params: {- name: "brain_operator_summary",- arguments: { top_actions: "3abc" },- },- })) as { error?: { code: number; message: string } };- expect(r.error?.code).toBe(-32602);- });-- test("rejects non-boolean include_dream via INVALID_PARAMS", async () => {- const server = new MCPServer({ vault, configPath });- await initialize(server);- const r = (await server.handleRequest({- jsonrpc: JSONRPC_VERSION,- id: 13,- method: "tools/call",- params: {- name: "brain_operator_summary",- arguments: { include_dream: "yes" },- },- })) as { error?: { code: number; message: string } };- expect(r.error?.code).toBe(-32602);+ for (const [id, args] of [+ [11, { top_actions: -1 }],+ [12, { top_actions: "3abc" }],+ [13, { include_dream: "yes" }],+ ] as const) {+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id,+ method: "tools/call",+ params: { name: "brain_operator_summary", arguments: args },+ })) as { error?: { code: number; message: string } };+ // JSON-RPC INVALID_PARAMS = -32602. Assert the specific code so+ // the test fails on the wrong failure mode (e.g. INTERNAL_ERROR+ // smuggled through).+ expect(r.error?.code).toBe(-32602);+ }});});diff --git a/tests/mcp/pay-memory.test.ts b/tests/mcp/pay-memory.test.tsindex 7ca82f51..1eafda2c 100644--- a/tests/mcp/pay-memory.test.ts+++ b/tests/mcp/pay-memory.test.ts@@ -47,7 +47,11 @@ async function initialize(server: MCPServer) {jsonrpc: JSONRPC_VERSION,id: 1,method: "initialize",- params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "t", version: "0" } },+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "t", version: "0" },+ },});await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });}@@ -336,7 +340,11 @@ describe("instructions include the Pay Memory paragraph", () => {jsonrpc: JSONRPC_VERSION,id: 1,method: "initialize",- params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "t", version: "0" } },+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "t", version: "0" },+ },})) as any;const text = r.result.instructions as string;for (const name of [diff --git a/tests/mcp/resources.test.ts b/tests/mcp/resources.test.tsindex 114b2533..c49cd577 100644--- a/tests/mcp/resources.test.ts+++ b/tests/mcp/resources.test.ts@@ -10,28 +10,14 @@* unknown URIs / missing files / malformed slug-or-date arguments.*/-import {- afterEach,- beforeEach,- describe,- expect,- test,-} from "bun:test";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import {- JSONRPC_VERSION,- MCPServer,- PROTOCOL_VERSION,-} from "../../src/mcp/index.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { bootstrapBrain } from "../../src/core/brain/init.ts";-import {- brainActivePath,- logPath,- preferencePath,-} from "../../src/core/brain/paths.ts";+import { brainActivePath, logPath, preferencePath } from "../../src/core/brain/paths.ts";import { writePreference } from "../../src/core/brain/preference.ts";import { writeSignal } from "../../src/core/brain/signal.ts";import { regenerateActive } from "../../src/core/brain/active.ts";@@ -124,12 +110,8 @@ describe("MCP resources — capabilities and discovery", () => {const server = makeServer();await initialize(server);const r = await listResources(server);- const uris = r.result.resources.map((x: any) => x.uri).sort();- expect(uris).toEqual([- "osb://digest/latest",- "osb://preferences/active",- "osb://status",- ]);+ const uris = r.result.resources.map((x: any) => x.uri).toSorted();+ expect(uris).toEqual(["osb://digest/latest", "osb://preferences/active", "osb://status"]);for (const desc of r.result.resources) {expect(desc.mimeType).toBe("text/markdown");expect(typeof desc.name).toBe("string");@@ -141,7 +123,7 @@ describe("MCP resources — capabilities and discovery", () => {const server = makeServer();await initialize(server);const r = await listTemplates(server);- const templates = r.result.resourceTemplates.map((t: any) => t.uriTemplate).sort();+ const templates = r.result.resourceTemplates.map((t: any) => t.uriTemplate).toSorted();expect(templates).toEqual(["osb://backlinks/{id}","osb://log/{date}",@@ -375,7 +357,6 @@ describe("MCP resources — read osb://status", () => {expect(text).toContain("confirmed: 1");expect(text).toContain("## Activity");});-});describe("MCP resources — read osb://backlinks/{id}", () => {diff --git a/tests/mcp/scope-filter.test.ts b/tests/mcp/scope-filter.test.tsindex 2c6a21d4..7117b211 100644--- a/tests/mcp/scope-filter.test.ts+++ b/tests/mcp/scope-filter.test.ts@@ -15,7 +15,7 @@ describe("buildToolTable scope filter", () => {test("writer scope returns the three writers plus brain_context (v0.10.10)", () => {const writer = buildToolTable("writer");- const names = writer.map((t) => t.name).sort();+ const names = writer.map((t) => t.name).toSorted();expect(names).toEqual(["brain_apply_evidence","brain_context",diff --git a/tests/mcp/search.test.ts b/tests/mcp/search.test.tsindex 868d5c58..0143ae30 100644--- a/tests/mcp/search.test.ts+++ b/tests/mcp/search.test.ts@@ -60,7 +60,11 @@ async function initialize(server: MCPServer): Promise<void> {});}-function call(server: MCPServer, name: string, args: Record<string, unknown> = {}): Promise<unknown> {+function call(+ server: MCPServer,+ name: string,+ args: Record<string, unknown> = {},+): Promise<unknown> {return server.handleRequest({jsonrpc: JSONRPC_VERSION,id: 99,@@ -111,7 +115,12 @@ test("brain_search happy path returns paths and respects 600-char content cap",await initialize(server);const resp = await call(server, "brain_search", { query: "fox", limit: 5 });const body = extractToolResult(resp);- const results = body["results"] as Array<{ content: string; path: string; searchType: string; score: number }>;+ const results = body["results"] as Array<{+ content: string;+ path: string;+ searchType: string;+ score: number;+ }>;expect(Array.isArray(results)).toBe(true);expect(results.length).toBeGreaterThan(0);expect(results[0]?.path).toBe("notes/foo.md");diff --git a/tests/mcp/temporal-mcp-tools.test.ts b/tests/mcp/temporal-mcp-tools.test.tsindex ed1af494..26898a14 100644--- a/tests/mcp/temporal-mcp-tools.test.ts+++ b/tests/mcp/temporal-mcp-tools.test.ts@@ -28,15 +28,9 @@ interface FixtureEvent {readonly body: Record<string, string | ReadonlyArray<string>>;}-function writeJsonl(- vault: string,- date: string,- events: ReadonlyArray<FixtureEvent>,-): void {+function writeJsonl(vault: string, date: string, events: ReadonlyArray<FixtureEvent>): void {const lines = events- .map((e) =>- JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }),- )+ .map((e) => JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body })).join("\n");writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");}diff --git a/tests/scripts/macos-sqlite-shim.test.ts b/tests/scripts/macos-sqlite-shim.test.tsindex 32e2457f..2bf945ac 100644--- a/tests/scripts/macos-sqlite-shim.test.ts+++ b/tests/scripts/macos-sqlite-shim.test.ts@@ -30,17 +30,25 @@ afterEach(() => {rmSync(tmp, { recursive: true, force: true });});+function shellQuote(value: string): string {+ return `'${value.replace(/'/g, `'\\''`)}'`;+}+async function runShim(env: Record<string, string>): Promise<string> {// Source the shim, then echo DYLD_LIBRARY_PATH. The shim returns 0// even on no-op, so we always read the echoed value (possibly empty).+ const hasDyld = Object.prototype.hasOwnProperty.call(env, "DYLD_LIBRARY_PATH");+ const dyldValue: string = hasDyld ? String(env["DYLD_LIBRARY_PATH"] ?? "") : "";+ const dyldSetup = hasDyld ? `export DYLD_LIBRARY_PATH=${shellQuote(dyldValue)}; ` : "";+ const spawnEnv: Record<string, string> = {};+ for (const [key, value] of Object.entries(env)) {+ if (key !== "DYLD_LIBRARY_PATH") spawnEnv[key] = value;+ }+ spawnEnv["PATH"] = process.env.PATH ?? "/usr/bin:/bin";const proc = Bun.spawn(- [- "bash",- "-c",- `. "${SHIM}"; echo "DYLD=\${DYLD_LIBRARY_PATH-}"`,- ],+ ["bash", "-c", `${dyldSetup}. "${SHIM}"; echo "DYLD=\${DYLD_LIBRARY_PATH-}"`],{- env: { ...env, PATH: process.env.PATH ?? "/usr/bin:/bin" },+ env: spawnEnv,stdout: "pipe",stderr: "pipe",},diff --git a/tsconfig.json b/tsconfig.jsonindex f0c2c872..e8d591f8 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -19,11 +19,5 @@"forceConsistentCasingInFileNames": true,"types": ["bun"]},- "include": [- "src/**/*.ts",- "src/**/*.d.ts",- "tests/**/*.ts",- "scripts/**/*.ts",- "hooks/**/*.ts"- ]+ "include": ["src/**/*.ts", "src/**/*.d.ts", "tests/**/*.ts", "scripts/**/*.ts", "hooks/**/*.ts"]}