Skip to content

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

TypeScript

v0.10.8 refactor: address CodeRabbit review (input validation + MCP errors + docs)

Sol Aitken6d65b7003d42
diff --git a/docs/plans/2026-05-19-v0.10.8-design.md b/docs/plans/2026-05-19-v0.10.8-design.md
index d056fa0d..ee72019e 100644
--- a/docs/plans/2026-05-19-v0.10.8-design.md
+++ b/docs/plans/2026-05-19-v0.10.8-design.md
@@ -579,8 +579,8 @@ caller (discipline-report, future tool)
| 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. |
+| JSONL write succeeds, markdown write fails (or vice versa) | Lock + atomic write under JSONL-first ordering: machine-side readers (which prefer JSONL) keep returning the correct count even after a partial failure; the markdown side may lag by one event until the next successful append. Re-syncing the markdown view from the JSONL is an explicit operator step (`o2b brain digest` regeneration / hand re-render), never automatic. |
+| Hand-edited markdown drifts from JSONL | Reader prefers JSONL, returns warnings on malformed lines. Deleting the JSONL is **not** a safe rebuild path on its own β€” the next append would create a new JSONL containing only the new event, not the historical ones. To force a rebuild, regenerate `<date>.jsonl` from the parsed markdown (out-of-band script, not part of `appendLogEvent`) before the 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. |
diff --git a/docs/plans/2026-05-19-v0.10.8-impl.md b/docs/plans/2026-05-19-v0.10.8-impl.md
index 7c538870..f2ba7fb4 100644
--- a/docs/plans/2026-05-19-v0.10.8-impl.md
+++ b/docs/plans/2026-05-19-v0.10.8-impl.md
@@ -473,8 +473,17 @@ function readJsonl(path: string): ReadLogDayResult {
let text: string;
try {
text = readFileSync(path, "utf8");
- } catch {
- return { entries: [], source: "jsonl", warnings: [] };
+ } catch (err) {
+ // The caller already verified `existsSync(path)`; a read failure
+ // here is anomalous (rotation race, permission flip, transient
+ // fs error). Surface it as a warning so discipline-report and
+ // doctor can flag the day instead of silently returning zero.
+ 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[] = [];
diff --git a/src/cli/brain/helpers.ts b/src/cli/brain/helpers.ts
index 1356dac6..9591cc3c 100644
--- a/src/cli/brain/helpers.ts
+++ b/src/cli/brain/helpers.ts
@@ -26,7 +26,7 @@
import { resolveVault } from "../../core/config.ts";
import { CliError, parseFlags, type FlagsSchema } from "../argparse.ts";
-import { NO_VAULT_ERROR } from "../helpers.ts";
+import { NO_VAULT_ERROR, normalizeFlagString } from "../helpers.ts";
// ── Vault resolution ────────────────────────────────────────────────────────
@@ -34,7 +34,13 @@ export function resolveBrainVault(
flagVal: string | undefined,
configPath: string | null,
): string {
- const vault = flagVal ?? resolveVault(configPath ?? undefined);
+ // Mirror `requireVault` in `../helpers.ts`: explicit `--vault ""`
+ // is a user error, not an excuse to fall through to `resolveVault`.
+ const explicit = normalizeFlagString(flagVal);
+ if (flagVal !== undefined && explicit === null) {
+ throw new CliError(NO_VAULT_ERROR);
+ }
+ const vault = explicit ?? resolveVault(configPath ?? undefined);
if (vault === null || vault === undefined) {
throw new CliError(NO_VAULT_ERROR);
}
@@ -58,7 +64,7 @@ export function parse(
export { CliError } from "../argparse.ts";
export { fail, info, ok, okJson } from "../output.ts";
export { ISO_8601_RE, parseOptionalIsoDate } from "../coerce.ts";
-export { NO_VAULT_ERROR } from "../helpers.ts";
+export { NO_VAULT_ERROR, normalizeFlagString } from "../helpers.ts";
export { BRAIN_HELP, VERB_HELP } from "./help-text.ts";
export {
diff --git a/src/cli/brain/verbs/apply-evidence.ts b/src/cli/brain/verbs/apply-evidence.ts
index 8875deab..e4b947ea 100644
--- a/src/cli/brain/verbs/apply-evidence.ts
+++ b/src/cli/brain/verbs/apply-evidence.ts
@@ -1,6 +1,6 @@
import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
import { appendApplyEvidence, BrainPreferenceNotFoundError } from "../../../core/brain/apply-evidence.ts";
-import { parse, fail, ok, okJson, resolveBrainVault } from "../helpers.ts";
+import { parse, fail, normalizeFlagString, ok, okJson, resolveBrainVault } from "../helpers.ts";
export async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
@@ -19,7 +19,11 @@ export async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {
}
const config = defaultConfigPath();
const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const explicitAgent = normalizeFlagString(flags["agent"]);
+ if (flags["agent"] !== undefined && explicitAgent === null) {
+ return fail("--agent must be a non-empty string when provided");
+ }
+ const agent = explicitAgent ?? resolveAgentName(config);
const resultStr = String(flags["result"]);
if (resultStr !== "applied" && resultStr !== "violated" && resultStr !== "outdated") {
diff --git a/src/cli/brain/verbs/explorer.ts b/src/cli/brain/verbs/explorer.ts
index 9211a7f8..77751126 100644
--- a/src/cli/brain/verbs/explorer.ts
+++ b/src/cli/brain/verbs/explorer.ts
@@ -41,7 +41,12 @@ export async function cmdBrainExplorer(argv: string[]): Promise<number> {
ok(`Live explorer at ${server.url}`);
info("Press Ctrl+C to stop.");
await new Promise<void>((resolveStop) => {
- const stop = (): void => { void server.close().then(() => resolveStop()); };
+ // `.catch(() => undefined).finally(...)` so the shutdown promise
+ // always settles β€” without the catch, a rejected `server.close()`
+ // leaves the outer await pending and Ctrl+C hangs the process.
+ const stop = (): void => {
+ void server.close().catch(() => undefined).finally(() => resolveStop());
+ };
process.once("SIGINT", stop);
process.once("SIGTERM", stop);
});
diff --git a/src/cli/brain/verbs/import-session.ts b/src/cli/brain/verbs/import-session.ts
index 3ba83986..268ab6df 100644
--- a/src/cli/brain/verbs/import-session.ts
+++ b/src/cli/brain/verbs/import-session.ts
@@ -5,7 +5,7 @@ import { SessionImportError } from "../../../core/brain/sessions/types.ts";
import { appendLogEvent } from "../../../core/brain/log.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
import { isoSecond } from "../../../core/brain/time.ts";
-import { parse, fail, ok, okJson, info, resolveBrainVault, ISO_8601_RE } from "../helpers.ts";
+import { parse, fail, info, normalizeFlagString, ok, okJson, resolveBrainVault, ISO_8601_RE } from "../helpers.ts";
export async function cmdBrainImportSession(argv: string[]): Promise<number> {
const { flags, positional } = parse(argv, {
@@ -20,7 +20,11 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {
const sessionPath = positional[0]!;
const config = defaultConfigPath();
const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const explicitAgent = normalizeFlagString(flags["agent"]);
+ if (flags["agent"] !== undefined && explicitAgent === null) {
+ return fail("--agent must be a non-empty string when provided");
+ }
+ const agent = explicitAgent ?? resolveAgentName(config);
const formatRaw = flags["format"] as string | undefined;
let format: "claude" | "codex" | "hermes" | undefined;
diff --git a/src/cli/brain/verbs/pin.ts b/src/cli/brain/verbs/pin.ts
index 101f265b..f5673faa 100644
--- a/src/cli/brain/verbs/pin.ts
+++ b/src/cli/brain/verbs/pin.ts
@@ -1,7 +1,7 @@
import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
import { setPinned } from "../../../core/brain/pin.ts";
import { BrainPreferenceNotFoundError } from "../../../core/brain/apply-evidence.ts";
-import { parse, fail, ok, okJson, resolveBrainVault } from "../helpers.ts";
+import { parse, fail, normalizeFlagString, ok, okJson, resolveBrainVault } from "../helpers.ts";
async function pinOrUnpin(argv: string[], value: boolean): Promise<number> {
const { flags } = parse(argv, {
@@ -9,7 +9,11 @@ async function pinOrUnpin(argv: string[], value: boolean): Promise<number> {
id: { type: "string" },
json: { type: "boolean" },
});
- if (typeof flags["id"] !== "string" || (flags["id"] as string).trim() === "") {
+ // Normalise once so `setPinned` and the slug rendering both see the
+ // same trimmed value β€” passing an untrimmed `" pref-foo "` into
+ // `setPinned` previously failed deep inside path resolution.
+ const id = normalizeFlagString(flags["id"]);
+ if (id === null) {
return fail(`brain ${value ? "pin" : "unpin"} missing required flag: --id`);
}
const config = defaultConfigPath();
@@ -17,8 +21,8 @@ async function pinOrUnpin(argv: string[], value: boolean): Promise<number> {
const agent = resolveAgentName(config);
try {
- const out = setPinned(vault, String(flags["id"]), value, { agent });
- const slug = String(flags["id"]).trim().replace(/^pref-/, "");
+ const out = setPinned(vault, id, value, { agent });
+ const slug = id.replace(/^pref-/, "");
const label = value ? "pinned" : "unpinned";
const idemLabel = value ? "already pinned" : "already unpinned";
if (flags["json"]) { okJson({ id: `pref-${slug}`, changed: out.changed, pinned: value }); }
diff --git a/src/cli/coerce.ts b/src/cli/coerce.ts
index 768c4c1e..e39b0a91 100644
--- a/src/cli/coerce.ts
+++ b/src/cli/coerce.ts
@@ -15,8 +15,14 @@ export function parseOptionalNumberFlag(
flags: Record<string, string | boolean | string[] | undefined>,
name: string,
): { value: number | null; error: string | null } {
- const raw = flags[name] as string | undefined;
+ const raw = flags[name];
if (raw === undefined) return { value: null, error: null };
+ // A non-string value (boolean / string[]) indicates a misconfigured
+ // flag schema β€” surface it as a clean validation error instead of
+ // throwing at the `.trim()` call below.
+ if (typeof raw !== "string") {
+ return { value: null, error: `--${name} must be provided as a single string value` };
+ }
const trimmed = raw.trim();
if (trimmed === "") return { value: null, error: null };
const parsed = Number(trimmed);
@@ -50,8 +56,11 @@ export function parseOptionalIsoDate(
flags: Record<string, string | boolean | string[] | undefined>,
name: string,
): { value: Date | null; error: string | null } {
- const raw = flags[name] as string | undefined;
+ const raw = flags[name];
if (raw === undefined) return { value: null, error: null };
+ if (typeof raw !== "string") {
+ return { value: null, error: `--${name} must be provided as a single string value` };
+ }
const trimmed = raw.trim();
if (trimmed === "") return { value: null, error: null };
if (!ISO_8601_RE.test(trimmed)) {
diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts
index e0c90979..b6baf2b6 100644
--- a/src/cli/helpers.ts
+++ b/src/cli/helpers.ts
@@ -16,8 +16,38 @@ export class NoVaultConfiguredError extends Error {
}
}
+/**
+ * Normalise a CLI flag value into a trimmed non-empty string, or
+ * `null` when the user did not supply something usable.
+ *
+ * Callers receive `null` for any of: `undefined`, non-string values
+ * (boolean / array β€” `parseFlags` can produce these for misconfigured
+ * schemas), the empty string, and whitespace-only strings.
+ *
+ * This is the load-bearing guard that prevents `--agent ""`,
+ * `--vault " "`, `--id $UNSET_VAR`, etc. from being treated as
+ * authoritative user input and silently producing malformed
+ * artefacts (`@` identities, vault paths pointing at the CWD,
+ * unparseable preference ids). Every verb that reads a string flag
+ * should normalise through this helper before falling back to
+ * config-driven defaults.
+ */
+export function normalizeFlagString(raw: unknown): string | null {
+ if (typeof raw !== "string") return null;
+ const trimmed = raw.trim();
+ return trimmed.length === 0 ? null : trimmed;
+}
+
export function requireVault(flagVal: string | undefined, configPath: string | null): string {
- const vault = flagVal ?? resolveVault(configPath ?? undefined);
+ // Explicit `--vault ""` / `" "` is a user error, not an excuse to
+ // fall through to `resolveVault` β€” treat it the same as the no-vault
+ // case so the operator sees a clean error instead of commands
+ // operating against an unintended relative path.
+ const explicit = normalizeFlagString(flagVal);
+ if (flagVal !== undefined && explicit === null) {
+ throw new NoVaultConfiguredError();
+ }
+ const vault = explicit ?? resolveVault(configPath ?? undefined);
if (vault === null || vault === undefined) {
throw new NoVaultConfiguredError();
}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index dad136fc..12b2451a 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -29,6 +29,7 @@ import { handleDisciplineSubcommand } from "./discipline.ts";
import { handleSearchSubcommand } from "./search.ts";
import {
NoVaultConfiguredError,
+ normalizeFlagString,
requireVault,
sortedReplacer,
} from "./helpers.ts";
@@ -262,7 +263,11 @@ async function cmdAppendEvent(argv: string[]): Promise<number> {
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 explicit = normalizeFlagString(flags["as"]);
+ if (flags["as"] !== undefined && explicit === null) {
+ process.stderr.write("error: --as must be a non-empty string when provided\n");
+ return 2;
+ }
const agent = explicit ?? resolveAgentName(config);
let path: string;
diff --git a/src/cli/pay-memory/verbs/request-approval.ts b/src/cli/pay-memory/verbs/request-approval.ts
index ecb6003f..6c881507 100644
--- a/src/cli/pay-memory/verbs/request-approval.ts
+++ b/src/cli/pay-memory/verbs/request-approval.ts
@@ -1,6 +1,6 @@
import { defaultConfigPath, resolveAgentName, resolveTimezone } from "../../../core/config.ts";
import { writePendingRequest } from "../../../core/pay-memory/index.ts";
-import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { normalizeFlagString, requireVault, sortedReplacer } from "../../helpers.ts";
import { parseOptionalNumberFlag } from "../../coerce.ts";
import { parseFlags } from "../../argparse.ts";
@@ -24,8 +24,12 @@ export async function cmdRequestPaymentApproval(argv: string[]): Promise<number>
});
const config = defaultConfigPath();
const vault = requireVault(flags["vault"] as string | undefined, config);
- const agent =
- (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const explicitAgent = normalizeFlagString(flags["agent"]);
+ if (flags["agent"] !== undefined && explicitAgent === null) {
+ process.stderr.write("error: --agent must be a non-empty string when provided\n");
+ return 2;
+ }
+ const agent = explicitAgent ?? resolveAgentName(config);
const tz = resolveTimezone(config);
const { value: expectedAmount, error: expectedErr } = parseOptionalNumberFlag(
diff --git a/src/core/validate.ts b/src/core/validate.ts
index 3c31bc6b..c76f3ab7 100644
--- a/src/core/validate.ts
+++ b/src/core/validate.ts
@@ -21,6 +21,11 @@ export function parseInteger(
range?: { readonly min?: number; readonly max?: number },
): number {
if (raw === null) return default_;
+ // `Number(" ")` returns 0 in JS β€” without this guard a whitespace-
+ // only config value would silently coerce to a valid integer.
+ if (raw.trim() === "") {
+ throw new Error(`${fieldName} must be an integer, got empty string`);
+ }
const n = Number(raw);
if (!Number.isFinite(n) || !Number.isInteger(n)) {
throw new Error(`${fieldName} must be an integer, got '${raw}'`);
@@ -44,6 +49,9 @@ export function parseFloat01(
fieldName: string,
): number {
if (raw === null) return default_;
+ if (raw.trim() === "") {
+ throw new Error(`${fieldName} must be a number in [0, 1], got empty string`);
+ }
const n = Number(raw);
if (!Number.isFinite(n) || n < 0 || n > 1) {
throw new Error(`${fieldName} must be a number in [0, 1], got '${raw}'`);
diff --git a/src/mcp/pay-memory-tools.ts b/src/mcp/pay-memory-tools.ts
index f6da31fe..cc036acc 100644
--- a/src/mcp/pay-memory-tools.ts
+++ b/src/mcp/pay-memory-tools.ts
@@ -97,7 +97,7 @@ async function toolPaymentReceiptAppend(
if (fromRequest) {
const loaded = loadPendingRequest(ctx.vault, fromRequest);
if (!loaded) {
- throw new Error(`pending request not found: ${fromRequest}`);
+ throw new MCPError(INVALID_PARAMS, `from_request not found: ${fromRequest}`);
}
const meta = loaded.metadata;
const get = (k: string): string | null => {
@@ -241,7 +241,7 @@ async function toolPaymentRequestStatus(
const id = coerceStr(args, "id", true)!;
const loaded = loadPendingRequest(ctx.vault, id);
if (!loaded) {
- throw new Error(`pending request not found: ${id}`);
+ throw new MCPError(INVALID_PARAMS, `id not found: ${id}`);
}
const meta = loaded.metadata;
const get = (k: string): string | null => {