A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
/**
* The vault memory layer — retrieval.
*
* Deliberately a separate module from the write path. They have different
* failure modes: a bad write costs one note, while a bad read puts another
* project's context into this session and is acted on as if it applied. Keeping
* them apart means the visibility rule can be reasoned about — and hammered —
* alone.
*
* THE PRECISION PROBLEM
*
* Retrieval has two failure modes pulling in opposite directions:
*
* false positive — a memory from an unrelated project surfaces. The expensive
* one: it is how a session gets "reminded" of a constraint
* that does not apply, and how one client's context reaches
* another's.
* false negative — a memory that would have helped stays hidden. Cheap in
* isolation, but it is the entire value proposition; a memory
* layer nobody's session ever sees is an expensive no-op.
*
* The resolution: reach is DECLARED at write time (`scope`) rather than guessed
* at read time. A reader never widens what a writer declared.
*/
import { readFileSync, readdirSync, statSync, existsSync } from "node:fs";
import { join } from "node:path";
import { MEMORY_ROOT, MEMORY_SOURCE, AGENT_SOURCES } from "./memory-write.ts";
import { parsePromotedMarker, type PromotedRef } from "./memory-promoted.ts";
import { supersedeResolver } from "./memory-supersede.ts";
// Re-exported so a reader can take the marker from the module it reads with,
// while the writer that stamps it stays the one place it is defined.
export { MEMORY_SOURCE };
export interface Facets {
readonly scope: string;
readonly projects: string[];
readonly platforms: string[];
readonly confidence: string;
readonly flags: string[];
readonly origin: string | null;
readonly date: string | null;
/** ISO timestamp of the write; breaks ties within a day. */
readonly session: string | null;
readonly superseded_by: string[];
readonly source: string | null;
/**
* The `brain/` note this capture was promoted into, if any.
*
* `recall` reads only the memory root and `search`/`expand` see everything
* but, so the two surfaces are disjoint: a promoted lesson exists twice, and
* a foreign repo can only ever reach this copy. That copy is the raw capture,
* which may predate a correction the promoted version has already had swept
* through it.
*
* Since v8.3.0 an ANCHORED marker closes that gap: `resolvePromotedRef` serves
* the promoted block itself, through the capture that still declares the
* reach. A bare `promoted: <note>` keeps the older behaviour of naming the
* corrected version without serving it, which stays legitimate — serving is a
* separate and deliberate act, and requiring an anchor would push one onto
* captures whose promoted block is not fit to leave the vault.
*
* **Parsed here so the marker format has ONE definition.** It had three — this
* field as a raw string, `parsePromotedMarker`, and a regex in
* `active-hygiene.ts` — and three parsers for one format drift the moment any
* one of them is edited. (#183)
*/
readonly promoted: PromotedRef | null;
/**
* The marker exactly as written, kept because `null` above is ambiguous.
*
* A capture with NO marker and a capture whose marker the parser REJECTED — a
* stray control character, a non-string — both parse to `null`, and only the
* second is a defect worth reporting. After the parse there is nothing left to
* tell them apart, so the raw string is carried alongside.
*/
readonly promotedRaw: string | null;
}
export interface Caller {
readonly project?: string | null;
readonly platforms?: readonly string[];
}
export interface MemoryEntry {
readonly rel: string;
readonly full: string;
readonly facets: Facets;
readonly title: string | null;
readonly body: string;
readonly why?: string;
}
// ---------------------------------------------------------------------------
// Frontmatter
// ---------------------------------------------------------------------------
/**
* Parse the subset of YAML this layer writes. Not a general parser on purpose:
* we own the writer, so supporting arbitrary YAML would be surface area with no
* caller. Anything unrecognised is ignored rather than guessed at.
*
* Returns `{}` for a file with no frontmatter — such a file is simply not a
* memory, and must not throw its way into a retrieval path.
*/
export function parseFrontmatter(md: unknown): Record<string, string | string[]> {
const m = String(md ?? "").match(/^---\r?\n([\s\S]*?)\r?\n---/);
if (!m) return {};
const out: Record<string, string | string[]> = {};
for (const line of (m[1] ?? "").split(/\r?\n/)) {
const kv = line.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);
if (!kv) continue;
const key = kv[1]!;
const raw = (kv[2] ?? "").trim();
if (raw === "") continue;
if (raw.startsWith("[") && raw.endsWith("]")) {
const inner = raw.slice(1, -1).trim();
out[key] = inner ? splitInlineList(inner).map((p) => unquote(p.trim())).filter(Boolean) : [];
} else {
out[key] = unquote(raw);
}
}
return out;
}
/**
* Split a YAML inline list on its SEPARATORS.
*
* A blind `split(",")` reads a comma inside a quoted scalar as a separator,
* and that severs precisely the entries this layer cannot afford to lose.
* `superseded_by` is the one list key whose entries are free prose: the
* `remember` contract asks for a lesson "stated as a claim", and claims take
* commas at an ordinary rate. Splitting one produces fragments carrying stray
* quote characters, so neither half can ever match a real title, and no author
* could hand-write a title that survives.
*
* The other list keys escaped this because `projects` and `platforms` are
* slug-validated at write time and `tags` are slugs by convention. It was never
* that commas are rare, only that everywhere else they are rejected before
* being written.
*
* Tracking quote state is sufficient here because this parser reads what this
* repo writes: `addToFrontmatterList` emits `JSON.stringify(value)`, so a
* backslash escape consumed whole inside a double-quoted scalar means neither
* `\"` nor `\\` can hide a separator or invent one. The single-quoted branch is
* carried for hand-written frontmatter, which `unquote` already accepts.
*/
function splitInlineList(inner: string): string[] {
const out: string[] = [];
let cur = "";
let quote: '"' | "'" | null = null;
for (let i = 0; i < inner.length; i++) {
const ch = inner[i]!;
if (quote === null) {
if (ch === '"' || ch === "'") quote = ch;
else if (ch === ",") {
out.push(cur);
cur = "";
continue;
}
} else if (ch === "\\" && quote === '"' && i + 1 < inner.length) {
cur += ch + inner[++i]!;
continue;
} else if (ch === quote) {
quote = null;
}
cur += ch;
}
out.push(cur);
return out;
}
function unquote(s: string): string {
const t = String(s).trim();
if (t.length >= 2 && t.startsWith('"') && t.endsWith('"')) {
try {
return JSON.parse(t) as string;
} catch {
return t.slice(1, -1);
}
}
if (t.length >= 2 && t.startsWith("'") && t.endsWith("'")) return t.slice(1, -1);
return t;
}
/** Normalize a parsed memory's facets so the visibility rule sees one shape. */
export function facetsOf(fm: Record<string, unknown> | null | undefined): Facets {
const list = (v: unknown): string[] =>
Array.isArray(v) ? v.filter(Boolean).map(String) : v ? [String(v)] : [];
const str = (v: unknown): string | null => (typeof v === "string" ? v : null);
return {
scope: typeof fm?.scope === "string" ? fm.scope : "project",
projects: list(fm?.projects),
platforms: list(fm?.platforms),
confidence: typeof fm?.confidence === "string" ? fm.confidence : "unverified",
flags: list(fm?.flags),
origin: str(fm?.origin),
date: str(fm?.date),
session: str(fm?.session),
superseded_by: list(fm?.superseded_by),
source: str(fm?.source),
promoted: parsePromotedMarker(fm?.promoted),
promotedRaw: str(fm?.promoted),
};
}
// ---------------------------------------------------------------------------
// Visibility — the precision rule
// ---------------------------------------------------------------------------
const eq = (a: unknown, b: unknown): boolean => String(a).toLowerCase() === String(b).toLowerCase();
const overlaps = (a: readonly string[], b: readonly string[]): boolean =>
a.some((x) => b.some((y) => eq(x, y)));
/**
* Is this memory visible to this caller? Evaluated in order, and the ORDER is
* the design:
*
* 1. `general` reaches everyone. The only scope that does, which is why
* write-side narrowing polices it so hard.
* 2. An explicit project listing always wins. If a memory names your project
* you see it, regardless of its declared scope — this is what makes the
* multi-project case work: `projects: [a, b]` reaches both, and neither has
* to know the other exists.
* 3. `platform` scope reaches any caller sharing a platform. The "same
* platform, different project" case: an iOS lesson learned in one app
* should reach the next iOS app and must NOT reach the web one.
* 4. Otherwise: not visible. Default deny — a memory with no matching facet
* stays put rather than surfacing on a near-miss.
*
* A caller with no identity (no MCP roots) sees only `general`. That is the
* safest reading of "I don't know who you are", and it degrades to useless
* rather than to wide-open.
*/
export function isVisibleTo(facets: Facets | null | undefined, caller: Caller | null | undefined): boolean {
const f = facets;
const project = caller?.project ?? null;
const platforms = Array.isArray(caller?.platforms) ? caller.platforms : [];
if (f?.scope === "general") return true;
if (project && (f?.projects ?? []).some((p) => eq(p, project))) return true;
if (f?.scope === "platform" && overlaps(f?.platforms ?? [], platforms)) return true;
return false;
}
/**
* Why a memory was or was not shown.
*
* Retrieval that cannot explain itself is impossible to debug and impossible to
* trust — and every failure in this layer presents identically as "no results".
* This string is what tells a renamed folder apart from an empty vault.
*/
export function visibilityReason(facets: Facets | null | undefined, caller: Caller | null | undefined): string {
const f = facets;
const project = caller?.project ?? null;
const platforms = Array.isArray(caller?.platforms) ? caller.platforms : [];
if (f?.scope === "general") return "general scope reaches every caller";
if (project && (f?.projects ?? []).some((p) => eq(p, project))) {
return `explicitly lists project "${project}"`;
}
if (f?.scope === "platform" && overlaps(f?.platforms ?? [], platforms)) {
return `platform scope overlaps caller platforms [${platforms.join(", ")}]`;
}
if (!project && platforms.length === 0) {
return "caller has no identity; only general memories are visible";
}
return `no facet matches caller (project="${project}", platforms=[${platforms.join(", ")}])`;
}
/** How `explain` names this exclusion, kept apart from the scope reasons. */
export const SUPERSEDED_OUT_OF_REACH = "superseded by a memory this caller cannot see";
/**
* Does this memory's replacement fail to reach where the memory itself reaches?
*
* Sinking a superseded memory is safe only while the reader can see what
* replaced it, ranked above. When a correction NARROWS reach — which is one of
* the most useful things a correction can do, a `general` lesson re-filed as
* `platform` once recognised as platform-specific — the original survives
* carrying the wider scope, and the caller the correction was written to
* exclude keeps receiving the retired claim. The narrower correction is
* precisely the half that got scoped away, so it is not returned alongside it.
*
* Serving the stale half ALONE is worse than serving neither: there is nothing
* above it, no signal it was retired, and no access to what replaced it.
*
* An unresolvable `superseded_by` claim leaves the memory visible. Reach is
* declared at write time, and a title matching nothing is metadata rot rather
* than a reach decision — withholding on it would silently lose a real memory
* to a typo.
*/
export function supersededOutOfReach(
entry: MemoryEntry,
corpus: readonly MemoryEntry[],
caller: Caller,
): boolean {
// A memory that never reached this caller is a SCOPE answer. Reporting it as
// a supersession one would send the reader after the wrong thing.
if (!isVisibleTo(entry.facets, caller)) return false;
return !servedAfterSupersession(corpus, caller).has(entry.rel);
}
/**
* Whether `a` was provably written before `b`: by the write's session
* timestamp where both have one, else by date. A side with neither, or a
* same-day pair missing a timestamp, is not provably older, so it is never
* ruled out. `session` is UTC and `date` the writer's local day, which across
* time zones can run ahead of a later write's, hence the timestamp first.
* `rankMemories` orders recency by date, then session; the two agree except
* across time zones and where a value is missing, which ranking sorts oldest.
*/
function olderThan(a: Facets, b: Facets): boolean {
const [ta, tb] = [Date.parse(a.session ?? ""), Date.parse(b.session ?? "")];
if (!Number.isNaN(ta) && !Number.isNaN(tb)) return ta < tb;
if (!a.date || !b.date) return false;
return a.date < b.date;
}
/**
* The rels that survive both filters, resolved together rather than in sequence.
*
* Asking only whether a replacement is *scope-visible* is one link short of the
* invariant. The served set is filtered by visibility AND by this rule, so a
* replacement can pass `isVisibleTo` and still be removed by the very rule being
* evaluated. With `A superseded_by B`, `B superseded_by C`, A and B general and C
* re-filed narrow, a caller outside C's reach kept A: B is visible so A was
* served, while B was withheld for its own correction being out of reach. The
* retired claim was served alone, which is the exact failure the rule exists to
* prevent. Two re-files is not exotic — narrowing is what a correction most
* usefully does, and the second narrowing is what re-opens it.
*
* Computed as a GREATEST fixpoint: begin with everything visible and remove only
* what is provably unserved. Two properties follow, and both are the reason for
* this direction rather than the least fixpoint.
*
* It terminates, because the set only ever shrinks.
*
* And a supersession CYCLE keeps its members rather than losing them. `X`
* superseding `Y` while `Y` supersedes `X` is metadata rot, not a reach
* decision, and the least fixpoint would answer it by withholding both — the
* same silent loss the unresolvable-claim escape hatch was written to avoid.
* Starting from visible and removing only on proof means neither is dropped
* because the other could not first be proven.
*/
export function servedAfterSupersession(
corpus: readonly MemoryEntry[],
caller: Caller,
): Set<string> {
const served = new Set<string>();
for (const e of corpus) if (isVisibleTo(e.facets, caller)) served.add(e.rel);
// Resolved ONCE, before the loop. Which memories a claim points at does not
// depend on what is currently served, so recomputing it every pass buys
// nothing and costs a factor of n: each pass becomes O(n²) and the fixpoint
// O(n³). Measured on a worst-case chain, where every pass retires exactly one
// link, that is 12s at 2000 memories against ~30ms hoisted.
const resolve = supersedeResolver(corpus);
const replacements = new Map<string, string[]>();
for (const entry of corpus) {
if (entry.facets.superseded_by.length === 0) continue;
// A correction that keeps its title makes the claim name the memory
// itself, and anything older under that title (#364). Neither replaces
// it: the memory itself is always served, so counting it would never
// withhold the stale copy, and an older one would let two retired copies
// keep each other served.
const matched = resolve(entry.facets.superseded_by).matched.filter(
(m) => m !== entry && !olderThan(m.facets, entry.facets),
);
// Unresolvable claims leave the memory alone, per the rule above, so they
// are never entered here and can never be withheld.
if (matched.length === 0) continue;
replacements.set(entry.rel, matched.map((m) => m.rel));
}
for (;;) {
let removed = false;
for (const [rel, reps] of replacements) {
if (!served.has(rel)) continue;
if (reps.some((r) => served.has(r))) continue;
served.delete(rel);
removed = true;
}
if (!removed) return served;
}
}
// ---------------------------------------------------------------------------
// Ranking
// ---------------------------------------------------------------------------
/**
* Specificity first, then recency.
*
* A memory naming your project is more likely to matter than one that happens to
* share a platform, which in turn beats a general one. Ranking by relevance
* alone would bury the precise hit under the broad ones exactly when the caller
* needs it most.
*/
export function specificity(facets: Facets | null | undefined, caller: Caller | null | undefined): number {
const project = caller?.project ?? null;
if (project && (facets?.projects ?? []).some((p) => eq(p, project))) {
// A memory naming ONLY your project is more specific than one naming five.
return 100 - Math.min(20, (facets?.projects ?? []).length);
}
if (facets?.scope === "platform") return 50;
if (facets?.scope === "general") return 10;
return 0;
}
/**
* Superseded memories sink rather than disappear: the correction is what you
* want, but the history is occasionally what you need.
*/
export function rankMemories<T extends { facets: Facets }>(entries: readonly T[], caller: Caller): T[] {
return [...entries].sort((a, b) => {
const supA = a.facets.superseded_by.length > 0 ? 1 : 0;
const supB = b.facets.superseded_by.length > 0 ? 1 : 0;
if (supA !== supB) return supA - supB;
const s = specificity(b.facets, caller) - specificity(a.facets, caller);
if (s !== 0) return s;
const byDate = String(b.facets.date ?? "").localeCompare(String(a.facets.date ?? ""));
if (byDate !== 0) return byDate;
// `date` is day-granular, so same-day memories would otherwise sort
// arbitrarily and a just-written one could fall outside the caller's limit
// entirely. `session` is the ISO timestamp of the write.
return String(b.facets.session ?? "").localeCompare(String(a.facets.session ?? ""));
});
}
// ---------------------------------------------------------------------------
// IO shell
// ---------------------------------------------------------------------------
/** Walk the memory tree. Shallow by design: `root/YYYY/MM/*.md`, nothing deeper. */
export function listMemoryFiles(vaultRoot: string, root: string = MEMORY_ROOT): { rel: string; full: string }[] {
const base = join(vaultRoot, root);
if (!existsSync(base)) return [];
const out: { rel: string; full: string }[] = [];
for (const year of safeDirs(base)) {
for (const month of safeDirs(join(base, year))) {
const dir = join(base, year, month);
let names: string[];
try {
names = readdirSync(dir);
} catch {
continue;
}
for (const name of names) {
if (name.endsWith(".md")) out.push({ rel: `${root}/${year}/${month}/${name}`, full: join(dir, name) });
}
}
}
return out;
}
function safeDirs(dir: string): string[] {
try {
// Dirents answer isDirectory() from the listing itself, so an ordinary
// folder costs no stat — and this runs on every read of the store.
//
// A symlink still needs one. `Dirent` reports a link-to-directory as
// isSymbolicLink() and NOT isDirectory(), so filtering on isDirectory()
// alone silently skips it: every memory under `memories/2025 -> /archive`
// disappears from recall, from the duplicate scan and from `health`, with
// no warning anywhere. The stat is paid only for links.
return readdirSync(dir, { withFileTypes: true })
.filter((e) => {
if (e.isDirectory()) return true;
if (!e.isSymbolicLink()) return false;
try {
return statSync(join(dir, e.name)).isDirectory();
} catch {
return false; // broken link
}
})
.map((e) => e.name);
} catch {
return [];
}
}
/**
* Parse one file from the store.
*
* The single parse implementation, so the cache in `memory-index.ts` and a cold
* read cannot drift into producing different entries from the same bytes.
*/
export function parseMemory(rel: string, full: string, md: string): MemoryEntry {
const heading = md.match(/^#\s+(.+)$/m);
return {
rel,
full,
facets: facetsOf(parseFrontmatter(md)),
title: heading ? (heading[1] ?? "").trim() : null,
// The body travels with the entry. A caller past the visibility rule has
// earned the content, and the memory root is not in the resource-exposure
// list anyway — so a pointer-only result hands back a path it cannot open.
body: md
.replace(/^---[\s\S]*?\r?\n---\r?\n/, "")
.replace(/^#\s+.*$/m, "")
.trim(),
};
}
/**
* Read and parse one file from the store, or null if it cannot be read.
*
* Shared by the cold path below and by the cache in `memory-index.ts`, so the
* two cannot drift on what counts as unreadable.
*/
export function readMemoryFile(file: { rel: string; full: string }): MemoryEntry | null {
try {
return parseMemory(file.rel, file.full, readFileSync(file.full, "utf8"));
} catch {
return null; // an unreadable file must not take down retrieval
}
}
/** Read and parse the whole store. The uncached path. */
export function readMemories(vaultRoot: string, root: string = MEMORY_ROOT): MemoryEntry[] {
const out: MemoryEntry[] = [];
for (const file of listMemoryFiles(vaultRoot, root)) {
const entry = readMemoryFile(file);
if (entry) out.push(entry);
}
return out;
}
/**
* The subset of a store that is agent-written.
*
* A human note that wandered into the memory folder is left alone rather than
* silently governed by these rules. One predicate, so "what counts as a memory"
* is answered in a single place.
*/
export function agentMemories(entries: readonly MemoryEntry[]): MemoryEntry[] {
// Both agent sources count. A capture the tool refused is what a session
// writes when the lesson is worth keeping anyway; excluding it meant the
// honest label cost the memory its whole audience, which punishes exactly the
// behaviour that saved the lesson. A note with any OTHER source, or none, is
// still left alone — that is the rule this predicate is for.
return entries.filter((m) => AGENT_SOURCES.includes(String(m.facets.source)));
}
/**
* Apply the visibility rule and rank what survives. PURE — no filesystem.
*
* This is the whole of recall's decision-making. `recall` below is the thin IO
* wrapper that feeds it from disk; the server feeds it from its parse cache.
*
* Taking a pre-parsed list as an OPTIONAL argument alongside `vaultRoot` and
* `root` was designed and rejected: it left both of those dead on every
* production call, and made it possible to hand in entries read from one root
* while naming another, with nothing able to notice.
*
* `explain` attaches the visibility reason to each entry AND returns the
* withheld ones with theirs — used to prove a memory was excluded deliberately
* rather than missed by accident.
*/
export function recallFrom(
entries: readonly MemoryEntry[],
caller: Caller,
opts?: { explain?: false },
): MemoryEntry[];
export function recallFrom(
entries: readonly MemoryEntry[],
caller: Caller,
opts: { explain: true },
): { visible: MemoryEntry[]; withheld: MemoryEntry[] };
export function recallFrom(
entries: readonly MemoryEntry[],
caller: Caller,
{ explain = false }: { explain?: boolean } = {},
): MemoryEntry[] | { visible: MemoryEntry[]; withheld: MemoryEntry[] } {
const visible: MemoryEntry[] = [];
const withheld: MemoryEntry[] = [];
// Judged against the agent corpus rather than the raw entries, so a claim is
// resolved against the set `recall` can actually serve.
const corpus = agentMemories(entries);
// Resolved once for the whole corpus rather than per entry: the answer for
// one memory depends on the answer for its replacement, so it is a property
// of the set and not of the row.
const served = servedAfterSupersession(corpus, caller);
for (const entry of corpus) {
const facets = entry.facets;
if (!isVisibleTo(facets, caller)) {
if (explain) withheld.push({ ...entry, why: visibilityReason(facets, caller) });
continue;
}
// Checked after visibility so the two kinds of exclusion stay
// distinguishable: a memory that never reached this caller is a scope
// answer, not a supersession one.
if (!served.has(entry.rel)) {
if (explain) {
// Name what replaced it, not just that something did. This is the
// one exclusion the reader cannot resolve by looking: the superseding
// memory is out of their scope, so it is absent from the very result
// they are reading, and finding it otherwise means a second query
// from a different identity, guessing at what to search for. The
// title is already on the withheld entry, so naming it costs nothing
// and discloses nothing the entry did not already carry.
//
// The constant stays the PREFIX so the two exclusion kinds remain
// distinguishable by their opening words, which is what `explain` is
// for. Empty claim lists fall back to the bare constant rather than
// emitting empty parentheses.
const by = entry.facets.superseded_by;
withheld.push({
...entry,
why: by.length ? `${SUPERSEDED_OUT_OF_REACH} (${by.join("; ")})` : SUPERSEDED_OUT_OF_REACH,
});
}
continue;
}
visible.push(explain ? { ...entry, why: visibilityReason(facets, caller) } : entry);
}
const ranked = rankMemories(visible, caller);
return explain ? { visible: ranked, withheld } : ranked;
}
/**
* Load every memory visible to this caller, ranked. The IO wrapper.
*
* No production caller: the server reads through `memory-index`. This is the
* on-disk oracle those cache tests assert equality against, so a dead-code sweep
* that removes it takes the equivalence guarantee with it.
*/
export function recall(
vaultRoot: string,
caller: Caller,
opts?: { root?: string; explain?: false },
): MemoryEntry[];
export function recall(
vaultRoot: string,
caller: Caller,
opts: { root?: string; explain: true },
): { visible: MemoryEntry[]; withheld: MemoryEntry[] };
export function recall(
vaultRoot: string,
caller: Caller,
{ root = MEMORY_ROOT, explain = false }: { root?: string; explain?: boolean } = {},
): MemoryEntry[] | { visible: MemoryEntry[]; withheld: MemoryEntry[] } {
const entries = readMemories(vaultRoot, root);
return explain ? recallFrom(entries, caller, { explain: true }) : recallFrom(entries, caller);
}