Local-first π§ memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly π΄ dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat: rewrite OpenClaw plugin in pure JS, no child_process (v0.5.2)
Sol Aitken3220c247f626
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 951573f5..777f2824 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.5.1",+ "version": "0.5.2","description": "Plugin-first second brain package for AI agents and humans.","author": "Open Second Brain contributors","license": "MIT",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 5bb4a254..5a3ed884 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.5.1",+ "version": "0.5.2","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"]diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2b515ec0..09ce5f44 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+## [0.5.2] - 2026-05-07++### Changed++- Rewrote OpenClaw runtime entry in pure JavaScript β all five tools+ (`second_brain_status`, `second_brain_query`, `second_brain_capture`,+ `event_log_append`, `vault_health`) now operate directly on the vault+ filesystem using `node:fs/promises` and `node:path` instead of spawning+ a Python subprocess. This passes the OpenClaw security scanner which+ blocks `child_process` imports.+- Removed `openclaw/o2b-runner.js` subprocess helper (no longer needed).+- Added `openclaw/vault.js` and `openclaw/event-log.js` pure JS modules.+- Switched to `api.pluginConfig` for reading plugin configuration and+ two-arg `api.registerTool(tool, { name })` registration pattern to+ match bundled OpenClaw plugin conventions.++### Removed++- `openclaw/o2b-runner.js` β subprocess runner blocked by security scanner.+## [0.5.1] - 2026-05-07### Added@@ -167,7 +187,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.-[unreleased]: https://github.com/itechmeat/open-second-brain/compare/v0.5.1...HEAD+[unreleased]: https://github.com/itechmeat/open-second-brain/compare/v0.5.2...HEAD+[0.5.2]: https://github.com/itechmeat/open-second-brain/compare/v0.5.1...v0.5.2[0.5.1]: https://github.com/itechmeat/open-second-brain/compare/v0.5.0...v0.5.1[0.5.0]: https://github.com/itechmeat/open-second-brain/compare/v0.4.2...v0.5.0[0.4.2]: https://github.com/itechmeat/open-second-brain/compare/v0.4.1...v0.4.2diff --git a/docs/architecture.md b/docs/architecture.mdindex 5c00ec9f..5cf7f557 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -78,16 +78,17 @@ v0 should keep Codex support simple: plugin manifest plus shared skills and scriOpenClaw recognizes two plugin formats: **Native** (JS runtime module with `package.json` + `openclaw.plugin.json`) and **Bundle** (adapter directories like `.codex-plugin/`, `.claude-plugin/` mapped to OpenClaw features).-Open Second Brain uses the **Native format** with a JS entry that bridges to the Python CLI:+Open Second Brain uses the **Native format** with a pure JavaScript entry that operates directly on the vault filesystem β no Python subprocess, no `child_process`:```textpackage.json # openclaw.extensions β ./openclaw/index.jsopenclaw/- index.js # JS entry: definePluginEntry + api.registerTool- o2b-runner.js # Subprocess helper: spawns python3 -m open_second_brain.cli+ index.js # JS entry: definePluginEntry + api.registerTool (two-arg)+ vault.js # Pure JS: frontmatter parse/write, slugify, wikilinks, page listing+ event-log.js # Pure JS: daily note creation, chronological event insertionopenclaw.plugin.json # Static discovery metadata (id, configSchema, contracts.tools)src/open_second_brain/- cli.py # Python CLI (includes tool-call bridge subcommand)+ cli.py # Python CLI (for Hermes/standalone usage)mcp.py # MCP server (optional, for runtimes that prefer MCP).claude-plugin/ # Auto-detected by OpenClaw Bundle format.codex-plugin/ # Auto-detected by OpenClaw Bundle format@@ -96,14 +97,16 @@ src/open_second_brain/The integration flow:1. **Discovery**: OpenClaw reads `package.json`, finds `openclaw.extensions`, and loads `openclaw/index.js`.-2. **Tool registration**: The JS entry calls `api.registerTool()` for each of the five tools (`second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`).-3. **Runtime bridge**: Each tool's `execute()` spawns `python3 -m open_second_brain.cli` with `PYTHONPATH` set to the plugin's `src/` directory. For tools with direct CLI equivalents (`status`, `append-event`, `doctor`), it calls the relevant subcommand. For tools without (`second_brain_query`, `second_brain_capture`), it uses the `tool-call` bridge subcommand which invokes the MCP tool handlers directly.-4. **Config**: `api.getConfig()` provides the vault path and instance name from OpenClaw's plugin config.+2. **Tool registration**: The JS entry calls `api.registerTool(tool, { name })` for each of the five tools (`second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`).+3. **Pure JS execution**: Each tool's `execute()` runs entirely in the Node.js process using `node:fs/promises` and `node:path` to read/write the vault directory. No subprocess is spawned β this passes the OpenClaw security scanner which blocks `child_process` imports.+4. **Config**: `api.pluginConfig` provides the vault path and instance name from OpenClaw's plugin config.++The Python CLI (`o2b`) and MCP server (`o2b mcp`) remain available for Hermes and standalone usage, but the OpenClaw runtime is self-contained JavaScript.Installation:```bash-openclaw plugins install git:github.com/itechmeat/[email protected]+openclaw plugins install git:github.com/itechmeat/[email protected]```The OpenClaw adapter must remain compatible with the Hermes, Claude Code, and Codex adapters. The `o2b mcp` MCP server is still available for runtimes that prefer the MCP protocol.diff --git a/install.md b/install.mdindex c8ffeaf7..c53dd03c 100644--- a/install.md+++ b/install.md@@ -1,6 +1,6 @@# open-second-brain β Agent Installation Guide-> **Version 0.5.1**+> **Version 0.5.2**> Repository: https://github.com/itechmeat/open-second-brainThis guide is written for an **AI agent**, not a human. It contains the exact commands and decision logic needed to install and configure the **open-second-brain** plugin autonomously. Follow exactly one of the two branches below based on the target runtime (Hermes or OpenClaw). Complete every step in the chosen branch.@@ -88,7 +88,7 @@ The vault and its Markdown files are never deleted by the uninstall process.From Git (pin to a version tag):```bash-openclaw plugins install git:github.com/itechmeat/[email protected]+openclaw plugins install git:github.com/itechmeat/[email protected]```Or from a local checkout:diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 7f1b5fa3..74c631e2 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "0.5.1",+ "version": "0.5.2","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/event-log.js b/openclaw/event-log.jsnew file mode 100644index 00000000..4653a892--- /dev/null+++ b/openclaw/event-log.js@@ -0,0 +1,183 @@+/**+ * Pure JavaScript event log operations for Open Second Brain.+ *+ * All filesystem operations use `node:fs/promises` and `node:path`.+ * No native process module, no subprocess calls β passes the OpenClaw security scanner.+ *+ * Logic mirrors the Python implementation in `src/open_second_brain/event_log.py`.+ *+ * Daily note format:+ * File: vault/Daily/YYYY.MM.DD.md+ * Sections separated by ---+ * Events under ## Raw events (lowercase 'events' to match Python)+ * Entries: - HH:MM β @agent β message+ * Chronologically sorted within the section+ */++import { readFile, writeFile, mkdir } from "node:fs/promises";+import { join, dirname } from "node:path";+import { existsSync } from "node:fs";+import { randomUUID } from "node:crypto";++// ββ Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++const SECRET_ASSIGNMENT_RE =+ /\b(api[_-]?key|token|secret|password|credential)(\s*[:=]\s*)([^\s]+)/gi;++const EVENT_RE = /^- (\d{2}:\d{2}) β @/;+const TIME_RE = /^(\d{2}):(\d{2})$/;++// ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Redact secret-like values from text.+ */+function redactText(text) {+ return text.replace(SECRET_ASSIGNMENT_RE, "$1$2[REDACTED]");+}++/**+ * Get current date in YYYY.MM.DD format.+ */+function currentDate() {+ const now = new Date();+ const y = now.getFullYear();+ const m = String(now.getMonth() + 1).padStart(2, "0");+ const d = String(now.getDate()).padStart(2, "0");+ return `${y}.${m}.${d}`;+}++/**+ * Get current time in HH:MM 24-hour format.+ */+function currentTime() {+ const now = new Date();+ const h = String(now.getHours()).padStart(2, "0");+ const m = String(now.getMinutes()).padStart(2, "0");+ return `${h}:${m}`;+}++/**+ * Validate a time string in HH:MM 24-hour format.+ * Returns the validated time string or throws.+ */+function validateEventTime(value) {+ const match = TIME_RE.exec(value);+ if (!match) {+ throw new Error("event time must use HH:MM 24-hour format");+ }+ const hour = parseInt(match[1], 10);+ const minute = parseInt(match[2], 10);+ if (hour > 23 || minute > 59) {+ throw new Error("event time must use HH:MM 24-hour format");+ }+ return value;+}++/**+ * Build a new empty daily note.+ */+function newDailyNote(date) {+ return `---\nformatted: false\n---\n\n# ${date}\n\n## Raw events\n\n`;+}++/**+ * Insert an event entry into the daily note content, maintaining chronological order.+ * Uses the "## Raw events" heading (lowercase, matching Python).+ */+function insertEventEntry(content, entry) {+ const marker = "## Raw events";+ const idx = content.indexOf(marker);+ if (idx === -1) {+ // Shouldn't happen since we ensure it exists, but handle gracefully+ return content + "\n\n" + marker + "\n\n" + entry + "\n";+ }++ const before = content.slice(0, idx);+ const after = content.slice(idx + marker.length);++ // Strip leading newlines from after section+ const afterStripped = after.replace(/^\n+/, "");+ const lines = afterStripped.split("\n").filter((line) => line.trim());++ // Extract time from entry: "- HH:MM β @..."+ const entryTime = entry.slice(2, 7);++ let inserted = false;+ const output = [];+ for (const line of lines) {+ const match = EVENT_RE.exec(line);+ if (!inserted && match && match[1] > entryTime) {+ output.push(entry);+ inserted = true;+ }+ output.push(line);+ }+ if (!inserted) {+ output.push(entry);+ }++ let rawEvents = output.join("\n");+ if (rawEvents) {+ rawEvents += "\n";+ }++ return before + marker + "\n\n" + rawEvents;+}++// ββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Append an event to the daily event log.+ *+ * @param {string} vaultPath - Absolute path to the vault directory.+ * @param {string} agent - Agent name (e.g., "hermes-agent").+ * @param {string} message - Event message text.+ * @param {string|null} date - Optional date in YYYY.MM.DD format.+ * @param {string|null} time - Optional time in HH:MM format.+ * @returns {Promise<{path: string, relativePath: string, agent: string, date: string|null, time: string|null}>}+ */+export async function appendEvent(vaultPath, agent, message, date = null, time = null) {+ const eventDate = date || currentDate();+ const eventTime = validateEventTime(time || currentTime());++ const dailyDir = join(vaultPath, "Daily");+ const filePath = join(dailyDir, `${eventDate}.md`);++ await mkdir(dailyDir, { recursive: true });++ // Build the event line (replace newlines in message with spaces)+ const cleanMessage = redactText(message).replace(/\n/g, " ");+ const entry = `- ${eventTime} β @${agent} β ${cleanMessage}`;++ let content;+ if (existsSync(filePath)) {+ content = await readFile(filePath, "utf8");+ } else {+ content = newDailyNote(eventDate);+ }++ // Ensure the Raw events section exists+ if (!content.includes("## Raw events")) {+ content = content.trimEnd() + "\n\n## Raw events\n\n";+ }++ const updated = insertEventEntry(content, entry);++ // Atomic write using a temp file in the same directory+ const tmpPath = join(dailyDir, `.${eventDate}.tmp-${randomUUID()}`);+ await writeFile(tmpPath, updated, "utf8");++ // Rename is atomic on same filesystem+ const { rename } = await import("node:fs/promises");+ await rename(tmpPath, filePath);++ const relativePath = `Daily${require("node:path").sep}${eventDate}.md`;+ return {+ path: filePath,+ relativePath,+ agent,+ date: date || null,+ time: time || null,+ };+}diff --git a/openclaw/index.js b/openclaw/index.jsindex 0588fc18..53601b3c 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -1,195 +1,572 @@/*** OpenClaw native plugin entry for Open Second Brain.*- * Imports `definePluginEntry` from the OpenClaw host runtime and registers- * five tools that delegate to the Python CLI via `runPython()`. The JS- * entry runs inside OpenClaw's Node.js process; it never imports Python- * directly β it spawns `python3 -m open_second_brain.cli` with PYTHONPATH- * pointed at the plugin's `src/` directory.+ * Pure JavaScript implementation β all five tools operate directly on the+ * vault filesystem using `node:fs/promises` and `node:path`. No+ * subprocess creation, no native process module. Passes the OpenClaw security scanner.*- * Tool parameter schemas are taken from `src/open_second_brain/mcp.py`.+ * Tool parameter schemas match `src/open_second_brain/mcp.py` exactly.*/import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";-import { runPython } from "./o2b-runner.js";+import {+ listVaultPages,+ writeFrontmatter,+ slugify,+} from "./vault.js";+import { appendEvent } from "./event-log.js";+import {+ readFile,+ writeFile,+ mkdir,+ access,+ readdir,+ stat,+ unlink,+} from "node:fs/promises";+import {+ join,+ resolve,+ relative,+ dirname,+ basename,+ sep,+} from "node:path";+import { existsSync } from "node:fs";++// ββ Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++const PLUGIN_VERSION = "0.5.2";++const SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"];++// ββ Config helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Parse a simple YAML key: value file into an object.+ */+function parseSimpleYaml(text) {+ const data = {};+ for (const rawLine of text.split("\n")) {+ const line = rawLine.trim();+ if (!line || line.startsWith("#")) continue;+ if (!line.includes(":")) continue;+ const idx = line.indexOf(":");+ let key = line.slice(0, idx).trim();+ let value = line.slice(idx + 1).trim();+ // Strip surrounding quotes+ if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);+ if (value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);+ if (key) data[key] = value;+ }+ return data;+}++/**+ * Redact values for keys that look like secrets.+ */+function redactMapping(data) {+ const redacted = {};+ for (const [key, value] of Object.entries(data)) {+ const lowered = key.toLowerCase();+ if (SECRET_KEY_PARTS.some((part) => lowered.includes(part))) {+ redacted[key] = "[REDACTED]";+ } else {+ redacted[key] = value;+ }+ }+ return redacted;+}++/**+ * Discover config from the vault or the default path.+ */+function resolveVaultPath(api) {+ const config = api.pluginConfig || {};+ return config.vault || process.env.VAULT_DIR || ".";+}++/**+ * Get current date in YYYY.MM.DD format.+ */+function currentDate() {+ const now = new Date();+ const y = now.getFullYear();+ const m = String(now.getMonth() + 1).padStart(2, "0");+ const d = String(now.getDate()).padStart(2, "0");+ return `${y}.${m}.${d}`;+}++/**+ * Get current time in HH:MM 24-hour format.+ */+function currentTime() {+ const now = new Date();+ const h = String(now.getHours()).padStart(2, "0");+ const m = String(now.getMinutes()).padStart(2, "0");+ return `${h}:${m}`;+}/**- * Escape a single shell argument so it can be safely joined into a- * command string. Wraps the value in single-quotes and escapes any- * embedded single-quotes.+ * Get UTC timestamp for frontmatter.*/-function shArg(value) {- return "'" + String(value).replace(/'/g, "'\\''") + "'";+function utcTimestamp() {+ return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");}+/**+ * Compute relative path from vault to target.+ */+function vaultRelpath(target, vault) {+ try {+ return relative(resolve(vault), resolve(target));+ } catch {+ return String(target);+ }+}++/**+ * Ensure a target path stays inside the vault.+ */+function ensureInsideVault(target, vault) {+ const resolvedTarget = resolve(target);+ const resolvedVault = resolve(vault);+ if (!resolvedTarget.startsWith(resolvedVault + sep) && resolvedTarget !== resolvedVault) {+ throw new Error(`path escapes vault: ${target}`);+ }+ return resolvedTarget;+}++// ββ Health checks (pure JS) ββββββββββββββββββββββββββββββββββββββββββββββββ++async function checkVaultWritable(vaultPath) {+ if (!existsSync(vaultPath)) {+ return { name: "vault_writeable", ok: false, message: `vault directory missing: ${vaultPath}` };+ }+ const testPath = join(vaultPath, ".open-second-brain-doctor-test");+ try {+ await writeFile(testPath, "", "utf8");+ await unlink(testPath);+ } catch (exc) {+ return { name: "vault_writeable", ok: false, message: `cannot write to vault: ${exc}` };+ }+ return { name: "vault_writeable", ok: true, message: `vault exists and is writable: ${vaultPath}` };+}++async function checkDailyNotesDir(vaultPath) {+ const dailyDir = join(vaultPath, "Daily");+ if (existsSync(dailyDir)) {+ return { name: "daily_notes_dir", ok: true, message: `Daily notes directory exists: ${dailyDir}` };+ }+ return { name: "daily_notes_dir", ok: false, message: `Daily notes directory missing: ${dailyDir}` };+}++async function checkAIWikiDir(vaultPath) {+ const wikiDir = join(vaultPath, "AI Wiki");+ if (existsSync(wikiDir)) {+ return { name: "ai_wiki_dir", ok: true, message: `AI Wiki directory exists: ${wikiDir}` };+ }+ return { name: "ai_wiki_dir", ok: false, message: `AI Wiki directory missing: ${wikiDir}` };+}++async function checkNotesDir(vaultPath) {+ const notesDir = join(vaultPath, "AI Wiki", "notes");+ if (existsSync(notesDir)) {+ return { name: "notes_dir", ok: true, message: `Notes directory exists: ${notesDir}` };+ }+ return { name: "notes_dir", ok: false, message: `Notes directory missing: ${notesDir}` };+}++// ββ Plugin entry βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+export default definePluginEntry({async register(api) {// ββ second_brain_status ββββββββββββββββββββββββββββββββββββββββββββ- api.registerTool({- name: "second_brain_status",- description: "Report Open Second Brain configuration and vault status.",- parameters: {- type: "object",- properties: {},- additionalProperties: false,- },- async execute(_id, _params) {- const config = api.getConfig();- const vault = config?.vault || process.env.VAULT_DIR || ".";- const result = await runPython(["status", "--vault", vault]);- return { content: [{ type: "text", text: result }] };+ api.registerTool(+ {+ description: "Report Open Second Brain configuration and vault status.",+ parameters: {+ type: "object",+ properties: {},+ additionalProperties: false,+ },+ async execute() {+ const pluginConfig = api.pluginConfig || {};+ const vault = resolveVaultPath(api);++ // Try to discover config from default path or env+ let configPath = null;+ let configExists = false;+ let configData = {};++ const configOverride = process.env.OPEN_SECOND_BRAIN_CONFIG;+ const xdgHome = process.env.XDG_CONFIG_HOME;+ const defaultConfig = configOverride+ ? resolve(configOverride.replace(/^~/, process.env.HOME || ""))+ : xdgHome+ ? join(xdgHome, "open-second-brain", "config.yaml")+ : join(process.env.HOME || "/root", ".config", "open-second-brain", "config.yaml");++ configPath = defaultConfig;+ if (existsSync(configPath)) {+ configExists = true;+ try {+ const text = await readFile(configPath, "utf8");+ configData = parseSimpleYaml(text);+ } catch {+ configExists = false;+ }+ }++ const vaultExists = existsSync(vault);+ const configKeys = Object.keys(configData).sort();++ const result = {+ config_path: String(configPath),+ config_exists: configExists,+ config_keys: configKeys,+ config: redactMapping(configData),+ vault_path: vault,+ vault_exists: vaultExists,+ };++ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };+ },},- });+ { name: "second_brain_status" },+ );// ββ second_brain_query βββββββββββββββββββββββββββββββββββββββββββββ- 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(+ {+ 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) {+ const vault = resolveVaultPath(api);+ if (!existsSync(vault)) {+ throw new Error(`vault directory missing: ${vault}`);+ }++ const pattern = params.pattern || null;+ const limit = typeof params.limit === "number" ? params.limit : 50;++ if (limit < 1 || limit > 500) {+ throw new Error("argument 'limit' must be between 1 and 500");+ }++ const { allPages, matched } = await listVaultPages(vault, pattern, limit);++ const pages = matched.map((p) => ({+ title: p.title,+ path: p.relativePath,+ metadata: p.metadata,+ }));++ const result = {+ vault_path: vault,+ total_pages: allPages.length,+ returned: pages.length,+ limit,+ pattern,+ pages,+ };++ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };},- additionalProperties: false,- },- async execute(_id, params) {- const config = api.getConfig();- const vault = params.vault || config?.vault || process.env.VAULT_DIR || ".";- const args = ["tool-call", "--vault", vault, "second_brain_query"];- if (params.pattern) args.push("--tool-arg", `pattern=${params.pattern}`);- if (params.limit != null) args.push("--tool-arg", `limit=${params.limit}`);- const result = await runPython(args);- return { content: [{ type: "text", text: result }] };},- });+ { name: "second_brain_query" },+ );// ββ second_brain_capture βββββββββββββββββββββββββββββββββββββββββββ- api.registerTool({- name: "second_brain_capture",- description:- "Write a new Markdown note to AI Wiki/notes/ with frontmatter.",- parameters: {- type: "object",- properties: {- title: {- type: "string",- description: "Human-readable note title.",- },- content: {- type: "string",- description: "Markdown body of the note.",- },- tags: {- type: "array",- items: { type: "string" },- description: "Optional list of tag strings.",- },- overwrite: {- type: "boolean",- description:- "Allow overwriting an existing note with the same slug.",+ api.registerTool(+ {+ description: "Write a new Markdown note to AI Wiki/notes/ with frontmatter.",+ parameters: {+ type: "object",+ properties: {+ title: {+ type: "string",+ description: "Human-readable note title.",+ },+ content: {+ type: "string",+ description: "Markdown body of the note.",+ },+ tags: {+ type: "array",+ items: { type: "string" },+ description: "Optional list of tag strings.",+ },+ overwrite: {+ type: "boolean",+ description: "Allow overwriting an existing note with the same slug.",+ },},+ required: ["title", "content"],+ additionalProperties: false,+ },+ async execute(_id, params) {+ const vault = resolveVaultPath(api);+ if (!existsSync(vault)) {+ throw new Error(`vault directory missing: ${vault}`);+ }++ const title = params.title;+ const content = params.content;+ const tags = params.tags || [];+ const overwrite = !!params.overwrite;++ if (!title || !title.trim()) {+ throw new Error("title must not be empty");+ }+ if (!content || !content.trim()) {+ throw new Error("content must not be empty");+ }++ const notesDir = join(vault, "AI Wiki", "notes");+ const slug = slugify(title);+ const target = join(notesDir, `${slug}.md`);+ ensureInsideVault(target, vault);++ await mkdir(notesDir, { recursive: true });++ const noteExisted = existsSync(target);+ if (noteExisted && !overwrite) {+ throw new Error(`note already exists: ${vaultRelpath(target, vault)}`);+ }++ const metadata = {+ title,+ type: "note",+ created: utcTimestamp(),+ };+ if (tags.length > 0) {+ metadata.tags = tags;+ }++ await writeFrontmatter(target, metadata, content.trim());++ const result = {+ path: vaultRelpath(target, vault),+ absolute_path: resolve(target),+ slug,+ overwritten: noteExisted && overwrite,+ };++ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };},- required: ["title", "content"],- additionalProperties: false,- },- async execute(_id, params) {- const config = api.getConfig();- const vault = config?.vault || process.env.VAULT_DIR || ".";- const args = [- "tool-call", "--vault", vault, "second_brain_capture",- "--tool-arg", `title=${params.title}`,- "--tool-arg", `content=${params.content}`,- ];- if (params.tags && params.tags.length > 0) {- args.push("--tool-arg", `tags=${JSON.stringify(params.tags)}`);- }- if (params.overwrite) {- args.push("--tool-arg", "overwrite=true");- }- const result = await runPython(args);- return { content: [{ type: "text", text: result }] };},- });+ { name: "second_brain_capture" },+ );// ββ event_log_append βββββββββββββββββββββββββββββββββββββββββββββββ- api.registerTool({- name: "event_log_append",- description:- "Append a single-line event to the daily Markdown event log.",- parameters: {- type: "object",- properties: {- message: {- type: "string",- description: "Single-line event message.",- },- agent: {- type: "string",- description: "Agent name (default 'agent').",- },- date: {- type: "string",- description: "Optional event date in YYYY.MM.DD format.",- },- time: {- type: "string",- description: "Optional event time in 24-hour HH:MM format.",+ api.registerTool(+ {+ description: "Append a single-line event to the daily Markdown event log.",+ parameters: {+ type: "object",+ properties: {+ message: {+ type: "string",+ description: "Single-line event message.",+ },+ agent: {+ type: "string",+ description: "Agent name (default 'agent').",+ },+ date: {+ type: "string",+ description: "Optional event date in YYYY.MM.DD format.",+ },+ time: {+ type: "string",+ description: "Optional event time in 24-hour HH:MM format.",+ },},+ required: ["message"],+ additionalProperties: false,+ },+ async execute(_id, params) {+ const vault = resolveVaultPath(api);+ const message = params.message;+ if (!message) {+ throw new Error("missing required argument: message");+ }++ const agent = params.agent || process.env.VAULT_AGENT_NAME || "agent";+ const date = params.date || null;+ const time = params.time || null;++ const result = await appendEvent(vault, agent, message, date, time);++ return {+ content: [+ {+ type: "text",+ text: JSON.stringify(+ {+ path: vaultRelpath(result.path, vault),+ absolute_path: resolve(result.path),+ agent: result.agent,+ date: result.date,+ time: result.time,+ },+ null,+ 2,+ ),+ },+ ],+ };},- required: ["message"],- additionalProperties: false,- },- async execute(_id, params) {- const config = api.getConfig();- const vault = config?.vault || process.env.VAULT_DIR || ".";- const args = ["append-event", "--vault", vault];- if (params.agent) args.push("--as", params.agent);- if (params.date) args.push("--date", params.date);- if (params.time) args.push("--time", params.time);- args.push("--");- args.push(params.message);- const result = await runPython(args);- return { content: [{ type: "text", text: result }] };},- });+ { name: "event_log_append" },+ );// ββ vault_health βββββββββββββββββββββββββββββββββββββββββββββββββββ- 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(+ {+ 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) {+ const vault = resolveVaultPath(api);+ const checks = [];++ // Vault writable check+ checks.push(await checkVaultWritable(vault));++ // Daily notes dir+ checks.push(await checkDailyNotesDir(vault));++ // AI Wiki dir+ checks.push(await checkAIWikiDir(vault));++ // Notes dir+ checks.push(await checkNotesDir(vault));++ // Plugin manifest checks (only if repo provided)+ if (params.repo) {+ const repoRoot = params.repo;++ // Check openclaw.plugin.json+ const openclawManifestPath = join(repoRoot, "openclaw.plugin.json");+ if (existsSync(openclawManifestPath)) {+ try {+ const text = await readFile(openclawManifestPath, "utf8");+ const data = JSON.parse(text);+ if (data.id && data.configSchema) {+ checks.push({+ name: "openclaw_manifest",+ ok: true,+ message: `valid OpenClaw manifest: ${openclawManifestPath}`,+ });+ } else {+ checks.push({+ name: "openclaw_manifest",+ ok: false,+ message: `schema invalid: ${openclawManifestPath} (missing id or configSchema)`,+ });+ }+ } catch (exc) {+ checks.push({+ name: "openclaw_manifest",+ ok: false,+ message: `invalid JSON: ${openclawManifestPath} (${exc})`,+ });+ }+ } else {+ checks.push({+ name: "openclaw_manifest",+ ok: false,+ message: `missing: ${openclawManifestPath}`,+ });+ }++ // Check package.json+ const pkgPath = join(repoRoot, "package.json");+ if (existsSync(pkgPath)) {+ try {+ const data = JSON.parse(await readFile(pkgPath, "utf8"));+ const extensions = data?.openclaw?.extensions;+ if (Array.isArray(extensions) && extensions.length > 0) {+ checks.push({+ name: "openclaw_package_json_extensions",+ ok: true,+ message: `package.json declares ${extensions.length} extension(s)`,+ });+ // Check each extension file+ for (const entry of extensions) {+ const entryPath = join(repoRoot, entry);+ if (existsSync(entryPath)) {+ checks.push({+ name: `openclaw_entry_${entry}`,+ ok: true,+ message: `extension entry exists: ${entry}`,+ });+ } else {+ checks.push({+ name: `openclaw_entry_${entry}`,+ ok: false,+ message: `missing extension entry: ${entry}`,+ });+ }+ }+ } else {+ checks.push({+ name: "openclaw_package_json_extensions",+ ok: false,+ message: "package.json missing or empty openclaw.extensions array",+ });+ }+ } catch (exc) {+ checks.push({+ name: "openclaw_package_json",+ ok: false,+ message: `invalid JSON: ${pkgPath} (${exc})`,+ });+ }+ } else {+ checks.push({+ name: "openclaw_package_json",+ ok: false,+ message: `missing: ${pkgPath}`,+ });+ }+ }++ const result = {+ vault_path: vault,+ ok: checks.every((c) => c.ok),+ checks,+ };++ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };},- additionalProperties: false,- },- async execute(_id, params) {- const config = api.getConfig();- const vault = config?.vault || process.env.VAULT_DIR || ".";- const args = ["doctor", "--vault", vault];- if (params.repo) args.push("--repo", params.repo);- const result = await runPython(args);- return { content: [{ type: "text", text: result }] };},- });+ { name: "vault_health" },+ );},});diff --git a/openclaw/o2b-runner.js b/openclaw/o2b-runner.jsdeleted file mode 100644index 2657928b..00000000--- a/openclaw/o2b-runner.js+++ /dev/null@@ -1,41 +0,0 @@-/**- * Subprocess helper for calling the Open Second Brain Python CLI from- * the OpenClaw JS plugin entry.- *- * Spawns `python3 -m open_second_brain.cli` with PYTHONPATH pointed at the- * plugin's `src/` directory so the package is importable even when `o2b`- * is not on PATH (e.g. after a `git:` or `npm-pack:` install).- */--import { execFile } from "node:child_process";-import { fileURLToPath } from "node:url";-import path from "node:path";--const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PLUGIN_ROOT = path.resolve(__dirname, "..");-const PYTHON_SRC = path.join(PLUGIN_ROOT, "src");--/**- * Run a Python CLI command and return stdout.- *- * @param {string[]} args - Arguments forwarded to `python3 -m open_second_brain.cli`.- * @param {number} [timeout=30000] - Maximum execution time in milliseconds.- * @returns {Promise<string>} Trimmed stdout from the subprocess.- */-export function runPython(args, timeout = 30000) {- return new Promise((resolve, reject) => {- const env = { ...process.env, PYTHONPATH: PYTHON_SRC };- execFile(- "python3",- ["-m", "open_second_brain.cli", ...args],- { env, timeout, maxBuffer: 1024 * 1024 },- (err, stdout, stderr) => {- if (err) {- reject(new Error(stderr || err.message));- return;- }- resolve(stdout.trim());- },- );- });-}diff --git a/openclaw/vault.js b/openclaw/vault.jsnew file mode 100644index 00000000..dc703c80--- /dev/null+++ b/openclaw/vault.js@@ -0,0 +1,277 @@+/**+ * Pure JavaScript vault operations for Open Second Brain.+ *+ * All filesystem operations use `node:fs/promises` and `node:path`.+ * No native process module, no subprocess calls β passes the OpenClaw security scanner.+ *+ * Logic mirrors the Python implementation in `src/open_second_brain/vault.py`.+ */++import { readdir, readFile, writeFile, mkdir } from "node:fs/promises";+import { join, relative, sep, extname, basename, dirname, resolve, posix } from "node:path";+import { existsSync } from "node:fs";++// ββ Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++export const EXCLUDED_DIRS = new Set([+ ".git",+ ".obsidian",+ ".trash",+ ".stversions",+ "node_modules",+ "__pycache__",+ ".venv",+ "build",+ "dist",+ ".claude-plugin",+ ".codex-plugin",+]);++export const EXCLUDED_FILES = new Set([".DS_Store", ".gitkeep"]);++const SKIP_FILE_NAMES = new Set(["index.md", "log.md"]);++const FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;+const KEY_VALUE_RE = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$/;+const PLAIN_SCALAR_RE = /^[A-Za-z0-9_./-](?:[A-Za-z0-9_./ -]*[A-Za-z0-9_./-])?$/;++const WIKILINK_RE = /\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]/g;+const CODE_BLOCK_RE = /```[\s\S]*?```|`[^`]+`/g;++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",+ ".pdf",+]);++const SLUG_INVALID_RE = /[^a-z0-9]+/g;+const SLUG_MAX_LEN = 64;++// ββ Frontmatter ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Parse YAML-like frontmatter from markdown content.+ * Returns { frontmatter: {...}, body: "..." } or null if no frontmatter found.+ */+export function parseFrontmatter(content) {+ const match = FRONTMATTER_RE.exec(content);+ if (!match) {+ return null;+ }++ const fmBlock = match[1];+ const body = content.slice(match[0].length).trim();+ const frontmatter = {};++ for (const rawLine of fmBlock.split("\n")) {+ const line = rawLine.trim();+ if (!line || line.startsWith("#")) continue;++ const kv = KEY_VALUE_RE.exec(line);+ if (kv) {+ const key = kv[1];+ let value = kv[2].trim();+ // Strip surrounding quotes+ if (+ (value.startsWith('"') && value.endsWith('"')) ||+ (value.startsWith("'") && value.endsWith("'"))+ ) {+ value = value.slice(1, -1);+ }+ // Parse inline YAML arrays: [a, b, c]+ if (value.startsWith("[") && value.endsWith("]")) {+ const inner = value.slice(1, -1).trim();+ if (inner) {+ frontmatter[key] = inner.split(",").map((s) => {+ s = s.trim();+ if (+ (s.startsWith('"') && s.endsWith('"')) ||+ (s.startsWith("'") && s.endsWith("'"))+ ) {+ s = s.slice(1, -1);+ }+ return s;+ });+ } else {+ frontmatter[key] = [];+ }+ } else {+ frontmatter[key] = value;+ }+ }+ }++ return { frontmatter, body };+}++/**+ * Format a YAML scalar value, quoting if necessary.+ */+function formatYamlScalar(value) {+ const text = String(value);+ if (+ text &&+ PLAIN_SCALAR_RE.test(text) &&+ !text.includes(": ") &&+ !text.includes(" #")+ ) {+ return text;+ }+ const escaped = text+ .replace(/\\/g, "\\\\")+ .replace(/"/g, '\\"')+ .replace(/\n/g, "\\n")+ .replace(/\r/g, "\\r")+ .replace(/\t/g, "\\t");+ return `"${escaped}"`;+}++/**+ * Format a YAML value (scalar or array).+ */+function formatYamlValue(value) {+ if (Array.isArray(value)) {+ return "[" + value.map((item) => formatYamlScalar(item)).join(", ") + "]";+ }+ return formatYamlScalar(value);+}++/**+ * Write a markdown file with YAML frontmatter and body.+ * Creates parent directories if needed.+ */+export async function writeFrontmatter(filePath, frontmatter, body) {+ await mkdir(dirname(filePath), { recursive: true });++ const lines = ["---"];+ for (const [key, value] of Object.entries(frontmatter)) {+ lines.push(`${key}: ${formatYamlValue(value)}`);+ }+ lines.push("---");++ if (body) {+ lines.push("");+ lines.push(body);+ }++ await writeFile(filePath, lines.join("\n") + "\n", "utf8");+}++// ββ Slugify ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Convert title to URL-safe slug.+ * Lowercase, replace non-alphanumeric with dashes, trim to max length.+ */+export function slugify(title) {+ const lowered = title.trim().toLowerCase();+ let slug = lowered.replace(SLUG_INVALID_RE, "-").replace(/^-+|-+$/g, "");+ if (!slug) slug = "note";+ slug = slug.slice(0, SLUG_MAX_LEN).replace(/-+$/, "");+ return slug || "note";+}++// ββ Wikilinks ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Extract [[wikilinks]] from markdown content.+ * Skips links inside code blocks and media file targets.+ * Returns unique targets in order of appearance.+ */+export function extractWikilinks(content) {+ // Mask code blocks+ const masked = content.replace(CODE_BLOCK_RE, " ");++ const seen = new Set();+ const result = [];++ // Reset the global regex+ WIKILINK_RE.lastIndex = 0;+ let match;+ while ((match = WIKILINK_RE.exec(masked)) !== null) {+ const target = match[1];+ const ext = extname(target).toLowerCase();+ if (MEDIA_EXTENSIONS.has(ext)) continue;+ if (!seen.has(target)) {+ seen.add(target);+ result.push(target);+ }+ }++ return result;+}++// ββ Vault page listing βββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Recursively list all markdown pages in a vault directory.+ * Returns [{ title, path, relativePath, metadata }].+ * Sorted alphabetically by title (case-insensitive).+ */+export async function listVaultPages(vaultPath, pattern = null, limit = 50) {+ const pages = [];++ async function walk(dir) {+ let entries;+ try {+ entries = await readdir(dir, { withFileTypes: true });+ } catch {+ return;+ }++ for (const entry of entries) {+ if (entry.isDirectory()) {+ if (EXCLUDED_DIRS.has(entry.name)) continue;+ await walk(join(dir, entry.name));+ } else if (entry.isFile() && entry.name.endsWith(".md")) {+ if (EXCLUDED_FILES.has(entry.name)) continue;+ if (SKIP_FILE_NAMES.has(entry.name.toLowerCase())) continue;++ const fullPath = join(dir, entry.name);+ const relPath = relative(vaultPath, fullPath);+ // Skip if any directory component is excluded+ const parts = relPath.split(sep);+ if (parts.some((p) => EXCLUDED_DIRS.has(p))) continue;++ let content;+ try {+ content = await readFile(fullPath, "utf8");+ } catch {+ continue;+ }++ const parsed = parseFrontmatter(content);+ const metadata = parsed ? parsed.frontmatter : {};+ const title =+ metadata && metadata.title ? metadata.title : basename(entry.name, ".md");++ pages.push({+ title,+ path: fullPath,+ relativePath: relPath,+ metadata: metadata || {},+ });+ }+ }+ }++ await walk(vaultPath);++ // Sort by title case-insensitive+ pages.sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase()));++ // Apply pattern filter+ let matched = pages;+ if (pattern) {+ const needle = pattern.toLowerCase();+ matched = pages.filter((p) => p.title.toLowerCase().includes(needle));+ }++ // Apply limit+ if (limit && matched.length > limit) {+ matched = matched.slice(0, limit);+ }++ return { allPages: pages, matched };+}diff --git a/package.json b/package.jsonindex d477f6c1..d6cc31ed 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.5.1",+ "version": "0.5.2","type": "module","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",diff --git a/plugin.yaml b/plugin.yamlindex c90b4cbd..7934c195 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.5.1"+version: "0.5.2"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 97b9ed63..07f7b494 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.5.1"+version: "0.5.2"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex 820c89d9..5fa01026 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "open-second-brain"-version = "0.5.1"+version = "0.5.2"description = "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw."readme = "README.md"requires-python = ">=3.11"diff --git a/src/open_second_brain/__init__.py b/src/open_second_brain/__init__.pyindex 75bac37d..dabb0218 100644--- a/src/open_second_brain/__init__.py+++ b/src/open_second_brain/__init__.py@@ -1,3 +1,3 @@"""Open Second Brain core package."""-__version__ = "0.5.1"+__version__ = "0.5.2"diff --git a/src/open_second_brain/mcp.py b/src/open_second_brain/mcp.pyindex f1a7d6a8..05249372 100644--- a/src/open_second_brain/mcp.py+++ b/src/open_second_brain/mcp.py@@ -29,7 +29,7 @@ from open_second_brain.vault import list_vault_pages, parse_frontmatter, write_fPROTOCOL_VERSION = "2025-06-18"SERVER_NAME = "open-second-brain"-SERVER_VERSION = "0.5.1"+SERVER_VERSION = "0.5.2"JSONRPC_VERSION = "2.0"# JSON-RPC 2.0 error codes used by the MCP server.diff --git a/tests/test_openclaw_plugin.py b/tests/test_openclaw_plugin.pyindex afa97cbc..4c1a55bb 100644--- a/tests/test_openclaw_plugin.py+++ b/tests/test_openclaw_plugin.py@@ -34,7 +34,7 @@ class OpenClawManifestValidityTests(unittest.TestCase):self.assertEqual(schema["type"], "object")def test_manifest_has_version(self):- self.assertEqual(self.manifest["version"], "0.5.1")+ self.assertEqual(self.manifest["version"], "0.5.2")def test_manifest_declares_tools(self):tools = self.manifest["contracts"]["tools"]@@ -133,7 +133,7 @@ class OpenClawPackageJsonTests(unittest.TestCase):self.assertEqual(self.pkg["name"], "open-second-brain")def test_package_json_has_version(self):- self.assertEqual(self.pkg["version"], "0.5.1")+ self.assertEqual(self.pkg["version"], "0.5.2")def test_package_json_has_type_module(self):self.assertEqual(self.pkg["type"], "module")@@ -228,9 +228,61 @@ class OpenClawInstallabilityTests(unittest.TestCase):"""The JS entry declared in package.json must exist."""self.assertTrue((ROOT / "openclaw" / "index.js").is_file())- def test_openclaw_runner_js_exists(self):- """The subprocess helper must exist."""- self.assertTrue((ROOT / "openclaw" / "o2b-runner.js").is_file())+ def test_openclaw_vault_js_exists(self):+ """The pure JS vault module must exist."""+ self.assertTrue((ROOT / "openclaw" / "vault.js").is_file())++ def test_openclaw_event_log_js_exists(self):+ """The pure JS event-log module must exist."""+ self.assertTrue((ROOT / "openclaw" / "event-log.js").is_file())+++class OpenClawSecurityTests(unittest.TestCase):+ """Verify that the OpenClaw JS entry contains no subprocess calls."""++ @classmethod+ def setUpClass(cls):+ cls.index_js = (ROOT / "openclaw" / "index.js").read_text(encoding="utf-8")+ cls.vault_js = (ROOT / "openclaw" / "vault.js").read_text(encoding="utf-8")+ cls.event_log_js = (ROOT / "openclaw" / "event-log.js").read_text(encoding="utf-8")++ def test_index_js_no_child_process_import(self):+ """index.js must not import child_process."""+ self.assertNotIn("child_process", self.index_js)++ def test_index_js_no_exec_file(self):+ """index.js must not call execFile."""+ self.assertNotIn("execFile", self.index_js)++ def test_index_js_no_exec(self):+ """index.js must not call exec (subprocess)."""+ for line in self.index_js.splitlines():+ stripped = line.strip()+ # Skip method definitions like "async execute()" and "async execute(_id, params)"+ if stripped.startswith("async execute("):+ continue+ # Look for standalone exec calls (not .exec() on regex)+ if "exec" in stripped.lower() and ".exec(" not in stripped:+ self.fail(f"Found subprocess-like 'exec' in index.js: {stripped}")++ def test_index_js_no_spawn(self):+ """index.js must not call spawn."""+ self.assertNotIn("spawn", self.index_js)++ def test_vault_js_no_child_process(self):+ """vault.js must not import child_process."""+ self.assertNotIn("child_process", self.vault_js)++ def test_event_log_js_no_child_process(self):+ """event-log.js must not import child_process."""+ self.assertNotIn("child_process", self.event_log_js)++ def test_runner_js_deleted(self):+ """o2b-runner.js must no longer exist."""+ self.assertFalse(+ (ROOT / "openclaw" / "o2b-runner.js").exists(),+ "openclaw/o2b-runner.js should have been deleted",+ )if __name__ == "__main__":