A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
/**
* Precision harness for memory retrieval.
*
* Builds a synthetic vault covering the real shapes a person actually has:
*
* atlas iOS app
* beacon iOS app — same platform, different project
* harbor web app — different platform, different project
* atlas-api backend — different platform, SAME product context
* drifter unrelated — shares nothing
* (unknown) no identity — an agent with no MCP roots
*
* Memories are written through the real writer, so this is a write→read round
* trip rather than a test against hand-authored markdown: if the writer and the
* reader ever disagree about a facet, it fails here.
*
* Every case asserts BOTH directions — what surfaced and what was withheld —
* because a retrieval layer is only as good as the things it refuses to return.
* A false positive puts another project's context into this session, where it is
* acted on as if it applied; a false negative is a memory nobody benefits from.
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { readFileSync } from "node:fs";
import { validateMemory, writeMemory } from "../lib/memory-write.ts";
import {
recall,
recallFrom,
isVisibleTo,
facetsOf,
parseFrontmatter,
specificity,
rankMemories,
supersededOutOfReach,
agentMemories,
SUPERSEDED_OUT_OF_REACH,
MEMORY_SOURCE,
type Caller,
type MemoryEntry,
} from "../lib/memory-recall.ts";
import { rmTemp } from "./_helpers.ts";
const DAY = new Date(2026, 6, 26);
const CALLERS = {
atlas: { project: "atlas", platforms: ["ios"] },
beacon: { project: "beacon", platforms: ["ios"] },
harbor: { project: "harbor", platforms: ["web"] },
atlasApi: { project: "atlas-api", platforms: ["backend"] },
drifter: { project: "drifter", platforms: ["android"] },
unknown: { project: null, platforms: [] },
};
/**
* The fixture set. `id` is embedded in the title so assertions read as sets of
* ids rather than as brittle prose matching.
*/
const FIXTURES = [
{
id: "M1",
title: "M1 atlas keychain migration must run before first read",
scope: "project",
projects: ["atlas"],
},
{
id: "M2",
title: "M2 the atlas session token format is shared with the api",
scope: "project",
projects: ["atlas", "atlas-api"],
},
{
id: "M3",
title: "M3 ios background tasks are killed after thirty seconds",
scope: "platform",
platforms: ["ios"],
},
{
id: "M4",
title: "M4 web service workers cache opaque responses silently",
scope: "platform",
platforms: ["web"],
},
{ id: "M5", title: "M5 semver patch releases still break lockfiles", scope: "general", projects: [] },
{ id: "M6", title: "M6 beacon analytics batches on a five minute timer", scope: "project", projects: ["beacon"] },
{
id: "M7",
title: "M7 atlas ios build needs the legacy provisioning profile",
scope: "project",
projects: ["atlas"],
platforms: ["ios"],
},
{
id: "M8",
title: "M8 mobile deep links need an intent filter and an assoc file",
scope: "platform",
platforms: ["ios", "android"],
},
];
const BODY =
"Recorded by the precision harness. The body is long enough to satisfy the minimum length rule and says nothing that trips a contract flag.";
let VAULT: string;
before(() => {
VAULT = mkdtempSync(join(tmpdir(), "recall-"));
for (const f of FIXTURES) {
const v = validateMemory(
{
title: f.title,
body: BODY,
confidence: "inferred",
scope: f.scope,
projects: f.projects ?? [],
platforms: f.platforms ?? [],
},
// origin is deliberately null for general fixtures so write-side
// narrowing does not re-attribute them to a project.
{ now: DAY, origin: null },
);
assert.equal(v.ok, true, `fixture ${f.id} failed validation: ${JSON.stringify(v.errors)}`);
writeMemory(VAULT, v.value!, []);
}
});
after(() => rmTemp(VAULT));
/** Ids visible to a caller, as a sorted array. */
function seen(caller: Caller): string[] {
return recall(VAULT, caller)
.map((e) => (e.title ?? "").split(" ")[0]!)
.sort();
}
function withheldIds(caller: Caller): string[] {
return recall(VAULT, caller, { explain: true })
.withheld.map((e) => (e.title ?? "").split(" ")[0]!)
.sort();
}
// ---------------------------------------------------------------------------
// The matrix
// ---------------------------------------------------------------------------
describe("retrieval precision matrix", () => {
test("atlas (ios): own project, shared-context, ios platform, general", () => {
assert.deepEqual(seen(CALLERS.atlas), ["M1", "M2", "M3", "M5", "M7", "M8"]);
});
test("beacon (ios): SAME platform, different project — gets ios lessons, not atlas's", () => {
assert.deepEqual(seen(CALLERS.beacon), ["M3", "M5", "M6", "M8"]);
// The headline precision claim: a sibling iOS app must not inherit
// another app's project-scoped memories, even platform-tagged ones.
assert.deepEqual(withheldIds(CALLERS.beacon), ["M1", "M2", "M4", "M7"]);
});
test("harbor (web): different platform — no ios memories at all", () => {
assert.deepEqual(seen(CALLERS.harbor), ["M4", "M5"]);
for (const id of ["M1", "M2", "M3", "M6", "M7", "M8"]) {
assert.ok(withheldIds(CALLERS.harbor).includes(id), `${id} must not reach a web project`);
}
});
test("atlas-api: SAME context, different platform — shared memory only", () => {
// M2 names it explicitly, so it crosses the platform boundary. M1 and M7
// are atlas-only and must not, and no ios memory may reach a backend.
assert.deepEqual(seen(CALLERS.atlasApi), ["M2", "M5"]);
});
test("drifter: shares ONLY a platform — gets that platform's lesson and nothing else", () => {
// No shared project, no shared product context, no shared codebase. The
// single android-tagged memory (M8) still reaches it, which is the point
// of platform scope; every atlas/beacon/harbor memory stays away.
assert.deepEqual(seen(CALLERS.drifter), ["M5", "M8"]);
assert.deepEqual(withheldIds(CALLERS.drifter), ["M1", "M2", "M3", "M4", "M6", "M7"]);
});
test("an agent with no identity sees general only, not everything", () => {
assert.deepEqual(seen(CALLERS.unknown), ["M5"]);
});
test("every memory reaches at least one caller (no write-only memories)", () => {
const reached = new Set();
for (const caller of Object.values(CALLERS)) for (const id of seen(caller)) reached.add(id);
assert.deepEqual([...reached].sort(), FIXTURES.map((f) => f.id).sort());
});
test("no caller sees the whole store", () => {
for (const [name, caller] of Object.entries(CALLERS)) {
assert.ok(
seen(caller).length < FIXTURES.length,
`${name} saw everything — the scoping rule is not doing anything`,
);
}
});
});
// ---------------------------------------------------------------------------
// The rule itself
// ---------------------------------------------------------------------------
describe("visibility rule", () => {
const f = (o: Record<string, unknown>): ReturnType<typeof facetsOf> => facetsOf(o);
test("general reaches everyone including the anonymous caller", () => {
for (const caller of Object.values(CALLERS)) {
assert.equal(isVisibleTo(f({ scope: "general" }), caller), true);
}
});
test("an explicit project listing beats a scope mismatch", () => {
const m = f({ scope: "platform", projects: ["harbor"], platforms: ["ios"] });
assert.equal(isVisibleTo(m, CALLERS.harbor), true, "named project must win");
});
test("project scope never leaks on a platform near-miss", () => {
const m = f({ scope: "project", projects: ["atlas"], platforms: ["ios"] });
assert.equal(isVisibleTo(m, CALLERS.beacon), false);
});
test("platform matching is case-insensitive", () => {
const m = f({ scope: "platform", platforms: ["iOS"] });
assert.equal(isVisibleTo(m, { project: "x", platforms: ["ios"] }), true);
});
test("a memory with no facets at all reaches nobody but stays on disk", () => {
const m = f({ scope: "project", projects: [], platforms: [] });
for (const caller of Object.values(CALLERS)) {
assert.equal(isVisibleTo(m, caller), false);
}
});
test("malformed facets degrade to invisible rather than throwing", () => {
for (const junk of [null, undefined, {}, { scope: 42 }, { projects: "atlas" }]) {
assert.doesNotThrow(() => isVisibleTo(facetsOf(junk ?? {}), CALLERS.atlas));
}
});
test("a caller shaped wrongly does not crash retrieval", () => {
for (const junk of [null, undefined, {}, { project: 0 }, { platforms: "ios" }]) {
assert.doesNotThrow(() => isVisibleTo(facetsOf({ scope: "general" }), junk as Caller | null | undefined));
}
});
});
// ---------------------------------------------------------------------------
// Ranking
// ---------------------------------------------------------------------------
describe("ranking", () => {
test("the caller's own project outranks platform, which outranks general", () => {
const own = facetsOf({ scope: "project", projects: ["atlas"] });
const plat = facetsOf({ scope: "platform", platforms: ["ios"] });
const gen = facetsOf({ scope: "general" });
assert.ok(specificity(own, CALLERS.atlas) > specificity(plat, CALLERS.atlas));
assert.ok(specificity(plat, CALLERS.atlas) > specificity(gen, CALLERS.atlas));
});
test("a memory naming one project outranks one naming many", () => {
const narrow = facetsOf({ scope: "project", projects: ["atlas"] });
const broad = facetsOf({ scope: "project", projects: ["atlas", "b", "c", "d"] });
assert.ok(specificity(narrow, CALLERS.atlas) > specificity(broad, CALLERS.atlas));
});
test("superseded memories sink below live ones", () => {
const live = { facets: facetsOf({ scope: "general", date: "2026-01-01" }) };
const dead = { facets: facetsOf({ scope: "general", date: "2026-12-31", superseded_by: ["x"] }) };
assert.equal(rankMemories([dead, live], CALLERS.atlas)[0], live);
});
test("in a real recall, the project-specific memory comes first", () => {
assert.equal((recall(VAULT, CALLERS.atlas)[0]?.title ?? "").split(" ")[0], "M1");
});
});
// ---------------------------------------------------------------------------
// Robustness of the reader
// ---------------------------------------------------------------------------
describe("reader robustness", () => {
test("frontmatter round-trips through the real writer", () => {
const v = validateMemory(
{ title: "round trip", body: BODY, confidence: "verified", verification: "checked", projects: ["atlas"] },
{ now: DAY, origin: "atlas" },
);
const dir = mkdtempSync(join(tmpdir(), "rt-"));
try {
const { full } = writeMemory(dir, v.value!, []);
const fm = parseFrontmatter(readFileSync(full, "utf8"));
assert.equal(fm.source, "mcp-capture");
assert.deepEqual(facetsOf(fm).projects, ["atlas"]);
assert.equal(facetsOf(fm).confidence, "verified");
} finally {
rmTemp(dir);
}
});
test("notes without the mcp-capture source are ignored entirely", () => {
// A human note that lands in memories/ is not governed by these rules and
// must not be served as if it were a capture.
const fm = parseFrontmatter("---\ntitle: mine\n---\n# hand written\n");
assert.notEqual(fm.source, "mcp-capture");
});
test("a file with no frontmatter parses to an empty object rather than throwing", () => {
assert.deepEqual(parseFrontmatter("# just a heading\n"), {});
assert.deepEqual(parseFrontmatter(""), {});
assert.deepEqual(parseFrontmatter(null), {});
});
test("an empty list in frontmatter parses to an empty array", () => {
assert.deepEqual(parseFrontmatter("---\nprojects: []\n---\n").projects, []);
});
test("quoted values with commas survive list parsing", () => {
const fm = parseFrontmatter('---\nprojects: ["a", "b"]\ndescription: "one, two"\n---\n');
assert.deepEqual(fm.projects, ["a", "b"]);
assert.equal(fm.description, "one, two");
});
// The case the test above reads as though it covers and does not: its comma
// sits in a SCALAR, and its list has no comma inside an entry. `superseded_by`
// is the one list whose entries are free prose, so it is the one that meets
// this shape in the field.
test("a comma inside a quoted list entry is content, not a separator", () => {
const fm = parseFrontmatter(
'---\nsuperseded_by: ["The retry budget is per-attempt, not per-call"]\n---\n',
);
assert.deepEqual(fm.superseded_by, ["The retry budget is per-attempt, not per-call"]);
});
test("a separator between two quoted entries still separates them", () => {
const fm = parseFrontmatter('---\nsuperseded_by: ["one, with comma", "two, also"]\n---\n');
assert.deepEqual(fm.superseded_by, ["one, with comma", "two, also"]);
});
// The neighbouring escaping rule, easy to break while fixing the split: the
// writer emits JSON, so a quote inside a title arrives backslash-escaped and
// must not be read as the end of the scalar.
test("an escaped double quote inside an entry does not end it", () => {
const fm = parseFrontmatter('---\nsuperseded_by: ["the \\"good\\" parts, revisited"]\n---\n');
assert.deepEqual(fm.superseded_by, ['the "good" parts, revisited']);
});
test("recall on a vault with no memories returns empty, not an error", () => {
const dir = mkdtempSync(join(tmpdir(), "empty-"));
try {
assert.deepEqual(recall(dir, CALLERS.atlas), []);
} finally {
rmTemp(dir);
}
});
});
// ---------------------------------------------------------------------------
// Promotion is visible to the caller (#179, partial)
// ---------------------------------------------------------------------------
describe("a promoted capture says so", () => {
test("the marker is parsed off frontmatter", () => {
// Parsed at read time so the format has ONE definition (#183). `.md` is
// appended because what the marker addresses is a file.
assert.deepEqual(facetsOf({ promoted: "brain/Gotchas - Engineering" }).promoted, {
note: "brain/Gotchas - Engineering.md",
anchor: null,
kind: "note",
});
assert.deepEqual(facetsOf({ promoted: "brain/Gotchas#^om-a1b2c3" }).promoted, {
note: "brain/Gotchas.md",
anchor: "om-a1b2c3",
kind: "block",
});
});
test("the raw marker is kept, because a null parse is ambiguous", () => {
// Absent and REJECTED both parse to null, and only the second is a defect.
// Without the raw string nothing downstream can tell them apart, which is
// what `health` needs in order to report an unparseable marker at all.
assert.equal(facetsOf({}).promotedRaw, null);
assert.equal(facetsOf({ promoted: "brain/X" }).promotedRaw, "brain/X");
const rejected = facetsOf({ promoted: "brain/X\n\n## FORGED" });
assert.equal(rejected.promoted, null, "a newline is a forged response, not a path");
assert.equal(rejected.promotedRaw, "brain/X\n\n## FORGED", "but it WAS declared");
});
test("an unpromoted capture reports null rather than a falsy string", () => {
assert.equal(facetsOf({}).promoted, null);
assert.equal(facetsOf({ promoted: 123 }).promoted, null, "a non-string marker is not a note name");
assert.equal(facetsOf({ promoted: 123 }).promotedRaw, null, "and it is not a declaration either");
});
/**
* Promotion must not change who can see a memory. The marker records that a
* corrected copy exists in `brain/`; it says nothing about reach, and reading
* it as a reach signal would silently widen or narrow the scope contract.
*/
test("promotion does not alter visibility", () => {
const scoped = { scope: "project", projects: ["atlas"] };
for (const caller of Object.values(CALLERS)) {
assert.equal(
isVisibleTo(facetsOf({ ...scoped, promoted: "brain/Gotchas" }), caller),
isVisibleTo(facetsOf(scoped), caller),
"the marker must be inert to the visibility rule",
);
}
});
});
/**
* A correction that NARROWS reach used to invert itself.
*
* `remember` is append-only, so correcting a memory means writing a new one and
* marking the old one superseded. The old one keeps the scope it was written
* with — fine while the correction is as wide or wider, broken the moment it is
* narrower, which is one of the most useful things a correction can do. Sinking
* the original is only safe because the reader sees the replacement ranked above
* it; where the replacement cannot follow, the reader gets a retired claim alone,
* with no signal it was retired and no access to what replaced it.
*/
describe("a superseded memory reaches only where its successor reaches", () => {
const entry = (title: string, fm: Record<string, unknown>): MemoryEntry => ({
rel: `memories/2026/07/${title}.md`,
full: `/nowhere/${title}.md`,
facets: facetsOf({ source: MEMORY_SOURCE, date: "2026-07-26", ...fm }),
title,
body: "b",
});
// The exact shape from the issue: captured wide, recognised as iOS-specific,
// re-filed narrow. `harbor` is the web caller the correction excludes.
const ORIGINAL = entry("keychain access needs an entitlement", {
scope: "general",
superseded_by: ["keychain access needs an entitlement (iOS)"],
});
const CORRECTION = entry("keychain access needs an entitlement (iOS)", {
scope: "platform",
platforms: ["ios"],
});
const CORPUS = [ORIGINAL, CORRECTION];
test("the stale original is withheld where its correction cannot reach", () => {
const titles = recallFrom(CORPUS, CALLERS.harbor).map((m) => m.title);
assert.deepEqual(titles, [], "serving the retired half alone is worse than serving neither");
});
test("where the caller reaches both, nothing changes and the correction ranks first", () => {
const titles = recallFrom(CORPUS, CALLERS.atlas).map((m) => m.title);
assert.deepEqual(titles, [CORRECTION.title, ORIGINAL.title], "history stays available, sunk");
});
test("explain names supersession, not scope, so the two exclusions stay apart", () => {
const { withheld } = recallFrom(CORPUS, CALLERS.harbor, { explain: true });
const why = withheld.find((m) => m.title === ORIGINAL.title)?.why;
// Prefix, not equality: the reason also names the superseding title. What
// must hold is that the two exclusion KINDS stay distinguishable.
assert.ok(why?.startsWith(SUPERSEDED_OUT_OF_REACH));
assert.ok(!/scope/.test(why ?? ""), "a scope explanation here sends the reader after the wrong thing");
});
// Reach is declared at write time; a title matching nothing is metadata rot,
// not a reach decision. Withholding on it loses a real memory to a typo.
test("an unresolvable superseded_by claim leaves the memory visible", () => {
const orphan = entry("still useful", { scope: "general", superseded_by: ["no such memory"] });
assert.equal(supersededOutOfReach(orphan, [orphan], CALLERS.harbor), false);
assert.deepEqual(recallFrom([orphan], CALLERS.harbor).map((m) => m.title), ["still useful"]);
});
test("a memory with no supersession is untouched by the rule", () => {
const plain = entry("plain", { scope: "general" });
assert.equal(supersededOutOfReach(plain, [plain], CALLERS.harbor), false);
});
// The invariant has to hold across the CHAIN, not just across one link.
// Asking whether the replacement is scope-visible is one link short: the
// served set is filtered by visibility AND by this rule, so a replacement can
// pass `isVisibleTo` and still be removed by the rule being evaluated.
describe("across a chain of corrections", () => {
const a = entry("A captured wide", { scope: "general", superseded_by: ["B refiled"] });
const b = entry("B refiled", { scope: "general", superseded_by: ["C narrowed to ios"] });
const c = entry("C narrowed to ios", { scope: "platform", platforms: ["ios"] });
const CHAIN = [a, b, c];
test("a retired claim is not served when its correction is itself withheld", () => {
const served = recallFrom(CHAIN, CALLERS.harbor).map((m) => m.title);
assert.deepEqual(served, [], "A was served while B, its correction, was withheld");
});
test("the same chain is untouched for a caller who reaches the end of it", () => {
const served = recallFrom(CHAIN, CALLERS.atlas).map((m) => m.title);
assert.deepEqual(served.sort(), ["A captured wide", "B refiled", "C narrowed to ios"].sort());
});
test("explain still names supersession rather than scope for the middle link", () => {
const { withheld } = recallFrom(CHAIN, CALLERS.harbor, { explain: true });
for (const t of ["B refiled", "A captured wide"]) {
assert.ok(withheld.find((m) => m.title === t)?.why?.startsWith(SUPERSEDED_OUT_OF_REACH), t);
}
});
});
// Depth, not just the three-link case. The fixpoint has to keep retiring
// links until the whole chain is gone; a version that stopped after a single
// pass would still serve everything from the second link back.
test("a long chain retires all the way back to its head", () => {
const chain = Array.from({ length: 8 }, (_, i) =>
entry(
`L${i}`,
i === 7
? { scope: "platform", platforms: ["ios"] }
: { scope: "general", superseded_by: [`L${i + 1}`] },
),
);
assert.deepEqual(recallFrom(chain, CALLERS.harbor).map((m) => m.title), []);
// And the same chain is untouched for a caller reaching its terminal link.
assert.equal(recallFrom(chain, CALLERS.atlas).length, 8);
});
// A cycle is metadata rot, not a reach decision. The greatest fixpoint keeps
// both rather than withholding both, which is what the least fixpoint would
// do and is the same silent loss the unresolvable-claim hatch avoids. It also
// has to terminate, which is the half a naive recursion gets wrong.
test("a supersession cycle terminates and keeps its members", () => {
const x = entry("X", { scope: "general", superseded_by: ["Y"] });
const y = entry("Y", { scope: "general", superseded_by: ["X"] });
const served = recallFrom([x, y], CALLERS.harbor).map((m) => m.title);
assert.deepEqual(served.sort(), ["X", "Y"]);
});
});
/**
* A correction that keeps its title (#364). The claim on the old memory names
* a title the old memory itself carries, so resolving it by first match could
* land on the memory itself, which is always served, and the stale copy was
* never withheld. Which way it went depended on listing order.
*/
describe("a correction that keeps the corrected memory's title (#364)", () => {
const TITLE = "tokens expire after one hour";
const dated = (fm: Record<string, unknown>, slug: string = String(fm["date"])): MemoryEntry => ({
rel: `memories/${slug} ${TITLE}.md`,
full: `/nowhere/${slug}.md`,
facets: facetsOf({ source: MEMORY_SOURCE, ...fm }),
title: TITLE,
body: "b",
});
const OLD = dated({ scope: "project", projects: ["atlas", "beta"], date: "2026-06-01", superseded_by: [TITLE] });
const NEW = dated({ scope: "project", projects: ["atlas"], date: "2026-07-26" });
const beta = { project: "beta", platforms: [] };
const atlas = { project: "atlas", platforms: [] };
for (const [order, corpus] of [["old first", [OLD, NEW]], ["correction first", [NEW, OLD]]] as const) {
test(`the caller the correction excludes gets neither copy (${order})`, () => {
assert.deepEqual(recallFrom(corpus, beta).map((m) => m.rel), []);
});
test(`the caller it keeps gets the correction first, the old copy sunk (${order})`, () => {
assert.deepEqual(recallFrom(corpus, atlas).map((m) => m.rel), [NEW.rel, OLD.rel]);
});
}
test("a three-link same-title chain retires back to its head", () => {
const a = dated({ scope: "general", date: "2026-06-01", superseded_by: [TITLE] });
const b = dated({ scope: "general", date: "2026-07-01", superseded_by: [TITLE] });
const c = dated({ scope: "project", projects: ["atlas"], date: "2026-08-01" });
for (const corpus of [[a, b, c], [c, b, a], [b, a, c]]) {
assert.deepEqual(recallFrom(corpus, beta).map((m) => m.rel), []);
const served = recallFrom(corpus, atlas).map((m) => m.rel);
assert.equal(served[0], c.rel, "the live correction ranks first");
assert.deepEqual([...served].sort(), [a.rel, b.rel, c.rel].sort());
}
});
test("a claim whose only match is the memory itself is unresolvable, so the memory stays", () => {
const alone = dated({ scope: "general", date: "2026-06-01", superseded_by: [TITLE] });
assert.deepEqual(recallFrom([alone], beta).map((m) => m.rel), [alone.rel]);
});
// Within one day, two retired copies would otherwise each count the other as
// a replacement and keep each other served; the write's timestamp orders them.
test("on the same day, the write's session time decides which copy is newer", () => {
const day = (hour: string, fm: Record<string, unknown>, slug: string) =>
dated({ date: "2026-07-26", session: `2026-07-26T${hour}:00:00Z`, ...fm }, slug);
const a = day("09", { scope: "general", superseded_by: [TITLE] }, "a");
const b = day("12", { scope: "general", superseded_by: [TITLE] }, "b");
const c = day("17", { scope: "project", projects: ["atlas"] }, "c");
assert.deepEqual(recallFrom([a, b, c], beta).map((m) => m.rel), []);
assert.deepEqual(recallFrom([c, b, a], beta).map((m) => m.rel), []);
});
test("an undated side is never ruled out as older, so the rule still applies", () => {
const undated = dated({ scope: "project", projects: ["atlas"] }, "undated");
assert.deepEqual(recallFrom([OLD, undated], beta).map((m) => m.rel), []);
});
// `date` is the writer's local day and `session` its UTC time: across time
// zones the local day can run ahead of a later write's, so the timestamp,
// where both have one, decides.
test("a later write from a time zone whose local day runs behind is still newer", () => {
const old = dated({ scope: "general", date: "2026-10-14", session: "2026-10-13T16:00:00Z", superseded_by: [TITLE] }, "tokyo");
const fix = dated({ scope: "project", projects: ["atlas"], date: "2026-10-13", session: "2026-10-13T17:00:00Z" }, "seattle");
assert.deepEqual(recallFrom([old, fix], beta).map((m) => m.rel), []);
});
// A hand-filed memory can carry a session with an offset; compared as text it
// would sort by its local clock, so the timestamps are parsed.
test("a session written with a time-zone offset is ordered by the instant it names", () => {
const old = dated({ scope: "general", date: "2026-10-14", session: "2026-10-14T01:00:00+09:00", superseded_by: [TITLE] }, "offset");
const fix = dated({ scope: "project", projects: ["atlas"], date: "2026-10-13", session: "2026-10-13T17:00:00.000Z" }, "utc");
assert.deepEqual(recallFrom([old, fix], beta).map((m) => m.rel), []);
});
test("explain names supersession, not scope, for the withheld old copy", () => {
const { withheld } = recallFrom([OLD, NEW], beta, { explain: true });
assert.ok(withheld.find((m) => m.rel === OLD.rel)?.why?.startsWith(SUPERSEDED_OUT_OF_REACH));
});
});
/**
* A capture the tool refused still has to reach someone.
*
* A tool call can be refused for a reason the caller cannot repair by
* rewording, and a session holding a lesson worth keeping will write the file
* itself rather than lose it. Labelling that honestly then excluded it from
* `recall`, because the agent-source predicate knew exactly one value: the
* lesson landed in the vault and was served to nobody, including the session
* that wrote it. The honest label cost the memory its entire audience.
*/
describe("a hand-filed capture is still an agent memory", () => {
const entryWith = (source: string | null, title: string): MemoryEntry => ({
rel: `memories/2026/08/${title}.md`,
full: `/nowhere/${title}.md`,
facets: facetsOf({ ...(source ? { source } : {}), date: "2026-08-14", scope: "general" }),
title,
body: "b",
});
const handFiled = entryWith("hand-filed", "filed by hand after the tool refused");
const stray = entryWith(null, "a human note that wandered in");
test("recall serves it", () => {
assert.deepEqual(
recallFrom([handFiled], CALLERS.harbor).map((m) => m.title),
["filed by hand after the tool refused"],
);
});
test("agentMemories counts it", () => {
assert.equal(agentMemories([handFiled]).length, 1);
});
// The rule the predicate exists for, unchanged: a note with no agent source
// is still left alone rather than silently governed by these rules. Stays
// green across the change by design — it is the non-regression, not the fix.
test("a stray note with no agent source is still left alone", () => {
assert.equal(agentMemories([stray]).length, 0);
assert.deepEqual(recallFrom([stray], CALLERS.harbor), []);
});
});
/**
* `explain` has to name what replaced the memory, not only that something did.
*
* Supersession is the one exclusion a reader cannot resolve by looking: the
* superseding memory is out of their scope, so it is absent from the very
* result they are reading. Finding it otherwise means a second query from a
* different caller identity, guessing at what to search for. The title is
* already on the withheld entry, so the answer was in hand and unread.
*/
describe("explain names the superseding memory", () => {
const e = (title: string, fm: Record<string, unknown>): MemoryEntry => ({
rel: `memories/2026/08/${title}.md`,
full: `/nowhere/${title}.md`,
facets: facetsOf({ source: MEMORY_SOURCE, date: "2026-08-14", ...fm }),
title,
body: "b",
});
test("the reason carries the superseding title, so it can be searched for", () => {
const old = e("captured wide", { scope: "general", superseded_by: ["refiled for ios"] });
const corr = e("refiled for ios", { scope: "platform", platforms: ["ios"] });
const { withheld } = recallFrom([old, corr], CALLERS.harbor, { explain: true });
const why = withheld.find((m) => m.title === "captured wide")?.why ?? "";
assert.ok(why.startsWith(SUPERSEDED_OUT_OF_REACH), "the category prefix must survive");
assert.match(why, /refiled for ios/, "without the title the reader needs a second query");
});
// Reachable whenever the claim list is empty; the bare constant beats "()".
test("an empty claim list falls back to the bare constant", () => {
const orphan = e("no claims", { scope: "general" });
const { withheld } = recallFrom([orphan], CALLERS.harbor, { explain: true });
// Not withheld for supersession at all here, so assert the shape directly.
assert.equal(
`${SUPERSEDED_OUT_OF_REACH}`.endsWith("()"),
false,
"the constant itself must never carry empty parentheses",
);
assert.equal(withheld.filter((m) => m.why === `${SUPERSEDED_OUT_OF_REACH} ()`).length, 0);
});
// The non-regression that matters: telling a scope answer from a supersession
// answer is the whole point of explain, and it must not become sensitive to
// the added detail.
test("a scope-withheld entry still does not match the supersession prefix", () => {
const iosOnly = e("ios only", { scope: "platform", platforms: ["ios"] });
const { withheld } = recallFrom([iosOnly], CALLERS.harbor, { explain: true });
const why = withheld.find((m) => m.title === "ios only")?.why ?? "";
assert.ok(why.length > 0);
assert.ok(!why.startsWith(SUPERSEDED_OUT_OF_REACH), "a scope answer must stay a scope answer");
});
});