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
/**
* Scoped current-intention chains (Agent Surface Suite, t_6d78f69e).
*
* A per-workstream "now" document: `Brain/intentions/<scope>.md` holds
* the current intention, every update bumps `version` and appends the
* superseded text to an in-file `## History` trail, and `move`
* retires the whole chain into `Brain/intentions/history/` so the
* active directory only ever shows live work. Markdown first - the
* chain is operator-readable without any tooling. `Brain/pinned.md`
* stays untouched as the scope-free scratchpad.
*/
import { mkdirSync, readFileSync, rmSync } from "node:fs";
import { join, posix } from "node:path";
import { atomicWriteFileSync, renameWithRetry } from "../fs-atomic.ts";
import { resolveSessionScope } from "./session-scope.ts";
import { isoDate, isoSecond } from "./time.ts";
import {
assertLaneWrite,
lanePageExists,
lanePagesInStore,
listLaneFiles,
moveLanePage,
parseLanePage,
writeLaneText,
} from "../store/lane-pages.ts";
export interface IntentionChain {
readonly scope: string;
readonly version: number;
readonly updatedAt: string;
readonly agent: string;
/** Current intention text (without the history trail). */
readonly text: string;
/** History lines, newest first. */
readonly history: ReadonlyArray<string>;
readonly path: string;
}
export interface SetIntentionInput {
readonly scope: string;
readonly text: string;
readonly agent: string;
readonly now?: Date;
}
export interface MoveIntentionInput {
readonly scope: string;
readonly now?: Date;
}
export interface MoveIntentionResult {
readonly scope: string;
readonly archivePath: string;
}
const HISTORY_HEADER = "## History";
const HISTORY_SNIPPET_CHARS = 120;
/** Where the active chains live, vault-relative. */
const INTENTIONS_REL = "Brain/intentions";
function intentionsDir(vault: string): string {
return join(vault, INTENTIONS_REL);
}
function intentionPath(vault: string, scope: string): string {
return join(intentionsDir(vault), `${scope}.md`);
}
/** The vault-relative page a scope label names, after the scope fold. */
export function intentionRel(scope: string): string {
return posix.join(INTENTIONS_REL, `${resolveSessionScope(scope)}.md`);
}
/**
* The vault-relative page of a listed chain, by its file stem as it is on
* disk. A hand-written chain's name need not be scope-shaped, so a listing
* judges the file it read rather than the scope fold of its name.
*/
export function intentionStemRel(stem: string): string {
return posix.join(INTENTIONS_REL, `${stem}.md`);
}
/** `move` found no active chain for the scope. */
export function noActiveIntentionError(scope: string): Error {
return new Error(`no active intention for scope: ${scope}`);
}
function renderChain(chain: Omit<IntentionChain, "path">): string {
const history =
chain.history.length === 0
? ""
: `\n${HISTORY_HEADER}\n\n${chain.history.map((line) => `- ${line}`).join("\n")}\n`;
// The agent name is caller-supplied: JSON.stringify-quote it so
// YAML-significant characters cannot corrupt the chain file
// (parseFrontmatter strips the quotes on read).
return [
"---",
`scope: ${chain.scope}`,
`version: ${chain.version}`,
`updated_at: ${chain.updatedAt}`,
`agent: ${JSON.stringify(chain.agent)}`,
"---",
"",
chain.text,
history,
].join("\n");
}
function parseChain(vault: string, scope: string): IntentionChain | null {
const path = intentionPath(vault, scope);
if (!lanePageExists(vault, path)) return null;
const [meta, body] = parseLanePage(vault, path);
const versionRaw = meta["version"];
const version =
typeof versionRaw === "string" && /^[0-9]+$/.test(versionRaw)
? Number.parseInt(versionRaw, 10)
: 1;
// Match the trail as a real heading line, not a substring, so
// intention text that merely mentions "## History" is never split.
const headerMatch = /^## History$/mu.exec(body);
const headerIndex = headerMatch?.index ?? -1;
const text = (headerIndex < 0 ? body : body.slice(0, headerIndex)).trim();
const history: string[] = [];
if (headerIndex >= 0) {
for (const line of body.slice(headerIndex + HISTORY_HEADER.length).split("\n")) {
const trimmed = line.trim();
if (trimmed.startsWith("- ")) history.push(trimmed.slice(2));
}
}
return Object.freeze({
scope,
version,
updatedAt: typeof meta["updated_at"] === "string" ? meta["updated_at"] : "",
agent: typeof meta["agent"] === "string" ? meta["agent"] : "",
text,
history: Object.freeze(history),
path,
});
}
/** Create or update the scoped intention; prior text lands in history. */
export function setIntention(vault: string, input: SetIntentionInput): IntentionChain {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertLaneWrite(vault);
const scope = resolveSessionScope(input.scope);
const now = input.now ?? new Date();
const text = input.text.trim();
if (text.length === 0) throw new Error("intention text must not be empty");
const prior = parseChain(vault, scope);
const history =
prior === null
? []
: [
`v${prior.version} (${prior.updatedAt}): ${prior.text.replace(/\s+/gu, " ").slice(0, HISTORY_SNIPPET_CHARS)}`,
...prior.history,
];
const chain = {
scope,
version: (prior?.version ?? 0) + 1,
updatedAt: isoSecond(now),
agent: input.agent,
text,
history: Object.freeze(history),
};
const path = intentionPath(vault, scope);
writeLaneText(vault, path, renderChain(chain));
return Object.freeze({ ...chain, path });
}
/** Current chain for a scope, or null. */
export function showIntention(vault: string, scope: string): IntentionChain | null {
return parseChain(vault, resolveSessionScope(scope));
}
/** Active chains sorted by scope. History entries are excluded. */
export function listIntentions(vault: string): IntentionChain[] {
const dir = intentionsDir(vault);
if (!lanePageExists(vault, dir)) return [];
const out: IntentionChain[] = [];
for (const name of listLaneFiles(vault, dir)) {
const chain = parseChain(vault, name.replace(/\.md$/u, ""));
if (chain !== null) out.push(chain);
}
return out.toSorted((a, b) => (a.scope < b.scope ? -1 : a.scope > b.scope ? 1 : 0));
}
/** Retire a chain into Brain/intentions/history/ and clear the active file. */
export function moveIntentionToHistory(
vault: string,
input: MoveIntentionInput,
): MoveIntentionResult {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertLaneWrite(vault);
const scope = resolveSessionScope(input.scope);
const now = input.now ?? new Date();
const activePath = intentionPath(vault, scope);
if (!lanePageExists(vault, activePath)) {
throw noActiveIntentionError(scope);
}
const historyDir = join(intentionsDir(vault), "history");
const base = `${scope}-${isoDate(now)}`;
let archivePath = join(historyDir, `${base}.md`);
for (let suffix = 2; lanePageExists(vault, archivePath); suffix++) {
archivePath = join(historyDir, `${base}-${suffix}.md`);
}
if (lanePagesInStore(vault)) {
// A store-only machine: one move record pair, no file in the vault.
moveLanePage(vault, activePath, archivePath);
} else {
mkdirSync(historyDir, { recursive: true });
try {
renameWithRetry(activePath, archivePath);
} catch {
// Cross-device fallback: copy then remove.
atomicWriteFileSync(archivePath, readFileSync(activePath, "utf8"));
rmSync(activePath, { force: true });
}
}
return Object.freeze({ scope, archivePath });
}