Repository navigation
Description
Version
LifeOS 8.761.0 · attestation: 34 system file(s) differ from danielmiessler/LifeOS@v8.761.0:
- hooks/SatisfactionCapture.hook.ts
- hooks/README.md
- skills/CreateCLI/SKILL.md
- skills/CreateCLI/Intents/CreateCli.md
- skills/Prompting/SKILL.md
- skills/RichFormat/tests/engine.test.tsx
- skills/RichFormat/hooks/register.tsx
- skills/LifeOSHooks/hooks/lib/build.ts
- skills/Herdr/Intents/Configure.md
- skills/LifeOS/SKILL.md
- skills/LifeOS/Intents/Setup.md
- skills/Fabric/SKILL.md
- agents/Sol.md
- LIFEOS/TOOLS/VideoMeaning/README.md
- LIFEOS/TOOLS/MemoryRetriever.ts
- LIFEOS/TOOLS/models.ts
- LIFEOS/TOOLS/model-pricing.json
- LIFEOS/DOCUMENTATION/Tools/Tools.md
- LIFEOS/DOCUMENTATION/Memory/MemorySystem.md
- LIFEOS/DOCUMENTATION/Location/LocationSystem.md
- LIFEOS/DOCUMENTATION/Pulse/TerminalTabs.md
- LIFEOS/DOCUMENTATION/Pulse/PulseSystem.md
- LIFEOS/DOCUMENTATION/Workflows/WorkflowsSystem.md
- LIFEOS/DOCUMENTATION/LifeosSystemArchitecture.md
- LIFEOS/DOCUMENTATION/ARCHITECTURE_SUMMARY.md
- LIFEOS/DOCUMENTATION/Algorithm/AscentStates.md
- LIFEOS/DOCUMENTATION/Testing/TestingDoctrine.md
- LIFEOS/DOCUMENTATION/Hooks/HookSystem.md
- LIFEOS/DOCUMENTATION/Work/WorkSystem.md
- LIFEOS/DOCUMENTATION/Assay/AssaySystem.md
- LIFEOS/DOCUMENTATION/Services/BackgroundServices.md
- LIFEOS/DOCUMENTATION/Router/RouterSystem.md
- LIFEOS/ALGORITHM/AlgorithmReference.md
- LIFEOS/ERRATA/fixtures/LabelBrief.md
What is broken
The memory reviewer names each knowledge item (and each idea) in free text, and the writer stores it at slugify(name). MemorySystem.add appends to an existing note only when that exact slug already exists, and the reviewer is never shown which notes exist. So the same topic, written a little differently on different days ("Gotchas: Mac mini", "Mac mini gotchas", "mini"), becomes a new note each time. Over eight days of normal use one archive gained about 40 new Research notes, and about 25 of them overlapped an existing note's topic. Retrieval then returns fragments of one topic that contradict each other. #2131 noted the exact-path limitation for accented titles; this is the same limit for word order, prefixes and case.
Where (file:line)
LIFEOS/TOOLS/MemorySystem.ts:642
Repro on a clean tree
# Clean 8.761.0 memory files (attest: MemorySystem.ts, MemoryTypes.ts, MemoryReviewer.ts unmodified).
# The probe runs the real MemorySystem.add in a throwaway install (HOME, CLAUDE_CONFIG_DIR, CORTEX roots under a temp dir):
# seed Research/gotchas-mac-mini.md titled "Gotchas: Mac mini", then add() a knowledge item named "Mac mini gotchas".
# Expected: appended to gotchas-mac-mini.md. Actual: a second note, mac-mini-gotchas.md (exit 1).
# NOTE_HOME_TOOLS=<repo>/LifeOS/install/LIFEOS/TOOLS points it at a source tree; default is the installed tools.
cat > note-home-probe.ts <<'PROBE'
// Negative control for the note-home report: a knowledge item whose name is the
// same topic as an existing note, spelled differently ("Mac mini gotchas" vs the
// note "Gotchas: Mac mini" at gotchas-mac-mini.md), should append to that note.
// Runs the real MemorySystem.add in a throwaway install. Exit 1 = new file created (red).
// Usage: bun note-home-probe.ts <path-to-LIFEOS/TOOLS>
import { mkdtempSync, mkdirSync, symlinkSync, writeFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const tools = realpathSync(process.argv[2] ?? process.env.NOTE_HOME_TOOLS ?? join(process.env.CLAUDE_CONFIG_DIR ?? join(require("node:os").homedir(), ".claude"), "LIFEOS", "TOOLS"));
const sb = realpathSync(mkdtempSync(join(realpathSync(tmpdir()), "note-home-probe-")));
try {
const user = join(sb, ".config", "LIFEOS", "USER");
const lifeos = join(sb, ".claude", "LIFEOS");
for (const d of ["PRINCIPAL", "DIGITAL_ASSISTANT", "MEMORY/OBSERVABILITY", "MEMORY/KNOWLEDGE/Research"]) mkdirSync(join(user, d), { recursive: true });
mkdirSync(lifeos, { recursive: true });
symlinkSync(user, join(lifeos, "USER"));
symlinkSync(join(user, "MEMORY"), join(lifeos, "MEMORY"));
const research = join(user, "MEMORY", "KNOWLEDGE", "Research");
writeFileSync(join(research, "gotchas-mac-mini.md"),
"---\ntitle: \"Gotchas: Mac mini\"\ntype: knowledge\ncreated: 2026-01-01\n---\n\n# Gotchas: Mac mini\n\nThe home server is reached over ssh.\n");
const child = `
const { add } = await import(${JSON.stringify(join(tools, "MemorySystem.ts"))});
const r = add({ type: "knowledge", entity_type: "research", name: "Mac mini gotchas", content: "Screen Sharing needs the M1 on the same network.", related: [] });
console.log(JSON.stringify({ ok: r.ok, path: r.path?.split("/").pop(), how: r.detail?.created_or_appended, msg: r.message }));
`;
const p = Bun.spawnSync([process.execPath, "-e", child], {
cwd: sb,
env: { PATH: process.env.PATH ?? "/usr/bin:/bin", TMPDIR: realpathSync(tmpdir()), HOME: sb,
CLAUDE_CONFIG_DIR: join(sb, ".claude"), LIFEOS_CONFIG_DIR: join(sb, ".config", "LIFEOS"),
CORTEX_MEMORY_ROOT: join(lifeos, "MEMORY"), CORTEX_LEDGER_ROOT: join(sb, ".claude"),
GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" },
});
const out = p.stdout.toString().trim().split("\n").pop() ?? "";
const files = readdirSync(research).sort();
console.log(`add() → ${out}`);
console.log(`Research/ now holds: ${files.join(", ")}`);
const r = JSON.parse(out || "{}");
const pass = r.ok && r.path === "gotchas-mac-mini.md" && r.how === "appended" && files.length === 1;
console.log(pass ? "PASS: appended to the existing note" : "FAIL: same topic under another spelling created a second note");
process.exit(pass ? 0 : 1);
} finally {
rmSync(sb, { recursive: true, force: true });
}
PROBE
bun note-home-probe.ts; echo "exit=$?"Negative control
Probe: bun "$NOTE_HOME_PROBE" · exit 1 · captured 2026-11-15T13:09:01.683Z
Red looks like: FAIL: same topic under another spelling created a second note
add() → {"ok":true,"path":"mac-mini-gotchas.md","how":"created"}
Research/ now holds: gotchas-mac-mini.md, mac-mini-gotchas.md
FAIL: same topic under another spelling created a second note
Suggested fix
Two layers, both deterministic:
- Writer guard. Before
add()creates a newknowledgeorideafile,NoteHome.findNoteHomelooks in the same folder for a note whose slug or frontmattertitlehas the same set of topic words as the new name, after folding case, word order, punctuation, diacritics (including stroke letters such as ł that NFKD leaves alone) and the genericgotchasword. A verbatim title also matches. On a hit the item is appended to that note (created_or_appended: "appended", plusredirected_fromin the result and the tier-b audit row), and therelated:merge runs as before. A shorter or longer name does not merge: "mini" is as often a parent topic as an abbreviation, and the tokens cannot tell which. If several notes match, the oldest bycreatedwins; a note that would refuse an append is skipped. - Reviewer hint. The reviewer's user message gets a capped
EXISTING NOTESlist (20 items, 2000 chars): the existing notes whose slug words overlap the conversation, with the instruction to use exactly that title for a topic on the list. This is what handles shorter and longer names.
Tests: 14 new checks in the MemorySystem smoke test and 7 in MemoryReviewer, each red before the code. Existing checks still pass (MemorySystem 35/35, MemoryReviewer 21/21, MemoryTypes 69/69). One sentence is added to MemorySystem.md.
diff --git a/LifeOS/install/LIFEOS/DOCUMENTATION/Memory/MemorySystem.md b/LifeOS/install/LIFEOS/DOCUMENTATION/Memory/MemorySystem.md
index 5a3362d..3d53df6 100644
--- a/LifeOS/install/LIFEOS/DOCUMENTATION/Memory/MemorySystem.md
+++ b/LifeOS/install/LIFEOS/DOCUMENTATION/Memory/MemorySystem.md
@@ -109,6 +109,8 @@ Defined in `LIFEOS/TOOLS/MemoryTypes.ts`. Frozen at module load — adding a typ
**Type is data, tier is permission.** Type tells the routing layer WHERE an item belongs. Tier tells the writer WHETHER the write is allowed. They're orthogonal — never collapsed.
+**One note home per topic.** Before `add` creates a new `idea` or `knowledge` note, `findNoteHome` in `LIFEOS/TOOLS/NoteHome.ts` looks in the same folder for a note whose slug or frontmatter `title` has the same set of topic words (case, word order, diacritics, punctuation and the word `gotchas` folded) or whose title matches verbatim, appends there instead (oldest frontmatter `created` wins a tie; `redirected_from` in the result and the tier-b-writes.jsonl row keeps the original slug), and leaves shorter or longer names to the reviewer, whose input lists those existing notes under `EXISTING NOTES`.
+
### Proposal subtypes (P1 2026-05-25)
Proposals carry a `target_kind` discriminator that tells the reviewer which curated-context file class the proposal targets. The reviewer's prompt teaches the model when to emit each subtype; the dispatcher validates `(target_kind, target_file)` against the closed allowlist in `PROPOSAL_KIND_TO_FILES` (`LIFEOS/TOOLS/MemoryTypes.ts`); the proposal surfacer renders the subtype as a `[kind]` badge in the proposal header. `target_kind` is optional for backwards compat — when absent, the dispatcher infers it from `target_file`. Since 2026-07-21 the enqueue path also PINS `target_file` via `pinProposalTargetFile` (public PR #1563, @anikinsasha): single-file kinds ignore the reviewer's free-text path and store the canonical one; identity proposals must name one of the two allowed files or the proposal is rejected (`EINVAL_ITEM`), so a hallucinated path can never be persisted.
diff --git a/LifeOS/install/LIFEOS/TOOLS/MemoryReviewer.ts b/LifeOS/install/LIFEOS/TOOLS/MemoryReviewer.ts
index eb23aea..37ecc88 100755
--- a/LifeOS/install/LIFEOS/TOOLS/MemoryReviewer.ts
+++ b/LifeOS/install/LIFEOS/TOOLS/MemoryReviewer.ts
@@ -36,6 +36,7 @@ import {
appendFileSync,
existsSync,
mkdirSync,
+ mkdtempSync,
readdirSync,
rmSync,
readFileSync,
@@ -45,6 +46,7 @@ import {
} from "node:fs";
import { getClaudeDir } from "./Paths"; // public issue #1665 @rogdex24, #1584 @ramazanpolat — aliased resolve sites missed by the 09-03 sweep
import { basename as pathBasename, dirname, join as pathJoin, resolve as pathResolve } from "node:path";
+import { tmpdir } from "node:os";
import { add as memoryAdd, sanitizeTypedItemForPersistence, type AddResult } from "./MemorySystem";
import { read as memoryWriterRead, CONSOLIDATE_THRESHOLD, CONSOLIDATION_FLOOR, MEMORY_CAP } from "./MemoryWriter";
@@ -56,6 +58,7 @@ import { getPrincipalName, getDAName } from "../../hooks/lib/identity";
import { ingestCaptureEnvelope, stripPrivateContent, type CaptureEnvelope } from "./CaptureEnvelope";
import { annotate as annotateEntries } from "./MemoryEntryMeta";
import { replayParked } from "./ParkedReplay";
+import { noteHomesFor, EXISTING_NOTES_MAX_CHARS, EXISTING_NOTES_MAX_ITEMS } from "./NoteHome";
import {
applyProposalEdit,
markProposal,
@@ -644,9 +647,21 @@ function renderCurrentMemory(snap: CurrentMemorySnapshot | undefined): string[]
];
}
-export function buildReviewerUserPrompt(exchanges: Exchange[], currentMemory?: CurrentMemorySnapshot): string {
+/** The EXISTING NOTES section of the reviewer's input (lines from NoteHome.noteHomesFor); empty when none. */
+function renderExistingNotes(noteHomes: string[] | undefined): string[] {
+ if (!noteHomes || noteHomes.length === 0) return [];
+ return [
+ "── EXISTING NOTES this conversation touches (folder/slug: \"title\") ──",
+ "Each is the one note for its topic. For an idea or knowledge item about a topic on this list, use exactly that title as the item's title (idea) or name (knowledge), with the kind its folder implies (Ideas → idea, Research → research, People → person, Companies → company), so the item appends to that note. A narrower subtopic that deserves its own note gets its own short name.",
+ ...noteHomes.map((h) => ` ${h}`),
+ "",
+ ];
+}
+
+export function buildReviewerUserPrompt(exchanges: Exchange[], currentMemory?: CurrentMemorySnapshot, noteHomes?: string[]): string {
const lines = [
...renderCurrentMemory(currentMemory),
+ ...renderExistingNotes(noteHomes),
`Recent conversation between ${PRINCIPAL_NAME} and ${DA_NAME} (last ` + exchanges.length + " exchanges):",
"",
];
@@ -1007,6 +1022,8 @@ export interface ReviewOptions {
/** Injectable inference boundary for callers that must verify zero egress. */
inference?: typeof inference;
timeoutMs?: number;
+ /** For testing: the folders searched for EXISTING NOTES (default: the registry's idea/knowledge folders). */
+ noteHomeDirs?: string[];
}
export interface ReviewResult {
@@ -1085,7 +1102,16 @@ export async function review(opts: ReviewOptions = {}): Promise<ReviewResult> {
// installs after the release scrubber) to the configured identity before the
// prompts reach the model. No-op in the live tree.
const systemPrompt = renderNames(REVIEWER_SYSTEM_PROMPT);
- const userPrompt = renderNames(buildReviewerUserPrompt(exchanges, snapshot));
+ // EXISTING NOTES: the notes this conversation touches, so the reviewer reuses
+ // their titles and an item appends to its topic's note (NoteHome.ts).
+ let noteHomes: string[] = [];
+ try {
+ const said = exchanges.map((ex) => `${stripPrivateContent(ex.user)}\n${stripPrivateContent(ex.assistant)}`).join("\n");
+ noteHomes = noteHomesFor(said, opts.noteHomeDirs).map((h) => stripPrivateContent(h)).filter((h) => h.trim().length > 0);
+ } catch {
+ /* best-effort hint: on failure the prompt goes without it and the writer's note-home guard still applies */
+ }
+ const userPrompt = renderNames(buildReviewerUserPrompt(exchanges, snapshot, noteHomes));
// --dry-run stops here: extract + prompt, no inference. It also writes no
// run directory and no ledger row — CortexHealth reads both as evidence of
@@ -1295,6 +1321,53 @@ async function smokeTest(): Promise<number> {
isGuardRefusal({ ok: false, code: "EWRITE_FAILED", message: "MemoryWriter rejected: ESUSPECT_EROSION — op would net-drop 2 entries" } as AddResult) === true &&
isGuardRefusal({ ok: false, code: "EWRITE_FAILED", message: "disk full" } as AddResult) === false);
+ // 6c. Note homes — the reviewer's input lists the existing notes the conversation touches.
+ {
+ const dir = mkdtempSync(pathJoin(tmpdir(), "note-home-"));
+ try {
+ const research = pathJoin(dir, "Research");
+ const ideas = pathJoin(dir, "Ideas");
+ mkdirSync(research);
+ mkdirSync(ideas);
+ writeFileSync(pathJoin(research, "gotchas-mac-mini.md"), `---\ntitle: "Gotchas: Mac mini"\ncreated: 2026-01-01\n---\n`);
+ writeFileSync(pathJoin(research, "gotchas-heat-pump.md"), `---\ntitle: "Gotchas: Heat pump"\ncreated: 2026-01-01\n---\n`);
+ for (let i = 0; i < 30; i++) writeFileSync(pathJoin(ideas, `mac-mini-part-${i}.md`), `---\ntitle: "Mac mini part ${i}"\n---\n`);
+ const homeLine = `Research/gotchas-mac-mini: "Gotchas: Mac mini"`;
+ const homes = noteHomesFor("Is FileVault on the mini? The Mac mini restarted.", [research, ideas]);
+ check("note homes: the conversation's topic is listed first", homes[0] === homeLine, homes.slice(0, 3).join(" | "));
+ check("note homes: an untouched topic is not listed", !homes.some((h) => h.includes("heat-pump")));
+ check("note homes: the item cap holds", homes.length === EXISTING_NOTES_MAX_ITEMS, `${homes.length} lines`);
+
+ const wordy = pathJoin(dir, "Companies");
+ mkdirSync(wordy);
+ for (let i = 0; i < 10; i++) writeFileSync(pathJoin(wordy, `mac-mini-vendor-${i}.md`), `---\ntitle: "${"Mac mini vendor ".repeat(20)}${i}"\n---\n`);
+ const capped = noteHomesFor("Mac mini", [wordy]);
+ const chars = capped.reduce((n, l) => n + l.length + 1, 0);
+ check("note homes: the character cap holds", capped.length > 0 && capped.length < 10 && chars <= EXISTING_NOTES_MAX_CHARS, `${capped.length} lines, ${chars} chars`);
+
+ const ex = [{ ts: "t", user: "mini", assistant: "ok" }];
+ const prompt = buildReviewerUserPrompt(ex, undefined, [homeLine]);
+ check("note homes: the prompt carries EXISTING NOTES and the reuse instruction",
+ prompt.includes("EXISTING NOTES") && prompt.includes(homeLine) && prompt.includes("use exactly that title"));
+ check("note homes: no list, no section", !buildReviewerUserPrompt(ex).includes("EXISTING NOTES"));
+
+ // Wiring: review() builds the list from the conversation and hands it to the model.
+ const transcript = pathJoin(dir, "t.jsonl");
+ writeFileSync(transcript, [
+ JSON.stringify({ timestamp: "2026-01-01T00:00:00Z", message: { role: "user", content: "The Mac mini lost its network share again." } }),
+ JSON.stringify({ timestamp: "2026-01-01T00:00:05Z", message: { role: "assistant", content: [{ type: "text", text: "Remounted it." }] } }),
+ ].join("\n"), "utf8");
+ const run = await review({ input: transcript, turns: 5, mockInferenceResponse: '{"items":[]}', noteHomeDirs: [research] });
+ const promptFile = pathJoin(RUNS_DEBUG_DIR, run.runId, "prompt.user.md");
+ const sent = existsSync(promptFile) ? readFileSync(promptFile, "utf8") : "";
+ check("note homes: review() sends the touched note and not the untouched one",
+ sent.includes("EXISTING NOTES") && sent.includes(homeLine) && !sent.includes("heat-pump"), `runId=${run.runId}`);
+ rmSync(pathJoin(RUNS_DEBUG_DIR, run.runId), { recursive: true, force: true });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
// 7. End-to-end with mocked inference — full pipeline
const mockResponse = JSON.stringify({
items: [
diff --git a/LifeOS/install/LIFEOS/TOOLS/MemorySystem.ts b/LifeOS/install/LIFEOS/TOOLS/MemorySystem.ts
index a5d5cab..6af0c6e 100755
--- a/LifeOS/install/LIFEOS/TOOLS/MemorySystem.ts
+++ b/LifeOS/install/LIFEOS/TOOLS/MemorySystem.ts
@@ -87,6 +87,7 @@ import { addUpgrade } from "./Upgrades";
import { getTier } from "./MutationTier";
import { getRelevantContext, type RelevantResultItem, bumpMemoryGeneration } from "./MemoryRetriever";
import { mintId, slugFromPath, SCHEMA_VERSION } from "./KnowledgeSchema";
+import { findNoteHome } from "./NoteHome";
import { stripPrivateContent } from "./CaptureEnvelope";
import { assertInsideUserData, userDataRoot } from "./lib/ForeignDataCheck";
import { atomicWrite, LockBusyError, withLock } from "./lib/Boundary";
@@ -128,7 +129,7 @@ export interface FindOptions {
// ── Tier audit / observability ──
-function logTierBWrite(filePath: string, bytes: number, type: MemoryTypeName): void {
+function logTierBWrite(filePath: string, bytes: number, type: MemoryTypeName, redirectedFrom?: string): void {
try {
mkdirSync(dirname(TIER_B_AUDIT_PATH), { recursive: true });
appendFileSync(
@@ -138,6 +139,7 @@ function logTierBWrite(filePath: string, bytes: number, type: MemoryTypeName): v
file: filePath.replace(CLAUDE_ROOT + "/", ""),
bytes_written: bytes,
type,
+ ...(redirectedFrom ? { redirected_from: redirectedFrom } : {}),
}) + "\n",
"utf8",
);
@@ -638,7 +640,27 @@ function mergeRelatedIntoExisting(content: string, incoming: RelatedLink[]): str
return fmMatch[1] + fm + fmMatch[3] + content.slice(fmMatch[0].length);
}
-function addNoteTypeItem(item: TypedItem & { type: "idea" | "knowledge" }, path: string): AddResult {
+/**
+ * True when the note at `path` passes the answer-artifact check every append
+ * re-runs (appendUnderLock). A hand-written note that fails it (a research note
+ * without `confidence`) would turn the append into a thrown InvariantViolation,
+ * so it never serves as another name's note home.
+ */
+function acceptsAppend(path: string): boolean {
+ try {
+ assertAnswerArtifact(readFileSync(path, "utf8"));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Write an idea/knowledge item to `path`: append when the note exists, else
+ * create it. `redirectedFrom` is the slug the item's own name resolved to when
+ * `path` is that topic's note home instead (see NoteHome.ts).
+ */
+function addNoteTypeItem(item: TypedItem & { type: "idea" | "knowledge" }, path: string, redirectedFrom?: string): AddResult {
const alreadyExists = existsSync(path);
let totalBytes = 0;
@@ -660,7 +682,7 @@ function addNoteTypeItem(item: TypedItem & { type: "idea" | "knowledge" }, path:
} catch (e: any) {
// Don't fail the whole add if the merge fails — the content already
// landed. Log via observability instead.
- logTierBWrite(path, 0, item.type);
+ logTierBWrite(path, 0, item.type, redirectedFrom);
}
}
} else {
@@ -670,7 +692,7 @@ function addNoteTypeItem(item: TypedItem & { type: "idea" | "knowledge" }, path:
totalBytes += writeResult.bytes;
}
- logTierBWrite(path, totalBytes, item.type);
+ logTierBWrite(path, totalBytes, item.type, redirectedFrom);
bumpMemoryGeneration();
return {
ok: true,
@@ -680,6 +702,7 @@ function addNoteTypeItem(item: TypedItem & { type: "idea" | "knowledge" }, path:
bytes_written: totalBytes,
created_or_appended: alreadyExists ? "appended" : "created",
related_links: item.related?.length ?? 0,
+ ...(redirectedFrom ? { redirected_from: redirectedFrom } : {}),
},
};
}
@@ -855,6 +878,20 @@ export function add(item: TypedItem, opts: { expectedFingerprint?: string } = {}
return { ok: false, code: "EINVAL_ITEM", message: `Storage path resolution failed: ${e?.message}` };
}
+ // Note home: a NEW idea/knowledge note whose topic already has a note in the
+ // same folder under another spelling appends to that note instead (NoteHome.ts).
+ // Runs before the boundary and tier checks below, so they judge the home path.
+ let redirectedFrom: string | undefined;
+ if (entry.write_mode === "append" && !existsSync(path)) {
+ const topic = item.type === "idea" ? item.title : item.type === "knowledge" ? item.name : undefined;
+ const home = topic === undefined ? null : findNoteHome(dirname(path), topic, acceptsAppend);
+ if (home) {
+ invariant(dirname(home.path) === dirname(path), `note home ${home.path} is outside the item's folder ${dirname(path)}`);
+ redirectedFrom = slugFromPath(path);
+ path = home.path;
+ }
+ }
+
// Boundary (2026-08-11 lifelog incident class): every Cortex write target
// must physically resolve into the private USER_DATA repo. The resolvers all
// point through the LIFEOS/USER and LIFEOS/MEMORY symlinks; if a symlink is
@@ -888,7 +925,7 @@ export function add(item: TypedItem, opts: { expectedFingerprint?: string } = {}
case "set-overwrite":
return addMemoryItem(item as TypedItem & { type: "memory" }, path, opts.expectedFingerprint);
case "append":
- return addNoteTypeItem(item as TypedItem & { type: "idea" | "knowledge" }, path);
+ return addNoteTypeItem(item as TypedItem & { type: "idea" | "knowledge" }, path, redirectedFrom);
case "queue": {
const r = enqueueProposal(item as TypedItem & { type: "proposal" });
if (!r.ok) return r;
@@ -1135,6 +1172,87 @@ async function smokeTest(): Promise<number> {
try { unlinkSync(r4c.path); } catch { /* ignore */ }
}
+ // 4c. Note home — a new idea/knowledge name for a topic that already has a note
+ // appends to that note instead of minting a second file (see NoteHome.ts).
+ {
+ const knowledgeDir = pathJoin(getClaudeDir(), "LIFEOS", "MEMORY", "KNOWLEDGE");
+ const research = pathJoin(knowledgeDir, "Research");
+ const ideas = pathJoin(knowledgeDir, "Ideas");
+ mkdirSync(research, { recursive: true });
+ mkdirSync(ideas, { recursive: true });
+ // Seeds mirror what the writer itself creates (research notes state confidence and source_kind).
+ const seed = (dir: string, slug: string, title: string, created: string, provenance = "confidence: 0.7\nsource_kind: internal\n"): string => {
+ const p = pathJoin(dir, `${slug}.md`);
+ writeFileSync(p, `---\ntype: research\ntitle: "${title}"\n${provenance}created: ${created}\nrelated: []\n---\n\n# ${title}\n\nSeed.\n`);
+ return p;
+ };
+ const how = (r: AddResult) => (r.ok ? (r.detail as any).created_or_appended : `error: ${(r as any).message}`);
+ const named = (r: AddResult) => (r.ok ? basename(r.path) : `error: ${(r as any).message}`);
+ const research_ = (name: string) => add({ type: "knowledge", entity_type: "research", name, content: `About ${name}.` });
+
+ const home = seed(research, "gotchas-mac-mini", "Gotchas: Mac mini", "2026-01-01T00:00:00.000Z");
+ const reordered = research_("Mac mini gotchas");
+ check("note home: \"Mac mini gotchas\" appends to gotchas-mac-mini.md",
+ reordered.ok && reordered.path === home && how(reordered) === "appended" && !existsSync(pathJoin(research, "mac-mini-gotchas.md")),
+ `${named(reordered)} (${how(reordered)})`);
+ check("note home: the result carries the originally computed slug",
+ reordered.ok && (reordered.detail as any).redirected_from === "mac-mini-gotchas", JSON.stringify(reordered.ok ? reordered.detail : reordered));
+ const auditRows = existsSync(TIER_B_AUDIT_PATH)
+ ? readFileSync(TIER_B_AUDIT_PATH, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l))
+ : [];
+ check("note home: the Tier B audit row records the home path and the original slug",
+ auditRows.some((row) => String(row.file).endsWith("Research/gotchas-mac-mini.md") && row.redirected_from === "mac-mini-gotchas"));
+ const unprefixed = research_("mini Mac");
+ check("note home: case and word order fold (\"mini Mac\")", unprefixed.ok && unprefixed.path === home && how(unprefixed) === "appended",
+ `${named(unprefixed)} (${how(unprefixed)})`);
+ check("note home: both appended sections landed in the home note", (readFileSync(home, "utf8").match(/^## Appended /gm) ?? []).length === 2);
+
+ const curatedTitle = "Gotchas: Heat pump (outdoor unit): defrost cycle, error codes";
+ const curated = seed(research, "gotchas-heat-pump", curatedTitle, "2026-01-01T00:00:00.000Z");
+ const verbatim = research_(curatedTitle);
+ check("note home: a listed note's verbatim title appends to that note", verbatim.ok && verbatim.path === curated && how(verbatim) === "appended",
+ `${named(verbatim)} (${how(verbatim)})`);
+ const bare = seed(research, "misc-gotchas", "Gotchas", "2026-01-01T00:00:00.000Z");
+ const bareVerbatim = research_("Gotchas");
+ check("note home: a verbatim title with no topic words still appends", bareVerbatim.ok && bareVerbatim.path === bare,
+ `${named(bareVerbatim)} (${how(bareVerbatim)})`);
+
+ const shorter = research_("mini");
+ check("note home: a shorter name gets its own note", shorter.ok && basename(shorter.path) === "mini.md" && how(shorter) === "created",
+ `${named(shorter)} (${how(shorter)})`);
+ const longer = research_("Mac mini home server");
+ check("note home: a longer name gets its own note", longer.ok && basename(longer.path) === "mac-mini-home-server.md" && how(longer) === "created",
+ `${named(longer)} (${how(longer)})`);
+ const fresh = research_("Gotchas: Solar inverter");
+ check("note home: a topic without a home creates its own file as before",
+ fresh.ok && basename(fresh.path) === "gotchas-solar-inverter.md" && how(fresh) === "created", `${named(fresh)} (${how(fresh)})`);
+ seed(research, "gotchas-cm-frontend", "Gotchas: cm-frontend", "2026-01-01T00:00:00.000Z");
+ const sibling = research_("Gotchas: cm-event-service");
+ check("note home: two topics sharing one word stay separate",
+ sibling.ok && basename(sibling.path) === "gotchas-cm-event-service.md" && how(sibling) === "created", `${named(sibling)} (${how(sibling)})`);
+ // "ł" has no NFKD decomposition: slugify("Wyłącznik") is "wy-acznik", so only the fold finds "wylacznik".
+ const ascii = seed(research, "wylacznik", "Wylacznik", "2026-01-01T00:00:00.000Z");
+ const polish = research_("Wyłącznik");
+ check("note home: \"Wyłącznik\" folds to the \"wylacznik\" note", polish.ok && polish.path === ascii && how(polish) === "appended",
+ `${named(polish)} (${how(polish)})`);
+
+ // A hand-written research note without `confidence` refuses every append (assertAnswerArtifact);
+ // it must not become a home, or a variant name would turn a clean create into a thrown write.
+ seed(research, "gotchas-backup-drive", "Gotchas: Backup drive", "2026-01-01T00:00:00.000Z", "");
+ let unfit: AddResult | string;
+ try { unfit = research_("Backup drive gotchas"); } catch (e: any) { unfit = `threw: ${e?.message}`; }
+ check("note home: a note that refuses appends is not a home",
+ typeof unfit !== "string" && unfit.ok && basename(unfit.path) === "backup-drive-gotchas.md" && how(unfit) === "created",
+ typeof unfit === "string" ? unfit : `${named(unfit)} (${how(unfit)})`);
+
+ // Tie: two homes for one topic; the older frontmatter `created` wins, not file age or name order.
+ seed(ideas, "backup-mac-mini", "Backup Mac mini", "2026-03-01T00:00:00.000Z");
+ const oldest = seed(ideas, "mac-mini-backup", "Mac mini backup", "2026-01-01T00:00:00.000Z");
+ const tie = add({ type: "idea", title: "mini Mac backup", content: "Weekly." });
+ check("note home: a tie goes to the oldest home by frontmatter created", tie.ok && tie.path === oldest && how(tie) === "appended",
+ `${named(tie)} (${how(tie)})`);
+ }
+
// 5. ISC-156 — proposal enqueues
const r5 = add({
type: "proposal",
diff --git a/LifeOS/install/LIFEOS/TOOLS/NoteHome.ts b/LifeOS/install/LIFEOS/TOOLS/NoteHome.ts
new file mode 100644
index 0000000..4733d2e
--- /dev/null
+++ b/LifeOS/install/LIFEOS/TOOLS/NoteHome.ts
@@ -0,0 +1,192 @@
+/**
+ * NoteHome — one note per topic in the knowledge archive.
+ *
+ * The memory reviewer names each `knowledge` item (`name`) and `idea` item
+ * (`title`) in free text, and the type registry turns that text into a slug.
+ * `MemorySystem.add` appends only when a file with exactly that slug exists
+ * (the exact-path limit noted in public issue #2131), so one topic named three
+ * ways ("Gotchas: Mac mini", "Mac mini gotchas", "mini Mac") used to mint three
+ * notes, and retrieval returned their fragments side by side.
+ *
+ * Two entry points, both deterministic (no model call):
+ *
+ * findNoteHome(dir, name) — the writer's guard. Before `add` creates a new
+ * note, it asks for the topic's note home among the existing notes in the
+ * same folder and appends there instead.
+ * noteHomesFor(text) — the reviewer's hint. The notes whose slug words
+ * the conversation mentions, capped, so the reviewer reuses an existing
+ * title in the first place.
+ *
+ * Matching rule (the writer's guard). A note is the home of `name` when either
+ * - its slug or its frontmatter `title` carries the identical SET of topic
+ * words as `name`, after folding case, diacritics (stroke letters such as
+ * "ł" included: NFKD leaves them whole), punctuation, word order, and the
+ * generic word "gotchas" (a kind prefix, not a topic; with word order folded
+ * its position carries nothing, so "Mac mini gotchas" is "Gotchas: Mac mini"); or
+ * - its title equals `name` verbatim.
+ * A shorter or longer name ("mini", "Mac mini home server" beside "Mac mini")
+ * may be the same topic, a parent or a subtopic. Words cannot tell which, so it
+ * gets its own note; reusing a listed title is the reviewer's call.
+ * Several homes for one topic: the oldest by frontmatter `created` wins (file
+ * birth time when a note has no parseable `created`), then the slug in sort order.
+ */
+
+import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
+import { basename, dirname, join as pathJoin } from "node:path";
+import { resolveStoragePath, type EntityType } from "./MemoryTypes";
+
+/** Most notes the reviewer's EXISTING NOTES section lists. */
+export const EXISTING_NOTES_MAX_ITEMS = 20;
+/** Most characters (lines plus newlines) that section's list may take. */
+export const EXISTING_NOTES_MAX_CHARS = 2000;
+/** Share of a note's slug words the conversation must mention for the note to be listed. */
+const MIN_MENTIONED_SHARE = 0.5;
+/** Bytes read from the top of each note: enough for frontmatter `title` and `created`. */
+const HEAD_BYTES = 4096;
+
+/** A kind prefix, not a topic. */
+const GENERIC_WORDS: ReadonlySet<string> = new Set(["gotchas", "gotcha"]);
+/** Stroke letters that NFKD does not decompose, folded to their base letter. */
+const STROKE_LETTERS: Readonly<Record<string, string>> = { "ł": "l", "đ": "d", "ø": "o", "ħ": "h" };
+const STROKE_RE = new RegExp(`[${Object.keys(STROKE_LETTERS).join("")}]`, "g");
+
+/** Every entity type, so a new one in the union fails compilation here until it is listed. */
+const ENTITY_TYPES: Record<EntityType, true> = { person: true, company: true, research: true };
+
+export interface NoteHome {
+ path: string;
+ slug: string;
+ title: string;
+}
+
+interface Note extends NoteHome {
+ slugWords: Set<string>;
+ bornMs: number;
+}
+
+function topicWords(text: string): Set<string> {
+ const words = text
+ .toLowerCase()
+ .replace(STROKE_RE, (c) => STROKE_LETTERS[c] ?? c)
+ .normalize("NFKD")
+ .replace(/\p{M}/gu, "")
+ .split(/[^a-z0-9]+/)
+ .filter((w) => w.length > 0 && !GENERIC_WORDS.has(w));
+ return new Set(words);
+}
+
+function sameWords(a: Set<string>, b: Set<string>): boolean {
+ if (a.size === 0 || a.size !== b.size) return false;
+ for (const w of a) if (!b.has(w)) return false;
+ return true;
+}
+
+function readHead(path: string): string {
+ const fd = openSync(path, "r");
+ try {
+ const buf = new Uint8Array(HEAD_BYTES);
+ const n = readSync(fd, buf, 0, HEAD_BYTES, 0);
+ return new TextDecoder().decode(buf.subarray(0, n));
+ } finally {
+ closeSync(fd);
+ }
+}
+
+/** One scalar frontmatter field, unquoted; null when absent or empty. Tolerates a head cut before the closing `---`. */
+function frontmatterField(head: string, field: string): string | null {
+ if (!head.startsWith("---\n")) return null;
+ const end = head.indexOf("\n---", 4);
+ const fm = end === -1 ? head.slice(4) : head.slice(4, end);
+ const line = fm.match(new RegExp(`^${field}:[ \\t]*(.*)$`, "m"));
+ if (!line) return null;
+ const raw = line[1].trim();
+ let value = raw;
+ if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) value = raw.slice(1, -1).replace(/\\(["\\])/g, "$1");
+ else if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) value = raw.slice(1, -1).replace(/''/g, "'");
+ return value.length > 0 ? value : null;
+}
+
+function notesIn(dir: string): Note[] {
+ if (!existsSync(dir)) return [];
+ const notes: Note[] = [];
+ for (const file of readdirSync(dir)) {
+ if (!file.endsWith(".md") || file.startsWith(".")) continue;
+ const path = pathJoin(dir, file);
+ try {
+ const st = statSync(path);
+ if (!st.isFile()) continue;
+ const head = readHead(path);
+ const slug = basename(file, ".md");
+ const created = Date.parse(frontmatterField(head, "created") ?? "");
+ notes.push({
+ path,
+ slug,
+ title: frontmatterField(head, "title") ?? slug,
+ slugWords: topicWords(slug),
+ bornMs: Number.isFinite(created) ? created : st.birthtimeMs || st.mtimeMs,
+ });
+ } catch {
+ /* an unreadable note is never a note home */
+ }
+ }
+ return notes;
+}
+
+/** The folders that hold `idea` and `knowledge` notes, as the type registry resolves them. */
+export function noteHomeDirs(): string[] {
+ const dirs = [dirname(resolveStoragePath({ type: "idea", title: "x", content: "" }))];
+ for (const entity_type of Object.keys(ENTITY_TYPES) as EntityType[]) {
+ dirs.push(dirname(resolveStoragePath({ type: "knowledge", entity_type, name: "x", content: "" })));
+ }
+ return [...new Set(dirs)];
+}
+
+/**
+ * The existing note in `dir` that is the home of the topic `name` (see the
+ * matching rule above), or null when the topic has none. `canHost` lets the
+ * writer pass over a note it could not append to; such a note is no home.
+ */
+export function findNoteHome(dir: string, name: string, canHost: (path: string) => boolean = () => true): NoteHome | null {
+ const verbatim = name.replace(/[\r\n]+/g, " ").trim();
+ if (verbatim.length === 0) return null;
+ const want = topicWords(verbatim);
+ let best: Note | null = null;
+ for (const note of notesIn(dir)) {
+ const isHome = note.title.trim() === verbatim || sameWords(want, note.slugWords) || sameWords(want, topicWords(note.title));
+ if (!isHome || !canHost(note.path)) continue;
+ if (!best || note.bornMs < best.bornMs || (note.bornMs === best.bornMs && note.slug < best.slug)) best = note;
+ }
+ return best ? { path: best.path, slug: best.slug, title: best.title } : null;
+}
+
+/**
+ * The notes in `dirs` whose topic `text` touches: at least MIN_MENTIONED_SHARE
+ * of the note's slug words occur in it. Ranked by that share, then by the
+ * number of words shared; at most EXISTING_NOTES_MAX_ITEMS lines within
+ * EXISTING_NOTES_MAX_CHARS characters. Each line reads `<folder>/<slug>: "<title>"`.
+ */
+export function noteHomesFor(text: string, dirs: string[] = noteHomeDirs()): string[] {
+ const mentioned = topicWords(text);
+ if (mentioned.size === 0) return [];
+ const hits: { line: string; share: number; shared: number }[] = [];
+ for (const dir of dirs) {
+ for (const note of notesIn(dir)) {
+ if (note.slugWords.size === 0) continue;
+ let shared = 0;
+ for (const w of note.slugWords) if (mentioned.has(w)) shared++;
+ const share = shared / note.slugWords.size;
+ if (share >= MIN_MENTIONED_SHARE) hits.push({ line: `${basename(dir)}/${note.slug}: ${JSON.stringify(note.title)}`, share, shared });
+ }
+ }
+ hits.sort((x, y) => y.share - x.share || y.shared - x.shared || x.line.localeCompare(y.line));
+ const lines: string[] = [];
+ let chars = 0;
+ for (const hit of hits) {
+ if (lines.length >= EXISTING_NOTES_MAX_ITEMS) break;
+ // A line that does not fit is skipped, not a stop: one long title must not starve the rest.
+ if (chars + hit.line.length + 1 > EXISTING_NOTES_MAX_CHARS) continue;
+ lines.push(hit.line);
+ chars += hit.line.length + 1;
+ }
+ return lines;
+}Environment
- OS: macOS 27.2 (arm64)
- Harness: claude-code
- bun: 1.4.4 · git: 2.54.0
- Doctor broken: none
Activity