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
/**
* Dead-end registry (t_be62c62d): the Brain's negative-knowledge
* class. Skill proposals mine positive procedures; nothing recorded
* what was TRIED and FAILED, so agents kept re-walking pruned
* branches. A dead-end is one markdown note under `Brain/dead-ends/`
* (approach + why it failed + context) - markdown-first so FTS
* indexes it with zero search changes and recall surfaces "avoid X"
* alongside "prefer Y". The active set is bounded to the most-recent
* N; overflow archives the oldest into `Brain/dead-ends/archive/`
* instead of deleting history.
*/
import { join } from "node:path";
import { vaultRelative } from "../path-safety.ts";
import { sanitiseTextField } from "../redactor.ts";
import { slugify } from "../vault.ts";
import {
assertLaneWrite,
listLaneFiles,
moveLanePage,
readLanePage,
writeLanePage,
} from "../store/lane-pages.ts";
import type { FrontmatterMap } from "../types.ts";
import { allocateAndCreate } from "./paths.ts";
import { isoDate, isoSecond } from "./time.ts";
/** Active dead-ends kept before overflow archives the oldest. */
export const DEAD_END_MAX_ACTIVE = 100;
const APPROACH_MAX_LEN = 256;
const REASON_MAX_LEN = 1024;
const CONTEXT_MAX_LEN = 1024;
export function deadEndsDir(vault: string): string {
return join(vault, "Brain", "dead-ends");
}
export interface DeadEndEntry {
readonly id: string;
readonly path: string;
readonly approach: string;
readonly reason: string;
readonly context: string | null;
readonly agent: string;
readonly created_at: string;
}
export interface RecordDeadEndInput {
/** What was tried (one line, the note title). */
readonly approach: string;
/** Why it failed or was deliberately set aside. */
readonly reason: string;
readonly context?: string;
readonly agent: string;
readonly now: Date;
/** Override the active-set cap (tests). */
readonly maxActive?: number;
/**
* Whether the caller may read a vault-relative page at its reach. When
* given, the overflow trim still counts every active dead end against
* the cap but archives only the readable ones: a withheld page is never
* moved on that caller's behalf.
*/
readonly readable?: (rel: string) => boolean;
}
export interface RecordDeadEndResult {
readonly entry: DeadEndEntry;
/** Ids archived by the overflow trim, oldest first. */
readonly archived: ReadonlyArray<string>;
}
export interface DeadEndParseWarning {
readonly path: string;
readonly message: string;
}
export interface ListDeadEndsResult {
readonly entries: ReadonlyArray<DeadEndEntry>;
readonly warnings: ReadonlyArray<DeadEndParseWarning>;
}
function renderBody(approach: string, reason: string, context: string | null): string {
return (
`## Approach\n\n${approach}\n\n` +
`## Why it failed\n\n${reason}\n\n` +
`## Context\n\n${context ?? "_(not provided)_"}\n`
);
}
/**
* Record one dead-end note and trim the active set. The id is
* `de-<date>-<slug-of-approach>` with `allocateAndCreate` collision
* suffixes, matching the signal naming discipline.
*/
export function recordDeadEnd(vault: string, input: RecordDeadEndInput): RecordDeadEndResult {
// Vault-identity write guard (context-integrity-gates, Unit J) on an
// unswitched machine; a store-only one checks the store identity.
assertLaneWrite(vault);
const approach = sanitiseTextField(input.approach, {
maxLen: APPROACH_MAX_LEN,
singleLine: true,
}).trim();
const reason = sanitiseTextField(input.reason, { maxLen: REASON_MAX_LEN }).trim();
const context =
input.context !== undefined
? sanitiseTextField(input.context, { maxLen: CONTEXT_MAX_LEN }).trim() || null
: null;
if (approach === "") throw new Error("dead-end missing field: approach");
if (reason === "") throw new Error("dead-end missing field: reason");
if (!input.agent || input.agent.trim() === "") throw new Error("dead-end missing field: agent");
const dir = deadEndsDir(vault);
const date = isoDate(input.now);
const createdAt = isoSecond(input.now);
// Allocation and creation are one step: two agents recording the same
// approach on the same day both see the bare name free, and the loser
// of that exclusive create must fall through to `-2` rather than lose
// the note (GitHub #161). The frontmatter `id` is derived per attempt
// because it must always equal the filename it ships in.
const { allocation: allocated, value: id } = allocateAndCreate(
{
vault,
targetDir: dir,
prefix: `de-${date}`,
slug: slugify(approach),
},
(allocation) => {
const deadEndId = `de-${date}-${allocation.slug}`;
const metadata: FrontmatterMap = {
kind: "brain-dead-end",
id: deadEndId,
created_at: createdAt,
agent: input.agent.trim(),
approach,
tags: ["brain", "brain/dead-end"],
};
writeLanePage(vault, allocation.path, metadata, renderBody(approach, reason, context), {
overwrite: false,
existsErrorKind: "dead-end",
vaultForRelativePath: vault,
});
return deadEndId;
},
);
const archived = trimActive(vault, input.maxActive ?? DEAD_END_MAX_ACTIVE, input.readable);
return Object.freeze({
entry: Object.freeze({
id,
path: allocated.path,
approach,
reason,
context,
agent: input.agent.trim(),
created_at: createdAt,
}),
archived: Object.freeze(archived),
});
}
/**
* Move the oldest active entries beyond the cap into `archive/`. The cap
* counts every entry; with `readable`, an overflow entry the caller cannot
* read stays where it is.
*/
function trimActive(
vault: string,
maxActive: number,
readable: ((rel: string) => boolean) | undefined,
): string[] {
const { entries } = listDeadEnds(vault);
if (entries.length <= maxActive) return [];
// `entries` is newest first; everything past the cap archives.
const overflow = entries
.slice(maxActive)
.toReversed()
.filter((entry) => readable === undefined || readable(vaultRelative(entry.path, vault)));
if (overflow.length === 0) return [];
const archiveDir = join(deadEndsDir(vault), "archive");
const archived: string[] = [];
for (const entry of overflow) {
moveLanePage(vault, entry.path, join(archiveDir, `${entry.id}.md`));
archived.push(entry.id);
}
return archived;
}
function parseSections(body: string): { reason: string; context: string | null } {
const reasonMatch = /## Why it failed\n\n([\s\S]*?)(?:\n## |$)/.exec(body);
const contextMatch = /## Context\n\n([\s\S]*?)(?:\n## |$)/.exec(body);
const contextRaw = contextMatch?.[1]?.trim() ?? "";
return {
reason: reasonMatch?.[1]?.trim() ?? "",
context: contextRaw === "" || contextRaw === "_(not provided)_" ? null : contextRaw,
};
}
/**
* List active dead-ends, newest first. Files that fail to parse (or
* carry the wrong kind) surface as warnings and never abort the list.
*/
export function listDeadEnds(vault: string): ListDeadEndsResult {
const dir = deadEndsDir(vault);
const entries: DeadEndEntry[] = [];
const warnings: DeadEndParseWarning[] = [];
for (const name of listLaneFiles(vault, dir)) {
const path = join(dir, name);
let metadata: FrontmatterMap;
let body: string;
try {
const page = readLanePage(vault, path);
if (page === null) continue;
({ frontmatter: metadata, body } = page);
} catch (exc) {
warnings.push({ path, message: `unparseable dead-end: ${(exc as Error).message ?? exc}` });
continue;
}
if (metadata["kind"] !== "brain-dead-end") {
warnings.push({ path, message: "missing kind: brain-dead-end" });
continue;
}
const id = typeof metadata["id"] === "string" ? metadata["id"] : name.replace(/\.md$/, "");
const approach = typeof metadata["approach"] === "string" ? metadata["approach"] : "";
const agent = typeof metadata["agent"] === "string" ? metadata["agent"] : "";
const createdAt = typeof metadata["created_at"] === "string" ? metadata["created_at"] : "";
if (approach === "" || createdAt === "") {
warnings.push({ path, message: "dead-end missing approach/created_at" });
continue;
}
const sections = parseSections(body);
entries.push(
Object.freeze({
id,
path,
approach,
reason: sections.reason,
context: sections.context,
agent,
created_at: createdAt,
}),
);
}
entries.sort((a, b) => {
if (a.created_at !== b.created_at) return a.created_at < b.created_at ? 1 : -1;
return a.id < b.id ? 1 : a.id > b.id ? -1 : 0;
});
return { entries: Object.freeze(entries), warnings: Object.freeze(warnings) };
}