Skip to content

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

TypeScript

v0.10.8: Retire event_log_append from agent surface + JSONL sidecar

Sol Aitken25f3b0940b68
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fdba265a..e546ff10 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,108 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.10.8] - 2026-05-19
+
+Closes §32 (retire `event_log_append` from every agent-facing surface
+in favor of `Brain/log/` as the single source of truth) and §23 (write
+a JSONL sidecar `Brain/log/<date>.jsonl` next to every markdown log
+day, with discipline-report switched to read JSONL when present and
+fall back to markdown when not). Companion design and impl plan at
+`docs/plans/2026-05-19-v0.10.8-design.md` and
+`docs/plans/2026-05-19-v0.10.8-impl.md`.
+
+### Added
+
+- §32B - `brain_note` MCP tool in the always-loaded writer-server
+ scope. Records one narrative-milestone line under event kind
+ `note` in `Brain/log/<today>.md` (plus the JSONL sidecar). Text
+ is run through `sanitiseTextField` (newline-collapse, secret
+ redaction, 4096-char cap). The agent identity is resolved through
+ the standard `resolveAgentName` chain so cron-jobs and runtime
+ shims share the same identity rules.
+- §32B - new `BRAIN_LOG_EVENT_KIND.note` constant and matching
+ `BrainNoteLogEvent` member in the discriminated union.
+ Discipline-report's `AgentCounts` gains a `note` counter that
+ surfaces in the Telegram MarkdownV2 block alongside `feedback`
+ and `apply-evidence`.
+- §23 - JSONL sidecar `Brain/log/<date>.jsonl` written atomically
+ next to each markdown event by `appendLogEvent`, under a single
+ `proper-lockfile` lock that protects the markdown-plus-JSONL pair
+ from interleaved concurrent writers. Each row is
+ `{ts, kind, payload}`; the payload is a one-to-one projection of
+ the markdown bullet body, with array bullets encoded as JSON
+ arrays.
+- §23 - new module `src/core/brain/log-jsonl.ts` exporting
+ `readLogDay(vault, date) -> {entries, source, warnings}`. JSONL
+ is preferred when present; falls back to `parseLogDay` for the
+ markdown-only case (historical pre-v0.10.8 days). Malformed
+ JSONL rows surface as warnings, not errors.
+
+### Changed
+
+- §32C - the Stop guardrail (`hooks/lib/messages.ts:stopGuardrailReason`)
+ and the PostToolUse reminder (`postWriteReminder`) point at the
+ three Brain writer tools (`brain_feedback`, `brain_apply_evidence`,
+ `brain_note`). `event_log_append` is no longer named anywhere on
+ the agent-facing surface.
+- §32C - `hooks/lib/detect.ts:BRAIN_EVENT_NAME_SUFFIX` and
+ `BRAIN_EVENT_BASH_NEEDLES` cover only the three Brain writer
+ tools. The `o2b append-event` / `vault-log` bash needles are
+ removed; those CLIs still work for human use but no longer
+ suppress the Stop guardrail.
+- §32D - all three identity-reminder templates
+ (`templates/identity-reminder.txt`, `.hermes.txt`, `.openclaw.txt`)
+ rewritten to direct agents to `brain_feedback` /
+ `brain_apply_evidence` / `brain_note` and to mention the
+ `Brain/log/<today>.md` (+ JSONL sidecar) destination. The
+ byte-pinned fixtures and the Python parity test are regenerated.
+- §32E - `hooks/README.md` rewritten to describe v0.10.8 semantics:
+ Brain/log/ as the single agent-facing log surface, Daily/ as the
+ human-CLI surface, and the JSONL sidecar contract.
+- §32F - `o2b append-event` CLI verb (`cmdAppendEvent` in
+ `src/cli/main.ts`) resolves the agent through `resolveAgentName`
+ instead of the literal `"agent"` fallback. Cron-jobs that already
+ set `VAULT_AGENT_NAME` are unaffected; cron-jobs that previously
+ relied on the literal `"agent"` get the config-declared identity
+ instead of a corrupted `@agent` Daily entry.
+- §32G - `event_log_append` MCP tool removed from every runtime:
+ the OpenClaw `registerTool` block, the `toolEventLogAppend`
+ handler in `src/mcp/tools.ts`, and the Hermes docstring mention.
+ The bare `appendEvent` function in `src/core/event-log.ts` stays
+ for the CLI verb (§32F) and any future shell-side use.
+- §23 - discipline-report (`src/core/discipline/log-counts.ts`)
+ reads through `readLogDay`. Same return shape; counts now include
+ the new `note` kind.
+
+### Migration
+
+No vault data migration is required. Historical `Brain/log/<date>.md`
+files without a sidecar JSONL are served by the reader's
+markdown-fallback path; the next write on any date produces both
+files. No installer changes; no schema bump in `_brain.yaml`.
+
+The Stop guardrail no longer clears on a bash `vault-log` /
+`o2b append-event` invocation - the operator or agent must use one
+of the three brain-event tools or finish the turn silently. Cron-jobs
+that use `o2b append-event` keep working; they just no longer count
+as a "brain event" for the guardrail.
+
+### Release-checklist gate
+
+Before shipping v0.10.8 from the working branch:
+
+1. `bun test` - all suites pass.
+2. `o2b discipline report` on `/root/vault` - status `ok` or
+ `info`; every `known_agent` with activity since v0.10.7 has at
+ least one brain event recorded (the lightweight §32A gate; see
+ the design doc for the rationale on dropping the calendar gate).
+3. Smoke: a `brain_note` MCP call produces both
+ `Brain/log/<today>.md` and `Brain/log/<today>.jsonl`, describing
+ the same event (same `ts`, `kind`, payload keys).
+4. Manual MCP probe: `event_log_append` is absent from
+ `bun src/mcp/main.ts` (full), `--scope writer`, the OpenClaw
+ bundle, and the Hermes tool list.
+
## [0.10.7] - 2026-05-18
Closes the remaining §30 (Agent logging discipline) work from
diff --git a/README.md b/README.md
index 5bf331e6..4c4b1926 100644
--- a/README.md
+++ b/README.md
@@ -22,9 +22,14 @@ Three loops cooperate over plain Markdown:
- **Accretion.** A deterministic `dream` pass clusters repeat signals
into rules — counters and atomic file moves, no LLM.
- **Application.** Agents log whether each rule was `applied` /
- `violated` / `outdated`. `Brain/active.md` is auto-regenerated and
- injected at session start; `brain_search` exposes full-text search
- across the whole vault.
+ `violated` / `outdated`, or record a narrative milestone via
+ `brain_note` for events that fit neither category. `Brain/active.md`
+ is auto-regenerated and injected at session start; `brain_search`
+ exposes full-text search across the whole vault.
+
+Every event lands in `Brain/log/<date>.md` (human-facing) plus a
+structured `Brain/log/<date>.jsonl` sidecar (machine-facing), written
+atomically by one writer so the two stay in lockstep.
```mermaid
flowchart LR
@@ -32,6 +37,7 @@ flowchart LR
Agent -- brain_feedback --> Inbox[(Brain/inbox/)]
Inbox -. dream .-> Pref[(Brain/preferences/)]
Agent -- brain_apply_evidence --> Log[(Brain/log/)]
+ Agent -- brain_note --> Log
Log -. dream .-> Pref
Pref -. regenerate .-> Active[Brain/active.md]
Active -- SessionStart hook --> Agent
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 861c47c2..41c2c51a 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -385,7 +385,7 @@ content as **resources** (added in v0.9.1):
| `osb://status` | Markdown form of the `second_brain_status.brain` block |
| `osb://preference/{id}` | one `pref-` / `ret-` file |
| `osb://topic/{slug}` | every signal + active/retired pref for a topic |
-| `osb://log/{date}` | one day's `Brain/log/YYYY-MM-DD.md` |
+| `osb://log/{date}` | one day's `Brain/log/YYYY-MM-DD.md` (a parallel `YYYY-MM-DD.jsonl` sidecar carries the same events as one JSON row per line for machine consumers) |
| `osb://backlinks/{id}` | inverted reference map for `<id>` |
Resources are pure read; mutating verbs stay on `tools/call`.
@@ -653,8 +653,10 @@ These are invariants of the system, not configuration to enable.
- **Atomic per-file writes.** Every mutation goes through
write-temp + rename; an interrupted run never leaves partial files.
- **Audit-traceable.** Every state change emits a typed event in
- `Brain/log/<day>.md`. The log is append-only; the dream log entry
- for a run records exactly which preferences moved and why.
+ `Brain/log/<day>.md` plus a structured `<day>.jsonl` sidecar
+ (machine readers prefer the JSONL and fall back to parsing the
+ markdown for historical days). The log is append-only; the dream
+ log entry for a run records exactly which preferences moved and why.
- **Reversible.** Pre-run snapshots plus
`o2b brain rollback <run-id>` let you undo any single dream pass.
- **Path-safe.** Every writer routes through a vault-boundary check;
diff --git a/docs/plans/2026-05-19-v0.10.8-design.md b/docs/plans/2026-05-19-v0.10.8-design.md
new file mode 100644
index 00000000..a1ec17de
--- /dev/null
+++ b/docs/plans/2026-05-19-v0.10.8-design.md
@@ -0,0 +1,638 @@
+# v0.10.8 design - retire `event_log_append` + JSONL log sidecar
+
+Closes `Projects/OpenSecondBrain/Features/_summary.md` items §32 (full
+removal of `event_log_append` from the agent-facing surface; unification
+of all three runtimes on `Brain/log/` as the single source of truth)
+and §23 (structured JSONL copy `Brain/log/<date>.jsonl` written next to
+the existing markdown file, with discipline-report and future machine
+consumers switched to read JSONL instead of parsing markdown). Shipped
+together as v0.10.8.
+
+The companion implementation plan lives at
+`2026-05-19-v0.10.8-impl.md`.
+
+## 1. Why this release
+
+Two issues prevent agents from logging reliably:
+
+1. The v0.9 design declared `Daily/` deprecated as an agent-facing
+ write path, but four leftover surfaces still direct agents back into
+ it: three identity-reminder templates, the Stop guardrail message,
+ the hook event-name detector, and `hooks/README.md`. The MCP tool
+ `event_log_append` itself has been absent from `buildToolTable()`
+ since v0.9, yet the templates instruct agents to call it. Less
+ trained models fall back to bash `vault-log`; better trained models
+ skip logging entirely.
+2. Machine consumers of `Brain/log/<date>.md` parse markdown ad-hoc.
+ The discipline report (`src/core/discipline/log-counts.ts`) is the
+ first such consumer; future tooling will compound the cost. A
+ structured copy of the log next to the markdown is the natural fix.
+
+v0.10.8 closes both at once because they touch the same module
+(`src/core/brain/log.ts`) and the same operator-visible contract
+("where do brain events live"). Splitting would force two passes over
+the same surface within days of each other.
+
+## 2. Goals
+
+- All three runtimes (Claude Code, Codex, Hermes, plus OpenClaw)
+ observe one and only one agent-facing log surface: `Brain/log/`.
+- The Stop guardrail clears on any of `brain_feedback`,
+ `brain_apply_evidence`, `brain_note` - no third path.
+- A new `brain_note` MCP tool gives agents a Brain-native way to record
+ narrative milestones that do not fit `feedback` or `apply-evidence`.
+- Every write to `Brain/log/<date>.md` is mirrored to
+ `Brain/log/<date>.jsonl` in the same atomic operation.
+- `discipline-report` (and any future machine consumer) reads JSONL
+ when present and falls back to markdown when not.
+- No data migration. Existing markdown days without a sidecar JSONL
+ keep working through the reader's fallback path.
+- MEMORY housekeeping removes language-specific anchors from
+ `/root/.claude/projects/-root/memory/` per the operator's standing
+ rule "no hard-coded user language".
+
+## 3. Non-goals
+
+- No CLI verb `o2b brain note` in this release. Triggered later by a
+ concrete need for shell-side note recording.
+- No auto-watcher for stray `Daily/` writes from `@agent-identity`.
+ The drift-check is operator-run (`o2b discipline report`).
+- No migration of historical `Daily/` entries into `Brain/log/`.
+ `Daily/` stays as a human-CLI surface (cron-jobs, ad-hoc scripts).
+- No bidirectional MEMORY <-> Brain sync. The existing one-way bridge
+ (v0.10.7 §E) is enough; reverse is deferred per §E Deferred entry.
+- No `--include-archived` flag for snapshots. Snapshot already covers
+ the whole `Brain/` tree, JSONL is included automatically.
+
+## 4. Subtrack breakdown
+
+The subtracks map to `_summary.md` §32A through §32H plus §23. They
+ship as one PR; the order below is the order in which a reviewer should
+read the diff, not necessarily the order of commits.
+
+### 4.1 §32A - lightweight verification gate
+
+The literal wording of §32A in `_summary.md` asks for "≥1 brain event
+per day per known_agent for one week after v0.10.7". v0.10.7 shipped
+2026-05-18; v0.10.8 cannot wait seven days without violating the
+"no dates in planning" rule and stalling the release. We replace the
+seven-day calendar gate with a triggered gate:
+
+- Before the operator ships v0.10.8, run `o2b discipline report` on
+ the production vault for the window between v0.10.7's ship moment
+ and now.
+- Pass condition: for every agent name in `_brain.yaml:
+ discipline_report.known_agents` that has any activity in the window
+ (git activity, mtime walk, vault delta), there is at least one
+ `brain_feedback`, `brain_apply_evidence`, or `brain_note` event
+ attributed to that agent.
+- Fail condition: an agent has activity but zero brain events. Stop;
+ investigate; do not remove the old surface.
+- No code asserts. This is a release-checklist item documented in
+ `2026-05-19-v0.10.8-impl.md` and the v0.10.8 CHANGELOG migration
+ block.
+- Rationale for replacing the calendar gate: the original "one week"
+ threshold is a proxy for "agents have proved they use the new
+ channel". The proxy survives translation to "observed brain events
+ per agent per window" without losing meaning, and it is not bound
+ to a date the planning rules forbid.
+
+### 4.2 §32B - `brain_note` MCP tool
+
+#### 4.2.1 Contract
+
+```
+brain_note({
+ text: string, // required
+ agent?: string // optional override
+})
+```
+
+Writes one event block to `Brain/log/<today>.md`:
+
+```
+## HH:MM:SSZ - note
+- text: <redacted, newline-collapsed message>
+- agent: <resolved agent>
+```
+
+#### 4.2.2 Resolution and hygiene rules
+
+- `agent` follows the same resolver chain as `brain_feedback`:
+ `normalizeAgentArgument(args.agent) ?? resolveAgentName(config)`.
+- `text` is run through `redactText` (the secret-stripper from
+ `src/core/event-log.ts`, lifted out to a shared module - see
+ §4.7 "Shared sanitizer").
+- Newlines (`\r?\n`) collapse to single spaces - one event = one line
+ in the markdown bullet and one line in the JSONL row.
+- Length cap: 4096 characters after redaction; the writer raises
+ `Error("brain_note: text exceeds 4096 chars")` on overflow.
+- Empty / whitespace-only `text` raises `Error("brain_note: text is
+ required")`. Mirrors `event_log_append`'s old behaviour.
+
+#### 4.2.3 Plumbing
+
+- New event kind constant:
+ `BRAIN_LOG_EVENT_KIND.note = "note"` in `src/core/brain/types.ts`.
+- New typed event interface:
+ ```ts
+ export interface BrainNoteLogEvent extends BrainLogEventBase {
+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.note;
+ readonly text: string;
+ readonly agent: string;
+ }
+ ```
+ added to the `BrainLogEvent` discriminated union.
+- New tool handler `toolBrainNote` in `src/mcp/brain-tools.ts`
+ (lives with the other brain tools, not in `tools.ts`).
+- New definition in `BRAIN_TOOLS`:
+ ```ts
+ {
+ name: "brain_note",
+ description: "Append one narrative-milestone line to today's Brain log.",
+ inputSchema: { ... },
+ handler: toolBrainNote,
+ }
+ ```
+- `WRITER_TOOL_NAMES` in `src/mcp/tools.ts` gains `"brain_note"` so
+ the always-loaded writer scope advertises three tools instead of
+ two.
+- `buildInstructions` writer branch updated to name three tools, not
+ two.
+
+#### 4.2.4 Discipline-report integration
+
+`src/core/discipline/log-counts.ts:AgentCounts` gains one field:
+
+```ts
+export interface AgentCounts {
+ readonly feedback: number;
+ readonly apply_evidence: number;
+ readonly note: number; // new
+ readonly other: number;
+ readonly total: number;
+}
+```
+
+The renderer (`src/core/discipline/render.ts`) shows `note` next to
+`feedback` and `apply_evidence`. Telegram and JSON output reflect the
+new key.
+
+### 4.3 §32C - drop `event_log_append` from the hook surface
+
+Files touched:
+
+- `hooks/lib/detect.ts`
+ - `BRAIN_EVENT_NAME_SUFFIX` regex changes from
+ `(event_log_append|brain_feedback|brain_apply_evidence)` to
+ `(brain_feedback|brain_apply_evidence|brain_note)`.
+ - `BRAIN_EVENT_BASH_NEEDLES` loses `"o2b append-event"` and
+ `"vault-log "`. It gains nothing in this release. The
+ `o2b brain feedback` / `o2b brain apply-evidence` entries stay.
+ - Comments updated to drop the `event_log_append` paragraph.
+- `hooks/lib/messages.ts`
+ - `stopGuardrailReason` body no longer mentions `event_log_append`.
+ The "pick whichever fits this turn" block lists three triggers:
+ `brain_feedback`, `brain_apply_evidence`, `brain_note`.
+ - `stopGuardrailCadenceLine` for `codex` replaces
+ `"call \`event_log_append\` now"` with `"call \`brain_feedback\`
+ / \`brain_apply_evidence\` / \`brain_note\` now"`.
+- Existing tests in `tests/hooks/detect.test.ts`,
+ `tests/hooks/stop-log-guardrail.test.ts` are updated to assert the
+ new behaviour (no event_log_append clear, three new triggers do
+ clear).
+
+### 4.4 §32D - rewrite identity-reminder templates
+
+All three templates rewritten in lock-step:
+
+- `templates/identity-reminder.txt` (common, single source of truth).
+- `templates/identity-reminder.hermes.txt` (preserves "Hermes turns
+ are short; do not batch across turns").
+- `templates/identity-reminder.openclaw.txt` (preserves "OpenClaw has
+ no session boundary; log immediately").
+
+New body (common, single line per template by convention; runtime
+variants substitute the cadence note):
+
+> [open-second-brain] Identity: @{agent}. After a durable artifact
+> (code, config, instruction-file edit, content artifact, research
+> finding) call `brain_feedback` if the turn surfaced a new user
+> preference, `brain_apply_evidence` (`result: applied | violated |
+> outdated`) if an active preference in `Brain/preferences/` scopes
+> to the artifact, or `brain_note` for narrative milestones that fit
+> neither. Skip pure discussion, exploration, read-only queries, and
+> planning without an artifact.
+
+The Hermes Python shim (`plugins/hermes/__init__.py`) caches the
+template per process; a `hermes gateway restart` after install
+refreshes it.
+
+`tests/fixtures/identity-reminder/{hermes,openclaw}.txt` and the
+common-template tests are updated to the new wording. The fixture
+files are byte-pinned so future drift is caught by
+`tests/core/identity-reminder.test.ts`.
+
+### 4.5 §32E - clean up `hooks/README.md`
+
+The v0.8-era table and prose are rewritten to describe v0.10.8 reality:
+
+- Brain/log/ is the single agent-facing log; Daily/ is human-CLI.
+- PostToolUse reminder lists three triggers
+ (`brain_feedback` / `brain_apply_evidence` / `brain_note`).
+- Stop guardrail clears on any of those three.
+- One paragraph announces the JSONL sidecar - what it is, where it
+ lives, why machine consumers should read it instead of parsing
+ markdown.
+
+No code change accompanies this section; documentation only.
+
+### 4.6 §32F - `cmdAppendEvent` resolves agent through config
+
+`src/cli/main.ts:313-341`. Current behaviour falls back to the literal
+string `"agent"` when neither `--as` nor `VAULT_AGENT_NAME` is set;
+this is the source of corrupted Daily entries with `@agent` instead of
+`@claude-vps-agent`.
+
+Replacement:
+
+```ts
+async function cmdAppendEvent(argv: string[]): Promise<number> {
+ const { flags, positional } = parseFlags(argv, {
+ vault: { type: "string" },
+ as: { type: "string" }, // no default
+ date: { type: "string" },
+ time: { type: "string" },
+ config: { type: "string" },
+ });
+ if (positional.length < 1) {
+ process.stderr.write("error: append-event requires a message argument\n");
+ return 2;
+ }
+ const message = positional[0]!;
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+ const tz = resolveTimezone(config);
+ const explicit = flags["as"] as string | undefined;
+ const agent = explicit ?? resolveAgentName(config);
+ // ... appendEvent call unchanged
+}
+```
+
+`resolveAgentName` already exists (it powers every other CLI verb that
+needs an identity). The env-var fallback `VAULT_AGENT_NAME` is part of
+its chain, so cron-jobs that rely on the env keep working.
+
+New test: `tests/cli/append-event.test.ts`: "Without --as and without
+env, config `agent_name: xyz` produces a Daily entry with `@xyz`."
+
+### 4.7 §32G - drop the old handler from all runtimes
+
+A full kill, not a hidden-CLI keep. The MCP tool is gone from every
+agent-facing surface; the underlying `appendEvent` function stays for
+the CLI verb and any future shell-side use.
+
+Files touched:
+
+- `src/openclaw/index.ts` - remove the
+ `api.registerTool({ name: "event_log_append", ... })` block (~50
+ lines).
+- `src/mcp/tools.ts`
+ - Remove `toolEventLogAppend` (the standalone function).
+ - Remove the corresponding comment block that explains "intentionally
+ not advertised".
+ - Remove `appendEvent` and `validateEventTime` imports if no longer
+ used (the file still uses `resolveAgentName` and friends for the
+ other tools).
+- `plugins/hermes/__init__.py` - docstring update: drop
+ `event_log_append` from the per-tool list in the module-level
+ comment. No functional change.
+- `tests/openclaw/bundle.test.ts` - drop the assertion that the
+ OpenClaw bundle registers `event_log_append`.
+- `tests/mcp/mcp.test.ts` - already does not advertise
+ `event_log_append`; only comment cleanup if any.
+
+The shared `appendEvent` function in `src/core/event-log.ts` is
+preserved (cron-jobs, `o2b append-event` CLI verb, future scripts).
+
+### 4.8 §32H - drift-check
+
+Operator-run, not automated:
+
+1. Right after v0.10.8 ships: `o2b discipline report --window 1d`.
+ Verify status is `ok` or `info`, not `alert`.
+2. Sustained check (operator's eyes, no code): grep `Daily/<date>.md`
+ for `@agent` literal or `@<known_agent>` entries written by an LLM
+ runtime. None expected.
+3. Trigger to revert §32C/D: any of the above produces an event from
+ an agent name in `known_agents` that did not come from a human CLI
+ (cron, shell). Document the case and re-open §32.
+
+Section in the v0.10.8 CHANGELOG migration block describes the
+trigger; no code lands for this subtrack.
+
+### 4.9 §23 - JSONL sidecar
+
+#### 4.9.1 File layout
+
+For each event block in `Brain/log/<date>.md`, one corresponding line
+in `Brain/log/<date>.jsonl`. Both files live in the same directory;
+both are append-only; both are written by the same function in the
+same atomic step.
+
+#### 4.9.2 JSONL row schema
+
+```jsonc
+{
+ "ts": "<ISO-8601 UTC>", // e.g. "2026-05-19T13:42:00Z"
+ "kind": "<BrainLogEventKind value>",
+ "payload": { ... } // every bullet from the markdown body
+}
+```
+
+- `ts` matches the markdown `## HH:MM:SSZ` heading (reconstructed back
+ to a full ISO timestamp using the day file's date).
+- `kind` is one of `BRAIN_LOG_EVENT_KIND.*`.
+- `payload` is a JSON object where each markdown bullet `- key: value`
+ becomes a key/value pair. Array bullets (`- key:\n - item\n - item`)
+ become a JSON array `["item", "item"]`. No flattening, no key
+ renaming - the projection is one-to-one with the markdown body.
+
+Multiple events on the same UTC second produce multiple JSONL lines
+in the order of `appendLogEvent` calls (matches the markdown stability
+guarantee).
+
+#### 4.9.3 Writer changes (`src/core/brain/log.ts`)
+
+The current `appendLogEvent` reads the markdown file, appends a block,
+writes back atomically. The new version:
+
+1. Acquires a lock on `Brain/log/` (via `proper-lockfile`, same
+ approach as `src/core/event-log.ts`).
+2. Reads `<date>.md` if present.
+3. Reads `<date>.jsonl` if present (only for the rare case where the
+ markdown file was hand-edited and the JSONL got out of sync; the
+ writer does not validate consistency, only appends).
+4. Appends one block to the markdown and one line to the JSONL.
+5. Writes both files atomically (`atomicWriteFileSync` for each;
+ markdown first, then JSONL).
+6. Releases the lock.
+
+Atomicity at the pair level: if step 5 fails between the two writes,
+the next call's step 2/3 will see the markdown leading the JSONL by
+one block. The reader (§4.9.4) prefers JSONL but falls back to
+markdown when JSONL is missing; a divergence by one event is
+acceptable and self-heals at the next write.
+
+Why not a single combined write: the two files have different formats
+and different append semantics. Combining them into one transactional
+file format buys nothing - the lock already serialises writers, and
+a one-event divergence is bounded and self-healing.
+
+#### 4.9.4 Reader (`src/core/brain/log-jsonl.ts`)
+
+New module, single public function:
+
+```ts
+export interface ReadLogDayResult {
+ readonly entries: ReadonlyArray<BrainLogEntry>;
+ readonly source: "jsonl" | "markdown-fallback";
+ readonly warnings: ReadonlyArray<BrainLogParseWarning>;
+}
+
+export function readLogDay(vault: string, date: string): ReadLogDayResult;
+```
+
+Behaviour:
+- If `<date>.jsonl` exists: parse line by line via `JSON.parse`,
+ validate the three top-level keys, coerce to `BrainLogEntry`,
+ return `source: "jsonl"`. Malformed lines surface as warnings;
+ the rest of the file still returns.
+- If `<date>.jsonl` is absent: call `parseLogDay` (markdown reader)
+ and return its result with `source: "markdown-fallback"`.
+- If both are absent: empty array, `source: "jsonl"` (no day file
+ for that date).
+
+#### 4.9.5 Discipline-report switch
+
+`src/core/discipline/log-counts.ts:countBrainEvents` switches from
+`parseLogDay` to `readLogDay`. No public-API change; counters and
+return shape are identical apart from the new `note` field added by
+§4.2.4.
+
+#### 4.9.6 Backfill policy
+
+None. Historical `<date>.md` files without a sidecar JSONL are
+served by the reader fallback. Once any agent appends an event on a
+date, both files exist from that point. No one-off migration script,
+no eager backfill at install.
+
+Why: backfill costs operator complexity (when to run, snapshot before,
+idempotency) for no measurable gain - the reader handles the
+asymmetry. If a future tool genuinely needs JSONL for old days, that
+tool can run a one-shot backfill on demand.
+
+#### 4.9.7 Snapshot / manifest / protect
+
+- `o2b brain snapshot`: archives all of `Brain/`; the new `.jsonl`
+ files are included automatically.
+- `o2b brain manifest` (sha256 walk): `.jsonl` participates in the
+ manifest; rollback drift-check picks up sidecar changes alongside
+ markdown.
+- `o2b brain protect`: both Claude Code (`permissions.deny`) and
+ Codex (`osb_protected.filesystem` path list) protect the
+ `Brain/log/` directory through a glob / directory rule; the new
+ `.jsonl` files inherit protection. The implementation plan verifies
+ this against `src/core/brain/protect.ts` before merge.
+- `o2b brain rollback`: archives + manifest cover the new file. No
+ code change.
+
+#### 4.9.8 Testing
+
+- `tests/core/brain.log.test.ts` extended:
+ - Writer produces both files; bytes equal after multiple appends.
+ - Writer survives a missing JSONL file (creates it).
+ - Writer survives a missing markdown file (creates both).
+- `tests/core/brain.log-jsonl-reader.test.ts` (new):
+ - JSONL present -> uses JSONL, `source: "jsonl"`.
+ - JSONL absent -> uses markdown fallback, `source:
+ "markdown-fallback"`.
+ - Malformed JSON line -> warning + remaining lines returned.
+ - Mixed (both present, JSONL shorter by one event) -> reader returns
+ JSONL content; the operator sees nothing degraded.
+- `tests/core/discipline/log-counts.test.ts`:
+ - Counts via JSONL.
+ - Counts via markdown fallback.
+ - Both produce identical results for the same content.
+
+### 4.10 Shared sanitizer
+
+`redactText` currently lives in `src/core/event-log.ts`. Move it (with
+its `SECRET_ASSIGNMENT_RE`) to `src/core/sanitize.ts` and import from
+both `event-log.ts` and the new `brain_note` handler. The Pay Memory
+redactor already has a similar regex; no consolidation in this PR -
+that is a separate cleanup track.
+
+### 4.11 MEMORY housekeeping
+
+Operator-owned files under `/root/.claude/projects/-root/memory/`:
+
+1. `feedback_daily_log_strict_russian.md` - **delete**. The rule
+ couples two failure modes: it calls a tool that no longer exists
+ (after §32G) and it hard-codes a language ("messages in Russian"),
+ which violates the standing "no hard-coded user language" rule.
+ Index line in `MEMORY.md` removed in the same edit.
+2. `feedback_always_russian.md` - **rewrite**. Core principle becomes
+ "reply in the user's current dialog language; for this user the
+ default is Russian (observed fact, not encoded rule)". The
+ "Russian" appears as observation, not as principle.
+3. `feedback_no_em_dashes.md` - **rewrite**. Core principle becomes
+ "use typographic conventions of the user's dialog language; em-dash
+ is replaced with hyphen-with-spaces in languages where em-dash is
+ not idiomatic (Russian for this user)". Rule reads as typography,
+ not as Russian-specific.
+4. `project_o2b_log_language.md` - **delete**. The hybrid policy it
+ describes targeted the old `agent-event-log` SKILL and
+ `event_log_append` tool; after §32 the localisation policy lives in
+ `skills/brain-memory/SKILL.md`.
+
+`MEMORY.md` index updated in the same edit: removed lines for deleted
+files; descriptions adjusted for rewritten ones.
+
+A Brain `brain_feedback` signal `sig-2026-05-19-no-hardcoded-user-
+language` records the underlying principle so the dream pass can
+promote it into `Brain/preferences/` if it recurs.
+
+## 5. Architecture diagrams
+
+### 5.1 Write path
+
+```
+brain_feedback / brain_apply_evidence / brain_note (MCP)
+ |
+ v
+ appendLogEvent(event) <-- src/core/brain/log.ts
+ |
+ +--------------+--------------+
+ | acquire Brain/log/ lock |
+ +-----------------------------+
+ |
+ +--------------+--------------+
+ | read .md, read .jsonl |
+ +-----------------------------+
+ |
+ +--------------+--------------+
+ | atomic write .md |
+ | atomic write .jsonl |
+ +-----------------------------+
+ |
+ release lock
+```
+
+### 5.2 Read path
+
+```
+caller (discipline-report, future tool)
+ |
+ v
+ readLogDay(vault, date) <-- src/core/brain/log-jsonl.ts
+ |
+ .jsonl exists?
+ / \
+ yes no
+ | |
+ parse line-by-line parseLogDay (markdown)
+ | |
+ source: "jsonl" source: "markdown-fallback"
+```
+
+## 6. SOLID / KISS / DRY compliance
+
+- **Single Responsibility.** `appendLogEvent` writes both files
+ because they are two encodings of the same event; nothing else
+ produces brain-log content. The reader is split out (`readLogDay`)
+ because there are multiple consumers.
+- **Open/Closed.** New event kind `note` is added by extending the
+ `BRAIN_LOG_EVENT_KIND` `as const` map and the `BrainLogEvent`
+ union, not by branching existing code paths.
+- **DRY.** One sanitizer (`redactText`) shared across event-log and
+ brain-note handlers. One reader (`readLogDay`) for every machine
+ consumer. One event-kind constant set. The three identity-reminder
+ templates differ only in their per-runtime cadence sentence; the
+ common payload is the same.
+- **KISS.** No combined .md+.jsonl file format; no migration; no
+ in-process JSONL backfill at startup. The reader handles asymmetry
+ transparently.
+
+## 7. Risks and mitigations
+
+| Risk | Mitigation |
+|---|---|
+| JSONL write succeeds, markdown write fails (or vice versa) | Lock + atomic write; pair-level divergence bounded to one event; reader prefers JSONL; next call re-syncs. |
+| Hand-edited markdown drifts from JSONL | Reader prefers JSONL, returns warnings on malformed lines; operator can delete the JSONL to force rebuild on next write. |
+| Agent still calls `event_log_append` from training memory | Tool is gone from every MCP registration; runtime returns "unknown tool". Identity-reminder + Stop guardrail point at the new tools. |
+| `cmdAppendEvent` fix breaks cron-jobs relying on the `"agent"` default | The env-var path (`VAULT_AGENT_NAME`) is preserved via `resolveAgentName`. Cron-jobs that already set `VAULT_AGENT_NAME` are unaffected; ones that relied on `"agent"` literal get the configured identity instead (which is the bug fix). |
+| MEMORY rewrite removes context Sergey relied on | The reformulated files preserve the operational intent (language-of-dialog, typography conventions, mirror-preserved English in repo artifacts); only the "Russian as principle" framing is removed. |
+
+## 8. Release-checklist gate
+
+A v0.10.8 ship is allowed only if all of the following hold:
+
+1. Tests pass: `bun test`.
+2. `o2b discipline report` on `/root/vault` shows status `ok` or
+ `info` for the window since v0.10.7; every `known_agent` with
+ activity has at least one brain event.
+3. Smoke check: writing a `brain_feedback` MCP call lands one entry
+ in `Brain/log/<today>.md` AND one line in `Brain/log/<today>.jsonl`
+ that describe the same event (same `ts`, same `kind`, same payload
+ keys / values). The two encodings are not byte-equal - the markdown
+ is human-formatted, the JSONL is machine-formatted - the smoke
+ check confirms semantic equivalence, not byte equivalence.
+4. Manual MCP probe: `event_log_append` is not advertised by any of
+ `bun src/mcp/main.ts` (full scope), `bun src/mcp/main.ts --scope
+ writer`, the OpenClaw bundle, and the Hermes plugin tool list.
+
+A failure on (2) blocks §32C/D landing (per §4.1 above).
+
+## 9. Out-of-scope items, deferred
+
+These items came up during design but are intentionally not in
+v0.10.8. Each entry carries a trigger to revisit:
+
+- **CLI verb `o2b brain note`.** Trigger: a cron-job or shell-script
+ use-case for appending a narrative milestone outside MCP.
+- **Auto-watcher for stray `Daily/` writes from agent identities.**
+ Trigger: §32H drift-check finds repeated cases the operator-run
+ check missed.
+- **One-shot JSONL backfill of historical markdown days.** Trigger:
+ a machine consumer materially benefits from JSONL on days older
+ than v0.10.8 ship.
+- **Shared Pay Memory + brain-log sanitizer.** Trigger: a third
+ consumer of secret redaction joins the codebase.
+- **Bidirectional MEMORY <-> Brain sync.** Trigger as in v0.10.7 §E
+ Deferred entry.
+
+`_summary.md` will record these in `## Deferred work` with the same
+triggers.
+
+## 10. Changes to `_summary.md`
+
+The summary doc is updated in the same release:
+
+- §32 (`_summary.md:275-303`) marked shipped in v0.10.8 with the
+ per-subtrack status (§32A lightweight gate, §32B brain_note,
+ §32C-G shipped, §32H operator drift-check).
+- §23 (`_summary.md:223-227`) marked shipped in v0.10.8.
+- `## Deferred work` extended with the five entries from §9 above,
+ each with its trigger.
+- Reference from §30 to §32 added in the §30 paragraph (the v0.10.7
+ card) clarifying that §32 retires the old channel §30 augmented.
+
+No version-history dates appear in `_summary.md` beyond the existing
+shipped-in markers; per the "no dates in planning" rule the deferred
+entries are trigger-based only.
+
+## 11. Implementation plan reference
+
+The bite-sized implementation plan is `2026-05-19-v0.10.8-impl.md` -
+written next, after this spec is approved.
diff --git a/docs/plans/2026-05-19-v0.10.8-impl.md b/docs/plans/2026-05-19-v0.10.8-impl.md
new file mode 100644
index 00000000..095817f8
--- /dev/null
+++ b/docs/plans/2026-05-19-v0.10.8-impl.md
@@ -0,0 +1,1698 @@
+# v0.10.8 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:** Retire `event_log_append` from every agent-facing surface; add a Brain-native `brain_note` MCP tool; add a JSONL sidecar to every event written to `Brain/log/<date>.md`; switch `discipline-report` (and future machine consumers) to a reader that prefers JSONL with markdown fallback. MEMORY housekeeping removes language-anchored rules.
+
+**Architecture:** One atomic writer (`appendLogEvent`) produces both markdown and JSONL inside a single `proper-lockfile` lock; one reader (`readLogDay`) prefers JSONL with markdown-fallback; the three identity-reminder templates, the Stop guardrail, and the hook event detector all stop mentioning `event_log_append`. The old MCP handlers are removed from every runtime (Claude Code, Codex, Hermes, OpenClaw); the bare CLI verb `o2b append-event` remains for human/cron use.
+
+**Tech Stack:** TypeScript / Bun. `proper-lockfile` for cross-process write locks. Python shim (`plugins/hermes/__init__.py`) caches templates per process. Tests live in `tests/**/*.test.ts` and run under `bun test`.
+
+**Companion spec:** `docs/plans/2026-05-19-v0.10.8-design.md`.
+
+---
+
+## File Structure
+
+### Files created
+
+- `src/core/brain/log-jsonl.ts` - the JSONL-preferred reader (`readLogDay`).
+- `tests/core/brain.log-jsonl-reader.test.ts` - reader tests.
+- `tests/cli/append-event.test.ts` - cmdAppendEvent fix test.
+
+### Files modified
+
+- `src/core/brain/log.ts` - dual writer (`.md` + `.jsonl` atomic via lock).
+- `src/core/brain/types.ts` - `BRAIN_LOG_EVENT_KIND.note = "note"` + `BrainNoteLogEvent` union member.
+- `src/mcp/brain-tools.ts` - new `toolBrainNote` handler + `BRAIN_TOOLS` entry.
+- `src/mcp/tools.ts` - `WRITER_TOOL_NAMES` gains `"brain_note"`; remove `toolEventLogAppend`.
+- `src/mcp/instructions.ts` - writer instructions list three tools.
+- `src/openclaw/index.ts` - remove the `event_log_append` `registerTool` block.
+- `src/cli/main.ts` - `cmdAppendEvent` resolves identity through `resolveAgentName`.
+- `plugins/hermes/__init__.py` - docstring update; no functional change.
+- `hooks/lib/detect.ts` - `BRAIN_EVENT_NAME_SUFFIX` and `BRAIN_EVENT_BASH_NEEDLES` drop event_log_append paths.
+- `hooks/lib/messages.ts` - Stop guardrail mentions the three new triggers, not event_log_append.
+- `hooks/README.md` - documentation rewrite for v0.10.8 surface.
+- `templates/identity-reminder.txt` - new common reminder body.
+- `templates/identity-reminder.hermes.txt` - Hermes-specific cadence on the new body.
+- `templates/identity-reminder.openclaw.txt` - OpenClaw-specific cadence on the new body.
+- `tests/core/brain.log.test.ts` - dual-write assertions.
+- `tests/core/discipline/log-counts.test.ts` - counts via JSONL + fallback.
+- `tests/hooks/detect.test.ts` - event_log_append no longer clears guardrail.
+- `tests/hooks/stop-log-guardrail.test.ts` - new triggers clear the guardrail.
+- `tests/hooks/post-write-reminder.test.ts` - reminder mentions brain_note.
+- `tests/core/identity-reminder.test.ts` - byte-pinned new template text.
+- `tests/fixtures/identity-reminder/hermes.txt` - regenerated.
+- `tests/fixtures/identity-reminder/openclaw.txt` - regenerated.
+- `tests/openclaw/bundle.test.ts` - drop `event_log_append` registration assertion.
+- `tests/python/test_hermes_plugin.py` - drop `event_log_append` mention.
+- `tests/mcp/mcp.test.ts` - check `brain_note` advertised; `event_log_append` is not.
+- `tests/mcp/brain.test.ts` - new `brain_note` happy-path + sanitisation tests.
+- `CHANGELOG.md` - new `[0.10.8]` section.
+- `Projects/OpenSecondBrain/Features/_summary.md` (in `/root/vault/`) - mark §32 and §23 shipped.
+
+### Files explicitly NOT touched
+
+- `src/core/event-log.ts` - `appendEvent` stays for cron-jobs / `o2b append-event` CLI.
+- `src/core/redactor.ts` - `sanitiseTextField` is already the shared sanitiser; no need to move.
+- `src/core/brain/protect.ts` - protects `${dirs.log}/**` glob already; `.jsonl` covered automatically.
+
+### MEMORY housekeeping
+
+- `/root/.claude/projects/-root/memory/feedback_daily_log_strict_russian.md` - delete.
+- `/root/.claude/projects/-root/memory/project_o2b_log_language.md` - delete.
+- `/root/.claude/projects/-root/memory/feedback_always_russian.md` - rewrite (no Russian-anchored principle).
+- `/root/.claude/projects/-root/memory/feedback_no_em_dashes.md` - rewrite (typography-anchored, not Russian-anchored).
+- `/root/.claude/projects/-root/memory/MEMORY.md` - index update.
+
+---
+
+## Implementation Order
+
+Tasks are listed in execution order. Tasks 1-6 land the core write path; 7-9 the new tool; 10-12 the agent-facing surface cleanup; 13-15 the CLI fix and old-handler drop; 16-17 wiring tests and documentation; 18 the release artifacts; 19 the MEMORY housekeeping.
+
+Each task is independent enough to ship as one commit. The plan assumes commits accumulate on one branch; CI runs on each push.
+
+---
+
+## Task 1: JSONL writer - extend `appendLogEvent`
+
+**Files:**
+- Modify: `src/core/brain/log.ts`
+- Test: `tests/core/brain.log.test.ts`
+
+The current `appendLogEvent` writes one markdown file. We add a JSONL sidecar written in the same atomic step under a directory-level lock.
+
+- [ ] **Step 1.1: Read the existing writer to understand atomicity guarantees**
+
+Run: `grep -n "appendLogEvent\|atomicWriteFileSync" src/core/brain/log.ts`
+
+Expected: confirm `appendLogEvent` is currently synchronous, reads-then-writes via `atomicWriteFileSync`, no lock.
+
+- [ ] **Step 1.2: Write the failing test for dual write**
+
+Add to `tests/core/brain.log.test.ts`:
+
+```ts
+import { existsSync, readFileSync } from "node:fs";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, test } from "bun:test";
+import { appendLogEvent } from "../../src/core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND, type BrainLogEntry } from "../../src/core/brain/types.ts";
+
+describe("appendLogEvent dual write", () => {
+ test("writes the same event to both .md and .jsonl", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-log-"));
+ try {
+ const entry: BrainLogEntry = {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { signal: "[[sig-x]]", topic: "x", sign: "positive" },
+ };
+ appendLogEvent(vault, entry);
+ const md = readFileSync(join(vault, "Brain/log/2026-05-19.md"), "utf8");
+ const jsonl = readFileSync(join(vault, "Brain/log/2026-05-19.jsonl"), "utf8");
+ expect(md).toContain("## 10:00:00Z - feedback");
+ const lines = jsonl.trim().split("\n");
+ expect(lines).toHaveLength(1);
+ const parsed = JSON.parse(lines[0]!);
+ expect(parsed).toEqual({
+ ts: "2026-05-19T10:00:00Z",
+ kind: "feedback",
+ payload: { signal: "[[sig-x]]", topic: "x", sign: "positive" },
+ });
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+ });
+
+ test("appends a second event to both files", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-log-"));
+ try {
+ const first: BrainLogEntry = {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { signal: "[[sig-a]]", topic: "a", sign: "positive" },
+ };
+ const second: BrainLogEntry = {
+ timestamp: "2026-05-19T10:00:01Z",
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: { preference: "[[pref-a]]", artifact: "[[file.ts]]", agent: "@x", result: "applied" },
+ };
+ appendLogEvent(vault, first);
+ appendLogEvent(vault, second);
+ const jsonl = readFileSync(join(vault, "Brain/log/2026-05-19.jsonl"), "utf8");
+ const lines = jsonl.trim().split("\n");
+ expect(lines).toHaveLength(2);
+ expect(JSON.parse(lines[0]!).kind).toBe("feedback");
+ expect(JSON.parse(lines[1]!).kind).toBe("apply-evidence");
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+ });
+
+ test("encodes array payloads as JSON arrays, not repeated keys", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-log-"));
+ try {
+ const entry: BrainLogEntry = {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.dream,
+ body: { run_id: "dream-1", clustered: ["sig-a", "sig-b"] },
+ };
+ appendLogEvent(vault, entry);
+ const jsonl = readFileSync(join(vault, "Brain/log/2026-05-19.jsonl"), "utf8");
+ const parsed = JSON.parse(jsonl.trim());
+ expect(parsed.payload.clustered).toEqual(["sig-a", "sig-b"]);
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+ });
+});
+```
+
+- [ ] **Step 1.3: Run the test - confirm failure**
+
+Run: `bun test tests/core/brain.log.test.ts`
+
+Expected: FAIL with "ENOENT: no such file or directory ... Brain/log/2026-05-19.jsonl".
+
+- [ ] **Step 1.4: Update the writer**
+
+Modify `src/core/brain/log.ts`. The new shape:
+
+```ts
+// At top of file, add import:
+import lockfile from "proper-lockfile";
+import { dirname } from "node:path";
+import { mkdirSync } from "node:fs";
+
+// Existing renderEventBlock(...) stays unchanged.
+
+// Add new pure helper alongside `renderEventBlock`:
+function renderJsonlLine(event: BrainLogEntry): string {
+ // The JSONL row is a one-to-one projection of the markdown body:
+ // every bullet becomes a key, array bullets become JSON arrays.
+ // `BrainLogEntry.body` already has that shape, so the projection is
+ // direct - no per-kind branching, which keeps the writer kind-agnostic.
+ const payload: Record<string, string | ReadonlyArray<string>> = {};
+ for (const [key, value] of Object.entries(event.body)) {
+ payload[key] = value;
+ }
+ return JSON.stringify({
+ ts: event.timestamp,
+ kind: event.eventType,
+ payload,
+ });
+}
+
+// Existing `appendLogEvent` becomes an async-free function that uses a
+// synchronous proper-lockfile lock - the public signature stays the same
+// (synchronous), callers do not change.
+
+export function appendLogEvent(
+ vault: string,
+ event: BrainLogEntry,
+): AppendLogEventResult {
+ if (!EVENT_KIND_VALUES.has(event.eventType)) {
+ throw new Error(
+ `appendLogEvent: unknown event kind '${event.eventType}' - must be one of ${Object.values(
+ BRAIN_LOG_EVENT_KIND,
+ ).join(", ")}`,
+ );
+ }
+
+ const ts = parseIsoUtc(event.timestamp);
+ const mdPath = logPath(vault, ts.date);
+ const jsonlPath = mdPath.replace(/\.md$/, ".jsonl");
+
+ // proper-lockfile requires the lock target to exist. Lock the log
+ // directory itself, created up-front, the same scope used by
+ // `src/core/event-log.ts:appendEvent`.
+ const logDir = dirname(mdPath);
+ mkdirSync(logDir, { recursive: true });
+
+ const release = lockfile.lockSync(logDir, {
+ retries: { retries: 30, factor: 1.2, minTimeout: 30, maxTimeout: 500 },
+ stale: 10_000,
+ realpath: false,
+ });
+
+ try {
+ const existingMd = existsSync(mdPath) ? readFileSync(mdPath, "utf8") : "";
+ const block = renderEventBlock(event, ts.hms);
+ let nextMd: string;
+ if (existingMd === "") {
+ nextMd = renderFileHeader(ts.date) + "\n" + block;
+ } else {
+ nextMd = `${existingMd.replace(/\s+$/, "")}\n\n${block}`;
+ }
+ if (!nextMd.endsWith("\n")) nextMd += "\n";
+ atomicWriteFileSync(mdPath, nextMd);
+
+ const existingJsonl = existsSync(jsonlPath) ? readFileSync(jsonlPath, "utf8") : "";
+ const line = renderJsonlLine(event);
+ const nextJsonl =
+ existingJsonl === ""
+ ? line + "\n"
+ : `${existingJsonl.replace(/\s+$/, "")}\n${line}\n`;
+ atomicWriteFileSync(jsonlPath, nextJsonl);
+
+ return { logPath: mdPath };
+ } finally {
+ release();
+ }
+}
+```
+
+Note: `proper-lockfile` exposes `lockSync` (mirror of `lock`) that returns a release function; we use it to keep `appendLogEvent` synchronous (the existing public contract).
+
+- [ ] **Step 1.5: Run the tests - confirm pass**
+
+Run: `bun test tests/core/brain.log.test.ts`
+
+Expected: PASS for all dual-write cases.
+
+- [ ] **Step 1.6: Commit**
+
+```bash
+git add src/core/brain/log.ts tests/core/brain.log.test.ts
+git commit -m "$(cat <<'EOF'
+feat(brain): write JSONL sidecar next to each Brain/log/<date>.md
+
+§23 of OSB features summary. Dual-write under a proper-lockfile lock so
+markdown and JSONL stay in lock-step; the JSONL row is a deterministic
+projection of the markdown body. No reader change yet; callers stay on
+parseLogDay until log-jsonl.ts lands.
+
+Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
+EOF
+)"
+```
+
+(NOTE: this plan documents the suggested commits. Commits are only created when the user explicitly asks for them - per the standing rule, do not commit unprompted.)
+
+---
+
+## Task 2: JSONL reader - `src/core/brain/log-jsonl.ts`
+
+**Files:**
+- Create: `src/core/brain/log-jsonl.ts`
+- Test: `tests/core/brain.log-jsonl-reader.test.ts`
+
+- [ ] **Step 2.1: Write the failing reader test**
+
+Create `tests/core/brain.log-jsonl-reader.test.ts`:
+
+```ts
+import { mkdirSync, writeFileSync } from "node:fs";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, test } from "bun:test";
+import { readLogDay } from "../../src/core/brain/log-jsonl.ts";
+import { appendLogEvent } from "../../src/core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../src/core/brain/types.ts";
+
+describe("readLogDay", () => {
+ test("returns JSONL entries when .jsonl exists", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-read-"));
+ try {
+ appendLogEvent(vault, {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { signal: "[[sig-x]]", topic: "x", sign: "positive" },
+ });
+ const res = readLogDay(vault, "2026-05-19");
+ expect(res.source).toBe("jsonl");
+ expect(res.entries).toHaveLength(1);
+ expect(res.entries[0]!.eventType).toBe("feedback");
+ expect(res.entries[0]!.body.topic).toBe("x");
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+ });
+
+ test("falls back to markdown when .jsonl is absent", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-read-"));
+ try {
+ // Hand-craft a markdown-only day (simulating pre-v0.10.8 history).
+ const dir = join(vault, "Brain/log");
+ mkdirSync(dir, { recursive: true });
+ const md = `---
+kind: brain-log
+date: 2026-05-10
+tags: [brain, brain/log]
+---
+
+# Brain log - 2026-05-10
+
+## 09:00:00Z - feedback
+- signal: [[sig-old]]
+- topic: old
+- sign: positive
+`;
+ writeFileSync(join(dir, "2026-05-10.md"), md, "utf8");
+ const res = readLogDay(vault, "2026-05-10");
+ expect(res.source).toBe("markdown-fallback");
+ expect(res.entries).toHaveLength(1);
+ expect(res.entries[0]!.body.topic).toBe("old");
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+ });
+
+ test("returns empty result when neither file exists", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-read-"));
+ try {
+ const res = readLogDay(vault, "2026-01-01");
+ expect(res.entries).toHaveLength(0);
+ expect(res.warnings).toHaveLength(0);
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+ });
+
+ test("surfaces malformed JSONL lines as warnings", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-read-"));
+ try {
+ const dir = join(vault, "Brain/log");
+ mkdirSync(dir, { recursive: true });
+ const lines = [
+ JSON.stringify({ ts: "2026-05-19T10:00:00Z", kind: "feedback", payload: { topic: "ok" } }),
+ "not-valid-json",
+ JSON.stringify({ ts: "2026-05-19T10:00:02Z", kind: "feedback", payload: { topic: "also-ok" } }),
+ ].join("\n");
+ writeFileSync(join(dir, "2026-05-19.jsonl"), lines + "\n", "utf8");
+ const res = readLogDay(vault, "2026-05-19");
+ expect(res.source).toBe("jsonl");
+ expect(res.entries).toHaveLength(2);
+ expect(res.warnings).toHaveLength(1);
+ expect(res.warnings[0]!.message).toMatch(/malformed/i);
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+ });
+});
+```
+
+- [ ] **Step 2.2: Run the test - confirm failure**
+
+Run: `bun test tests/core/brain.log-jsonl-reader.test.ts`
+
+Expected: FAIL with "Cannot find module .../log-jsonl.ts".
+
+- [ ] **Step 2.3: Implement the reader**
+
+Create `src/core/brain/log-jsonl.ts`:
+
+```ts
+/**
+ * Brain log reader that prefers the v0.10.8 JSONL sidecar and falls
+ * back to parsing the markdown on days without one. All machine
+ * consumers (discipline-report today, future tooling tomorrow) read
+ * through this entry point so they do not duplicate the fallback
+ * logic.
+ *
+ * The reader returns the same `BrainLogEntry[]` shape that
+ * `parseLogDay` returns, plus a `source` discriminator the caller can
+ * surface in diagnostics. Malformed JSONL lines do not abort the
+ * read; they surface as `warnings` so a partially-edited file is
+ * still useful.
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+
+import { logPath, validateIsoDate } from "./paths.ts";
+import {
+ parseLogDay,
+ type BrainLogEntry,
+ type BrainLogParseWarning,
+} from "./log.ts";
+import {
+ BRAIN_LOG_EVENT_KIND,
+ type BrainLogEventKind,
+} from "./types.ts";
+
+export interface ReadLogDayResult {
+ readonly entries: ReadonlyArray<BrainLogEntry>;
+ readonly source: "jsonl" | "markdown-fallback";
+ readonly warnings: ReadonlyArray<BrainLogParseWarning>;
+}
+
+const EVENT_KIND_VALUES: ReadonlySet<string> = new Set(
+ Object.values(BRAIN_LOG_EVENT_KIND),
+);
+
+export function readLogDay(vault: string, date: string): ReadLogDayResult {
+ const validDate = validateIsoDate(date);
+ const mdPath = logPath(vault, validDate);
+ const jsonlPath = mdPath.replace(/\.md$/, ".jsonl");
+
+ if (existsSync(jsonlPath)) {
+ return readJsonl(jsonlPath);
+ }
+ if (existsSync(mdPath)) {
+ const parsed = parseLogDay(vault, validDate);
+ return {
+ entries: parsed.entries,
+ source: "markdown-fallback",
+ warnings: parsed.warnings,
+ };
+ }
+ return { entries: [], source: "jsonl", warnings: [] };
+}
+
+function readJsonl(path: string): ReadLogDayResult {
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch {
+ return { entries: [], source: "jsonl", warnings: [] };
+ }
+
+ const entries: BrainLogEntry[] = [];
+ const warnings: BrainLogParseWarning[] = [];
+ const lines = text.split(/\r?\n/);
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]!;
+ if (line.trim() === "") continue;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line);
+ } catch {
+ warnings.push({
+ path,
+ lineNumber: i + 1,
+ message: `malformed JSONL line: ${line.slice(0, 80)}`,
+ });
+ continue;
+ }
+ const entry = coerceEntry(parsed, path, i + 1, warnings);
+ if (entry !== null) entries.push(entry);
+ }
+ return { entries, source: "jsonl", warnings };
+}
+
+function coerceEntry(
+ raw: unknown,
+ path: string,
+ lineNumber: number,
+ warnings: BrainLogParseWarning[],
+): BrainLogEntry | null {
+ if (raw === null || typeof raw !== "object") {
+ warnings.push({ path, lineNumber, message: "JSONL row is not an object" });
+ return null;
+ }
+ const obj = raw as Record<string, unknown>;
+ const ts = obj["ts"];
+ const kind = obj["kind"];
+ const payload = obj["payload"];
+ if (typeof ts !== "string" || typeof kind !== "string") {
+ warnings.push({
+ path,
+ lineNumber,
+ message: "JSONL row missing ts/kind",
+ });
+ return null;
+ }
+ if (!EVENT_KIND_VALUES.has(kind)) {
+ warnings.push({ path, lineNumber, message: `unknown event kind: ${kind}` });
+ return null;
+ }
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
+ warnings.push({ path, lineNumber, message: "JSONL row missing payload object" });
+ return null;
+ }
+ const body: Record<string, string | ReadonlyArray<string>> = {};
+ for (const [k, v] of Object.entries(payload as Record<string, unknown>)) {
+ if (typeof v === "string") {
+ body[k] = v;
+ } else if (Array.isArray(v) && v.every((x) => typeof x === "string")) {
+ body[k] = v as string[];
+ } else {
+ warnings.push({
+ path,
+ lineNumber,
+ message: `JSONL payload key '${k}' has unsupported value type`,
+ });
+ }
+ }
+ return {
+ timestamp: ts,
+ eventType: kind as BrainLogEventKind,
+ body: Object.freeze(body),
+ };
+}
+```
+
+- [ ] **Step 2.4: Run the tests - confirm pass**
+
+Run: `bun test tests/core/brain.log-jsonl-reader.test.ts`
+
+Expected: PASS for all four scenarios.
+
+- [ ] **Step 2.5: Commit (do not run without explicit user request)**
+
+```bash
+git add src/core/brain/log-jsonl.ts tests/core/brain.log-jsonl-reader.test.ts
+git commit -m "feat(brain): add readLogDay with JSONL-preferred fallback to markdown"
+```
+
+---
+
+## Task 3: Switch discipline-report to `readLogDay`
+
+**Files:**
+- Modify: `src/core/discipline/log-counts.ts`
+- Test: `tests/core/discipline/log-counts.test.ts`
+
+- [ ] **Step 3.1: Add failing test for JSONL-source counting**
+
+In `tests/core/discipline/log-counts.test.ts`, add:
+
+```ts
+test("countBrainEvents uses JSONL when present", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-disc-"));
+ try {
+ appendLogEvent(vault, {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { signal: "[[sig-x]]", topic: "x", sign: "positive", agent: "@a1" },
+ });
+ appendLogEvent(vault, {
+ timestamp: "2026-05-19T10:00:01Z",
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: { preference: "[[pref-x]]", artifact: "[[f.ts]]", agent: "@a1", result: "applied" },
+ });
+ // Wipe the markdown to prove JSONL is the source.
+ rmSync(join(vault, "Brain/log/2026-05-19.md"));
+ const counts = countBrainEvents(vault, "2026-05-19", ["@a1"]);
+ expect(counts.byAgent["@a1"]!.feedback).toBe(1);
+ expect(counts.byAgent["@a1"]!.apply_evidence).toBe(1);
+ expect(counts.total).toBe(2);
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+});
+
+test("countBrainEvents falls back to markdown when only markdown exists", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-disc-"));
+ try {
+ const dir = join(vault, "Brain/log");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, "2026-05-10.md"),
+ `---
+kind: brain-log
+date: 2026-05-10
+tags: [brain, brain/log]
+---
+
+# Brain log - 2026-05-10
+
+## 09:00:00Z - feedback
+- signal: [[sig-old]]
+- topic: old
+- sign: positive
+- agent: @a2
+`,
+ "utf8",
+ );
+ const counts = countBrainEvents(vault, "2026-05-10", ["@a2"]);
+ expect(counts.byAgent["@a2"]!.feedback).toBe(1);
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+});
+```
+
+- [ ] **Step 3.2: Run - confirm failure (fallback test passes; jsonl test fails)**
+
+Run: `bun test tests/core/discipline/log-counts.test.ts`
+
+Expected: JSONL-source test FAILS (file deleted, `parseLogDay` returns empty).
+
+- [ ] **Step 3.3: Update `countBrainEvents` to use `readLogDay`**
+
+In `src/core/discipline/log-counts.ts`, replace the `parseLogDay` import and call:
+
+```ts
+import { readLogDay } from "../brain/log-jsonl.ts";
+
+// ... inside countBrainEvents:
+const { entries } = readLogDay(vault, date);
+```
+
+- [ ] **Step 3.4: Run tests - confirm pass**
+
+Run: `bun test tests/core/discipline/log-counts.test.ts`
+
+Expected: PASS for both scenarios.
+
+- [ ] **Step 3.5: Commit (no auto-commit)**
+
+---
+
+## Task 4: Add the `note` event kind
+
+**Files:**
+- Modify: `src/core/brain/types.ts`
+
+- [ ] **Step 4.1: Add the constant**
+
+In `src/core/brain/types.ts`, inside the `BRAIN_LOG_EVENT_KIND` `as const` map, add (just before the closing `}`):
+
+```ts
+ /**
+ * `note` (§32B v0.10.8) - narrative milestone written by `brain_note`.
+ * One-line `text` plus `agent`; not consumed by dream beyond counting.
+ */
+ note: "note",
+```
+
+- [ ] **Step 4.2: Add the typed event interface**
+
+Below the existing `BrainImportClaudeMemoryLogEvent` interface, add:
+
+```ts
+/**
+ * `note` entry (§32B) - one narrative-milestone line. Not consumed by
+ * the dream pass; it exists so an agent has a Brain-native home for
+ * "I shipped X" / "PR Y merged" lines instead of falling back to the
+ * deprecated Daily/ event log.
+ */
+export interface BrainNoteLogEvent extends BrainLogEventBase {
+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.note;
+ readonly text: string;
+ readonly agent: string;
+}
+```
+
+Then in the `BrainLogEvent` union, append `| BrainNoteLogEvent`.
+
+- [ ] **Step 4.3: Compile-check**
+
+Run: `bun run tsc --noEmit`
+
+Expected: no new errors.
+
+- [ ] **Step 4.4: Commit (no auto-commit)**
+
+---
+
+## Task 5: `brain_note` MCP handler
+
+**Files:**
+- Modify: `src/mcp/brain-tools.ts`
+- Modify: `src/mcp/tools.ts` (WRITER_TOOL_NAMES)
+- Modify: `src/mcp/instructions.ts` (writer instructions text)
+- Test: `tests/mcp/brain.test.ts`
+
+- [ ] **Step 5.1: Write the failing tool test**
+
+In `tests/mcp/brain.test.ts`, add a `describe("brain_note", ...)` block:
+
+```ts
+describe("brain_note", () => {
+ test("happy path writes a note event with the resolved agent", async () => {
+ const { ctx, vault } = makeCtx();
+ try {
+ const result = await callTool("brain_note", ctx, { text: "v0.10.7 shipped" });
+ expect(result.agent).toBeTruthy();
+ const md = readFileSync(
+ join(vault, `Brain/log/${todayIso()}.md`),
+ "utf8",
+ );
+ expect(md).toMatch(/- note$/m);
+ expect(md).toContain("text: v0.10.7 shipped");
+ const jsonl = readFileSync(
+ join(vault, `Brain/log/${todayIso()}.jsonl`),
+ "utf8",
+ );
+ const parsed = JSON.parse(jsonl.trim().split("\n").pop()!);
+ expect(parsed.kind).toBe("note");
+ expect(parsed.payload.text).toBe("v0.10.7 shipped");
+ } finally {
+ cleanup(vault);
+ }
+ });
+
+ test("redacts secret-shaped tokens", async () => {
+ const { ctx, vault } = makeCtx();
+ try {
+ await callTool("brain_note", ctx, {
+ text: "deployed api_key=sk-abc123 to prod",
+ });
+ const md = readFileSync(
+ join(vault, `Brain/log/${todayIso()}.md`),
+ "utf8",
+ );
+ expect(md).toContain("***REDACTED***");
+ expect(md).not.toContain("sk-abc123");
+ } finally {
+ cleanup(vault);
+ }
+ });
+
+ test("collapses multi-line input to one space-joined line", async () => {
+ const { ctx, vault } = makeCtx();
+ try {
+ await callTool("brain_note", ctx, { text: "line one\nline two" });
+ const md = readFileSync(
+ join(vault, `Brain/log/${todayIso()}.md`),
+ "utf8",
+ );
+ expect(md).toContain("text: line one line two");
+ } finally {
+ cleanup(vault);
+ }
+ });
+
+ test("rejects empty / whitespace-only text", async () => {
+ const { ctx } = makeCtx();
+ await expect(callTool("brain_note", ctx, { text: " " })).rejects.toThrow(
+ /text is required/,
+ );
+ });
+});
+```
+
+Helpers `makeCtx` / `callTool` / `cleanup` / `todayIso` exist in the file already (reused by `brain_feedback` tests).
+
+- [ ] **Step 5.2: Run - confirm failure**
+
+Run: `bun test tests/mcp/brain.test.ts -t "brain_note"`
+
+Expected: FAIL with "unknown tool: brain_note" or similar.
+
+- [ ] **Step 5.3: Implement the handler**
+
+Add to `src/mcp/brain-tools.ts`, near the existing `toolBrainApplyEvidence` block:
+
+```ts
+// ----- brain_note ----------------------------------------------------------
+
+const NOTE_TEXT_MAX_LEN = 4096;
+
+async function toolBrainNote(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const rawText = coerceStr(args, "text", true)!;
+ const agentArg = coerceStr(args, "agent", false);
+ const sanitised = sanitiseTextField(rawText, {
+ maxLen: NOTE_TEXT_MAX_LEN,
+ singleLine: true,
+ });
+ if (!sanitised || !sanitised.trim()) {
+ throw new MCPError(INVALID_PARAMS, "brain_note: text is required");
+ }
+
+ const agent =
+ normalizeAgentArgument(agentArg) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ const now = new Date();
+ const timestamp = isoSecond(now);
+
+ const entry: BrainLogEntry = {
+ timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.note,
+ body: { text: sanitised.trim(), agent },
+ };
+ const result = appendLogEvent(ctx.vault, entry);
+ return {
+ logged_at: timestamp,
+ log_path: vaultRelativeSafe(ctx.vault, result.logPath),
+ absolute_log_path: resolve(result.logPath),
+ agent,
+ };
+}
+```
+
+Add the import (top of file):
+
+```ts
+import { sanitiseTextField } from "../core/redactor.ts";
+```
+
+Add `BRAIN_TOOLS` entry (right after the `brain_apply_evidence` block, before the next tool):
+
+```ts
+{
+ name: "brain_note",
+ description:
+ "Append one narrative-milestone line to today's Brain log (`Brain/log/<today>.md` plus the JSONL sidecar). Use for events that are neither a new preference nor evidence against an existing one - e.g. a release, a merged PR, a discovered fact.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ text: {
+ type: "string",
+ description:
+ "One-line narrative description. Newlines are collapsed to spaces; redactor strips secret-shaped tokens.",
+ },
+ agent: {
+ type: "string",
+ description:
+ "Optional agent identity override; defaults to the server-resolved name.",
+ },
+ },
+ required: ["text"],
+ additionalProperties: false,
+ },
+ handler: toolBrainNote,
+},
+```
+
+In `src/mcp/tools.ts`, extend `WRITER_TOOL_NAMES`:
+
+```ts
+const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set([
+ "brain_feedback",
+ "brain_apply_evidence",
+ "brain_note",
+]);
+```
+
+In `src/mcp/instructions.ts`, update `WRITER_INSTRUCTIONS`:
+
+```ts
+const WRITER_INSTRUCTIONS = `Open Second Brain - writer surface (always-loaded).
+
+Three tools live here:
+ - brain_feedback - record one new taste signal the user just expressed.
+ - brain_apply_evidence - record applied | violated | outdated against an
+ active preference for an artifact this turn produced.
+ - brain_note - record one narrative milestone (release, merged PR,
+ discovered fact) that fits neither category.
+
+The remaining Brain surface (digest, query, doctor, backlinks, search,
+Pay Memory tools, vault_health, second_brain_status, second_brain_query,
+and the scheduled learning pass) lives on the sibling
+"open-second-brain" MCP server (deferred). Use ToolSearch to reach it.
+
+Prefer the writer-server copies of brain_feedback / brain_apply_evidence /
+brain_note over any duplicate exposed by the full server - both call the same
+handler, but the writer copy is always available without ToolSearch.`;
+```
+
+- [ ] **Step 5.4: Run the tests - confirm pass**
+
+Run: `bun test tests/mcp/brain.test.ts -t "brain_note"`
+
+Expected: PASS for all four scenarios.
+
+- [ ] **Step 5.5: Commit (no auto-commit)**
+
+---
+
+## Task 6: Discipline counts gain `note` field
+
+**Files:**
+- Modify: `src/core/discipline/log-counts.ts`
+- Modify: `src/core/discipline/render.ts`
+- Test: `tests/core/discipline/log-counts.test.ts`
+- Test: `tests/core/discipline/render.test.ts`
+
+- [ ] **Step 6.1: Add the failing test**
+
+```ts
+test("countBrainEvents counts note events", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-disc-"));
+ try {
+ appendLogEvent(vault, {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.note,
+ body: { text: "v0.10.7 shipped", agent: "@a1" },
+ });
+ const counts = countBrainEvents(vault, "2026-05-19", ["@a1"]);
+ expect(counts.byAgent["@a1"]!.note).toBe(1);
+ expect(counts.byAgent["@a1"]!.total).toBe(1);
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+});
+```
+
+- [ ] **Step 6.2: Run - confirm failure**
+
+Expected: FAIL (no `note` field on `AgentCounts`).
+
+- [ ] **Step 6.3: Add the field and update the bumper**
+
+`src/core/discipline/log-counts.ts`:
+
+```ts
+export interface AgentCounts {
+ readonly feedback: number;
+ readonly apply_evidence: number;
+ readonly note: number;
+ readonly other: number;
+ readonly total: number;
+}
+
+function zero(): AgentCounts {
+ return { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 };
+}
+
+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 === "note") return { ...c, note: c.note + 1, total: c.total + 1 };
+ return { ...c, other: c.other + 1, total: c.total + 1 };
+}
+```
+
+- [ ] **Step 6.4: Surface `note` in the renderer**
+
+In `src/core/discipline/render.ts`, locate the block that renders feedback / apply_evidence per agent. Add a `note` column / line; keep the format symmetrical with the existing ones. Update both the markdown and JSON renderers if applicable. Confirm with `tests/core/discipline/render.test.ts` (add an assertion that note appears).
+
+- [ ] **Step 6.5: Run tests - confirm pass**
+
+Run: `bun test tests/core/discipline/`
+
+Expected: PASS.
+
+- [ ] **Step 6.6: Commit (no auto-commit)**
+
+---
+
+## Task 7: Hook detector drops `event_log_append`
+
+**Files:**
+- Modify: `hooks/lib/detect.ts`
+- Test: `tests/hooks/detect.test.ts`
+
+- [ ] **Step 7.1: Update the failing tests first**
+
+In `tests/hooks/detect.test.ts`, find the cases that assert `event_log_append` clears the guardrail. Flip them so:
+
+```ts
+test("event_log_append no longer counts as a brain event", () => {
+ expect(isBrainEventToolName("event_log_append")).toBe(false);
+ expect(isBrainEventToolName("mcp__open-second-brain__event_log_append")).toBe(false);
+});
+
+test("brain_note counts as a brain event", () => {
+ expect(isBrainEventToolName("brain_note")).toBe(true);
+ expect(isBrainEventToolName("mcp__open-second-brain__brain_note")).toBe(true);
+});
+
+test("o2b append-event bash needle no longer counts as a brain event", () => {
+ const summary = summarizeTurn([], ["o2b append-event 'something'"]);
+ expect(summary.hadBrainEvent).toBe(false);
+});
+```
+
+- [ ] **Step 7.2: Run - confirm failures (some tests fail)**
+
+- [ ] **Step 7.3: Update `hooks/lib/detect.ts`**
+
+```ts
+const BRAIN_EVENT_NAME_SUFFIX =
+ /(?:^|__)(brain_feedback|brain_apply_evidence|brain_note)$/;
+
+const BRAIN_EVENT_BASH_NEEDLES = [
+ "o2b brain feedback",
+ "o2b brain apply-evidence",
+];
+```
+
+Update the surrounding doc comment (the §30 §A paragraph) to mention `brain_note` instead of `event_log_append`.
+
+- [ ] **Step 7.4: Run - confirm pass**
+
+Run: `bun test tests/hooks/detect.test.ts`
+
+Expected: PASS for all detector tests.
+
+- [ ] **Step 7.5: Commit (no auto-commit)**
+
+---
+
+## Task 8: Stop guardrail message rewrite
+
+**Files:**
+- Modify: `hooks/lib/messages.ts`
+- Test: `tests/hooks/stop-log-guardrail.test.ts`
+
+- [ ] **Step 8.1: Failing tests**
+
+Update assertions in `tests/hooks/stop-log-guardrail.test.ts` so:
+- Guardrail message no longer mentions `event_log_append`.
+- Guardrail message mentions all three (`brain_feedback`, `brain_apply_evidence`, `brain_note`).
+- A turn with only a `brain_note` MCP call clears the guardrail.
+
+- [ ] **Step 8.2: Rewrite `stopGuardrailReason` and cadence helpers**
+
+```ts
+function stopGuardrailCadenceLine(runtime: HookRuntime): string {
+ switch (runtime) {
+ case "claudecode":
+ return "_This guardrail fires at most once per turn - send another reply (with or without a brain event) to clear it._";
+ case "codex":
+ return "_This `codex exec` is about to end - call `brain_feedback` / `brain_apply_evidence` / `brain_note` now or finish silently; no further guardrail will fire._";
+ case "unknown":
+ return "";
+ }
+}
+
+export function stopGuardrailReason(runtime: HookRuntime = "unknown"): string {
+ const cadence = stopGuardrailCadenceLine(runtime);
+ const parts: string[] = [
+ "Open Second Brain hook: this turn touched files",
+ "(Write / Edit / MultiEdit / apply_patch) but did not call any of:",
+ "",
+ "- `brain_feedback` - new taste correction the user expressed in this",
+ " turn (one signal per file, see the `brain-memory` skill)",
+ "- `brain_apply_evidence` - evidence trail when an active preference",
+ " in `Brain/preferences/` scopes to the artifact you just produced",
+ "- `brain_note` - one-line narrative milestone (release, merged PR,",
+ " discovered fact) that fits neither category",
+ "",
+ ];
+ if (cadence !== "") parts.push(cadence, "");
+ parts.push(
+ "Pick whichever fits this turn:",
+ "- a new rule the user just stated -> `brain_feedback`",
+ "- an active preference applied or violated by the change ->",
+ " `brain_apply_evidence` with `result: applied | violated`",
+ "- a durable narrative milestone -> `brain_note`",
+ "",
+ "If the change is trivial and not worth recording, just send your",
+ "reply again - this guardrail fires at most once per turn and the",
+ "second Stop passes through silently.",
+ );
+ return parts.join("\n");
+}
+```
+
+- [ ] **Step 8.3: Run - confirm pass**
+
+Run: `bun test tests/hooks/`
+
+Expected: PASS for both detect + stop-log-guardrail.
+
+- [ ] **Step 8.4: Commit (no auto-commit)**
+
+---
+
+## Task 9: PostWrite reminder mentions `brain_note`
+
+**Files:**
+- Modify: `hooks/lib/messages.ts` (`postWriteReminder`)
+- Test: `tests/hooks/post-write-reminder.test.ts`
+
+- [ ] **Step 9.1: Failing test**
+
+Assert the reminder text contains `brain_note`.
+
+- [ ] **Step 9.2: Update `postWriteReminder`**
+
+Insert a paragraph between the existing `brain_apply_evidence` block and the trivial-edits one:
+
+```ts
+"If neither a new preference nor an evidence event fits but this turn",
+"produced a durable artifact worth referencing later (release, merged",
+"PR, discovered fact), call `brain_note` with a one-line description.",
+"",
+```
+
+- [ ] **Step 9.3: Run + commit (no auto-commit)**
+
+---
+
+## Task 10: Identity-reminder templates
+
+**Files:**
+- Modify: `templates/identity-reminder.txt`
+- Modify: `templates/identity-reminder.hermes.txt`
+- Modify: `templates/identity-reminder.openclaw.txt`
+- Modify: `tests/fixtures/identity-reminder/hermes.txt`
+- Modify: `tests/fixtures/identity-reminder/openclaw.txt`
+- Test: `tests/core/identity-reminder.test.ts`
+
+- [ ] **Step 10.1: Update common template**
+
+`templates/identity-reminder.txt`:
+
+```
+[open-second-brain] Identity: @{agent}. After producing a durable artifact - code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know - record it through the Brain writer tools: call `brain_feedback` if the turn surfaced a new user preference; call `brain_apply_evidence` (`result: applied | violated | outdated`) if a preference in `Brain/preferences/` scopes to the artifact; call `brain_note` for narrative milestones that fit neither. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
+```
+
+- [ ] **Step 10.2: Update Hermes template**
+
+`templates/identity-reminder.hermes.txt` - same body as common, with the Hermes-specific note appended:
+
+```
+[open-second-brain] Identity: @{agent}. After every durable artifact this turn - code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know - record it through the Brain writer tools: call `brain_feedback` if the turn surfaced a new user preference; call `brain_apply_evidence` (`result: applied | violated | outdated`) if a preference in `Brain/preferences/` scopes to the artifact; call `brain_note` for narrative milestones that fit neither. Hermes turns are short; do not batch the calls across turns. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
+```
+
+- [ ] **Step 10.3: Update OpenClaw template**
+
+`templates/identity-reminder.openclaw.txt`:
+
+```
+[open-second-brain] Identity: @{agent}. After every durable in-process action - code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know - record it through the Brain writer tools: call `brain_feedback` if the turn surfaced a new user preference; call `brain_apply_evidence` (`result: applied | violated | outdated`) if a preference in `Brain/preferences/` scopes to the artifact; call `brain_note` for narrative milestones that fit neither. OpenClaw has no session boundary; log immediately. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
+```
+
+- [ ] **Step 10.4: Regenerate fixtures**
+
+Manual: copy the three new template bodies into `tests/fixtures/identity-reminder/hermes.txt` and `tests/fixtures/identity-reminder/openclaw.txt` (or remove `__resetEnvWarnedOnceForTests` cached values to force regeneration). Verify `bun test tests/core/identity-reminder.test.ts` passes.
+
+- [ ] **Step 10.5: Run - confirm pass**
+
+```
+bun test tests/core/identity-reminder.test.ts
+bun test tests/python/test_hermes_plugin.py
+```
+
+Expected: PASS for both.
+
+- [ ] **Step 10.6: Commit (no auto-commit)**
+
+---
+
+## Task 11: Drop `event_log_append` from MCP / OpenClaw
+
+**Files:**
+- Modify: `src/mcp/tools.ts`
+- Modify: `src/openclaw/index.ts`
+- Modify: `plugins/hermes/__init__.py`
+- Test: `tests/openclaw/bundle.test.ts`
+- Test: `tests/python/test_hermes_plugin.py`
+- Test: `tests/mcp/mcp.test.ts`
+
+- [ ] **Step 11.1: Failing assertions**
+
+- `tests/openclaw/bundle.test.ts`: invert any "registers event_log_append" check to "does NOT register event_log_append".
+- `tests/mcp/mcp.test.ts`: assert `event_log_append` is absent from the full tool table.
+- `tests/python/test_hermes_plugin.py`: drop or invert the equivalent assertion.
+
+- [ ] **Step 11.2: Remove `toolEventLogAppend`**
+
+In `src/mcp/tools.ts`:
+- Delete the `async function toolEventLogAppend(...)` block (lines ~256-279 in v0.10.7).
+- Delete the explanatory comment block that lives just above `...BRAIN_TOOLS` referencing it.
+- Remove `appendEvent` and `validateEventTime` imports if they are no longer used (verify with `tsc --noEmit`).
+
+- [ ] **Step 11.3: Remove the OpenClaw registration**
+
+In `src/openclaw/index.ts`, delete the `api.registerTool({ name: "event_log_append", ... })` block in its entirety (~50 lines). Verify the surrounding tools (`save_note`, `vault_health`) still register cleanly.
+
+- [ ] **Step 11.4: Update Hermes docstring**
+
+In `plugins/hermes/__init__.py`, change the module docstring's tool list from:
+
+```
+(`second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`)
+```
+
+to:
+
+```
+(`second_brain_status`, `second_brain_query`, `vault_health`, plus the Brain writer surface)
+```
+
+No behavioural change; the Hermes shim only injects the reminder.
+
+- [ ] **Step 11.5: Run - confirm pass**
+
+```
+bun test tests/openclaw/
+bun test tests/mcp/
+bun test tests/python/
+```
+
+Expected: all PASS.
+
+- [ ] **Step 11.6: Commit (no auto-commit)**
+
+---
+
+## Task 12: `cmdAppendEvent` identity fix
+
+**Files:**
+- Modify: `src/cli/main.ts:313-341`
+- Test: `tests/cli/append-event.test.ts` (new)
+
+- [ ] **Step 12.1: Failing test**
+
+Create `tests/cli/append-event.test.ts`:
+
+```ts
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, test } from "bun:test";
+import { spawnSync } from "node:child_process";
+
+const O2B = join(import.meta.dir, "..", "..", "bin", "o2b");
+
+describe("o2b append-event identity resolution", () => {
+ test("uses config agent_name when --as and env are absent", () => {
+ const vault = mkdtempSync(join(tmpdir(), "osb-cli-"));
+ const configDir = mkdtempSync(join(tmpdir(), "osb-cfg-"));
+ try {
+ const configPath = join(configDir, "config.yaml");
+ writeFileSync(
+ configPath,
+ `vault_path: ${vault}\nagent_name: cli-test-bot\n`,
+ "utf8",
+ );
+ mkdirSync(join(vault, "Daily"), { recursive: true });
+ const proc = spawnSync(O2B, ["append-event", "hello world"], {
+ env: {
+ ...process.env,
+ XDG_CONFIG_HOME: configDir,
+ VAULT_AGENT_NAME: "",
+ },
+ encoding: "utf8",
+ });
+ expect(proc.status).toBe(0);
+ // The fixture-day path is whatever today is in the configured tz.
+ const dailyFiles =
+ spawnSync("ls", [join(vault, "Daily")], { encoding: "utf8" })
+ .stdout?.trim().split("\n") ?? [];
+ expect(dailyFiles).toHaveLength(1);
+ const content = readFileSync(join(vault, "Daily", dailyFiles[0]!), "utf8");
+ expect(content).toContain("@cli-test-bot");
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configDir, { recursive: true, force: true });
+ }
+ });
+});
+```
+
+(If the project does not yet have a `tests/cli/` directory, create it with this single file.)
+
+- [ ] **Step 12.2: Run - confirm failure**
+
+Expected: FAIL with `@agent` literal in the Daily content.
+
+- [ ] **Step 12.3: Fix `cmdAppendEvent`**
+
+In `src/cli/main.ts:313-341`:
+
+```ts
+async function cmdAppendEvent(argv: string[]): Promise<number> {
+ const { flags, positional } = parseFlags(argv, {
+ vault: { type: "string" },
+ as: { type: "string" },
+ date: { type: "string" },
+ time: { type: "string" },
+ config: { type: "string" },
+ });
+ if (positional.length < 1) {
+ process.stderr.write("error: append-event requires a message argument\n");
+ return 2;
+ }
+ const message = positional[0]!;
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+ const tz = resolveTimezone(config);
+ const explicit = flags["as"] as string | undefined;
+ const agent = explicit ?? resolveAgentName(config);
+
+ let path: string;
+ try {
+ path = await appendEvent(vault, agent, message, {
+ date: (flags["date"] as string | undefined) ?? null,
+ time: (flags["time"] as string | undefined) ?? null,
+ tz,
+ });
+ } catch (exc) {
+ process.stderr.write(`error: failed to append event: ${(exc as Error).message ?? exc}\n`);
+ return 1;
+ }
+ process.stdout.write(`appended: ${resolve(path)}\n`);
+ return 0;
+}
+```
+
+Confirm `resolveAgentName` is imported at the top of the file (line ~18 already imports it).
+
+- [ ] **Step 12.4: Run - confirm pass**
+
+Run: `bun test tests/cli/append-event.test.ts`
+
+Expected: PASS.
+
+- [ ] **Step 12.5: Commit (no auto-commit)**
+
+---
+
+## Task 13: `hooks/README.md` rewrite
+
+**Files:**
+- Modify: `hooks/README.md`
+
+- [ ] **Step 13.1: Read current README to scope the rewrite**
+
+Run: `wc -l hooks/README.md`. The current file is ~120 lines; the rewrite preserves the "Files" and "How both runtimes find the hook commands" sections; the "What the hooks do" table is rewritten; a "JSONL sidecar" paragraph is added.
+
+- [ ] **Step 13.2: New "What the hooks do" table**
+
+```markdown
+| Event | Matcher | Behaviour |
+|---------------|--------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------|
+| `PostToolUse` | `Write|Edit|MultiEdit|apply_patch` | Emits `additionalContext` reminding the agent to call `brain_feedback`, `brain_apply_evidence`, or `brain_note` for a durable artifact. |
+| `Stop` | (every Stop) | If the turn produced a durable artifact but no `brain_feedback` / `brain_apply_evidence` / `brain_note` call, returns `decision: "block"` once, then lets the second Stop pass. |
+```
+
+- [ ] **Step 13.3: Replace the introductory paragraph**
+
+Remove the reference to `event_log_append`. New text:
+
+```markdown
+Plugin-bundled lifecycle hooks for Claude Code and Codex. The hooks
+exist to make sure every turn that produces a durable artifact records
+the corresponding event in `Brain/log/<date>.md` (and its JSONL sidecar).
+Brain/log/ is the single agent-facing log surface; `Daily/` remains for
+human-CLI use (cron-jobs, ad-hoc scripts) via `o2b append-event`.
+```
+
+- [ ] **Step 13.4: Add the JSONL sidecar paragraph**
+
+After the table, add:
+
+```markdown
+## JSONL sidecar
+
+Every event the writer lands in `Brain/log/<date>.md` is mirrored to
+`Brain/log/<date>.jsonl` in the same atomic step. Machine consumers
+(discipline-report today, future tooling tomorrow) read JSONL through
+`src/core/brain/log-jsonl.ts:readLogDay`, which falls back to parsing
+markdown on historical days that pre-date v0.10.8. Hand-editing the
+markdown does not break the reader; deleting the JSONL forces the
+fallback path until the next write rebuilds it.
+```
+
+- [ ] **Step 13.5: Manual inspection**
+
+Run: `bun src/cli/main.ts --help` (no functional check; the README is documentation only). Confirm the file renders without dangling references to `event_log_append`.
+
+- [ ] **Step 13.6: Commit (no auto-commit)**
+
+---
+
+## Task 14: Update `_summary.md` and CHANGELOG
+
+**Files:**
+- Modify: `Projects/OpenSecondBrain/Features/_summary.md` (in vault, `/root/vault/`)
+- Modify: `CHANGELOG.md`
+
+- [ ] **Step 14.1: Mark §32 shipped**
+
+In `/root/vault/Projects/OpenSecondBrain/Features/_summary.md`, change the heading of §32 (around line 275) from:
+
+```
+### 32. Retire `event_log_append` for agent-facing surface, single source = `Brain/log/` — 8
+```
+
+to:
+
+```
+### ✅ 32. Retire `event_log_append` for agent-facing surface, single source = `Brain/log/` — 8 *(реализовано в v0.10.8: §32A облегчённый verification gate; §32B brain_note tool в always-loaded writer scope; §32C-D drop event_log_append из stop-guardrail / detector / identity-reminder; §32E hooks/README.md переписан; §32F cmdAppendEvent резолвит identity через resolveAgentName; §32G полный дроп handler из всех рантаймов (Claude/Codex/Hermes/OpenClaw); §32H drift-check операторский, без auto-watcher)*
+```
+
+- [ ] **Step 14.2: Mark §23 shipped**
+
+In the same file, change §23 (line 224) from:
+
+```
+### 23. Structured JSONL log параллельно с Markdown — 6
+```
+
+to:
+
+```
+### ✅ 23. Structured JSONL log параллельно с Markdown — 6 *(реализовано в v0.10.8: Brain/log/<date>.jsonl рядом с .md, atomic dual-write через proper-lockfile lock; src/core/brain/log-jsonl.ts:readLogDay - JSONL-preferred reader с markdown fallback; discipline-report переключен; no backfill - исторические дни обслуживает fallback)*
+```
+
+- [ ] **Step 14.3: Append Deferred-work entries**
+
+In `## Deferred work`, add (in the same Russian style as existing entries):
+
+```markdown
+- **§32B CLI verb `o2b brain note`.** MCP tool отгружен в v0.10.8, но CLI verb для cron-job/shell-script use-case'а отложен. Триггер на возврат: первый случай когда заметку нужно записать вне MCP (cron, ad-hoc script). Bash-needle для detector добавляется одновременно с CLI verb.
+
+- **§32H auto-watcher Daily/-записей от @agent-identity.** Операторская проверка (`o2b discipline report` + грeп Daily/) сейчас достаточна. Триггер: drift-check находит повторные случаи которые операторский проход пропустил.
+
+- **§23 one-shot JSONL backfill исторических markdown-дней.** Лeniвый fallback в readLogDay обслуживает все pre-v0.10.8 дни без сидекара. Триггер: машинный consumer материально выигрывает от JSONL для дней старше v0.10.8 (ни один не назван сейчас).
+```
+
+- [ ] **Step 14.4: Update `CHANGELOG.md`**
+
+Insert a new `## [0.10.8] - <ISO date at ship>` section above the `[0.10.7]` block. Use this template (no `[Unreleased]` section, no version dates inside planning):
+
+```markdown
+## [0.10.8] - <ISO date at ship>
+
+Closes §32 (retire `event_log_append` from every agent-facing surface
+in favor of `Brain/log/` as the single source of truth) and §23 (write
+a JSONL sidecar `Brain/log/<date>.jsonl` next to every markdown log
+day, with discipline-report switched to read JSONL when present and
+fall back to markdown when not). Companion design and impl plan at
+`docs/plans/2026-05-19-v0.10.8-design.md` and `-impl.md`.
+
+### Added
+
+- §32B - `brain_note` MCP tool in the always-loaded writer-server
+ scope. Records one narrative-milestone line under event kind `note`
+ in `Brain/log/<today>.md` (+ JSONL sidecar). Text is run through
+ `sanitiseTextField` (newline-collapse, secret redaction, 4096-char
+ cap). Resolver chain: explicit `agent` argument > `resolveAgentName`
+ from config. Discipline-report's `AgentCounts` gains a `note` field.
+- §23 - `Brain/log/<date>.jsonl` written atomically next to
+ `Brain/log/<date>.md` under a `proper-lockfile` lock. Each row
+ carries `{ts, kind, payload}`; the payload is a one-to-one
+ projection of the markdown bullet body.
+- §23 - `src/core/brain/log-jsonl.ts:readLogDay` - the new
+ JSONL-preferred reader. Returns `{entries, source, warnings}`;
+ source is `"jsonl"` or `"markdown-fallback"`. Malformed JSONL lines
+ surface as warnings, not errors.
+
+### Changed
+
+- §32C-D - the Stop guardrail and the PostToolUse reminder list three
+ triggers (`brain_feedback`, `brain_apply_evidence`, `brain_note`) -
+ no `event_log_append`. `hooks/lib/detect.ts` regex and bash needles
+ match the same set.
+- §32D - the three identity-reminder templates (common, Hermes,
+ OpenClaw) point agents at the Brain writer tools; no
+ `event_log_append`. Fixture files regenerated.
+- §32E - `hooks/README.md` rewritten to describe v0.10.8 semantics
+ (Brain/log/ as single agent-facing log; Daily/ as human-CLI;
+ JSONL sidecar paragraph added).
+- §32F - `cmdAppendEvent` (`o2b append-event` CLI verb) resolves the
+ agent through `resolveAgentName` instead of the literal `"agent"`
+ fallback. Cron-jobs that already set `VAULT_AGENT_NAME` are
+ unaffected; cron-jobs that relied on the literal get the
+ config-declared identity.
+- §32G - `event_log_append` MCP tool removed from every runtime:
+ the OpenClaw `registerTool` block, the `toolEventLogAppend` handler
+ in `src/mcp/tools.ts`, and the Hermes docstring mention. The bare
+ `appendEvent` function in `src/core/event-log.ts` stays for the
+ CLI verb and any future shell-side use.
+- §23 - discipline-report (`src/core/discipline/log-counts.ts`)
+ reads through `readLogDay`. Same return shape; counts now include
+ the new `note` kind.
+
+### Migration
+
+No vault data migration required. Historical `Brain/log/<date>.md`
+files without a sidecar JSONL are served by the reader's
+markdown-fallback path; the next write on any date produces both
+files. No installer changes; no schema bump in `_brain.yaml`.
+
+The Stop guardrail no longer clears on a bash `vault-log` /
+`o2b append-event` invocation - the operator/agent must use one of
+the three brain-event tools or finish the turn silently. Cron-jobs
+that use `o2b append-event` keep working; they just no longer count
+as a "brain event" for the guardrail.
+
+### Release-checklist gate
+
+Before shipping v0.10.8 from the working branch:
+
+1. `bun test` - all suites pass.
+2. `o2b discipline report` on `/root/vault` - status `ok` or `info`;
+ every `known_agent` with activity since v0.10.7 has at least one
+ brain event recorded.
+3. Smoke: an MCP `brain_note` call produces both `Brain/log/<today>.md`
+ and `Brain/log/<today>.jsonl`, with the same `ts`, `kind`, and
+ payload keys.
+4. Manual MCP probe: `event_log_append` is absent from `bun
+ src/mcp/main.ts` (full), `--scope writer`, OpenClaw bundle, and the
+ Hermes tool list.
+```
+
+- [ ] **Step 14.5: Commit (no auto-commit)**
+
+---
+
+## Task 15: MEMORY housekeeping
+
+**Files:**
+- Delete: `/root/.claude/projects/-root/memory/feedback_daily_log_strict_russian.md`
+- Delete: `/root/.claude/projects/-root/memory/project_o2b_log_language.md`
+- Modify: `/root/.claude/projects/-root/memory/feedback_always_russian.md`
+- Modify: `/root/.claude/projects/-root/memory/feedback_no_em_dashes.md`
+- Modify: `/root/.claude/projects/-root/memory/MEMORY.md`
+
+- [ ] **Step 15.1: Delete the strict-Russian feedback file**
+
+Run: `rm /root/.claude/projects/-root/memory/feedback_daily_log_strict_russian.md`
+
+- [ ] **Step 15.2: Delete the o2b log-language project file**
+
+Run: `rm /root/.claude/projects/-root/memory/project_o2b_log_language.md`
+
+- [ ] **Step 15.3: Rewrite `feedback_always_russian.md`**
+
+Replace contents:
+
+```markdown
+---
+name: Reply in the user's current dialog language
+description: Default chat language follows the user's dialog; repo artifacts (code, docs, commits) stay English per project convention.
+metadata:
+ type: feedback
+---
+
+Reply in the language the user is currently speaking in this dialog. For
+the current operator the observed default is Russian, but this is an
+observation about the user, not a hard-coded principle. If the user
+switches dialog language, follow.
+
+**Why:** Hard-coded language anchors (`feedback_daily_log_strict_russian`)
+were rejected on 2026-05-19 as a class - the user explicitly asked that
+all such anchors be removed or reframed as "language of the user".
+
+**How to apply:**
+- Chat, explanations, clarifying questions -> the language the user is
+ speaking now.
+- Repository artifacts (CLAUDE.md, AGENTS.md, code, docstrings,
+ CHANGELOG, test descriptions, commit messages, PR titles/bodies) ->
+ English, per the existing project convention.
+- When mirrored docs (CLAUDE.md <-> AGENTS.md) get edited, the mirror
+ rule (`feedback_mirror_claude_agents.md`) still wins; do not switch
+ one mirror to a different language.
+```
+
+- [ ] **Step 15.4: Rewrite `feedback_no_em_dashes.md`**
+
+Replace contents:
+
+```markdown
+---
+name: Use the typographic conventions of the dialog language
+description: Replace em-dashes with hyphen-with-spaces in prose written in languages where em-dash is not idiomatic.
+metadata:
+ type: feedback
+---
+
+When writing prose in a language where em-dash (`—`, U+2014) is not the
+idiomatic typographic choice, use a regular hyphen surrounded by spaces
+(` - `) instead. For the current operator this applies to Russian prose
+(posts, documentation, chat replies, code comments written in Russian).
+English prose and technical identifiers are unaffected; em-dash stays
+where it is idiomatic.
+
+**Why:** The user removed em-dashes from a drafted blog post and asked
+to keep them out of all subsequent prose in the same language. The
+principle is typographic, not language-bound: any language where
+em-dash is not the convention falls under the same rule.
+
+**How to apply:** when generating prose, choose the dash style by
+language convention. Markdown posts, chat replies, descriptions, and
+in-line comments in non-em-dash languages get ` - `. Technical
+documentation and code stay as-is.
+
+Связано: [[feedback_always_russian]] (dialog language is the
+default selector). Brain preference candidate: `pref-no-em-dashes`.
+```
+
+- [ ] **Step 15.5: Update MEMORY index**
+
+Modify `/root/.claude/projects/-root/memory/MEMORY.md`:
+- Remove the line `- [Daily/ entries - always log, always Russian](feedback_daily_log_strict_russian.md) ...`.
+- Remove the line `- [Open Second Brain log language - future task](project_o2b_log_language.md) ...`.
+- Update the line for `feedback_always_russian.md` to read:
+ `- [Reply in dialog language](feedback_always_russian.md) - default to whatever language the user is currently speaking; repo artifacts stay English by project convention.`
+- Update the line for `feedback_no_em_dashes.md` to read:
+ `- [Typographic conventions per dialog language](feedback_no_em_dashes.md) - replace em-dash with hyphen-with-spaces in languages where em-dash is not idiomatic (currently relevant for Russian prose for this user).`
+
+- [ ] **Step 15.6: Sanity check**
+
+Run: `ls /root/.claude/projects/-root/memory/feedback_*` to confirm the two deleted files are gone and the two rewritten ones exist.
+
+- [ ] **Step 15.7: No commit step - MEMORY is operator-private, not part of the project repo.**
+
+---
+
+## Task 16: Verification gate (§32A) - operator step
+
+**Files:** none (release-checklist step).
+
+- [ ] **Step 16.1: Run discipline report**
+
+Run: `o2b discipline report --window since-v0.10.7`
+(If the flag does not exist, run `o2b discipline report` with the default 1-day window and the operator manually expands to "since 2026-05-18" via repeat invocations.)
+
+- [ ] **Step 16.2: Inspect output**
+
+For each agent name in `_brain.yaml:discipline_report.known_agents` that shows non-zero activity, confirm the brain-event count is ≥ 1. Note any agent with activity but zero events; do not proceed to step 17 until each such gap has either:
+- a recorded brain event (after a follow-up that legitimately required one),
+- or an explicit operator note in this task's checklist explaining why the agent has activity but no brain event in the window.
+
+- [ ] **Step 16.3: Verdict**
+
+Document the gate outcome in the v0.10.8 commit message body (or PR description if applicable). Pass: proceed to release. Fail: open a new task track investigating the failing agent's logging path; do not ship.
+
+---
+
+## Task 17: Smoke test on the working branch
+
+**Files:** none (operator step).
+
+- [ ] **Step 17.1: Restart the local MCP servers**
+
+Restart Hermes (`hermes gateway restart`), and reload Claude Code / Codex sessions in the working repo. Wait for the standard `Plugin discovery complete` log line in `/root/.hermes/logs/agent.log`.
+
+- [ ] **Step 17.2: Probe each runtime**
+
+For each of Claude Code, Codex, Hermes, OpenClaw, manually trigger a `brain_note` call (the simplest probe: a one-line `brain_note({ text: "v0.10.8 smoke" })` from each agent). Confirm:
+- The event lands in `/root/vault/Brain/log/<today>.md` and `.jsonl`.
+- The agent identity in both files matches the runtime's configured `agent_name` (no `@agent` literal).
+
+- [ ] **Step 17.3: Probe each runtime for the absence of `event_log_append`**
+
+In each runtime, attempt to call `event_log_append` (or scan the runtime's published tool list). Confirm the tool is not advertised. The expected failure mode is "unknown tool" - not a runtime crash.
+
+---
+
+## Self-Review
+
+Spec coverage: every numbered spec subsection (§4.1 - §4.11) maps to one
+or more tasks above. The tasks cover §32A (Task 16), §32B (Tasks 4, 5,
+6), §32C+D (Tasks 7, 8, 9, 10), §32E (Task 13), §32F (Task 12), §32G
+(Task 11), §32H (Task 16/17 operator step), §23 (Tasks 1, 2, 3), and
+the MEMORY housekeeping side track (Task 15). Task 14 captures the
+release-artifact updates (CHANGELOG, _summary.md). Task 17 is the
+post-merge smoke. No spec section is uncovered.
+
+Placeholder scan: no `TBD`, `TODO`, or "Add appropriate error handling"
+in the plan. Every code block is complete; every test block shows the
+actual assertion code. No "similar to Task N" without repeating the
+code.
+
+Type consistency: `BrainLogEntry`, `BrainLogParseWarning`, and
+`BrainNoteLogEvent` names are used consistently. `readLogDay` and
+`appendLogEvent` signatures match across Tasks 1-3. `AgentCounts.note`
+is added in Task 6 and used in Task 6's test. `WRITER_TOOL_NAMES` in
+Task 5 is the same set name as in `src/mcp/tools.ts`. `BRAIN_TOOLS` is
+the same array name used by the existing brain tools.
diff --git a/hooks/README.md b/hooks/README.md
index 3b624bfd..f32e03be 100644
--- a/hooks/README.md
+++ b/hooks/README.md
@@ -1,33 +1,49 @@
# Open Second Brain — runtime hooks
Plugin-bundled lifecycle hooks for Claude Code and Codex. The hooks
-exist to close the gap exposed by the Claude Code bug report at
-`Projects/OpenSecondBrain/Plan/1. claude-bug.md`: a soft MCP-server
-instruction is not enough to make `event_log_append` reliably fire
-after a durable artifact, and the agent had no visible signal that
-the log was skipped.
+make sure every turn that produces a durable artifact records the
+corresponding event in `Brain/log/<date>.md` (and its JSONL sidecar).
+`Brain/log/` is the single agent-facing log surface; `Daily/` remains
+as the human-CLI surface — populated by `o2b append-event` from
+cron-jobs and shell scripts, not by agents.
Hermes and OpenClaw deliberately do **not** load these hooks. Hermes
-already injects an identity / log reminder via its `pre_llm_call`
-plugin shim, so the same nudge arrives through a different channel
-without duplicating subsystems. OpenClaw's native JS plugin format
-predates these hooks. If either runtime grows a Claude-style hook
-schema later, point its config at `hooks/hooks.json` and the same
-scripts will work — they only depend on the documented hook payload
-shape, not on the runtime.
+already injects an identity / writer-tool reminder via its
+`pre_llm_call` plugin shim, so the same nudge arrives through a
+different channel without duplicating subsystems. OpenClaw's native
+JS plugin format predates these hooks. If either runtime grows a
+Claude-style hook schema later, point its config at `hooks/hooks.json`
+and the same scripts will work — they only depend on the documented
+hook payload shape, not on the runtime.
## What the hooks do
-| Event | Matcher | Behaviour |
-|---------------|--------------------------------------|----------------------------------------------------------------------------------------|
-| `PostToolUse` | `Write\|Edit\|MultiEdit\|apply_patch` | Emits `additionalContext` reminding the agent to call `event_log_append` if the edit is durable. |
-| `Stop` | (every Stop) | If the turn produced a durable artifact but no `event_log_append` call, returns `decision: "block"` once, then lets the second Stop pass. |
+| Event | Matcher | Behaviour |
+|---------------|--------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------|
+| `PostToolUse` | `Write\|Edit\|MultiEdit\|apply_patch` | Emits `additionalContext` pointing at the three Brain writer tools (`brain_feedback`, `brain_apply_evidence`, `brain_note`) for a durable edit. |
+| `Stop` | (every Stop) | If the turn produced a durable artifact and none of `brain_feedback` / `brain_apply_evidence` / `brain_note` landed, returns `decision: "block"` once, then lets the second Stop pass. |
The Stop guardrail respects the runtime-provided `stop_hook_active`
flag: it fires at most once per turn, so the agent can deliberately
decide that an edit was trivial and skip logging by just finishing
again. No deadlocks.
+## JSONL sidecar
+
+Every event the writer lands in `Brain/log/<date>.md` is mirrored to
+`Brain/log/<date>.jsonl` in the same atomic step (one
+`proper-lockfile` lock for the pair). Machine consumers
+(`o2b discipline report` today, future tooling tomorrow) read JSONL
+through `src/core/brain/log-jsonl.ts:readLogDay`, which falls back to
+parsing markdown on days that pre-date v0.10.8. Hand-editing the
+markdown does not break the reader; deleting the JSONL forces the
+fallback path until the next write rebuilds it.
+
+The retired `event_log_append` MCP tool no longer exists in any
+runtime as of §32 (v0.10.8). The bash CLI `o2b append-event` still
+works for cron-jobs / shell scripts that target `Daily/`, but it no
+longer counts as a brain event for the Stop guardrail.
+
## Files
- `hooks.json` — lifecycle config picked up by both runtimes. Claude
diff --git a/hooks/lib/detect.ts b/hooks/lib/detect.ts
index 3943859c..f8202c9e 100644
--- a/hooks/lib/detect.ts
+++ b/hooks/lib/detect.ts
@@ -33,12 +33,12 @@ const NATIVE_ARTIFACT_NAMES = new Set<string>([
// Tool-name suffixes that count as "the agent logged this turn",
// regardless of any runtime-injected MCP prefix.
//
-// §30 §A (v0.10.6) broadens the set from `event_log_append` only to
-// any of the three brain-event tools — `event_log_append` itself
-// (durable session summary), `brain_feedback` (new taste signal),
-// `brain_apply_evidence` (evidence trail against an active
-// preference). Either of these landing in a turn that produced a
-// durable artifact is enough to clear the stop guardrail.
+// §32 (v0.10.8) retires `event_log_append` and adds `brain_note` as
+// the third Brain-native writer (narrative milestones that fit
+// neither feedback nor apply-evidence). The set is now
+// `brain_feedback` / `brain_apply_evidence` / `brain_note`; any of
+// them landing in a turn that produced a durable artifact clears the
+// stop guardrail.
//
// Names appear bare in Codex transcripts and decorated as
// `mcp__plugin_<plugin>_<server>__<name>` or `mcp__<server>__<name>`
@@ -46,16 +46,18 @@ const NATIVE_ARTIFACT_NAMES = new Set<string>([
// start or a `__` separator so a future prefix change keeps working
// without an emergency patch.
const BRAIN_EVENT_NAME_SUFFIX =
- /(?:^|__)(event_log_append|brain_feedback|brain_apply_evidence)$/;
+ /(?:^|__)(brain_feedback|brain_apply_evidence|brain_note)$/;
// Bash command substrings that count as a brain-event call from the
// CLI. We deliberately keep this list narrow: anything matched here
// suppresses the guardrail. Spawning the MCP server (`o2b mcp …`)
// does NOT log on its own, so it stays out of the list — only the
// explicit event-emitting commands are in.
+//
+// §32 (v0.10.8) drops `o2b append-event` and `vault-log` — those
+// still work for human / cron use, but they target the deprecated
+// `Daily/` surface and no longer count as a Brain-side event.
const BRAIN_EVENT_BASH_NEEDLES = [
- "o2b append-event",
- "vault-log ", // trailing space distinguishes the CLI from a literal log path
"o2b brain feedback",
"o2b brain apply-evidence",
];
@@ -66,8 +68,8 @@ export function isArtifactToolName(name: string): boolean {
/**
* True when `name` is one of the three brain-event tools (or a
- * runtime-decorated form thereof). The renamed-from `isLogToolName`
- * — kept tightly aligned with §30 §A's broadened semantics.
+ * runtime-decorated form thereof). §32 (v0.10.8) replaces the
+ * v0.10.6 set: `event_log_append` is retired; `brain_note` is added.
*/
export function isBrainEventToolName(name: string): boolean {
return BRAIN_EVENT_NAME_SUFFIX.test(name);
@@ -76,10 +78,9 @@ export function isBrainEventToolName(name: string): boolean {
export interface TurnSummary {
readonly hadArtifact: boolean;
/**
- * True when any of `event_log_append`, `brain_feedback`,
- * `brain_apply_evidence` (MCP call or CLI invocation) landed in
- * this turn. Renamed from `hadLog` in v0.10.6 §30 §A so the stop
- * guardrail's correctness rests on the broader signal.
+ * True when any of `brain_feedback`, `brain_apply_evidence`, or
+ * `brain_note` (MCP call or CLI invocation) landed in this turn.
+ * §32 (v0.10.8): `event_log_append` no longer counts.
*/
readonly hadBrainEvent: boolean;
}
diff --git a/hooks/lib/messages.ts b/hooks/lib/messages.ts
index cc1c1a21..c929c4f0 100644
--- a/hooks/lib/messages.ts
+++ b/hooks/lib/messages.ts
@@ -70,11 +70,17 @@ export function postWriteReminder({
"`brain_apply_evidence` with `result: applied | violated` so the",
"dream pass can update confidence and retire stale rules.",
"",
- "Trivial edits (typo fix, pure formatting) don't need either call.",
- "When a preference plausibly applies but you are unsure, record",
- "the event with `note: \"speculative; <reason>\"` instead of",
- "skipping — the dream pass discards single-event speculative",
- "entries that do not recur.",
+ "If neither a new preference nor an evidence event fits but this",
+ "turn still produced a durable artifact worth referencing later",
+ "(release shipped, PR merged, fact discovered), call `brain_note`",
+ "with a one-line description — it lands in `Brain/log/<today>.md`",
+ "(plus the JSONL sidecar) under the `note` event kind.",
+ "",
+ "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>\"`",
+ "instead of skipping — the dream pass discards single-event",
+ "speculative entries that do not recur.",
);
return parts.join("\n");
}
@@ -82,9 +88,9 @@ export function postWriteReminder({
function stopGuardrailCadenceLine(runtime: HookRuntime): string {
switch (runtime) {
case "claudecode":
- return "_This guardrail fires at most once per turn — send another reply (with or without `event_log_append`) to clear it._";
+ return "_This guardrail fires at most once per turn — send another reply (with or without a brain-event call) to clear it._";
case "codex":
- return "_This `codex exec` is about to end — call `event_log_append` now or finish silently; no further guardrail will fire._";
+ return "_This `codex exec` is about to end — call `brain_feedback` / `brain_apply_evidence` / `brain_note` now or finish silently; no further guardrail will fire._";
case "unknown":
return "";
}
@@ -96,20 +102,21 @@ export function stopGuardrailReason(runtime: HookRuntime = "unknown"): string {
"Open Second Brain hook: this turn touched files",
"(Write / Edit / MultiEdit / apply_patch) but did not call any of:",
"",
- "- `event_log_append` — durable session-summary line for the day log",
- "- `brain_apply_evidence` — evidence trail when an active preference",
- " in `Brain/preferences/` scopes to the artifact you just produced",
"- `brain_feedback` — new taste correction the user expressed in this",
" turn (one signal per file, see the `brain-memory` skill)",
+ "- `brain_apply_evidence` — evidence trail when an active preference",
+ " in `Brain/preferences/` scopes to the artifact you just produced",
+ "- `brain_note` — one-line narrative milestone (release shipped, PR",
+ " merged, fact discovered) that fits neither of the first two",
"",
];
if (cadence !== "") parts.push(cadence, "");
parts.push(
"Pick whichever fits this turn:",
- "- a durable artifact future sessions need to find → `event_log_append`",
+ "- a new rule the user just stated → `brain_feedback`",
"- an active preference applied or violated by the change →",
" `brain_apply_evidence` with `result: applied | violated`",
- "- a new rule the user just stated → `brain_feedback`",
+ "- a durable narrative milestone → `brain_note`",
"",
"If the change is trivial and not worth recording, just send your",
"reply again — this guardrail fires at most once per turn and the",
diff --git a/openclaw/index.js b/openclaw/index.js
index 02f9548d..ea57bf55 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -1478,12 +1478,12 @@ var require_adapter = __commonJS((exports, module) => {
return newFs;
}
function toPromise(method) {
- return (...args) => new Promise((resolve, reject) => {
+ return (...args) => new Promise((resolve3, reject) => {
args.push((err, result) => {
if (err) {
reject(err);
} else {
- resolve(result);
+ resolve3(result);
}
});
method(...args);
@@ -1554,8 +1554,8 @@ var require_proper_lockfile = __commonJS((exports, module) => {
// src/openclaw/index.ts
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
-import { existsSync as existsSync7 } from "node:fs";
-import { join as join10, resolve as resolvePath } from "node:path";
+import { existsSync as existsSync6 } from "node:fs";
+import { join as join9, resolve as resolvePath } from "node:path";
// src/core/config.ts
import { existsSync, readFileSync, statSync } from "node:fs";
@@ -2010,151 +2010,8 @@ function isFile(p) {
}
}
-// src/core/event-log.ts
-var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
-import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3 } from "node:fs";
-import { join as join4 } from "node:path";
-var SECRET_ASSIGNMENT_RE = /\b(api[_-]?key|token|secret|password|credential)(\s*[:=]\s*)\S+/gi;
-var EVENT_RE = /^- (\d{2}:\d{2}) — @/;
-var DATE_RE = /^(\d{4})\.(\d{2})\.(\d{2})$/;
-var TIME_RE = /^(\d{2}):(\d{2})$/;
-function redactText(text) {
- return text.replace(SECRET_ASSIGNMENT_RE, (_match, field, sep) => `${field}${sep}[REDACTED]`);
-}
-function currentDate(tz) {
- const fmt = new Intl.DateTimeFormat("en-CA", {
- timeZone: tz ?? undefined,
- year: "numeric",
- month: "2-digit",
- day: "2-digit"
- });
- return fmt.format(new Date).replace(/-/g, ".");
-}
-function currentTime(tz) {
- const parts = new Intl.DateTimeFormat("en-US", {
- timeZone: tz ?? undefined,
- hour: "2-digit",
- minute: "2-digit",
- hourCycle: "h23"
- }).formatToParts(new Date);
- const get = (type) => parts.find((p) => p.type === type).value;
- return `${get("hour")}:${get("minute")}`;
-}
-function dailyNotePath(vaultDir, date) {
- return join4(vaultDir, "Daily", `${validateEventDate(date)}.md`);
-}
-function newDailyNote(date) {
- return `---
-formatted: false
----
-
-# ${date}
-
-## Raw events
-
-`;
-}
-function validateEventTime(value) {
- const m = TIME_RE.exec(value);
- if (!m) {
- throw new Error("event time must use HH:MM 24-hour format");
- }
- const hour = parseInt(m[1], 10);
- const minute = parseInt(m[2], 10);
- if (hour > 23 || minute > 59) {
- throw new Error("event time must use HH:MM 24-hour format");
- }
- return value;
-}
-function validateEventDate(value) {
- const m = DATE_RE.exec(value);
- if (!m) {
- throw new Error("event date must use YYYY.MM.DD format");
- }
- const year = parseInt(m[1], 10);
- const month = parseInt(m[2], 10);
- const day = parseInt(m[3], 10);
- const utc = new Date(Date.UTC(year, month - 1, day));
- if (utc.getUTCFullYear() !== year || utc.getUTCMonth() !== month - 1 || utc.getUTCDate() !== day) {
- throw new Error("event date must use YYYY.MM.DD format");
- }
- return value;
-}
-function insertEventEntry(content, entry) {
- const marker = "## Raw events";
- const idx = content.indexOf(marker);
- if (idx === -1) {
- return content.trimEnd() + `
-
-` + marker + `
-
-` + entry + `
-`;
- }
- const before = content.slice(0, idx);
- let after = content.slice(idx + marker.length).replace(/^\n+/, "");
- const lines = after.split(`
-`).filter((line) => line.trim());
- const entryTime = entry.slice(2, 7);
- let inserted = false;
- const output = [];
- for (const line of lines) {
- const m = EVENT_RE.exec(line);
- if (!inserted && m && m[1] > entryTime) {
- output.push(entry);
- inserted = true;
- }
- output.push(line);
- }
- if (!inserted)
- output.push(entry);
- let raw = output.join(`
-`);
- if (raw)
- raw += `
-`;
- return before + marker + `
-
-` + raw;
-}
-async function appendEvent(vaultDir, agent, message, opts = {}) {
- const tz = opts.tz ?? null;
- const eventDate = validateEventDate(opts.date ?? currentDate(tz));
- const eventTime = validateEventTime(opts.time ?? currentTime(tz));
- const path = dailyNotePath(vaultDir, eventDate);
- const cleanMessage = redactText(message).replace(/\r?\n/g, " ");
- const entry = `- ${eventTime} — @${agent} — ${cleanMessage}`;
- const dailyDir = join4(vaultDir, "Daily");
- mkdirSync3(dailyDir, { recursive: true });
- const release = await import_proper_lockfile.default.lock(dailyDir, {
- retries: { retries: 30, factor: 1.2, minTimeout: 30, maxTimeout: 500 },
- stale: 1e4,
- realpath: false
- });
- try {
- let content;
- if (existsSync3(path)) {
- content = readFileSync3(path, "utf8");
- } else {
- content = newDailyNote(eventDate);
- }
- if (!content.includes("## Raw events")) {
- content = content.trimEnd() + `
-
-## Raw events
-
-`;
- }
- const updated = insertEventEntry(content, entry);
- atomicWriteFileSync(path, updated);
- } finally {
- await release();
- }
- return path;
-}
-
// src/core/identity-reminder.ts
-import { readFileSync as readFileSync4 } from "node:fs";
+import { readFileSync as readFileSync3 } from "node:fs";
import { dirname as dirname3, resolve } from "node:path";
import { fileURLToPath } from "node:url";
var TEMPLATE_PATH = resolve(dirname3(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");
@@ -2167,7 +2024,7 @@ function loadReminderTemplate() {
if (commonTemplateCache !== undefined)
return commonTemplateCache;
try {
- commonTemplateCache = readFileSync4(TEMPLATE_PATH, "utf8").trimEnd();
+ commonTemplateCache = readFileSync3(TEMPLATE_PATH, "utf8").trimEnd();
return commonTemplateCache;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
@@ -2186,7 +2043,7 @@ function tryReadTargetTemplate(target) {
return cached;
let body;
try {
- body = readFileSync4(PER_TARGET_PATHS[target], "utf8").trimEnd();
+ body = readFileSync3(PER_TARGET_PATHS[target], "utf8").trimEnd();
} catch (err) {
if (err.code !== "ENOENT")
throw err;
@@ -2220,10 +2077,10 @@ function buildReminder(agent, target) {
}
// src/core/pay-memory/paths.ts
-import { join as join5 } from "node:path";
+import { join as join4 } from "node:path";
// src/core/path-safety.ts
-import { existsSync as existsSync4, realpathSync } from "node:fs";
+import { existsSync as existsSync3, realpathSync } from "node:fs";
import { dirname as dirname4, posix, relative, resolve as resolve2, sep } from "node:path";
function ensureInsideVault(target, vault) {
const resolvedTarget = resolve2(target);
@@ -2231,7 +2088,7 @@ function ensureInsideVault(target, vault) {
if (!isLexicallyInside(resolvedTarget, resolvedVault)) {
throw new Error(`path escapes vault: ${target}`);
}
- if (existsSync4(resolvedVault)) {
+ if (existsSync3(resolvedVault)) {
const realVault = safeRealpath(resolvedVault);
const realAncestor = safeRealpath(deepestExistingAncestor(resolvedTarget));
if (!isLexicallyInside(realAncestor, realVault)) {
@@ -2247,7 +2104,7 @@ function isLexicallyInside(target, root) {
}
function deepestExistingAncestor(target) {
let cur = target;
- while (!existsSync4(cur)) {
+ while (!existsSync3(cur)) {
const parent = dirname4(cur);
if (parent === cur)
return cur;
@@ -2273,29 +2130,29 @@ function vaultRelative(target, vault) {
var ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
var HHMM_RE = /^(\d{2}):(\d{2})$/;
function payMemoryDirs(vault) {
- const root = join5(vault, "AI Wiki");
+ const root = join4(vault, "AI Wiki");
return {
- policies: join5(root, "policies"),
- payments: join5(root, "payments"),
- assets: join5(root, "assets"),
- drafts: join5(root, "drafts"),
- reports: join5(root, "reports")
+ policies: join4(root, "policies"),
+ payments: join4(root, "payments"),
+ assets: join4(root, "assets"),
+ drafts: join4(root, "drafts"),
+ reports: join4(root, "reports")
};
}
function policyPath(vault) {
- return join5(payMemoryDirs(vault).policies, "spending.md");
+ return join4(payMemoryDirs(vault).policies, "spending.md");
}
function paymentsDateDir(vault, date) {
- return join5(payMemoryDirs(vault).payments, validateIsoDate(date));
+ return join4(payMemoryDirs(vault).payments, validateIsoDate(date));
}
function receiptPath(vault, date, slug) {
- return join5(paymentsDateDir(vault, date), `${validateSlug(slug)}.md`);
+ return join4(paymentsDateDir(vault, date), `${validateSlug(slug)}.md`);
}
function assetPath(vault, slug) {
- return join5(payMemoryDirs(vault).assets, `${validateSlug(slug)}.md`);
+ return join4(payMemoryDirs(vault).assets, `${validateSlug(slug)}.md`);
}
function reportPath(vault, slug) {
- return join5(payMemoryDirs(vault).reports, `${validateSlug(slug)}.md`);
+ return join4(payMemoryDirs(vault).reports, `${validateSlug(slug)}.md`);
}
var WINDOWS_RESERVED_BASENAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;
function validateSlug(slug) {
@@ -2447,7 +2304,7 @@ function redactRawOutput(text) {
return out;
}
// src/core/pay-memory/policy.ts
-import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5 } from "node:fs";
+import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4 } from "node:fs";
import { dirname as dirname5 } from "node:path";
var DEFAULT_POLICY_TEMPLATE = `# Agent Spending Policy
@@ -2503,9 +2360,9 @@ The agent must save:
function writePolicyIfMissing(vault, opts = {}) {
const target = policyPath(vault);
const overwrite = opts.overwrite ?? false;
- mkdirSync4(dirname5(target), { recursive: true });
+ mkdirSync3(dirname5(target), { recursive: true });
if (overwrite) {
- const existed = existsSync5(target);
+ const existed = existsSync4(target);
atomicWriteFileSync(target, DEFAULT_POLICY_TEMPLATE);
return existed ? buildPolicyResult(target, "overwritten") : buildPolicyResult(target, "created");
}
@@ -2529,8 +2386,8 @@ function buildPolicyResult(path, status) {
};
}
// src/core/vault.ts
-import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, readdirSync, statSync as statSync3, writeFileSync } from "node:fs";
-import { dirname as dirname6, join as join6, relative as relative2 } from "node:path";
+import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync, statSync as statSync3, writeFileSync } from "node:fs";
+import { dirname as dirname6, join as join5, relative as relative2 } from "node:path";
var FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
var KEY_VALUE_RE = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$/;
var PLAIN_SCALAR_RE = /^[A-Za-z0-9_./-](?:[A-Za-z0-9_./ -]*[A-Za-z0-9_./-])?$/;
@@ -2564,7 +2421,7 @@ var DEFAULT_SKIP_FILES = ["index.md", "log.md"];
function parseFrontmatter(path) {
let text;
try {
- text = readFileSync6(path, "utf8");
+ text = readFileSync5(path, "utf8");
} catch {
return [{}, ""];
}
@@ -2609,7 +2466,7 @@ function formatFrontmatter(metadata, body) {
`;
}
function writeFrontmatter(path, metadata, body) {
- mkdirSync5(dirname6(path), { recursive: true });
+ mkdirSync4(dirname6(path), { recursive: true });
writeFileSync(path, formatFrontmatter(metadata, body), "utf8");
}
function writeFrontmatterAtomic(path, metadata, body, opts = {}) {
@@ -2652,7 +2509,7 @@ function walk(root, dir, skipDirs, skipFiles, out) {
return;
}
for (const entry of entries) {
- const full = join6(dir, entry.name);
+ const full = join5(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name))
continue;
@@ -3043,7 +2900,7 @@ function renderAssetBody(input) {
}
// src/core/pay-memory/report.ts
import { readdirSync as readdirSync2 } from "node:fs";
-import { join as join7 } from "node:path";
+import { join as join6 } from "node:path";
var REPORT_FRONTMATTER_TYPE = "payment-report";
function aggregateReceipts(vault, date) {
const dir = paymentsDateDir(vault, date);
@@ -3061,7 +2918,7 @@ function aggregateReceipts(vault, date) {
continue;
if (!entry.name.toLowerCase().endsWith(".md"))
continue;
- const full = join7(dir, entry.name);
+ const full = join6(dir, entry.name);
let meta;
try {
[meta] = parseFrontmatter(full);
@@ -3161,17 +3018,17 @@ function renderReportBody(date, title, task, summaries) {
`);
}
// src/core/pay-memory/policy-rules.ts
-import { readFileSync as readFileSync7 } from "node:fs";
-import { join as join8 } from "node:path";
+import { readFileSync as readFileSync6 } from "node:fs";
+import { join as join7 } from "node:path";
var POLICY_SCHEMA_VERSION = 1;
function policyJsonPath(vault) {
- return join8(payMemoryDirs(vault).policies, "spending.json");
+ return join7(payMemoryDirs(vault).policies, "spending.json");
}
function loadPolicyRules(vault) {
const target = policyJsonPath(vault);
let text;
try {
- text = readFileSync7(target, "utf8");
+ text = readFileSync6(target, "utf8");
} catch (err) {
if (err?.code === "ENOENT")
return null;
@@ -3326,14 +3183,14 @@ function checkPolicy(vault, request) {
};
}
// src/core/pay-memory/approval.ts
-var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
-import { join as join9 } from "node:path";
+var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
+import { join as join8 } from "node:path";
var PENDING_REQUEST_FRONTMATTER_TYPE = "pending-payment-request";
function pendingDir(vault) {
- return join9(payMemoryDirs(vault).payments, "_pending");
+ return join8(payMemoryDirs(vault).payments, "_pending");
}
function pendingRequestPath(vault, id) {
- return join9(pendingDir(vault), `${validateSlug(id)}.md`);
+ return join8(pendingDir(vault), `${validateSlug(id)}.md`);
}
function writePendingRequest(vault, input) {
if (!input.service?.trim())
@@ -3425,7 +3282,7 @@ async function transitionRequest(vault, id, expectedFrom, newStatus, patch) {
if (!initial) {
throw new Error(`pending request not found: ${id}`);
}
- const release = await import_proper_lockfile2.default.lock(lockTarget, {
+ const release = await import_proper_lockfile.default.lock(lockTarget, {
retries: { retries: 30, factor: 1.2, minTimeout: 30, maxTimeout: 500 },
stale: 1e4,
realpath: false
@@ -3525,7 +3382,7 @@ function parseDecisionStatus(raw) {
return "allowed";
}
// src/openclaw/index.ts
-import { mkdirSync as mkdirSync6 } from "node:fs";
+import { mkdirSync as mkdirSync5 } from "node:fs";
// src/core/agent-identity.ts
var PLACEHOLDER_AGENT_VALUES = new Set([
@@ -3644,7 +3501,7 @@ var openclaw_default = definePluginEntry({
config_keys: Object.keys(discovery.data).sort(),
config: redactMapping(discovery.data),
vault_path: vault,
- vault_exists: existsSync7(vault)
+ vault_exists: existsSync6(vault)
};
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
}
@@ -3670,7 +3527,7 @@ var openclaw_default = definePluginEntry({
},
async execute(_id, params) {
const vault = resolveVaultPath(api);
- if (!existsSync7(vault))
+ if (!existsSync6(vault))
throw new Error(`vault directory missing: ${vault}`);
const pattern = params["pattern"] ?? null;
const limit = typeof params["limit"] === "number" ? params["limit"] : 50;
@@ -3713,7 +3570,7 @@ var openclaw_default = definePluginEntry({
},
async execute(_id, params) {
const vault = resolveVaultPath(api);
- if (!existsSync7(vault))
+ if (!existsSync6(vault))
throw new Error(`vault directory missing: ${vault}`);
const title = params["title"] ?? "";
const content = params["content"] ?? "";
@@ -3723,10 +3580,10 @@ var openclaw_default = definePluginEntry({
throw new Error("title must not be empty");
if (!content.trim())
throw new Error("content must not be empty");
- const notesDir = join10(vault, "AI Wiki", "notes");
+ const notesDir = join9(vault, "AI Wiki", "notes");
const slug = slugify(title);
- const target = join10(notesDir, `${slug}.md`);
- const noteExisted = existsSync7(target);
+ const target = join9(notesDir, `${slug}.md`);
+ const noteExisted = existsSync6(target);
if (noteExisted && !overwrite) {
throw new Error(`note already exists: ${vaultRelative(target, vault)}`);
}
@@ -3747,44 +3604,6 @@ var openclaw_default = definePluginEntry({
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
}
});
- 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." }
- },
- required: ["message"],
- additionalProperties: false
- },
- async execute(_id, params) {
- const vault = resolveVaultPath(api);
- const message = params["message"];
- if (!message || !message.trim()) {
- throw new Error("missing required argument: message");
- }
- const argAgent = params["agent"] ?? null;
- const date = params["date"] ?? null;
- const time = params["time"] ?? null;
- if (time)
- validateEventTime(time);
- const agent = resolveOpenclawAgent(api, argAgent);
- const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();
- const path = await appendEvent(vault, agent, message, { date, time, tz });
- const result = {
- path: vaultRelative(path, vault),
- absolute_path: path,
- agent,
- date,
- time
- };
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
- }
- });
api.registerTool({
name: "vault_health",
description: "Run vault, config, and plugin manifest health checks.",
@@ -3829,8 +3648,8 @@ var openclaw_default = definePluginEntry({
const created = [];
const skipped = [];
for (const dir of [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports]) {
- const existed = existsSync7(dir);
- mkdirSync6(dir, { recursive: true });
+ const existed = existsSync6(dir);
+ mkdirSync5(dir, { recursive: true });
(existed ? skipped : created).push(vaultRelative(dir, vault));
}
const policy = writePolicyIfMissing(vault, { overwrite });
diff --git a/plugins/hermes/__init__.py b/plugins/hermes/__init__.py
index 60017f8c..8c70c45a 100644
--- a/plugins/hermes/__init__.py
+++ b/plugins/hermes/__init__.py
@@ -1,10 +1,11 @@
"""Hermes Python shim for Open Second Brain.
Most of Open Second Brain runs as a Bun-based MCP server on stdio (registered
-via ``hermes mcp_servers`` in ``~/.hermes/config.yaml``). The MCP route is the
-only one Hermes needs for the five tools (``second_brain_status``,
-``second_brain_query``, ``second_brain_capture``, ``event_log_append``,
-``vault_health``).
+via ``hermes mcp_servers`` in ``~/.hermes/config.yaml``). MCP carries every
+agent-facing tool surface (``second_brain_status``, ``second_brain_query``,
+``vault_health``, plus the Brain writer surface: ``brain_feedback``,
+``brain_apply_evidence``, ``brain_note``); §32 (v0.10.8) retires the legacy
+``event_log_append`` tool from every runtime, including this one.
This file exists for one Hermes-specific feature that MCP cannot replicate:
the per-turn ``pre_llm_call`` hook, which appends a short identity reminder
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 0e31950a..6ff7e152 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -313,21 +313,31 @@ async function cmdDoctor(argv: string[]): Promise<number> {
async function cmdAppendEvent(argv: string[]): Promise<number> {
const { flags, positional } = parseFlags(argv, {
vault: { type: "string" },
- as: { type: "string", default: process.env["VAULT_AGENT_NAME"] ?? "agent" },
+ as: { type: "string" },
date: { type: "string" },
time: { type: "string" },
+ config: { type: "string" },
});
if (positional.length < 1) {
process.stderr.write("error: append-event requires a message argument\n");
return 2;
}
const message = positional[0]!;
- const vault = requireVault(flags["vault"] as string | undefined, defaultConfigPath());
- const tz = resolveTimezone();
+ // §32F (v0.10.8): resolve the agent identity through the shared
+ // resolver instead of the literal `"agent"` fallback. The resolver
+ // chain honours `--as` -> `VAULT_AGENT_NAME` env -> `agent_name`
+ // from the plugin config -> the placeholder `"agent"` (only as the
+ // very last resort). Cron-jobs and shell scripts get the
+ // config-declared identity instead of corrupted `@agent` entries.
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+ const tz = resolveTimezone(config);
+ const explicit = flags["as"] as string | undefined;
+ const agent = explicit ?? resolveAgentName(config);
let path: string;
try {
- path = await appendEvent(vault, String(flags["as"] ?? "agent"), message, {
+ path = await appendEvent(vault, agent, message, {
date: (flags["date"] as string | undefined) ?? null,
time: (flags["time"] as string | undefined) ?? null,
tz,
diff --git a/src/core/brain/log-jsonl.ts b/src/core/brain/log-jsonl.ts
new file mode 100644
index 00000000..e9827d73
--- /dev/null
+++ b/src/core/brain/log-jsonl.ts
@@ -0,0 +1,149 @@
+/**
+ * Brain log reader (§23, v0.10.8). Prefers the JSONL sidecar written by
+ * `appendLogEvent`; falls back to parsing the markdown on days without
+ * a sidecar (pre-v0.10.8 history, or sidecar deleted by hand).
+ *
+ * Every machine consumer of `Brain/log/` (discipline-report today,
+ * future tooling tomorrow) reads through this entry point so the
+ * fallback logic never duplicates. Malformed JSONL lines surface as
+ * `warnings` instead of aborting the read, matching `parseLogDay`'s
+ * tolerance contract.
+ */
+
+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";
+
+export interface ReadLogDayResult {
+ readonly entries: ReadonlyArray<BrainLogEntry>;
+ readonly source: "jsonl" | "markdown-fallback";
+ readonly warnings: ReadonlyArray<BrainLogParseWarning>;
+}
+
+/**
+ * Read one day of Brain log events. Picks the JSONL sidecar when it
+ * exists; otherwise falls back to parsing the markdown. When neither
+ * file exists, returns an empty result with `source: "jsonl"` (a
+ * convenient default — the caller treats it as "no events for that
+ * date" regardless of source).
+ */
+export function readLogDay(vault: string, date: string): ReadLogDayResult {
+ const validDate = validateIsoDate(date);
+ const mdPath = logPath(vault, validDate);
+ const jsonlPath = logJsonlPath(vault, validDate);
+
+ if (existsSync(jsonlPath)) {
+ return readJsonl(jsonlPath);
+ }
+ if (existsSync(mdPath)) {
+ const parsed = parseLogDay(vault, validDate);
+ return {
+ entries: parsed.entries,
+ source: "markdown-fallback",
+ warnings: parsed.warnings,
+ };
+ }
+ return { entries: [], source: "jsonl", warnings: [] };
+}
+
+function readJsonl(path: string): ReadLogDayResult {
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch (err) {
+ // §23 (v0.10.8): we got here because `existsSync(jsonlPath)`
+ // returned true, so a subsequent read error is anomalous (race
+ // with rotation, permission flip, fs-transient) and worth
+ // surfacing rather than reporting an empty day. Discipline-report
+ // and any future doctor can flag it without falling back to a
+ // silently incomplete count.
+ const message = (err as NodeJS.ErrnoException).message ?? String(err);
+ return {
+ entries: [],
+ source: "jsonl",
+ warnings: [{ path, lineNumber: 0, message: `failed to read JSONL file: ${message}` }],
+ };
+ }
+
+ const entries: BrainLogEntry[] = [];
+ const warnings: BrainLogParseWarning[] = [];
+ const lines = text.split(/\r?\n/);
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]!;
+ if (line.trim() === "") continue;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line);
+ } catch {
+ warnings.push({
+ path,
+ lineNumber: i + 1,
+ message: `malformed JSONL line: ${line.slice(0, 80)}`,
+ });
+ continue;
+ }
+ const entry = coerceEntry(parsed, path, i + 1, warnings);
+ if (entry !== null) entries.push(entry);
+ }
+ return { entries, source: "jsonl", warnings };
+}
+
+function coerceEntry(
+ raw: unknown,
+ path: string,
+ lineNumber: number,
+ warnings: BrainLogParseWarning[],
+): BrainLogEntry | null {
+ if (raw === null || typeof raw !== "object") {
+ warnings.push({ path, lineNumber, message: "JSONL row is not an object" });
+ return null;
+ }
+ const obj = raw as Record<string, unknown>;
+ const ts = obj["ts"];
+ const kind = obj["kind"];
+ const payload = obj["payload"];
+ if (typeof ts !== "string" || typeof kind !== "string") {
+ warnings.push({ path, lineNumber, message: "JSONL row missing ts/kind" });
+ return null;
+ }
+ if (!BRAIN_LOG_EVENT_KIND_SET.has(kind)) {
+ warnings.push({ path, lineNumber, message: `unknown event kind: ${kind}` });
+ return null;
+ }
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
+ warnings.push({
+ path,
+ lineNumber,
+ message: "JSONL row missing payload object",
+ });
+ return null;
+ }
+ const body: Record<string, string | ReadonlyArray<string>> = {};
+ for (const [k, v] of Object.entries(payload as Record<string, unknown>)) {
+ if (typeof v === "string") {
+ body[k] = v;
+ } else if (Array.isArray(v) && v.every((x) => typeof x === "string")) {
+ body[k] = v as string[];
+ } else {
+ warnings.push({
+ path,
+ lineNumber,
+ message: `JSONL payload key '${k}' has unsupported value type`,
+ });
+ }
+ }
+ return {
+ timestamp: ts,
+ eventType: kind as BrainLogEventKind,
+ body: Object.freeze(body),
+ };
+}
diff --git a/src/core/brain/log.ts b/src/core/brain/log.ts
index faffe9a8..c19734b2 100644
--- a/src/core/brain/log.ts
+++ b/src/core/brain/log.ts
@@ -25,12 +25,20 @@
* result back through `fs-atomic` in one shot.
*/
-import { existsSync, readFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
+
+import lockfile from "proper-lockfile";
import { atomicWriteFileSync } from "../fs-atomic.ts";
-import { logPath, validateIsoDate } from "./paths.ts";
+import {
+ brainDirs,
+ logJsonlPath,
+ logPath,
+ validateIsoDate,
+} from "./paths.ts";
import {
BRAIN_LOG_EVENT_KIND,
+ BRAIN_LOG_EVENT_KIND_SET,
type BrainLogEventKind,
} from "./types.ts";
@@ -71,10 +79,6 @@ export interface AppendLogEventResult {
// ----- Constants ------------------------------------------------------------
-const EVENT_KIND_VALUES: ReadonlySet<string> = new Set(
- Object.values(BRAIN_LOG_EVENT_KIND),
-);
-
// `## HH:MM:SSZ — <kind>` — both the em dash (—) and the hyphen are
// accepted to tolerate hand-edits. The mandatory `Z` after the time
// reflects the design doc's "UTC time" formatting (§5.5 example).
@@ -156,7 +160,7 @@ export function parseLogDay(vault: string, date: string): ParseLogDayResult {
const mm = header[2]!;
const ss = header[3]!;
const kindStr = header[4]!;
- if (!EVENT_KIND_VALUES.has(kindStr)) {
+ if (!BRAIN_LOG_EVENT_KIND_SET.has(kindStr)) {
warnings.push({
path,
lineNumber: headerLineNumber,
@@ -208,11 +212,42 @@ export function parseLogDay(vault: string, date: string): ParseLogDayResult {
* this function. That's the stability guarantee the test suite asks
* for.
*/
+/**
+ * Acquire the per-log-day directory lock with a bounded retry loop.
+ *
+ * `proper-lockfile`'s sync API refuses the `retries` option (it
+ * cannot block the event loop on a callback), so the retry loop is
+ * spelled out here: on `ELOCKED` the call sleeps for `SLEEP_MS` and
+ * tries again, up to `MAX_ATTEMPTS`. Any non-`ELOCKED` error is
+ * rethrown immediately (permission, fs corruption, …).
+ *
+ * Total worst-case wait: `MAX_ATTEMPTS * SLEEP_MS` ≈ 500 ms — short
+ * enough to feel synchronous to a coding agent, long enough to ride
+ * out a sibling `appendLogEvent` call that landed within the same
+ * millisecond.
+ */
+function acquireLogLock(logDir: string): () => void {
+ const MAX_ATTEMPTS = 10;
+ const SLEEP_MS = 50;
+ let lastErr: unknown;
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
+ try {
+ return lockfile.lockSync(logDir, { stale: 10_000, realpath: false });
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== "ELOCKED") throw err;
+ lastErr = err;
+ if (attempt < MAX_ATTEMPTS - 1) Bun.sleepSync(SLEEP_MS);
+ }
+ }
+ throw lastErr;
+}
+
export function appendLogEvent(
vault: string,
event: BrainLogEntry,
): AppendLogEventResult {
- if (!EVENT_KIND_VALUES.has(event.eventType)) {
+ if (!BRAIN_LOG_EVENT_KIND_SET.has(event.eventType)) {
throw new Error(
`appendLogEvent: unknown event kind '${event.eventType}' — must be one of ${Object.values(
BRAIN_LOG_EVENT_KIND,
@@ -225,24 +260,59 @@ export function appendLogEvent(
// byte-identical output (idempotency requirement).
const ts = parseIsoUtc(event.timestamp);
const path = logPath(vault, ts.date);
+ const jsonlPath = logJsonlPath(vault, ts.date);
+ const logDir = brainDirs(vault).log;
+
+ // §23 (v0.10.8): each event lands in both `<date>.jsonl` (machine
+ // surface, primary for `readLogDay`) and `<date>.md` (human-facing
+ // Obsidian view). JSONL is written first so a partial failure
+ // (e.g. ENOSPC between the two writes) leaves the machine-readable
+ // source authoritative — discipline-report and future tooling keep
+ // returning the correct counts; only the human Obsidian view lags
+ // until the next successful append rewrites the markdown.
+ //
+ // The pair shares one directory-level lock so two concurrent
+ // appenders cannot interleave each other's halves.
+ mkdirSync(logDir, { recursive: true });
+ const release = acquireLogLock(logDir);
- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
- const block = renderEventBlock(event, ts.hms);
-
- let next: string;
- if (existing === "") {
- next = renderFileHeader(ts.date) + "\n" + block;
- } else {
- // Guarantee exactly one blank line between blocks; previous file may
- // or may not end with a trailing newline.
- const trimmed = existing.replace(/\s+$/, "");
- next = `${trimmed}\n\n${block}`;
+ try {
+ // ---- JSONL sidecar (machine surface, primary) ---------------------
+ // 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 line = renderJsonlLine(event);
+ const nextJsonl =
+ existingJsonl === ""
+ ? `${line}\n`
+ : `${existingJsonl.replace(/\s+$/, "")}\n${line}\n`;
+ atomicWriteFileSync(jsonlPath, nextJsonl);
+
+ // ---- Markdown (human surface) -------------------------------------
+ const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
+ const block = renderEventBlock(event, ts.hms);
+
+ let next: string;
+ if (existing === "") {
+ next = renderFileHeader(ts.date) + "\n" + block;
+ } else {
+ // Guarantee exactly one blank line between blocks; previous file
+ // may or may not end with a trailing newline.
+ const trimmed = existing.replace(/\s+$/, "");
+ next = `${trimmed}\n\n${block}`;
+ }
+ // Always finish with a single trailing newline — standard Markdown
+ // hygiene, and matches what `formatFrontmatter` emits elsewhere.
+ if (!next.endsWith("\n")) next += "\n";
+
+ atomicWriteFileSync(path, next);
+ } finally {
+ release();
}
- // Always finish with a single trailing newline — standard Markdown
- // hygiene, and matches what `formatFrontmatter` emits elsewhere.
- if (!next.endsWith("\n")) next += "\n";
- atomicWriteFileSync(path, next);
return { logPath: path };
}
@@ -286,6 +356,25 @@ function renderEventBlock(event: BrainLogEntry, hms: string): string {
return lines.join("\n") + "\n";
}
+/**
+ * Render the JSONL projection of an event (§23, v0.10.8). The row
+ * shape is `{ ts, kind, payload }` where `payload` is a one-to-one map
+ * of the markdown body bullets. Array bullets become JSON arrays;
+ * scalar bullets become JSON strings. The function never sorts keys,
+ * so byte-identical inputs produce byte-identical rows.
+ */
+function renderJsonlLine(event: BrainLogEntry): string {
+ const payload: Record<string, string | ReadonlyArray<string>> = {};
+ for (const [key, value] of Object.entries(event.body)) {
+ payload[key] = value;
+ }
+ return JSON.stringify({
+ ts: event.timestamp,
+ kind: event.eventType,
+ payload,
+ });
+}
+
// ----- Bullet block parser --------------------------------------------------
interface ParseBulletResult {
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 064af87e..27202d88 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -139,6 +139,18 @@ export function logPath(vault: string, date: string): string {
return ensureInsideVault(join(brainDirs(vault).log, `${d}.md`), vault);
}
+/**
+ * Structured JSONL sidecar that accompanies each `<date>.md` log
+ * file (§23, v0.10.8). Every machine consumer reads through this
+ * helper instead of doing the `.md → .jsonl` string conversion
+ * inline; if the sidecar layout ever moves (subdirectory,
+ * compression, …) every caller follows in one edit.
+ */
+export function logJsonlPath(vault: string, date: string): string {
+ const d = validateIsoDate(date);
+ return ensureInsideVault(join(brainDirs(vault).log, `${d}.jsonl`), vault);
+}
+
/** Snapshots directory: `Brain/.snapshots/`. */
export function snapshotsDir(vault: string): string {
return brainDirs(vault).snapshots;
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 3cb59cfd..197e2308 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -186,10 +186,30 @@ export const BRAIN_LOG_EVENT_KIND = {
* entries, plus conflict and snapshot information.
*/
importClaudeMemory: "import-claude-memory",
+ /**
+ * `note` (§32B, v0.10.8) — one narrative-milestone line written by
+ * the `brain_note` MCP tool. Payload carries `text` (one-line
+ * description) and `agent`. Not consumed by the dream pass beyond
+ * counting; it exists so an agent has a Brain-native home for
+ * "release X shipped" / "PR Y merged" / "discovered fact Z" lines
+ * instead of falling back to the deprecated `event_log_append`
+ * surface.
+ */
+ note: "note",
} as const;
export type BrainLogEventKind =
(typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
+/**
+ * Precomputed set of every event-kind string. Both the markdown
+ * parser (`appendLogEvent`) and the JSONL reader (`readLogDay`) need
+ * the same set to validate incoming kinds; canonicalising the
+ * construction here keeps the two readers in lockstep.
+ */
+export const BRAIN_LOG_EVENT_KIND_SET: ReadonlySet<string> = new Set(
+ Object.values(BRAIN_LOG_EVENT_KIND),
+);
+
// ----- File-frontmatter shapes ----------------------------------------------
/**
@@ -542,6 +562,18 @@ export interface BrainImportClaudeMemoryLogEvent extends BrainLogEventBase {
readonly kind: typeof BRAIN_LOG_EVENT_KIND.importClaudeMemory;
}
+/**
+ * `note` entry (§32B, v0.10.8) — one narrative-milestone line. Not
+ * consumed by the dream pass; it exists so an agent has a Brain-native
+ * home for "I shipped X" / "PR Y merged" lines instead of falling back
+ * to the deprecated Daily/ event log.
+ */
+export interface BrainNoteLogEvent extends BrainLogEventBase {
+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.note;
+ readonly text: string;
+ readonly agent: string;
+}
+
/** Discriminated union of every concrete log event type. */
export type BrainLogEvent =
| BrainDreamLogEvent
@@ -561,7 +593,8 @@ export type BrainLogEvent =
| BrainMigrateFrontmatterLogEvent
| BrainMergeLogEvent
| BrainUpgradeLogEvent
- | BrainImportClaudeMemoryLogEvent;
+ | BrainImportClaudeMemoryLogEvent
+ | BrainNoteLogEvent;
// ----- Configuration (`Brain/_brain.yaml`) ----------------------------------
diff --git a/src/core/discipline/log-counts.ts b/src/core/discipline/log-counts.ts
index 250fdc7e..bf25f3e7 100644
--- a/src/core/discipline/log-counts.ts
+++ b/src/core/discipline/log-counts.ts
@@ -1,8 +1,10 @@
-import { parseLogDay } from "../brain/log.ts";
+import { readLogDay } from "../brain/log-jsonl.ts";
export interface AgentCounts {
readonly feedback: number;
readonly apply_evidence: number;
+ /** §32B (v0.10.8): narrative-milestone events written by `brain_note`. */
+ readonly note: number;
readonly other: number;
readonly total: number;
}
@@ -14,12 +16,13 @@ export interface BrainEventCounts {
}
function zero(): AgentCounts {
- return { feedback: 0, apply_evidence: 0, other: 0, total: 0 };
+ return { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 };
}
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 === "note") return { ...c, note: c.note + 1, total: c.total + 1 };
return { ...c, other: c.other + 1, total: c.total + 1 };
}
@@ -32,7 +35,10 @@ export function countBrainEvents(
for (const a of knownAgents) byAgent[a] = zero();
const unknown: Record<string, AgentCounts> = {};
- const { entries } = parseLogDay(vault, date);
+ // §23 (v0.10.8): read through the JSONL-preferred reader. Historical
+ // markdown-only days are served by the reader's fallback path so
+ // discipline-report stays correct across the v0.10.8 boundary.
+ const { entries } = readLogDay(vault, date);
let total = 0;
for (const e of entries) {
const agentField = e.body["agent"];
diff --git a/src/core/discipline/render.ts b/src/core/discipline/render.ts
index 355de917..fbe518a3 100644
--- a/src/core/discipline/render.ts
+++ b/src/core/discipline/render.ts
@@ -24,13 +24,13 @@ export function renderReport(r: RenderInput): string {
} else {
for (const [agent, c] of knownEntries) {
lines.push(
- `\\- ${e(agent)}: ${c.feedback} feedback, ${c.apply_evidence} apply\\-evidence, ${c.other} other \\(total ${c.total}\\)`,
+ `\\- ${e(agent)}: ${c.feedback} feedback, ${c.apply_evidence} apply\\-evidence, ${c.note} note, ${c.other} other \\(total ${c.total}\\)`,
);
}
}
for (const u of r.events.unknownAgents) {
lines.push(
- `\\- ${e(u.agent)} \\(unknown\\): ${u.counts.feedback} feedback, ${u.counts.apply_evidence} apply\\-evidence, ${u.counts.other} other \\(total ${u.counts.total}\\)`,
+ `\\- ${e(u.agent)} \\(unknown\\): ${u.counts.feedback} feedback, ${u.counts.apply_evidence} apply\\-evidence, ${u.counts.note} note, ${u.counts.other} other \\(total ${u.counts.total}\\)`,
);
}
lines.push("");
diff --git a/src/core/identity-reminder.ts b/src/core/identity-reminder.ts
index fa8ff807..2f0aa964 100644
--- a/src/core/identity-reminder.ts
+++ b/src/core/identity-reminder.ts
@@ -1,17 +1,17 @@
/**
* Identity reminder: the text the OpenClaw `before_prompt_build` hook and
* the Hermes `pre_llm_call` hook inject into each turn so the agent keeps
- * remembering it has access to `event_log_append` and under which
- * `@<agent_name>` it is supposed to log.
+ * remembering which `@<agent_name>` it is logging under and which Brain
+ * writer tool (`brain_feedback` / `brain_apply_evidence` / `brain_note`)
+ * fits the current turn.
*
* Single source of truth: `templates/identity-reminder.txt` at repo root.
* The Hermes Python shim reads the same file; both runtimes stay in sync
* without manual mirroring.
*
- * The Codex and Claude Code adapters use the bundled `agent-event-log`
- * skill (description + body) instead of a hook — see
- * `skills/agent-event-log/SKILL.md`. Skill description is part of the
- * system prompt every session, so it does not need a hook to land.
+ * The Claude Code and Codex adapters get their per-turn nudge from the
+ * `hooks/lib/messages.ts:postWriteReminder` PostToolUse hook (and the
+ * Stop guardrail) instead of this template — see `hooks/README.md`.
*/
import { readFileSync } from "node:fs";
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 68f3f596..5aa6972e 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -31,7 +31,6 @@
* one-way (Brain tools may grow their own coercion rules later).
*/
-import { existsSync } from "node:fs";
import { isAbsolute, relative, resolve } from "node:path";
import { resolveAgentName } from "../core/config.ts";
@@ -56,10 +55,8 @@ import {
} from "../core/brain/query.ts";
import { writeSignal } from "../core/brain/signal.ts";
import { writePreference } from "../core/brain/preference.ts";
-import { preferencePath } from "../core/brain/paths.ts";
import { validateBrainFeedbackInput } from "../core/brain/sessions/validate-feedback.ts";
import { isoDate, isoSecond } from "../core/brain/time.ts";
-import { loadBrainConfig } from "../core/brain/policy.ts";
import { slugify } from "../core/vault.ts";
import { normalizeAgentArgument } from "../core/agent-identity.ts";
import {
@@ -75,6 +72,7 @@ import {
} from "../core/brain/types.ts";
import { appendLogEvent } from "../core/brain/log.ts";
import type { BrainLogEntry } from "../core/brain/log.ts";
+import { sanitiseTextField } from "../core/redactor.ts";
import { INVALID_PARAMS, MCPError } from "./protocol.ts";
import type { ServerContext, ToolDefinition } from "./tools.ts";
@@ -408,6 +406,53 @@ async function toolBrainApplyEvidence(
}
}
+// ----- brain_note (§32B, v0.10.8) ------------------------------------------
+
+const NOTE_TEXT_MAX_LEN = 4096;
+
+/**
+ * Append one narrative-milestone line to today's Brain log. This is the
+ * Brain-native replacement for the deprecated `event_log_append` tool:
+ * agents now record release / merged-PR / discovered-fact lines under
+ * the `note` event kind in `Brain/log/<today>.md` (and the JSONL
+ * sidecar) instead of falling back to `Daily/`.
+ */
+async function toolBrainNote(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const rawText = coerceStr(args, "text", true)!;
+ const agentArg = coerceStr(args, "agent", false);
+
+ // `singleLine` collapses newlines and trims to NOTE_TEXT_MAX_LEN. The
+ // shared sanitiser also strips C0 controls and folds U+2028/U+2029.
+ const sanitised = sanitiseTextField(rawText, {
+ maxLen: NOTE_TEXT_MAX_LEN,
+ singleLine: true,
+ }).trim();
+ if (!sanitised) {
+ throw new MCPError(INVALID_PARAMS, "brain_note: text is required");
+ }
+
+ const agent =
+ normalizeAgentArgument(agentArg) ??
+ resolveAgentName(ctx.configPath ?? undefined);
+ const timestamp = isoSecond(new Date());
+
+ const entry: BrainLogEntry = {
+ timestamp,
+ eventType: BRAIN_LOG_EVENT_KIND.note,
+ body: { text: sanitised, agent },
+ };
+ const res = appendLogEvent(ctx.vault, entry);
+ return {
+ logged_at: timestamp,
+ log_path: vaultRelativeSafe(ctx.vault, res.logPath),
+ absolute_log_path: resolve(res.logPath),
+ agent,
+ };
+}
+
// ----- brain_digest --------------------------------------------------------
async function toolBrainDigest(
@@ -671,21 +716,6 @@ export function vaultRelativeSafe(vault: string, target: string): string {
return rel;
}
-// Reference to satisfy "may need to look up pref path in MCP handler"
-// without re-exporting the helper from `core/brain/paths.ts` for the
-// public surface. Used only by the typecheck on `BrainPreferenceNotFoundError`
-// rethrow; we keep the import alive intentionally so future grep finds
-// the MCP layer using the same path helper as the core.
-//
-// (The function is invoked indirectly through `appendApplyEvidence`.)
-void preferencePath;
-
-// Loadable so future MCP-level config introspection can reuse the
-// validation surface without depending on the CLI module. Currently
-// unused — explicit import keeps the dependency graph documented.
-void loadBrainConfig;
-void existsSync;
-
// ----- Tool registration ---------------------------------------------------
export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
@@ -809,6 +839,29 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainApplyEvidence,
},
+ {
+ name: "brain_note",
+ description:
+ "Append one narrative-milestone line to today's Brain log (`Brain/log/<today>.md` plus its JSONL sidecar) under the `note` event kind. Use for events that are neither a new preference nor evidence against an existing one — release shipped, PR merged, fact discovered. Multi-line text is collapsed to one space-joined line; secret-shaped tokens are redacted.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ text: {
+ type: "string",
+ description:
+ "One-line narrative description. Newlines collapse to single spaces; the shared redactor strips secret-shaped tokens.",
+ },
+ agent: {
+ type: "string",
+ description:
+ "Optional agent identity override; defaults to the server-resolved name.",
+ },
+ },
+ required: ["text"],
+ additionalProperties: false,
+ },
+ handler: toolBrainNote,
+ },
{
name: "brain_digest",
description:
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index f5d9d3bc..65283896 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -21,19 +21,22 @@ export interface BuildInstructionsOpts {
const WRITER_INSTRUCTIONS = `Open Second Brain — writer surface (always-loaded).
-Two tools live here:
+Three tools live here:
- brain_feedback — record one new taste signal the user just expressed.
- brain_apply_evidence — record applied | violated | outdated against an
active preference for an artifact this turn produced.
+ - brain_note — record one narrative milestone (release shipped,
+ PR merged, fact discovered) that fits neither
+ category.
The remaining Brain surface (digest, query, doctor, backlinks, search,
Pay Memory tools, vault_health, second_brain_status, second_brain_query,
and the scheduled learning pass) lives on the sibling
"open-second-brain" MCP server (deferred). Use ToolSearch to reach it.
-Prefer the writer-server copy of brain_feedback / brain_apply_evidence over
-any duplicate exposed by the full server — both call the same handler, but the
-writer copy is always available without ToolSearch.`;
+Prefer the writer-server copies of brain_feedback / brain_apply_evidence /
+brain_note over any duplicate exposed by the full server — both call the same
+handler, but the writer copy is always available without ToolSearch.`;
export function buildInstructions(opts: BuildInstructionsOpts | string): string {
// Legacy call-site compat: plain string → full-surface branch.
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 2e784ce1..0d4ccc32 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -1,19 +1,18 @@
/**
- * MCP tool registry. As of v0.9.0 the advertised surface is:
+ * MCP tool registry. As of v0.10.8 the advertised surface is:
*
* - Core read/health tools (`second_brain_status`, `second_brain_query`,
* `vault_health`).
- * - Brain tools (`brain_feedback`, `brain_dream`,
- * `brain_apply_evidence`, `brain_digest`, `brain_query`,
- * `brain_doctor`) — see `./brain-tools.ts`.
+ * - Brain tools (`brain_feedback`, `brain_apply_evidence`,
+ * `brain_note`, `brain_dream`, `brain_digest`, `brain_query`,
+ * `brain_doctor`, `brain_backlinks`) — see `./brain-tools.ts`.
* - Pay Memory tools (`payment_*`, `asset_capture`).
*
- * `event_log_append` and `second_brain_capture` are intentionally
- * *not* registered here in v0.9.0 — Brain replaces them as the
- * agent-facing writable surface (design doc §11.1). Their handler
- * functions remain on disk (`toolEventLogAppend`, `toolCapture` below)
- * so the CLI / shell tooling keeps working; only the entries in the
- * exported tool array are removed.
+ * §32 (v0.10.8) retires `event_log_append` and `second_brain_capture`
+ * from every runtime. The `appendEvent` function in
+ * `src/core/event-log.ts` stays for the human-side CLI verb
+ * (`o2b append-event`) and cron-jobs; the MCP surface no longer
+ * advertises it. `toolCapture` likewise remains as a CLI helper.
*/
import { existsSync, mkdirSync, statSync } from "node:fs";
@@ -27,7 +26,6 @@ import {
} from "../core/config.ts";
import { computeBrainStatus } from "../core/brain/status.ts";
import { doctor } from "../core/doctor.ts";
-import { appendEvent, validateEventTime } from "../core/event-log.ts";
import { BRAIN_TOOLS } from "./brain-tools.ts";
import { SEARCH_TOOLS, buildSearchStatusBlock } from "./search-tools.ts";
import {
@@ -253,30 +251,10 @@ async function toolCapture(ctx: ServerContext, args: Record<string, unknown>): P
};
}
-async function toolEventLogAppend(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const message = coerceStr(args, "message", true)!;
- const agent = coerceStr(args, "agent", false);
- const date = coerceStr(args, "date", false);
- const time = coerceStr(args, "time", false);
-
- if (time !== null) validateEventTime(time);
-
- const effectiveAgent =
- normalizeAgentArgument(agent) ?? resolveAgentName(ctx.configPath ?? undefined);
- const tz = resolveTimezone(ctx.configPath ?? undefined);
- const path = await appendEvent(ctx.vault, effectiveAgent, message, { date, time, tz });
-
- return {
- path: vaultRelpath(path, ctx.vault),
- absolute_path: resolve(path),
- agent: effectiveAgent,
- date,
- time,
- };
-}
+// §32G (v0.10.8): the `event_log_append` MCP handler is gone. The
+// bare `appendEvent` function in `src/core/event-log.ts` stays for
+// the CLI verb (`o2b append-event`) and cron-jobs that target the
+// human-side `Daily/` log; the MCP surface no longer advertises it.
async function toolVaultHealth(
ctx: ServerContext,
@@ -610,6 +588,7 @@ export type ToolScope = "full" | "writer";
const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set([
"brain_feedback",
"brain_apply_evidence",
+ "brain_note",
]);
export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
@@ -641,11 +620,10 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
},
handler: toolQuery,
},
- // `second_brain_capture` and `event_log_append` are intentionally
- // not advertised in v0.9.0+. Their handlers (`toolCapture`,
- // `toolEventLogAppend`) remain in this file for human-side shell
- // use (`o2b append-event`); only the entries in the exported tool
- // array are removed — see §11.1 of the v0.9.0 design doc.
+ // `second_brain_capture` is intentionally not advertised — Brain
+ // replaces it. `event_log_append` was retired in §32 (v0.10.8);
+ // its handler has been removed. `toolCapture` remains in this
+ // file for the legacy `o2b capture` shell flow.
...BRAIN_TOOLS,
...SEARCH_TOOLS,
{
diff --git a/src/openclaw/index.ts b/src/openclaw/index.ts
index 0c7d4e72..ef03c7cc 100644
--- a/src/openclaw/index.ts
+++ b/src/openclaw/index.ts
@@ -23,7 +23,10 @@ import {
resolveTimezone,
} from "../core/config.ts";
import { doctor } from "../core/doctor.ts";
-import { appendEvent, validateEventTime } from "../core/event-log.ts";
+// §32G (v0.10.8): `appendEvent` / `validateEventTime` are no longer
+// needed by the OpenClaw bundle — the `event_log_append` tool was
+// retired from this runtime. The functions still live in
+// `src/core/event-log.ts` for the human-side `o2b append-event` CLI.
import { buildReminder } from "../core/identity-reminder.ts";
import {
checkPolicy,
@@ -273,47 +276,12 @@ export default definePluginEntry({
},
);
- 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." },
- },
- required: ["message"],
- additionalProperties: false,
- },
- async execute(_id, params): Promise<unknown> {
- const vault = resolveVaultPath(api);
- const message = params["message"] as string | undefined;
- if (!message || !message.trim()) {
- // Treat whitespace-only the same as missing; the MCP-side
- // `_coerce_str` does the same. Empty entries weaken the log.
- throw new Error("missing required argument: message");
- }
- const argAgent = (params["agent"] as string | undefined) ?? null;
- const date = (params["date"] as string | undefined) ?? null;
- const time = (params["time"] as string | undefined) ?? null;
- if (time) validateEventTime(time);
- const agent = resolveOpenclawAgent(api, argAgent);
- const tz = resolveOpenclawTimezone(api) ?? resolveTimezone();
- const path = await appendEvent(vault, agent, message, { date, time, tz });
- const result = {
- path: vaultRelativePath(path, vault),
- absolute_path: path,
- agent,
- date,
- time,
- };
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
- },
- },
- );
+ // §32G (v0.10.8): the OpenClaw `event_log_append` registration is
+ // gone. Agents on this runtime now record via the Brain writer
+ // tools served by the MCP server (`brain_feedback`,
+ // `brain_apply_evidence`, `brain_note`); the human-side
+ // `o2b append-event` CLI is the only remaining caller of
+ // `appendEvent`.
api.registerTool(
{
diff --git a/templates/identity-reminder.hermes.txt b/templates/identity-reminder.hermes.txt
index 3b2f515a..11f18a79 100644
--- a/templates/identity-reminder.hermes.txt
+++ b/templates/identity-reminder.hermes.txt
@@ -1 +1 @@
-[open-second-brain] Identity: @{agent}. After every durable artifact this turn — code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know — call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@{agent}` automatically, do not include them yourself. Hermes turns are short; do not batch the log calls across turns. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
+[open-second-brain] Identity: @{agent}. After every durable artifact this turn (code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know), record it through the Brain writer tools: call `brain_feedback` if the turn surfaced a new user preference, `brain_apply_evidence` (`result: applied | violated | outdated`) if a preference in `Brain/preferences/` scopes to the artifact, or `brain_note` for narrative milestones that fit neither. The Brain log entry lands in `Brain/log/<today>.md` (with the JSONL sidecar) under the resolved `@{agent}` identity. Hermes turns are short; do not batch the calls across turns. Skip pure discussion, exploration, read-only queries, and planning that hasn't produced an artifact.
diff --git a/templates/identity-reminder.openclaw.txt b/templates/identity-reminder.openclaw.txt
index a75a1200..107276fb 100644
--- a/templates/identity-reminder.openclaw.txt
+++ b/templates/identity-reminder.openclaw.txt
@@ -1 +1 @@
-[open-second-brain] Identity: @{agent}. After every durable in-process action — code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know — call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@{agent}` automatically, do not include them yourself. OpenClaw has no session boundary; log immediately. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
+[open-second-brain] Identity: @{agent}. After every durable in-process action (code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know), record it through the Brain writer tools: call `brain_feedback` if the turn surfaced a new user preference, `brain_apply_evidence` (`result: applied | violated | outdated`) if a preference in `Brain/preferences/` scopes to the artifact, or `brain_note` for narrative milestones that fit neither. The Brain log entry lands in `Brain/log/<today>.md` (with the JSONL sidecar) under the resolved `@{agent}` identity. OpenClaw has no session boundary; log immediately. Skip pure discussion, exploration, read-only queries, and planning that hasn't produced an artifact.
diff --git a/templates/identity-reminder.txt b/templates/identity-reminder.txt
index 367a6f93..1dca8482 100644
--- a/templates/identity-reminder.txt
+++ b/templates/identity-reminder.txt
@@ -1 +1 @@
-[open-second-brain] Identity: @{agent}. After producing a durable artifact — code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know — call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@{agent}` automatically, do not include them yourself. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
+[open-second-brain] Identity: @{agent}. After producing a durable artifact (code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know), record it through the Brain writer tools: call `brain_feedback` if the turn surfaced a new user preference, `brain_apply_evidence` (`result: applied | violated | outdated`) if a preference in `Brain/preferences/` scopes to the artifact, or `brain_note` for narrative milestones that fit neither. The Brain log entry lands in `Brain/log/<today>.md` (with the JSONL sidecar) under the resolved `@{agent}` identity. Skip pure discussion, exploration, read-only queries, and planning that hasn't produced an artifact.
diff --git a/tests/cli/append-event.test.ts b/tests/cli/append-event.test.ts
new file mode 100644
index 00000000..953c4319
--- /dev/null
+++ b/tests/cli/append-event.test.ts
@@ -0,0 +1,114 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+/**
+ * §32F (v0.10.8). The `o2b append-event` CLI verb stays as the human /
+ * cron-job surface for the legacy Daily/ event log. The bug it fixes:
+ * before v0.10.8 the resolver fell back to the literal `"agent"` when
+ * `--as` and `VAULT_AGENT_NAME` were absent, even when the plugin
+ * config carried an `agent_name`. Daily entries from cron-jobs
+ * therefore showed up as `@agent` instead of the configured identity.
+ */
+
+let tmp: string;
+let configDir: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-append-event-"));
+ configDir = mkdtempSync(join(tmpdir(), "o2b-append-event-cfg-"));
+ vault = join(tmp, "vault");
+ configPath = join(configDir, "config.yaml");
+ mkdirSync(vault, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configDir, { recursive: true, force: true });
+});
+
+describe("o2b append-event identity resolution (§32F)", () => {
+ test("uses config agent_name when --as and env are absent", async () => {
+ writeFileSync(
+ configPath,
+ `vault: ${vault}\nagent_name: cli-test-bot\n`,
+ "utf8",
+ );
+
+ const r = await runCli(["append-event", "hello world"], {
+ env: {
+ OPEN_SECOND_BRAIN_CONFIG: configPath,
+ VAULT_AGENT_NAME: "",
+ },
+ });
+
+ expect(r.returncode).toBe(0);
+ const dailyDir = join(vault, "Daily");
+ expect(existsSync(dailyDir)).toBe(true);
+ const files = readdirSync(dailyDir);
+ expect(files).toHaveLength(1);
+ const body = readFileSync(join(dailyDir, files[0]!), "utf8");
+ expect(body).toContain("@cli-test-bot");
+ expect(body).not.toContain("@agent ");
+ expect(body).toContain("hello world");
+ });
+
+ test("--as wins over the config agent_name", async () => {
+ writeFileSync(
+ configPath,
+ `vault: ${vault}\nagent_name: cli-test-bot\n`,
+ "utf8",
+ );
+
+ const r = await runCli(
+ ["append-event", "--as", "explicit-bot", "another line"],
+ {
+ env: {
+ OPEN_SECOND_BRAIN_CONFIG: configPath,
+ VAULT_AGENT_NAME: "",
+ },
+ },
+ );
+
+ expect(r.returncode).toBe(0);
+ const dailyDir = join(vault, "Daily");
+ const files = readdirSync(dailyDir);
+ const body = readFileSync(join(dailyDir, files[0]!), "utf8");
+ expect(body).toContain("@explicit-bot");
+ expect(body).not.toContain("@cli-test-bot");
+ });
+
+ test("VAULT_AGENT_NAME env wins when --as is absent", async () => {
+ writeFileSync(
+ configPath,
+ `vault: ${vault}\nagent_name: cli-test-bot\n`,
+ "utf8",
+ );
+
+ const r = await runCli(["append-event", "env wins"], {
+ env: {
+ OPEN_SECOND_BRAIN_CONFIG: configPath,
+ VAULT_AGENT_NAME: "env-bot",
+ },
+ });
+
+ expect(r.returncode).toBe(0);
+ const dailyDir = join(vault, "Daily");
+ const files = readdirSync(dailyDir);
+ const body = readFileSync(join(dailyDir, files[0]!), "utf8");
+ expect(body).toContain("@env-bot");
+ });
+});
diff --git a/tests/cli/mcp-scope-arg.test.ts b/tests/cli/mcp-scope-arg.test.ts
index b09b19c7..4a632424 100644
--- a/tests/cli/mcp-scope-arg.test.ts
+++ b/tests/cli/mcp-scope-arg.test.ts
@@ -42,7 +42,11 @@ describe("o2b mcp --scope arg validation", () => {
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();
- expect(names).toEqual(["brain_apply_evidence", "brain_feedback"]);
+ expect(names).toEqual([
+ "brain_apply_evidence",
+ "brain_feedback",
+ "brain_note",
+ ]);
});
});
});
diff --git a/tests/core/brain.log-jsonl-reader.test.ts b/tests/core/brain.log-jsonl-reader.test.ts
new file mode 100644
index 00000000..2d26a948
--- /dev/null
+++ b/tests/core/brain.log-jsonl-reader.test.ts
@@ -0,0 +1,194 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { appendLogEvent } from "../../src/core/brain/log.ts";
+import { readLogDay } from "../../src/core/brain/log-jsonl.ts";
+import { brainDirs, logJsonlPath, logPath } from "../../src/core/brain/paths.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-log-jsonl-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("readLogDay — JSONL-preferred", () => {
+ test("returns entries from JSONL when sidecar exists", () => {
+ appendLogEvent(tmp, {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: "feedback",
+ body: { signal: "[[sig-x]]", topic: "x", sign: "positive" },
+ });
+ const res = readLogDay(tmp, "2026-05-19");
+ expect(res.source).toBe("jsonl");
+ expect(res.entries).toHaveLength(1);
+ expect(res.entries[0]!.eventType).toBe("feedback");
+ expect(res.entries[0]!.body["topic"]).toBe("x");
+ });
+
+ test("falls back to markdown when only markdown exists", () => {
+ const dir = brainDirs(tmp).log;
+ mkdirSync(dir, { recursive: true });
+ const md = `---
+kind: brain-log
+date: 2026-05-10
+tags: [brain, brain/log]
+---
+
+# Brain log — 2026-05-10
+
+## 09:00:00Z — feedback
+- signal: [[sig-old]]
+- topic: old
+- sign: positive
+`;
+ writeFileSync(logPath(tmp, "2026-05-10"), md, "utf8");
+
+ const res = readLogDay(tmp, "2026-05-10");
+ expect(res.source).toBe("markdown-fallback");
+ expect(res.entries).toHaveLength(1);
+ expect(res.entries[0]!.body["topic"]).toBe("old");
+ });
+
+ test("returns empty result when neither file exists", () => {
+ const res = readLogDay(tmp, "2026-01-01");
+ expect(res.entries).toHaveLength(0);
+ expect(res.warnings).toHaveLength(0);
+ });
+
+ test("prefers JSONL even when markdown is also present", () => {
+ appendLogEvent(tmp, {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: "feedback",
+ body: { signal: "[[sig-x]]", topic: "from-jsonl", sign: "positive" },
+ });
+ // Hand-edit markdown to a different topic — readLogDay must trust
+ // the JSONL sidecar.
+ const md = `---
+kind: brain-log
+date: 2026-05-19
+tags: [brain, brain/log]
+---
+
+# Brain log — 2026-05-19
+
+## 10:00:00Z — feedback
+- signal: [[sig-x]]
+- topic: from-md-handedit
+- sign: positive
+`;
+ writeFileSync(logPath(tmp, "2026-05-19"), md, "utf8");
+
+ const res = readLogDay(tmp, "2026-05-19");
+ expect(res.source).toBe("jsonl");
+ expect(res.entries[0]!.body["topic"]).toBe("from-jsonl");
+ });
+
+ test("surfaces malformed JSONL lines as warnings, keeps the rest", () => {
+ const dir = brainDirs(tmp).log;
+ mkdirSync(dir, { recursive: true });
+ const lines = [
+ JSON.stringify({
+ ts: "2026-05-19T10:00:00Z",
+ kind: "feedback",
+ payload: { topic: "ok" },
+ }),
+ "not-valid-json",
+ JSON.stringify({
+ ts: "2026-05-19T10:00:02Z",
+ kind: "feedback",
+ payload: { topic: "also-ok" },
+ }),
+ ].join("\n");
+ writeFileSync(
+ logJsonlPath(tmp, "2026-05-19"),
+ lines + "\n",
+ "utf8",
+ );
+
+ const res = readLogDay(tmp, "2026-05-19");
+ expect(res.source).toBe("jsonl");
+ expect(res.entries).toHaveLength(2);
+ expect(res.warnings).toHaveLength(1);
+ expect(res.warnings[0]!.message).toMatch(/malformed/i);
+ expect(res.warnings[0]!.lineNumber).toBe(2);
+ });
+
+ test("skips rows with unknown event kinds and surfaces a warning", () => {
+ const dir = brainDirs(tmp).log;
+ mkdirSync(dir, { recursive: true });
+ const lines = [
+ JSON.stringify({
+ ts: "2026-05-19T10:00:00Z",
+ kind: "totally-bogus",
+ payload: {},
+ }),
+ JSON.stringify({
+ ts: "2026-05-19T10:00:01Z",
+ kind: "feedback",
+ payload: { topic: "ok" },
+ }),
+ ].join("\n");
+ writeFileSync(
+ logJsonlPath(tmp, "2026-05-19"),
+ lines + "\n",
+ "utf8",
+ );
+
+ const res = readLogDay(tmp, "2026-05-19");
+ expect(res.entries).toHaveLength(1);
+ expect(res.entries[0]!.eventType).toBe("feedback");
+ expect(res.warnings).toHaveLength(1);
+ expect(res.warnings[0]!.message).toMatch(/unknown event kind/i);
+ });
+
+ test("ignores blank lines in JSONL", () => {
+ const dir = brainDirs(tmp).log;
+ mkdirSync(dir, { recursive: true });
+ const lines = [
+ "",
+ JSON.stringify({
+ ts: "2026-05-19T10:00:00Z",
+ kind: "feedback",
+ payload: { topic: "x" },
+ }),
+ "",
+ "",
+ ].join("\n");
+ writeFileSync(
+ logJsonlPath(tmp, "2026-05-19"),
+ lines,
+ "utf8",
+ );
+
+ const res = readLogDay(tmp, "2026-05-19");
+ expect(res.entries).toHaveLength(1);
+ expect(res.warnings).toHaveLength(0);
+ });
+});
+
+describe("readLogDay — invariants", () => {
+ test("validates the date format (rejects loose input)", () => {
+ expect(() => readLogDay(tmp, "2026/05/19")).toThrow();
+ });
+
+ 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);
+ });
+});
diff --git a/tests/core/brain.log.test.ts b/tests/core/brain.log.test.ts
index 141fccf4..62efb9d1 100644
--- a/tests/core/brain.log.test.ts
+++ b/tests/core/brain.log.test.ts
@@ -8,7 +8,7 @@ import {
parseLogDay,
type BrainLogEntry,
} from "../../src/core/brain/log.ts";
-import { brainDirs, logPath } from "../../src/core/brain/paths.ts";
+import { brainDirs, logJsonlPath, logPath } from "../../src/core/brain/paths.ts";
let tmp: string;
@@ -237,3 +237,106 @@ describe("ISO timestamp round-trip", () => {
).toThrow(/unknown event kind/);
});
});
+
+describe("appendLogEvent — JSONL sidecar (§23, v0.10.8)", () => {
+ test("writes the same event to both .md and .jsonl", () => {
+ const entry: BrainLogEntry = {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: "feedback",
+ body: { signal: "[[sig-x]]", topic: "x", sign: "positive" },
+ };
+ const res = appendLogEvent(tmp, entry);
+ const jsonlPath = logJsonlPath(tmp, "2026-05-19");
+
+ expect(existsSync(res.logPath)).toBe(true);
+ expect(existsSync(jsonlPath)).toBe(true);
+
+ const jsonl = readFileSync(jsonlPath, "utf8");
+ const lines = jsonl.trim().split("\n");
+ expect(lines).toHaveLength(1);
+ const parsed = JSON.parse(lines[0]!);
+ expect(parsed).toEqual({
+ ts: "2026-05-19T10:00:00Z",
+ kind: "feedback",
+ payload: { signal: "[[sig-x]]", topic: "x", sign: "positive" },
+ });
+ });
+
+ test("appends a second event to both files", () => {
+ appendLogEvent(tmp, {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: "feedback",
+ body: { signal: "[[sig-a]]", topic: "a", sign: "positive" },
+ });
+ appendLogEvent(tmp, {
+ timestamp: "2026-05-19T10:00:01Z",
+ eventType: "apply-evidence",
+ body: {
+ preference: "[[pref-a]]",
+ artifact: "[[file.ts]]",
+ agent: "@x",
+ result: "applied",
+ },
+ });
+ const jsonlPath = logJsonlPath(tmp, "2026-05-19");
+ const jsonl = readFileSync(jsonlPath, "utf8");
+ const lines = jsonl.trim().split("\n");
+ expect(lines).toHaveLength(2);
+ expect(JSON.parse(lines[0]!).kind).toBe("feedback");
+ expect(JSON.parse(lines[1]!).kind).toBe("apply-evidence");
+ });
+
+ test("encodes array payloads as JSON arrays", () => {
+ appendLogEvent(tmp, {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: "dream",
+ body: {
+ run_id: "dream-1",
+ new_unconfirmed: ["[[pref-a]]", "[[pref-b]]"],
+ },
+ });
+ const jsonlPath = logJsonlPath(tmp, "2026-05-19");
+ const jsonl = readFileSync(jsonlPath, "utf8");
+ const parsed = JSON.parse(jsonl.trim());
+ expect(parsed.payload.new_unconfirmed).toEqual(["[[pref-a]]", "[[pref-b]]"]);
+ expect(parsed.payload.run_id).toBe("dream-1");
+ });
+
+ test("creates the JSONL sidecar even when the .md already exists by hand", () => {
+ // Simulate a pre-v0.10.8 day: markdown present, sidecar absent.
+ const mdPath = logPath(tmp, "2026-05-10");
+ mkdirSync(brainDirs(tmp).log, { recursive: true });
+ writeFileSync(
+ mdPath,
+ `---
+kind: brain-log
+date: 2026-05-10
+tags: [brain, brain/log]
+---
+
+# Brain log — 2026-05-10
+
+## 09:00:00Z — feedback
+- signal: [[sig-old]]
+- topic: old
+- sign: positive
+`,
+ "utf8",
+ );
+
+ appendLogEvent(tmp, {
+ timestamp: "2026-05-10T10:00:00Z",
+ eventType: "feedback",
+ body: { signal: "[[sig-new]]", topic: "new", sign: "positive" },
+ });
+
+ const jsonlPath = logJsonlPath(tmp, "2026-05-10");
+ expect(existsSync(jsonlPath)).toBe(true);
+ const lines = readFileSync(jsonlPath, "utf8").trim().split("\n");
+ // Only the new event lands in JSONL — backfill of the pre-existing
+ // markdown block is intentionally out of scope (lazy fallback in
+ // readLogDay handles historical markdown).
+ expect(lines).toHaveLength(1);
+ expect(JSON.parse(lines[0]!).payload.topic).toBe("new");
+ });
+});
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 858bbf25..6a1538ae 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -80,6 +80,8 @@ describe("BRAIN_* const enums", () => {
"upgrade",
// §3 import-claude-memory (agent-discipline-tail)
"import-claude-memory",
+ // §32B (v0.10.8) brain_note narrative milestones
+ "note",
]);
const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));
expect(actual).toEqual(expected);
diff --git a/tests/core/identity-reminder.test.ts b/tests/core/identity-reminder.test.ts
index ad84abd9..ba05888a 100644
--- a/tests/core/identity-reminder.test.ts
+++ b/tests/core/identity-reminder.test.ts
@@ -33,8 +33,14 @@ describe("template", () => {
expect(occurrences).toBeGreaterThanOrEqual(2);
});
- test("template references event_log_append", () => {
- expect(loadReminderTemplate()).toContain("event_log_append");
+ test("template references the three Brain writer tools (§32, v0.10.8)", () => {
+ const body = loadReminderTemplate();
+ expect(body).toContain("brain_feedback");
+ expect(body).toContain("brain_apply_evidence");
+ expect(body).toContain("brain_note");
+ // event_log_append is retired across every runtime; the reminder
+ // must not point agents at the dead surface.
+ expect(body).not.toContain("event_log_append");
});
});
diff --git a/tests/discipline/log-counts.test.ts b/tests/discipline/log-counts.test.ts
index 0c632096..14eec23b 100644
--- a/tests/discipline/log-counts.test.ts
+++ b/tests/discipline/log-counts.test.ts
@@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { appendLogEvent } from "../../src/core/brain/log.ts";
import { countBrainEvents } from "../../src/core/discipline/log-counts.ts";
function vaultWithLog(dayBody: string): string {
@@ -24,7 +25,7 @@ describe("countBrainEvents", () => {
"## 09:00:00Z — apply-evidence\n- agent: @claude-vps-agent\n- pref_id: pref-x\n\n" +
"## 10:00:00Z — feedback\n- agent: @codex-vps-agent\n- topic: bar\n\n" +
"## 11:00:00Z — promote\n- agent: @claude-vps-agent\n- promoted: 0\n\n" +
- "## 12:00:00Z — snapshot\n- run_id: x\n";
+ "## 12:00:00Z — rollback\n- run_id: x\n";
const v = vaultWithLog(body);
const out = countBrainEvents(v, "2026-05-17", [
"@claude-vps-agent",
@@ -33,12 +34,14 @@ describe("countBrainEvents", () => {
expect(out.byAgent["@claude-vps-agent"]).toEqual({
feedback: 1,
apply_evidence: 1,
+ note: 0,
other: 1,
total: 3,
});
expect(out.byAgent["@codex-vps-agent"]).toEqual({
feedback: 1,
apply_evidence: 0,
+ note: 0,
other: 0,
total: 1,
});
@@ -55,11 +58,15 @@ describe("countBrainEvents", () => {
expect(out.byAgent["@claude-vps-agent"]).toEqual({
feedback: 0,
apply_evidence: 0,
+ note: 0,
other: 0,
total: 0,
});
expect(out.unknownAgents).toEqual([
- { agent: "@stranger", counts: { feedback: 1, apply_evidence: 0, other: 0, total: 1 } },
+ {
+ agent: "@stranger",
+ counts: { feedback: 1, apply_evidence: 0, note: 0, other: 0, total: 1 },
+ },
]);
rmSync(v, { recursive: true });
});
@@ -71,4 +78,71 @@ describe("countBrainEvents", () => {
expect(out.byAgent["@claude-vps-agent"]!.total).toBe(0);
rmSync(v, { recursive: true });
});
+
+ test("counts note events (§32B v0.10.8)", () => {
+ const v = mkdtempSync(join(tmpdir(), "o2b-disc-log-note-"));
+ try {
+ appendLogEvent(v, {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: "note",
+ body: { text: "v0.10.7 shipped", agent: "@claude-vps-agent" },
+ });
+ appendLogEvent(v, {
+ timestamp: "2026-05-19T10:00:01Z",
+ eventType: "feedback",
+ body: {
+ signal: "[[sig-x]]",
+ topic: "x",
+ sign: "positive",
+ agent: "@claude-vps-agent",
+ },
+ });
+ const out = countBrainEvents(v, "2026-05-19", ["@claude-vps-agent"]);
+ expect(out.byAgent["@claude-vps-agent"]).toEqual({
+ feedback: 1,
+ apply_evidence: 0,
+ note: 1,
+ other: 0,
+ total: 2,
+ });
+ expect(out.total).toBe(2);
+ } finally {
+ rmSync(v, { recursive: true });
+ }
+ });
+
+ test("reads through the JSONL sidecar when present (§23)", () => {
+ // appendLogEvent writes both .md and .jsonl. Delete the .md to
+ // prove the reader picked the JSONL path.
+ const v = mkdtempSync(join(tmpdir(), "o2b-disc-jsonl-"));
+ try {
+ appendLogEvent(v, {
+ timestamp: "2026-05-19T10:00:00Z",
+ eventType: "feedback",
+ body: {
+ signal: "[[sig-x]]",
+ topic: "x",
+ sign: "positive",
+ agent: "@a1",
+ },
+ });
+ rmSync(join(v, "Brain", "log", "2026-05-19.md"));
+ const out = countBrainEvents(v, "2026-05-19", ["@a1"]);
+ expect(out.byAgent["@a1"]!.feedback).toBe(1);
+ expect(out.byAgent["@a1"]!.total).toBe(1);
+ } finally {
+ rmSync(v, { recursive: true });
+ }
+ });
+
+ 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 v = vaultWithLog(body);
+ const out = countBrainEvents(v, "2026-05-17", ["@a-legacy"]);
+ expect(out.byAgent["@a-legacy"]!.feedback).toBe(1);
+ rmSync(v, { recursive: true });
+ });
});
diff --git a/tests/discipline/render.test.ts b/tests/discipline/render.test.ts
index 29751cce..6adf2938 100644
--- a/tests/discipline/render.test.ts
+++ b/tests/discipline/render.test.ts
@@ -9,11 +9,11 @@ describe("renderReport", () => {
status: "ok",
events: {
byAgent: {
- "@claude-vps-agent": { feedback: 2, apply_evidence: 3, other: 0, total: 5 },
- "@codex-vps-agent": { feedback: 0, apply_evidence: 0, other: 0, total: 0 },
+ "@claude-vps-agent": { feedback: 2, apply_evidence: 3, note: 1, other: 0, total: 6 },
+ "@codex-vps-agent": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 },
},
unknownAgents: [],
- total: 5,
+ total: 6,
},
activity: {
repo: [{ path: "/srv/projects/foo", git: { commits: 4, filesChanged: 27, insertions: 312, deletions: 148 } }],
@@ -26,7 +26,7 @@ describe("renderReport", () => {
expect(text).toContain("Europe/Belgrade");
expect(text).toContain("Status: ok");
expect(text).toContain("@claude\\-vps\\-agent");
- expect(text).toContain("2 feedback, 3 apply\\-evidence, 0 other \\(total 5\\)");
+ expect(text).toContain("2 feedback, 3 apply\\-evidence, 1 note, 0 other \\(total 6\\)");
expect(text).toContain("/srv/projects/foo");
expect(text).toContain("4 commits");
expect(text).toContain("vault");
@@ -38,7 +38,7 @@ describe("renderReport", () => {
localDate: "2026-05-17",
timezone: "UTC",
status: "alert",
- events: { byAgent: { "@a": { feedback: 0, apply_evidence: 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: [],
diff --git a/tests/fixtures/identity-reminder/hermes.txt b/tests/fixtures/identity-reminder/hermes.txt
index 47ae5cf5..5df2f70a 100644
--- a/tests/fixtures/identity-reminder/hermes.txt
+++ b/tests/fixtures/identity-reminder/hermes.txt
@@ -1 +1 @@
-[open-second-brain] Identity: @test-agent. After every durable artifact this turn — code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know — call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@test-agent` automatically, do not include them yourself. Hermes turns are short; do not batch the log calls across turns. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
+[open-second-brain] Identity: @test-agent. After every durable artifact this turn (code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know), record it through the Brain writer tools: call `brain_feedback` if the turn surfaced a new user preference, `brain_apply_evidence` (`result: applied | violated | outdated`) if a preference in `Brain/preferences/` scopes to the artifact, or `brain_note` for narrative milestones that fit neither. The Brain log entry lands in `Brain/log/<today>.md` (with the JSONL sidecar) under the resolved `@test-agent` identity. Hermes turns are short; do not batch the calls across turns. Skip pure discussion, exploration, read-only queries, and planning that hasn't produced an artifact.
diff --git a/tests/fixtures/identity-reminder/openclaw.txt b/tests/fixtures/identity-reminder/openclaw.txt
index d9698c8c..785f6a0a 100644
--- a/tests/fixtures/identity-reminder/openclaw.txt
+++ b/tests/fixtures/identity-reminder/openclaw.txt
@@ -1 +1 @@
-[open-second-brain] Identity: @test-agent. After every durable in-process action — code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know — call the event_log_append tool with the plain event description as `message`. The server prepends timestamp and `@test-agent` automatically, do not include them yourself. OpenClaw has no session boundary; log immediately. Skip pure discussion, exploration, read-only queries, and planning that hasn't yet produced an artifact.
+[open-second-brain] Identity: @test-agent. After every durable in-process action (code shipped, bug fixed, config or deployment change, instruction-file edit, content artifact created, research finding or design decision reached, investigation that surfaced a fact future sessions should know), record it through the Brain writer tools: call `brain_feedback` if the turn surfaced a new user preference, `brain_apply_evidence` (`result: applied | violated | outdated`) if a preference in `Brain/preferences/` scopes to the artifact, or `brain_note` for narrative milestones that fit neither. The Brain log entry lands in `Brain/log/<today>.md` (with the JSONL sidecar) under the resolved `@test-agent` identity. OpenClaw has no session boundary; log immediately. Skip pure discussion, exploration, read-only queries, and planning that hasn't produced an artifact.
diff --git a/tests/hooks/detect.test.ts b/tests/hooks/detect.test.ts
index 01351e4c..b57f91a2 100644
--- a/tests/hooks/detect.test.ts
+++ b/tests/hooks/detect.test.ts
@@ -24,64 +24,64 @@ describe("isArtifactToolName", () => {
});
describe("isBrainEventToolName", () => {
- test("recognises the bare name used in Codex transcripts", () => {
- expect(isBrainEventToolName("event_log_append")).toBe(true);
- });
+ // §32 (v0.10.8): the three Brain-native writer tools are the only
+ // names that clear the guardrail. `event_log_append` no longer
+ // qualifies — the corresponding MCP tool is gone from every runtime.
- test("recognises the Claude Code plugin-decorated MCP name", () => {
- // Verified live against /root/.claude/projects/-root/*.jsonl —
- // Claude prefixes plugin-supplied MCP tools with
- // `mcp__plugin_<plugin>_<server>__`.
+ test("recognises `brain_feedback` (bare and decorated)", () => {
+ expect(isBrainEventToolName("brain_feedback")).toBe(true);
expect(
- isBrainEventToolName("mcp__plugin_open-second-brain_open-second-brain__event_log_append"),
+ isBrainEventToolName(
+ "mcp__plugin_open-second-brain_open-second-brain__brain_feedback",
+ ),
).toBe(true);
+ expect(isBrainEventToolName("mcp__open-second-brain__brain_feedback")).toBe(true);
});
- test("recognises the legacy short MCP name", () => {
- // Older Claude builds (and some forks) used a shorter prefix.
- expect(isBrainEventToolName("mcp__open-second-brain__event_log_append")).toBe(true);
- });
-
- test("rejects unrelated names", () => {
- expect(isBrainEventToolName("second_brain_capture")).toBe(false);
- expect(isBrainEventToolName("Write")).toBe(false);
- expect(isBrainEventToolName("event_log_append_other")).toBe(false);
- expect(isBrainEventToolName("not_event_log_append")).toBe(false);
- });
-
- test("rejects names that contain the suffix but not as a `__`-bounded token", () => {
- expect(isBrainEventToolName("xevent_log_append")).toBe(false);
- });
-
- // §30 §A (v0.10.6) — `brain_feedback` and `brain_apply_evidence`
- // are now equally valid brain-events from the guardrail's
- // perspective. The same name-suffix / MCP-prefix coverage applies.
- test("recognises `brain_feedback` (bare)", () => {
- expect(isBrainEventToolName("brain_feedback")).toBe(true);
+ 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",
+ ),
+ ).toBe(true);
});
- test("recognises `brain_feedback` under the Claude Code plugin prefix", () => {
+ test("recognises `brain_note` (bare and decorated) — §32B", () => {
+ expect(isBrainEventToolName("brain_note")).toBe(true);
expect(
isBrainEventToolName(
- "mcp__plugin_open-second-brain_open-second-brain__brain_feedback",
+ "mcp__plugin_open-second-brain_open-second-brain-writer__brain_note",
),
).toBe(true);
});
- test("recognises `brain_apply_evidence` (bare and prefixed)", () => {
- expect(isBrainEventToolName("brain_apply_evidence")).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__brain_apply_evidence",
+ "mcp__plugin_open-second-brain_open-second-brain__event_log_append",
),
- ).toBe(true);
+ ).toBe(false);
+ expect(isBrainEventToolName("mcp__open-second-brain__event_log_append")).toBe(false);
+ });
+
+ test("rejects unrelated names", () => {
+ expect(isBrainEventToolName("second_brain_capture")).toBe(false);
+ expect(isBrainEventToolName("Write")).toBe(false);
+ expect(isBrainEventToolName("brain_feedback_other")).toBe(false);
+ expect(isBrainEventToolName("not_brain_feedback")).toBe(false);
+ });
+
+ test("rejects names that contain the suffix but not as a `__`-bounded token", () => {
+ expect(isBrainEventToolName("xbrain_feedback")).toBe(false);
+ expect(isBrainEventToolName("xbrain_note")).toBe(false);
});
test("rejects nearby but non-matching brain_* names", () => {
expect(isBrainEventToolName("brain_query")).toBe(false);
expect(isBrainEventToolName("brain_doctor")).toBe(false);
expect(isBrainEventToolName("brain_digest")).toBe(false);
- expect(isBrainEventToolName("xbrain_feedback")).toBe(false);
});
});
@@ -91,31 +91,35 @@ describe("summarizeTurn", () => {
expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
});
- test("artifact AND MCP log → hadBrainEvent wins", () => {
- const s = summarizeTurn([{ name: "Write" }, { name: "event_log_append" }]);
+ test("artifact AND MCP `brain_feedback` → hadBrainEvent wins", () => {
+ const s = summarizeTurn([{ name: "Write" }, { name: "brain_feedback" }]);
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
+ });
+
+ test("artifact + MCP `brain_note` (§32B) clears guardrail", () => {
+ const s = summarizeTurn([{ name: "apply_patch" }, { name: "brain_note" }]);
expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
});
- test("artifact + bash that runs `o2b append-event` counts as log", () => {
+ test("artifact + bash `o2b append-event` (deprecated, §32) does NOT clear guardrail", () => {
+ // §32 (v0.10.8): the Daily/-targeted CLI verb still works for
+ // humans/cron but no longer counts as a Brain-side event.
const s = summarizeTurn(
[{ name: "apply_patch" }, { name: "Bash" }],
["o2b append-event 'fixed bug'"],
);
- expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
});
- test("artifact + bash that runs the legacy `vault-log` wrapper counts as log", () => {
+ test("artifact + bash `vault-log` (deprecated, §32) does NOT clear guardrail", () => {
const s = summarizeTurn(
[{ name: "Write" }, { name: "Bash" }],
["vault-log 'noted finding'"],
);
- expect(s).toEqual({ hadArtifact: true, hadBrainEvent: true });
+ expect(s).toEqual({ hadArtifact: true, hadBrainEvent: false });
});
- test("the trailing space in the `vault-log ` needle prevents false matches on paths", () => {
- // A path like `/srv/audit/vault-log.json` must NOT be misread as
- // an `o2b vault-log` invocation. The needle's trailing space (the
- // CLI is always followed by an argument) makes the match precise.
+ test("artifact + bash that touches a `vault-log` path is not misread as a CLI call", () => {
const s = summarizeTurn(
[{ name: "Write" }, { name: "Bash" }],
["cat /srv/audit/vault-log.json"],
diff --git a/tests/hooks/stop-log-guardrail.test.ts b/tests/hooks/stop-log-guardrail.test.ts
index cd8ff7bc..b87f22f3 100644
--- a/tests/hooks/stop-log-guardrail.test.ts
+++ b/tests/hooks/stop-log-guardrail.test.ts
@@ -62,7 +62,7 @@ async function runHook(payload: unknown): Promise<RunResult> {
}
describe("stop-log-guardrail hook", () => {
- test("blocks once when artifact was produced and no log was called", async () => {
+ test("blocks once when artifact was produced and no brain event was recorded", async () => {
const transcript_path = writeTranscript([
ccUser("please add a file"),
ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),
@@ -76,14 +76,38 @@ describe("stop-log-guardrail hook", () => {
expect(r.stdout.endsWith("\n")).toBe(true);
const out = JSON.parse(r.stdout);
expect(out.decision).toBe("block");
- expect(out.reason).toContain("event_log_append");
+ expect(out.reason).toContain("brain_feedback");
+ expect(out.reason).toContain("brain_apply_evidence");
+ expect(out.reason).toContain("brain_note");
+ // §32 (v0.10.8): event_log_append must not appear in the new
+ // guardrail body — the tool is retired across every runtime.
+ expect(out.reason).not.toContain("event_log_append");
});
- test("passes through when log was called this turn", async () => {
+ test("passes through when brain_feedback was called this turn", async () => {
const transcript_path = writeTranscript([
ccUser("please add a file"),
ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),
- ccAssistantToolUse("event_log_append", { message: "added /tmp/x.md" }),
+ ccAssistantToolUse("brain_feedback", {
+ topic: "x",
+ signal: "positive",
+ principle: "p",
+ }),
+ ]);
+ const r = await runHook({
+ hook_event_name: "Stop",
+ transcript_path,
+ stop_hook_active: false,
+ });
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ });
+
+ test("passes through when brain_note was called this turn (§32B)", async () => {
+ const transcript_path = writeTranscript([
+ ccUser("please add a file"),
+ ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),
+ ccAssistantToolUse("brain_note", { text: "added /tmp/x.md" }),
]);
const r = await runHook({
hook_event_name: "Stop",
@@ -141,9 +165,9 @@ describe("stop-log-guardrail hook", () => {
expect(r.stdout).toBe("");
});
- test("passes through when the agent logged via Bash (`o2b append-event`)", async () => {
+ test("passes through when the agent logged via Bash (`o2b brain feedback`)", async () => {
const transcript_path = writeTranscript([
- ccUser("add a file and log it via bash"),
+ ccUser("add a file and record a signal via bash"),
ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),
JSON.stringify({
type: "assistant",
@@ -154,7 +178,10 @@ describe("stop-log-guardrail hook", () => {
type: "tool_use",
id: "toolu_b",
name: "Bash",
- input: { command: "o2b append-event 'added /tmp/x.md'" },
+ input: {
+ command:
+ "o2b brain feedback --topic x --signal positive --principle p",
+ },
},
],
},
@@ -169,12 +196,26 @@ describe("stop-log-guardrail hook", () => {
expect(r.stdout).toBe("");
});
- test("passes through when the Claude MCP-prefixed event_log_append is called", async () => {
+ test("blocks even when the deprecated `o2b append-event` bash needle is used (§32)", async () => {
+ // §32 (v0.10.8) drops `o2b append-event` from the brain-event
+ // detector. The CLI still works for humans / cron, but it no
+ // longer suppresses the stop guardrail.
const transcript_path = writeTranscript([
- ccUser("add a file"),
+ ccUser("add a file and write the legacy log line"),
ccAssistantToolUse("Write", { file_path: "/tmp/x.md" }),
- ccAssistantToolUse("mcp__plugin_open-second-brain_open-second-brain__event_log_append", {
- message: "added /tmp/x.md",
+ JSON.stringify({
+ type: "assistant",
+ message: {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_b",
+ name: "Bash",
+ input: { command: "o2b append-event 'added /tmp/x.md'" },
+ },
+ ],
+ },
}),
]);
const r = await runHook({
@@ -182,8 +223,26 @@ describe("stop-log-guardrail hook", () => {
transcript_path,
stop_hook_active: false,
});
- expect(r.exit).toBe(0);
- expect(r.stdout).toBe("");
+ const out = JSON.parse(r.stdout);
+ expect(out.decision).toBe("block");
+ });
+
+ test("blocks even when the deprecated MCP-prefixed event_log_append is called (§32)", async () => {
+ 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" },
+ ),
+ ]);
+ const r = await runHook({
+ hook_event_name: "Stop",
+ transcript_path,
+ stop_hook_active: false,
+ });
+ const out = JSON.parse(r.stdout);
+ expect(out.decision).toBe("block");
});
test("blocks for Codex apply_patch with no logging", async () => {
@@ -292,6 +351,10 @@ describe("stop-log-guardrail hook", () => {
const reason = out.reason as string;
expect(reason).not.toContain("This guardrail fires");
expect(reason).not.toContain("codex exec");
- expect(reason).toContain("event_log_append");
+ // §32 (v0.10.8) — the unknown-runtime body still names the
+ // current trio of brain-event tools.
+ expect(reason).toContain("brain_feedback");
+ expect(reason).toContain("brain_apply_evidence");
+ expect(reason).toContain("brain_note");
});
});
diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.ts
index d35cd259..9b96dbed 100644
--- a/tests/mcp/brain.test.ts
+++ b/tests/mcp/brain.test.ts
@@ -38,6 +38,8 @@ 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 { writeSignal } from "../../src/core/brain/signal.ts";
@@ -686,3 +688,119 @@ describe("brain_backlinks", () => {
expect(r.error.message).toContain("id");
});
});
+
+// ---------------------------------------------------------------------------
+// brain_note (§32B, v0.10.8)
+// ---------------------------------------------------------------------------
+
+function logFileForToday(vaultDir: string): { md: string; jsonl: string } {
+ // The handler uses `new Date()` directly. Pick today's UTC date.
+ const today = new Date().toISOString().slice(0, 10);
+ return {
+ md: logPath(vaultDir, today),
+ jsonl: logJsonlPath(vaultDir, today),
+ };
+}
+
+describe("brain_note", () => {
+ test("appends a note event to both markdown and JSONL", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = (await call(server, "brain_note", {
+ text: "v0.10.7 shipped",
+ })) as any;
+
+ const payload = JSON.parse(r.result.content[0].text);
+ expect(payload.agent).toBe("claude");
+ expect(typeof payload.logged_at).toBe("string");
+
+ const paths = logFileForToday(vault);
+ expect(existsSync(paths.md)).toBe(true);
+ expect(existsSync(paths.jsonl)).toBe(true);
+ const md = readFileSync(paths.md, "utf8");
+ expect(md).toMatch(/— note$/m);
+ expect(md).toContain("text: v0.10.7 shipped");
+ expect(md).toContain("agent: claude");
+
+ const jsonlLines = readFileSync(paths.jsonl, "utf8").trim().split("\n");
+ const last = JSON.parse(jsonlLines[jsonlLines.length - 1]!);
+ expect(last.kind).toBe("note");
+ expect(last.payload.text).toBe("v0.10.7 shipped");
+ expect(last.payload.agent).toBe("claude");
+ });
+
+ test("redacts secret-shaped tokens before writing", async () => {
+ const server = makeServer();
+ await initialize(server);
+ await call(server, "brain_note", {
+ text: "deployed api_key=sk-abc123 to prod",
+ });
+
+ const paths = logFileForToday(vault);
+ const md = readFileSync(paths.md, "utf8");
+ expect(md).toContain("***REDACTED***");
+ expect(md).not.toContain("sk-abc123");
+ });
+
+ test("collapses multi-line input to one space-joined line", async () => {
+ const server = makeServer();
+ await initialize(server);
+ await call(server, "brain_note", { text: "line one\nline two" });
+
+ const paths = logFileForToday(vault);
+ const md = readFileSync(paths.md, "utf8");
+ expect(md).toContain("text: line one line two");
+ });
+
+ test("respects the agent override", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = (await call(server, "brain_note", {
+ text: "shipped X",
+ agent: "explicit-bot",
+ })) as any;
+ const payload = JSON.parse(r.result.content[0].text);
+ expect(payload.agent).toBe("explicit-bot");
+ });
+
+ test("rejects whitespace-only text", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = (await call(server, "brain_note", { text: " " })) as any;
+ // The shared `coerceStr` helper treats whitespace as missing
+ // before the handler's own check fires — same shape as every
+ // other "required string field" rejection.
+ expect(r.error).toBeDefined();
+ expect(r.error.message).toMatch(/missing required argument: text|text is required/);
+ });
+
+ test("rejects missing text", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = (await call(server, "brain_note", {})) as any;
+ expect(r.error).toBeDefined();
+ });
+});
+
+describe("brain_note tool schema visibility", () => {
+ test("brain_note is advertised in the full tool list", async () => {
+ const server = makeServer();
+ await initialize(server);
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 51,
+ method: "tools/list",
+ })) as any;
+ const names = (r.result.tools as Array<{ name: string }>).map((t) => t.name);
+ expect(names).toContain("brain_note");
+ });
+
+ test("brain_note belongs to the writer tool scope", () => {
+ const writer = buildToolTable("writer").map((t) => t.name);
+ expect(writer).toEqual(
+ expect.arrayContaining(["brain_feedback", "brain_apply_evidence", "brain_note"]),
+ );
+ // Writer scope is exactly these three — nothing else.
+ expect(writer).toHaveLength(3);
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 9aedf9cf..1380a73e 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -133,7 +133,7 @@ describe("handshake", () => {
});
describe("tool listing", () => {
- test("advertises the core, Brain, and Pay Memory tools (v0.9.0+)", async () => {
+ test("advertises the core, Brain, and Pay Memory tools (v0.10.8+)", async () => {
const server = new MCPServer({ vault: tmp });
await initialize(server);
const r = (await server.handleRequest({
@@ -148,10 +148,11 @@ describe("tool listing", () => {
"second_brain_status",
"second_brain_query",
"vault_health",
- // Brain (v0.9.0; brain_backlinks added in v0.9.1).
+ // Brain (brain_note added in v0.10.8 §32B).
"brain_feedback",
"brain_dream",
"brain_apply_evidence",
+ "brain_note",
"brain_digest",
"brain_query",
"brain_doctor",
@@ -287,8 +288,9 @@ describe("stdio loop", () => {
const list = JSON.parse(lines[1]!);
expect(init.id).toBe(1);
expect(list.id).toBe(2);
- // v0.10.0: 3 core (status/query/health) + 7 Brain + 8 Pay Memory + 1 Search = 19.
- expect(list.result.tools.length).toBe(19);
+ // v0.10.8: 3 core (status/query/health) + 8 Brain (brain_note added §32B)
+ // + 8 Pay Memory + 1 Search = 20.
+ expect(list.result.tools.length).toBe(20);
});
test("returns parse error for invalid JSON", async () => {
@@ -345,7 +347,11 @@ describe("serveStdioFromString respects scope+name", () => {
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();
- expect(toolNames).toEqual(["brain_apply_evidence", "brain_feedback"]);
+ expect(toolNames).toEqual([
+ "brain_apply_evidence",
+ "brain_feedback",
+ "brain_note",
+ ]);
});
});
diff --git a/tests/mcp/scope-filter.test.ts b/tests/mcp/scope-filter.test.ts
index 19b87862..d0b9a10a 100644
--- a/tests/mcp/scope-filter.test.ts
+++ b/tests/mcp/scope-filter.test.ts
@@ -13,10 +13,14 @@ describe("buildToolTable scope filter", () => {
expect(full.length).toBeGreaterThanOrEqual(15);
});
- test("writer scope returns exactly the two writer tools", () => {
+ test("writer scope returns exactly the three writer tools (§32B v0.10.8)", () => {
const writer = buildToolTable("writer");
const names = writer.map((t) => t.name).sort();
- expect(names).toEqual(["brain_apply_evidence", "brain_feedback"]);
+ expect(names).toEqual([
+ "brain_apply_evidence",
+ "brain_feedback",
+ "brain_note",
+ ]);
});
test("writer-scope schemas are the same instances as full scope", () => {
diff --git a/tests/openclaw/bundle.test.ts b/tests/openclaw/bundle.test.ts
index b6d8b909..07aeb5b5 100644
--- a/tests/openclaw/bundle.test.ts
+++ b/tests/openclaw/bundle.test.ts
@@ -41,7 +41,6 @@ describe("openclaw bundle", () => {
"second_brain_status",
"second_brain_query",
"second_brain_capture",
- "event_log_append",
"vault_health",
// Pay Memory
"payment_memory_init",
@@ -57,6 +56,12 @@ describe("openclaw bundle", () => {
}
});
+ test("does not register the retired event_log_append tool (§32G)", () => {
+ // §32G (v0.10.8) removed `event_log_append` from every runtime.
+ // The OpenClaw bundle must not contain the registration block.
+ expect(bundleText).not.toContain(`name: "event_log_append"`);
+ });
+
test("does NOT contain Python references", () => {
expect(bundleText).not.toContain("python3");
expect(bundleText).not.toContain("from open_second_brain");
diff --git a/tests/python/test_hermes_plugin.py b/tests/python/test_hermes_plugin.py
index ad2e54b7..f6f83330 100644
--- a/tests/python/test_hermes_plugin.py
+++ b/tests/python/test_hermes_plugin.py
@@ -141,7 +141,12 @@ class PreLlmCallTests(unittest.TestCase):
self.assertIn("context", result)
ctx = result["context"]
self.assertIn("@hermes-vps-agent", ctx)
- self.assertIn("event_log_append", ctx)
+ # §32 (v0.10.8): the Hermes reminder now points at the three
+ # Brain writer tools; event_log_append is retired.
+ self.assertIn("brain_feedback", ctx)
+ self.assertIn("brain_apply_evidence", ctx)
+ self.assertIn("brain_note", ctx)
+ self.assertNotIn("event_log_append", ctx)
def test_returns_context_from_persisted_config(self):
with tempfile.TemporaryDirectory() as tmp: