Skip to content

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

TypeScript

feat: add CLI foundation (#2)

Sol Aitken37de4a020b9d
diff --git a/README.md b/README.md
index 286390c3..83e2b487 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@ Open Second Brain is an open-source, plugin-first second brain package for AI ag
It is designed to give Hermes Agent, Claude Code, OpenAI Codex, and other agentic runtimes a shared, portable way to remember durable project knowledge, append operational event logs, query an Obsidian-compatible vault, and carry the same workflow across machines without locking knowledge into one agent runtime.
-Status: experimental v0 design. The first release target is documentation, CLI foundations, skills, and plugin manifests. Deeper runtime integrations and MCP support are planned for later versions.
+Status: experimental v0. The repository currently includes documentation, a tested Python CLI foundation, skills, and plugin manifests. Deeper runtime integrations and MCP support are planned for later versions.
## Goals
@@ -58,6 +58,42 @@ Open Second Brain is plugin-first, but not plugin-only.
- CLI tools provide deterministic operations that should not depend on model reasoning.
- MCP can be added later as a shared tool API over the same core.
+## CLI foundation
+
+Run the local CLI without installing the package:
+
+```bash
+scripts/asb status
+scripts/asb append-event --vault /path/to/vault --as agent-name --date 2026.05.06 --time 10:15 "created first entry"
+scripts/asb export-config --config ~/.config/open-second-brain/config.yaml --output /tmp/open-second-brain-config.json
+scripts/vault-log --vault /path/to/vault --as agent-name "compatibility event entry"
+```
+
+The current CLI is intentionally small and dependency-free. It supports:
+
+- config path discovery through `OPEN_SECOND_BRAIN_CONFIG`, `XDG_CONFIG_HOME`, or `~/.config/open-second-brain/config.yaml`;
+- redacted config export;
+- append-only daily Markdown event logging;
+- a `vault-log` compatibility wrapper.
+
+## Development
+
+Run the test suite with the Python standard library:
+
+```bash
+PYTHONPATH=src python3 -m unittest discover -s tests -v
+```
+
+Run static syntax checks used by the initial PRs:
+
+```bash
+python3 -m json.tool .claude-plugin/plugin.json >/dev/null
+python3 -m json.tool .codex-plugin/plugin.json >/dev/null
+python3 -m py_compile plugins/hermes/__init__.py
+bash -n scripts/asb
+bash -n scripts/vault-log
+```
+
## License
MIT. See `LICENSE`.
diff --git a/docs/plans/2026-05-06-cli-foundation.md b/docs/plans/2026-05-06-cli-foundation.md
new file mode 100644
index 00000000..4b458e95
--- /dev/null
+++ b/docs/plans/2026-05-06-cli-foundation.md
@@ -0,0 +1,397 @@
+# CLI Foundation Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Replace placeholder shell scripts with a tested Python CLI foundation for Open Second Brain.
+
+**Architecture:** The repository will expose a small Python package under `src/open_second_brain/`. The CLI entrypoint will be `open_second_brain.cli:main`, with the existing `scripts/asb` and `scripts/vault-log` shell wrappers delegating to Python modules. v0 keeps dependencies to the Python standard library.
+
+**Tech Stack:** Python 3.11+, argparse, unittest, pathlib, json, datetime, tempfile.
+
+---
+
+## File Structure
+
+- Create `pyproject.toml`: package metadata, Python requirement, console scripts for future installers.
+- Create `src/open_second_brain/__init__.py`: package version.
+- Create `src/open_second_brain/config.py`: config path discovery and minimal redacted status model.
+- Create `src/open_second_brain/event_log.py`: append-only daily Markdown event log backend.
+- Create `src/open_second_brain/cli.py`: `asb` CLI with `status`, `append-event`, and `export-config` commands.
+- Create `src/open_second_brain/vault_log.py`: compatibility CLI for `vault-log`.
+- Modify `scripts/asb`: shell wrapper that runs `python3 -m open_second_brain.cli` with local `src` on `PYTHONPATH`.
+- Modify `scripts/vault-log`: shell wrapper that runs `python3 -m open_second_brain.vault_log` with local `src` on `PYTHONPATH`.
+- Create `tests/test_config.py`: config path/status tests.
+- Create `tests/test_event_log.py`: append-only daily Markdown backend tests.
+- Create `tests/test_cli.py`: CLI smoke tests.
+- Modify `README.md`: add CLI development/test commands.
+- Modify `docs/roadmap.md`: mark CLI foundation as in progress/done after implementation.
+
+## Task 1: Package Metadata
+
+**Files:**
+- Create: `pyproject.toml`
+- Create: `src/open_second_brain/__init__.py`
+
+- [ ] **Step 1: Add package metadata**
+
+Create `pyproject.toml`:
+
+```toml
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "open-second-brain"
+version = "0.0.1"
+description = "Plugin-first second brain package for AI agents and humans."
+readme = "README.md"
+requires-python = ">=3.11"
+license = { text = "MIT" }
+authors = [{ name = "Open Second Brain contributors" }]
+keywords = ["second-brain", "obsidian", "agents", "skills", "event-log"]
+dependencies = []
+
+[project.scripts]
+asb = "open_second_brain.cli:main"
+vault-log = "open_second_brain.vault_log:main"
+
+[tool.setuptools.packages.find]
+where = ["src"]
+```
+
+Create `src/open_second_brain/__init__.py`:
+
+```python
+"""Open Second Brain core package."""
+
+__version__ = "0.0.1"
+```
+
+- [ ] **Step 2: Verify metadata imports**
+
+Run:
+
+```bash
+PYTHONPATH=src python3 -c "import open_second_brain; print(open_second_brain.__version__)"
+```
+
+Expected output:
+
+```text
+0.0.1
+```
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add pyproject.toml src/open_second_brain/__init__.py
+git commit -m "chore: add python package metadata"
+```
+
+## Task 2: Config Discovery
+
+**Files:**
+- Create: `src/open_second_brain/config.py`
+- Create: `tests/test_config.py`
+
+- [ ] **Step 1: Write failing config tests**
+
+Create `tests/test_config.py`:
+
+```python
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from open_second_brain.config import default_config_path, discover_config, redact_mapping
+
+
+class ConfigTests(unittest.TestCase):
+ def test_default_config_path_uses_env_override(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "custom.yaml"
+ with patch.dict(os.environ, {"OPEN_SECOND_BRAIN_CONFIG": str(path)}):
+ self.assertEqual(default_config_path(), path)
+
+ def test_default_config_path_uses_xdg_config_home(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ with patch.dict(os.environ, {"XDG_CONFIG_HOME": tmp}, clear=False):
+ with patch.dict(os.environ, {"OPEN_SECOND_BRAIN_CONFIG": ""}, clear=False):
+ self.assertEqual(default_config_path(), Path(tmp) / "open-second-brain" / "config.yaml")
+
+ def test_discover_config_reports_missing_config(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "missing.yaml"
+ result = discover_config(path)
+ self.assertFalse(result.exists)
+ self.assertEqual(result.path, path)
+ self.assertEqual(result.data, {})
+
+ def test_discover_config_reads_simple_key_value_yaml(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "config.yaml"
+ path.write_text("instance_name: Test Brain\nruntime: hermes\n", encoding="utf-8")
+ result = discover_config(path)
+ self.assertTrue(result.exists)
+ self.assertEqual(result.data["instance_name"], "Test Brain")
+ self.assertEqual(result.data["runtime"], "hermes")
+
+ def test_redact_mapping_redacts_secret_like_keys(self):
+ redacted = redact_mapping({"api_key": "abc", "path": "/tmp/vault", "token": "xyz"})
+
+ self.assertEqual(redacted["api_key"], "[REDACTED]")
+ self.assertEqual(redacted["token"], "[REDACTED]")
+ self.assertEqual(redacted["path"], "/tmp/vault")
+
+
+if __name__ == "__main__":
+ unittest.main()
+```
+
+- [ ] **Step 2: Run tests and verify failure**
+
+Run:
+
+```bash
+PYTHONPATH=src python3 -m unittest tests.test_config -v
+```
+
+Expected: FAIL because `open_second_brain.config` does not exist yet.
+
+- [ ] **Step 3: Implement config module**
+
+Create `src/open_second_brain/config.py` with:
+
+```python
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+SECRET_KEY_PARTS = ("key", "token", "secret", "password", "credential")
+
+
+@dataclass(frozen=True)
+class ConfigDiscovery:
+ path: Path
+ exists: bool
+ data: dict[str, str]
+
+
+def default_config_path() -> Path:
+ override = os.environ.get("OPEN_SECOND_BRAIN_CONFIG")
+ if override:
+ return Path(override).expanduser()
+ config_home = os.environ.get("XDG_CONFIG_HOME")
+ if config_home:
+ return Path(config_home).expanduser() / "open-second-brain" / "config.yaml"
+ return Path.home() / ".config" / "open-second-brain" / "config.yaml"
+
+
+def parse_simple_yaml(text: str) -> dict[str, str]:
+ data: dict[str, str] = {}
+ for raw_line in text.splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("#"):
+ continue
+ if ":" not in line:
+ continue
+ key, value = line.split(":", 1)
+ key = key.strip()
+ value = value.strip().strip('"').strip("'")
+ if key:
+ data[key] = value
+ return data
+
+
+def discover_config(path: Path | None = None) -> ConfigDiscovery:
+ resolved = path or default_config_path()
+ if not resolved.exists():
+ return ConfigDiscovery(path=resolved, exists=False, data={})
+ return ConfigDiscovery(path=resolved, exists=True, data=parse_simple_yaml(resolved.read_text(encoding="utf-8")))
+
+
+def redact_mapping(data: dict[str, Any]) -> dict[str, Any]:
+ redacted: dict[str, Any] = {}
+ for key, value in data.items():
+ lowered = key.lower()
+ if any(part in lowered for part in SECRET_KEY_PARTS):
+ redacted[key] = "[REDACTED]"
+ else:
+ redacted[key] = value
+ return redacted
+```
+
+- [ ] **Step 4: Run tests and verify pass**
+
+Run:
+
+```bash
+PYTHONPATH=src python3 -m unittest tests.test_config -v
+```
+
+Expected: OK.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add src/open_second_brain/config.py tests/test_config.py
+git commit -m "feat: add config discovery"
+```
+
+## Task 3: Event Log Backend
+
+**Files:**
+- Create: `src/open_second_brain/event_log.py`
+- Create: `tests/test_event_log.py`
+
+- [ ] **Step 1: Write failing event log tests**
+
+Create tests for daily Markdown creation, append-only behavior, explicit date/time, and secret redaction.
+
+- [ ] **Step 2: Run tests and verify failure**
+
+Run:
+
+```bash
+PYTHONPATH=src python3 -m unittest tests.test_event_log -v
+```
+
+Expected: FAIL because `open_second_brain.event_log` does not exist yet.
+
+- [ ] **Step 3: Implement event log module**
+
+Implement `append_event(vault_dir, agent, message, date, time)` with default daily Markdown backend.
+
+- [ ] **Step 4: Run tests and verify pass**
+
+Run:
+
+```bash
+PYTHONPATH=src python3 -m unittest tests.test_event_log -v
+```
+
+Expected: OK.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add src/open_second_brain/event_log.py tests/test_event_log.py
+git commit -m "feat: add daily markdown event log backend"
+```
+
+## Task 4: CLI Commands
+
+**Files:**
+- Create: `src/open_second_brain/cli.py`
+- Create: `src/open_second_brain/vault_log.py`
+- Modify: `scripts/asb`
+- Modify: `scripts/vault-log`
+- Create: `tests/test_cli.py`
+
+- [ ] **Step 1: Write failing CLI tests**
+
+Test `asb status`, `asb append-event`, and `vault-log --as` using temporary vault directories.
+
+- [ ] **Step 2: Run tests and verify failure**
+
+Run:
+
+```bash
+PYTHONPATH=src python3 -m unittest tests.test_cli -v
+```
+
+Expected: FAIL because CLI modules do not exist yet.
+
+- [ ] **Step 3: Implement CLI modules and wrappers**
+
+Use argparse. Keep output stable and plain-text.
+
+- [ ] **Step 4: Run tests and verify pass**
+
+Run:
+
+```bash
+PYTHONPATH=src python3 -m unittest tests.test_cli -v
+```
+
+Expected: OK.
+
+- [ ] **Step 5: Run full tests**
+
+Run:
+
+```bash
+PYTHONPATH=src python3 -m unittest discover -s tests -v
+```
+
+Expected: OK.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add src/open_second_brain/cli.py src/open_second_brain/vault_log.py scripts/asb scripts/vault-log tests/test_cli.py
+git commit -m "feat: add cli entrypoints"
+```
+
+## Task 5: Documentation Update and PR
+
+**Files:**
+- Modify: `README.md`
+- Modify: `docs/roadmap.md`
+
+- [ ] **Step 1: Document development commands**
+
+Add commands for running tests and invoking local scripts.
+
+- [ ] **Step 2: Run full verification**
+
+Run:
+
+```bash
+PYTHONPATH=src python3 -m unittest discover -s tests -v
+python3 -m json.tool .claude-plugin/plugin.json >/dev/null
+python3 -m json.tool .codex-plugin/plugin.json >/dev/null
+python3 -m py_compile plugins/hermes/__init__.py
+bash -n scripts/asb
+bash -n scripts/vault-log
+```
+
+Expected: all commands pass.
+
+- [ ] **Step 3: Commit documentation**
+
+```bash
+git add README.md docs/roadmap.md docs/plans/2026-05-06-cli-foundation.md
+git commit -m "docs: add cli foundation plan and usage notes"
+```
+
+- [ ] **Step 4: Push and open PR**
+
+```bash
+git push -u origin feat/cli-foundation
+gh pr create --base main --head feat/cli-foundation --title "feat: add CLI foundation" --body "..."
+```
+
+## Self-review
+
+Spec coverage:
+
+- v0 CLI foundation is covered by package metadata, config discovery, event log backend, CLI entrypoints, tests, and documentation.
+- Plugin manifests and skills remain in place.
+- MCP and deep runtime hooks remain future work.
+
+Placeholder scan:
+
+- The plan includes concrete files, commands, and expected outcomes for every implementation step.
+- Implementation followed strict TDD: tests were written and observed failing before production modules were added.
+
+Type consistency:
+
+- Config module names are consistent: `default_config_path`, `discover_config`, `redact_mapping`.
+- Event log command names are consistent: `asb append-event`, `vault-log --as`.
diff --git a/docs/roadmap.md b/docs/roadmap.md
index bb45f034..50425c7b 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -8,7 +8,7 @@ Scope:
- README and design documentation;
- architecture notes;
-- CLI placeholders;
+- tested CLI foundation;
- event log concept;
- skills for Open Second Brain and event logging;
- Hermes plugin skeleton;
@@ -20,25 +20,28 @@ Scope:
## v0.1: deterministic CLI
-Planned commands:
+Implemented foundation:
```text
-asb init
asb status
-asb doctor
asb export-config
asb append-event
vault-log
```
-Expected behavior:
+Current behavior:
+
+- locate config through `OPEN_SECOND_BRAIN_CONFIG`, `XDG_CONFIG_HOME`, or the default user config path;
+- append event log entries to daily Markdown notes;
+- export redacted config snapshots;
+- keep the CLI dependency-free and testable with Python `unittest`.
+
+Still planned for this track:
-- locate config;
-- initialize machine-local config;
-- adopt an existing vault profile;
-- append event log entries;
-- export redacted snapshots;
-- validate schema and paths.
+```text
+asb init
+asb doctor
+```
## v0.2: vault profile bootstrap
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 00000000..6ae408e4
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,21 @@
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "open-second-brain"
+version = "0.0.1"
+description = "Plugin-first second brain package for AI agents and humans."
+readme = "README.md"
+requires-python = ">=3.11"
+license = { text = "MIT" }
+authors = [{ name = "Open Second Brain contributors" }]
+keywords = ["second-brain", "obsidian", "agents", "skills", "event-log"]
+dependencies = []
+
+[project.scripts]
+asb = "open_second_brain.cli:main"
+vault-log = "open_second_brain.vault_log:main"
+
+[tool.setuptools.packages.find]
+where = ["src"]
diff --git a/scripts/asb b/scripts/asb
index a9557484..eddbb05e 100755
--- a/scripts/asb
+++ b/scripts/asb
@@ -1,15 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
-cat <<'MSG'
-open-second-brain CLI placeholder
-
-Planned commands:
- asb init
- asb status
- asb doctor
- asb export-config
- asb append-event
-
-This repository is currently at the v0 documentation/skeleton stage.
-MSG
+SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
+REPO_ROOT=$(cd -- "$SCRIPT_DIR/.." && pwd)
+export PYTHONPATH="$REPO_ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
+exec python3 -m open_second_brain.cli "$@"
diff --git a/scripts/vault-log b/scripts/vault-log
index e9c163d7..dcfefcf6 100755
--- a/scripts/vault-log
+++ b/scripts/vault-log
@@ -1,9 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
-cat <<'MSG'
-vault-log placeholder for open-second-brain
-
-This compatibility command will append short factual entries to the configured event log backend.
-In v0, the implementation is intentionally not included yet.
-MSG
+SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
+REPO_ROOT=$(cd -- "$SCRIPT_DIR/.." && pwd)
+export PYTHONPATH="$REPO_ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
+exec python3 -m open_second_brain.vault_log "$@"
diff --git a/src/open_second_brain/__init__.py b/src/open_second_brain/__init__.py
new file mode 100644
index 00000000..2be37a4f
--- /dev/null
+++ b/src/open_second_brain/__init__.py
@@ -0,0 +1,3 @@
+"""Open Second Brain core package."""
+
+__version__ = "0.0.1"
diff --git a/src/open_second_brain/cli.py b/src/open_second_brain/cli.py
new file mode 100644
index 00000000..50f44ec1
--- /dev/null
+++ b/src/open_second_brain/cli.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+
+from open_second_brain.config import discover_config, redact_mapping
+from open_second_brain.event_log import append_event
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(prog="asb", description="Open Second Brain CLI")
+ subcommands = parser.add_subparsers(dest="command", required=True)
+
+ status = subcommands.add_parser("status", help="Show Open Second Brain configuration status")
+ status.add_argument("--config", type=Path, default=None, help="Config file path")
+
+ append = subcommands.add_parser("append-event", help="Append an event to the configured event log backend")
+ append.add_argument("message", help="Single-line event message")
+ append.add_argument("--vault", type=Path, default=None, help="Vault directory")
+ append.add_argument("--as", dest="agent", default=os.environ.get("VAULT_AGENT_NAME", "agent"), help="Agent name")
+ append.add_argument("--date", default=None, help="Event date as YYYY.MM.DD")
+ append.add_argument("--time", default=None, help="Event time as HH:MM")
+
+ export = subcommands.add_parser("export-config", help="Write a redacted config snapshot")
+ export.add_argument("--config", type=Path, default=None, help="Config file path")
+ export.add_argument("--output", type=Path, required=True, help="Output JSON file")
+
+ return parser
+
+
+def command_status(args: argparse.Namespace) -> int:
+ result = discover_config(args.config)
+ print(f"config_path: {result.path}")
+ print(f"config_exists: {str(result.exists).lower()}")
+ if result.data:
+ print("config_keys:")
+ for key in sorted(result.data):
+ print(f"- {key}")
+ return 0
+
+
+def command_append_event(args: argparse.Namespace) -> int:
+ vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))
+ path = append_event(vault, args.agent, args.message, date=args.date, time=args.time)
+ print(f"appended: {path}")
+ return 0
+
+
+def command_export_config(args: argparse.Namespace) -> int:
+ result = discover_config(args.config)
+ snapshot = {
+ "config_path": str(result.path),
+ "config_exists": result.exists,
+ "config": redact_mapping(result.data),
+ }
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(json.dumps(snapshot, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ print(f"exported: {args.output}")
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ if args.command == "status":
+ return command_status(args)
+ if args.command == "append-event":
+ return command_append_event(args)
+ if args.command == "export-config":
+ return command_export_config(args)
+ raise AssertionError(f"unhandled command: {args.command}")
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/open_second_brain/config.py b/src/open_second_brain/config.py
new file mode 100644
index 00000000..6c9e6cb6
--- /dev/null
+++ b/src/open_second_brain/config.py
@@ -0,0 +1,65 @@
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+SECRET_KEY_PARTS = ("key", "token", "secret", "password", "credential")
+
+
+@dataclass(frozen=True)
+class ConfigDiscovery:
+ path: Path
+ exists: bool
+ data: dict[str, str]
+
+
+def default_config_path() -> Path:
+ override = os.environ.get("OPEN_SECOND_BRAIN_CONFIG")
+ if override:
+ return Path(override).expanduser()
+
+ config_home = os.environ.get("XDG_CONFIG_HOME")
+ if config_home:
+ return Path(config_home).expanduser() / "open-second-brain" / "config.yaml"
+
+ return Path.home() / ".config" / "open-second-brain" / "config.yaml"
+
+
+def parse_simple_yaml(text: str) -> dict[str, str]:
+ data: dict[str, str] = {}
+ for raw_line in text.splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("#"):
+ continue
+ if ":" not in line:
+ continue
+ key, value = line.split(":", 1)
+ key = key.strip()
+ value = value.strip().strip('"').strip("'")
+ if key:
+ data[key] = value
+ return data
+
+
+def discover_config(path: Path | None = None) -> ConfigDiscovery:
+ resolved = path or default_config_path()
+ if not resolved.is_file():
+ return ConfigDiscovery(path=resolved, exists=False, data={})
+ try:
+ data = parse_simple_yaml(resolved.read_text(encoding="utf-8"))
+ except (OSError, UnicodeDecodeError, ValueError):
+ return ConfigDiscovery(path=resolved, exists=False, data={})
+ return ConfigDiscovery(path=resolved, exists=True, data=data)
+
+
+def redact_mapping(data: dict[str, Any]) -> dict[str, Any]:
+ redacted: dict[str, Any] = {}
+ for key, value in data.items():
+ lowered = key.lower()
+ if any(part in lowered for part in SECRET_KEY_PARTS):
+ redacted[key] = "[REDACTED]"
+ else:
+ redacted[key] = value
+ return redacted
diff --git a/src/open_second_brain/event_log.py b/src/open_second_brain/event_log.py
new file mode 100644
index 00000000..a012d54f
--- /dev/null
+++ b/src/open_second_brain/event_log.py
@@ -0,0 +1,128 @@
+from __future__ import annotations
+
+import fcntl
+import os
+import re
+import tempfile
+from datetime import datetime
+from pathlib import Path
+
+SECRET_ASSIGNMENT_RE = re.compile(
+ r"\b(api[_-]?key|token|secret|password|credential)(\s*[:=]\s*)([^\s]+)",
+ re.IGNORECASE,
+)
+EVENT_RE = re.compile(r"^- (\d{2}:\d{2}) β€” @")
+TIME_RE = re.compile(r"^(\d{2}):(\d{2})$")
+
+
+def redact_text(text: str) -> str:
+ return SECRET_ASSIGNMENT_RE.sub(lambda match: f"{match.group(1)}{match.group(2)}[REDACTED]", text)
+
+
+def current_date() -> str:
+ return datetime.now().strftime("%Y.%m.%d")
+
+
+def current_time() -> str:
+ return datetime.now().strftime("%H:%M")
+
+
+def daily_note_path(vault_dir: Path, date: str) -> Path:
+ return vault_dir / "Daily" / f"{date}.md"
+
+
+def new_daily_note(date: str) -> str:
+ return f"---\nformatted: false\n---\n\n# {date}\n\n## Raw events\n\n"
+
+
+def validate_event_time(value: str) -> str:
+ match = TIME_RE.match(value)
+ if not match:
+ raise ValueError("event time must use HH:MM 24-hour format")
+ hour = int(match.group(1))
+ minute = int(match.group(2))
+ if hour > 23 or minute > 59:
+ raise ValueError("event time must use HH:MM 24-hour format")
+ return value
+
+
+def append_event(
+ vault_dir: Path,
+ agent: str,
+ message: str,
+ *,
+ date: str | None = None,
+ time: str | None = None,
+) -> Path:
+ event_date = date or current_date()
+ event_time = validate_event_time(time or current_time())
+ path = daily_note_path(vault_dir, event_date)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ lock_path = path.with_name(f".{path.name}.lock")
+
+ entry = f"- {event_time} β€” @{agent} β€” {redact_text(message).replace(chr(10), ' ')}"
+ temp_name: str | None = None
+
+ with lock_path.open("a+b") as lock_file:
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
+ try:
+ if path.exists():
+ content = path.read_text(encoding="utf-8")
+ else:
+ content = new_daily_note(event_date)
+
+ if "## Raw events" not in content:
+ content = content.rstrip() + "\n\n## Raw events\n\n"
+
+ updated = insert_event_entry(content, entry)
+ with tempfile.NamedTemporaryFile(
+ "w",
+ encoding="utf-8",
+ dir=path.parent,
+ prefix=f".{path.name}.",
+ suffix=".tmp",
+ delete=False,
+ ) as temp_file:
+ temp_name = temp_file.name
+ temp_file.write(updated)
+ temp_file.flush()
+ os.fsync(temp_file.fileno())
+ os.replace(temp_name, path)
+ temp_name = None
+ dir_fd = os.open(path.parent, os.O_RDONLY)
+ try:
+ os.fsync(dir_fd)
+ finally:
+ os.close(dir_fd)
+ finally:
+ if temp_name is not None:
+ try:
+ os.unlink(temp_name)
+ except FileNotFoundError:
+ pass
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
+ return path
+
+
+def insert_event_entry(content: str, entry: str) -> str:
+ marker = "## Raw events"
+ before, after = content.split(marker, 1)
+ after = after.lstrip("\n")
+ lines = [line for line in after.splitlines() if line.strip()]
+
+ entry_time = entry[2:7]
+ inserted = False
+ output: list[str] = []
+ for line in lines:
+ match = EVENT_RE.match(line)
+ if not inserted and match and match.group(1) > entry_time:
+ output.append(entry)
+ inserted = True
+ output.append(line)
+ if not inserted:
+ output.append(entry)
+
+ raw_events = "\n".join(output)
+ if raw_events:
+ raw_events += "\n"
+ return before + marker + "\n\n" + raw_events
diff --git a/src/open_second_brain/vault_log.py b/src/open_second_brain/vault_log.py
new file mode 100644
index 00000000..860dec5b
--- /dev/null
+++ b/src/open_second_brain/vault_log.py
@@ -0,0 +1,29 @@
+from __future__ import annotations
+
+import argparse
+import os
+from pathlib import Path
+
+from open_second_brain.event_log import append_event
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(prog="vault-log", description="Append an Open Second Brain event log entry")
+ parser.add_argument("message", help="Single-line event message")
+ parser.add_argument("--as", dest="agent", default=os.environ.get("VAULT_AGENT_NAME", "agent"), help="Agent name")
+ parser.add_argument("--vault", type=Path, default=None, help="Vault directory")
+ parser.add_argument("--date", default=None, help="Event date as YYYY.MM.DD")
+ parser.add_argument("--time", default=None, help="Event time as HH:MM")
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))
+ path = append_event(vault, args.agent, args.message, date=args.date, time=args.time)
+ print(f"appended: {path}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_cli.py b/tests/test_cli.py
new file mode 100644
index 00000000..ffa9935c
--- /dev/null
+++ b/tests/test_cli.py
@@ -0,0 +1,94 @@
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[1]
+ENV = {**os.environ, "PYTHONPATH": str(ROOT / "src")}
+
+
+def run_module(module, *args, env=None):
+ return subprocess.run(
+ [sys.executable, "-m", module, *args],
+ cwd=ROOT,
+ env={**ENV, **(env or {})},
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=30,
+ )
+
+
+def run_cli(*args, env=None):
+ return run_module("open_second_brain.cli", *args, env=env)
+
+
+class CliTests(unittest.TestCase):
+ def test_status_reports_missing_config(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ config = Path(tmp) / "missing.yaml"
+ result = run_cli("status", env={"OPEN_SECOND_BRAIN_CONFIG": str(config)})
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("config_exists: false", result.stdout)
+ self.assertIn(str(config), result.stdout)
+
+ def test_append_event_writes_daily_note(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ result = run_cli(
+ "append-event",
+ "created CLI",
+ "--vault",
+ tmp,
+ "--as",
+ "test-agent",
+ "--date",
+ "2026.05.06",
+ "--time",
+ "10:15",
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ daily = Path(tmp) / "Daily" / "2026.05.06.md"
+ self.assertIn("- 10:15 β€” @test-agent β€” created CLI", daily.read_text(encoding="utf-8"))
+
+ def test_export_config_writes_redacted_json(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ config = Path(tmp) / "config.yaml"
+ config.write_text("api_key: abc\nvault_path: /tmp/vault\n", encoding="utf-8")
+ output = Path(tmp) / "snapshot.json"
+ result = run_cli(
+ "export-config",
+ "--config",
+ str(config),
+ "--output",
+ str(output),
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ data = json.loads(output.read_text(encoding="utf-8"))
+ self.assertEqual(data["config"]["api_key"], "[REDACTED]")
+ self.assertEqual(data["config"]["vault_path"], "/tmp/vault")
+
+ def test_vault_log_compatibility_module(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ result = run_module(
+ "open_second_brain.vault_log",
+ "--as",
+ "compat-agent",
+ "--vault",
+ tmp,
+ "--date",
+ "2026.05.06",
+ "--time",
+ "10:30",
+ "compat entry",
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ daily = Path(tmp) / "Daily" / "2026.05.06.md"
+ self.assertIn("- 10:30 β€” @compat-agent β€” compat entry", daily.read_text(encoding="utf-8"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_config.py b/tests/test_config.py
new file mode 100644
index 00000000..6af80074
--- /dev/null
+++ b/tests/test_config.py
@@ -0,0 +1,64 @@
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from open_second_brain.config import default_config_path, discover_config, redact_mapping
+
+
+class ConfigTests(unittest.TestCase):
+ def test_default_config_path_uses_env_override(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "custom.yaml"
+ with patch.dict(os.environ, {"OPEN_SECOND_BRAIN_CONFIG": str(path)}):
+ self.assertEqual(default_config_path(), path)
+
+ def test_default_config_path_uses_xdg_config_home(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ with patch.dict(os.environ, {"XDG_CONFIG_HOME": tmp, "OPEN_SECOND_BRAIN_CONFIG": ""}, clear=False):
+ self.assertEqual(default_config_path(), Path(tmp) / "open-second-brain" / "config.yaml")
+
+ def test_discover_config_reports_missing_config(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "missing.yaml"
+ result = discover_config(path)
+ self.assertFalse(result.exists)
+ self.assertEqual(result.path, path)
+ self.assertEqual(result.data, {})
+
+ def test_discover_config_reads_simple_key_value_yaml(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "config.yaml"
+ path.write_text("instance_name: Test Brain\nruntime: hermes\n", encoding="utf-8")
+ result = discover_config(path)
+ self.assertTrue(result.exists)
+ self.assertEqual(result.data["instance_name"], "Test Brain")
+ self.assertEqual(result.data["runtime"], "hermes")
+
+ def test_discover_config_reports_directory_as_missing(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp)
+ result = discover_config(path)
+ self.assertFalse(result.exists)
+ self.assertEqual(result.path, path)
+ self.assertEqual(result.data, {})
+
+ def test_discover_config_reports_invalid_utf8_as_missing(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "config.yaml"
+ path.write_bytes(b"\xff\xfe\x00")
+ result = discover_config(path)
+ self.assertFalse(result.exists)
+ self.assertEqual(result.path, path)
+ self.assertEqual(result.data, {})
+
+ def test_redact_mapping_redacts_secret_like_keys(self):
+ redacted = redact_mapping({"api_key": "abc", "path": "/tmp/vault", "token": "xyz"})
+ self.assertEqual(redacted["api_key"], "[REDACTED]")
+ self.assertEqual(redacted["token"], "[REDACTED]")
+ self.assertEqual(redacted["path"], "/tmp/vault")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_event_log.py b/tests/test_event_log.py
new file mode 100644
index 00000000..70bf425c
--- /dev/null
+++ b/tests/test_event_log.py
@@ -0,0 +1,79 @@
+import multiprocessing
+import tempfile
+import unittest
+from pathlib import Path
+
+from open_second_brain.event_log import append_event, redact_text
+
+
+def append_concurrent_event(vault_dir: str, index: int) -> None:
+ append_event(
+ Path(vault_dir),
+ "worker",
+ f"entry {index}",
+ date="2026.05.06",
+ time=f"10:{index:02d}",
+ )
+
+
+class EventLogTests(unittest.TestCase):
+ def test_append_event_creates_daily_note_with_raw_events_section(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = append_event(
+ vault_dir=Path(tmp),
+ agent="test-agent",
+ message="created project skeleton",
+ date="2026.05.06",
+ time="09:30",
+ )
+ self.assertEqual(path, Path(tmp) / "Daily" / "2026.05.06.md")
+ self.assertEqual(
+ path.read_text(encoding="utf-8"),
+ "---\nformatted: false\n---\n\n# 2026.05.06\n\n## Raw events\n\n- 09:30 β€” @test-agent β€” created project skeleton\n",
+ )
+
+ def test_append_event_preserves_manual_content_above_raw_events(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ daily = Path(tmp) / "Daily" / "2026.05.06.md"
+ daily.parent.mkdir(parents=True)
+ daily.write_text("# 2026.05.06\n\nManual note.\n\n## Raw events\n\n- 08:00 β€” @old β€” old entry\n", encoding="utf-8")
+ append_event(Path(tmp), "new", "new entry", date="2026.05.06", time="09:00")
+ self.assertEqual(
+ daily.read_text(encoding="utf-8"),
+ "# 2026.05.06\n\nManual note.\n\n## Raw events\n\n- 08:00 β€” @old β€” old entry\n- 09:00 β€” @new β€” new entry\n",
+ )
+
+ def test_append_event_inserts_entries_chronologically(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ append_event(Path(tmp), "agent", "later", date="2026.05.06", time="11:00")
+ append_event(Path(tmp), "agent", "earlier", date="2026.05.06", time="09:00")
+ content = (Path(tmp) / "Daily" / "2026.05.06.md").read_text(encoding="utf-8")
+ self.assertLess(content.index("09:00"), content.index("11:00"))
+
+ def test_append_event_rejects_invalid_explicit_times(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ for invalid_time in ("9:00", "25:00", "bad"):
+ with self.subTest(invalid_time=invalid_time):
+ with self.assertRaises(ValueError):
+ append_event(Path(tmp), "agent", "message", date="2026.05.06", time=invalid_time)
+
+ def test_concurrent_process_appends_keep_all_entries(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ processes = [multiprocessing.Process(target=append_concurrent_event, args=(tmp, index)) for index in range(12)]
+ for process in processes:
+ process.start()
+ for process in processes:
+ process.join(10)
+ self.assertEqual(process.exitcode, 0)
+
+ content = (Path(tmp) / "Daily" / "2026.05.06.md").read_text(encoding="utf-8")
+ for index in range(12):
+ self.assertIn(f"- 10:{index:02d} β€” @worker β€” entry {index}", content)
+ self.assertEqual(content.count("@worker β€” entry"), 12)
+
+ def test_redact_text_removes_secret_like_assignments(self):
+ self.assertEqual(redact_text("api_key=abc token: xyz password = qwerty"), "api_key=[REDACTED] token: [REDACTED] password = [REDACTED]")
+
+
+if __name__ == "__main__":
+ unittest.main()