A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: mark and order closed notes in search results (#343)
yi11140b0347649e0
diff --git a/.claude/scripts/lib/correction-sweep.ts b/.claude/scripts/lib/correction-sweep.tsindex 6684296..47bd674 100644--- a/.claude/scripts/lib/correction-sweep.ts+++ b/.claude/scripts/lib/correction-sweep.ts@@ -89,8 +89,14 @@ const HISTORICAL_DIRS = new Set(["archive", "1-1", "meetings", "thinking", "memo* `completed` is included on purpose. A finished piece of work describes what* was done, and editing it to agree with the present falsifies the record just* as surely as editing a dated capture would.+ *+ * Exported because search needs the same definition and not a second one. A+ * status that closed a note to the correction sweep must close it in search too,+ * and a copy of this list is exactly the kind that drifts: the sweep's list grows+ * a value, search keeps demoting nothing, and the two disagree about what+ * "closed" means without either being wrong on its own terms.*/-const HISTORICAL_STATUS = new Set(["superseded", "archived", "completed", "deprecated", "done"]);+export const HISTORICAL_STATUS = new Set(["superseded", "archived", "completed", "deprecated", "done"]);/** A date anywhere in the filename, not only as a prefix. */const DATE_IN_NAME = /\d{4}-\d{2}-\d{2}/;diff --git a/.claude/scripts/lib/mcp-qmd-client.ts b/.claude/scripts/lib/mcp-qmd-client.tsindex fd75c99..5c809d1 100644--- a/.claude/scripts/lib/mcp-qmd-client.ts+++ b/.claude/scripts/lib/mcp-qmd-client.ts@@ -15,8 +15,12 @@*/import { spawn, type ChildProcess } from "node:child_process";+import { existsSync, readdirSync, readFileSync } from "node:fs";import { join } from "node:path";+import { HISTORICAL_STATUS } from "./correction-sweep.ts";+import { facetsOf, parseFrontmatter } from "./memory-recall.ts";+/** One hit as qmd reports it in `structuredContent.results`. */export interface QmdHit {readonly file?: string;@@ -110,6 +114,143 @@ export function qmdRelKey(qmdPath: unknown): string {return i >= 0 ? p.slice(i + 1) : p;}+// ---------------------------------------------------------------------------+// Lifecycle — the one thing qmd cannot know about a hit+// ---------------------------------------------------------------------------++/**+ * What a note's own frontmatter says about whether it still asserts anything.+ *+ * Deliberately narrower than `isHistoricalNote`. That function also treats a+ * dated filename and a record-keeping folder as historical, which is right for+ * deciding what the correction sweep must not rewrite and wrong for search: it+ * would demote every dated capture, and dated captures are often exactly what a+ * query is looking for. Only an explicit closed status, or a non-empty+ * `superseded_by`, changes the order here.+ */+export interface NoteLifecycle {+ /** The closed `status` value, lowercased. Absent when the note is live. */+ readonly status?: string;+ /** Titles that replaced this note. Non-empty means it was superseded. */+ readonly supersededBy?: readonly string[];+}++/**+ * Read one hit's lifecycle from the vault. Returns `null` for anything it+ * cannot read or parse — an unreadable note is shown unmarked, never dropped.+ *+ * A callback rather than a vault path so `scopeResults` keeps taking its input+ * as data: the ordering and the marker below stay provable without a filesystem,+ * which is the property the rest of this file is split around.+ */+export type LifecycleReader = (relPath: string) => NoteLifecycle | null;++/**+ * qmd's own path, collection prefix removed and case left alone.+ *+ * `qmdRelKey` folds case and whitespace because COMPARISON needs them equal.+ * Opening the file needs the name as it is on disk: qmd reports+ * `brain/key-decisions.md` for a note stored as `Key Decisions.md`, and+ * joining the comparison key would miss a file that exists.+ */+export function qmdRelPath(qmdPath: unknown): string {+ const p = String(qmdPath ?? "").replace(/\\/g, "/");+ const i = p.indexOf("/");+ return i >= 0 ? p.slice(i + 1) : p;+}++/**+ * Find a note on disk from the path qmd reported, case- and space-insensitively.+ *+ * Falls back to walking the segments because qmd normalises what it indexes and+ * a miss here is silent in the worst way: the note comes back unmarked, which is+ * indistinguishable from a live one.+ */+function resolveNote(vaultRoot: string, relPath: string): string | null {+ const direct = join(vaultRoot, relPath);+ if (existsSync(direct)) return direct;+ let cur = vaultRoot;+ for (const seg of relPath.split("/")) {+ if (!seg) continue;+ let entries: string[];+ try {+ entries = readdirSync(cur);+ } catch {+ return null;+ }+ const want = pathKey(seg);+ const match = entries.find((e) => pathKey(e) === want);+ if (match === undefined) return null;+ cur = join(cur, match);+ }+ return cur;+}++/**+ * Build a reader over a real vault.+ *+ * Called for at most `limit` hits per search, each a small markdown file, so the+ * cost is a handful of reads — not the index sweep this deliberately avoids.+ *+ * `superseded_by` goes through `facetsOf` so this reader and recall agree on+ * what the key means. Reading `fm.superseded_by` directly would treat the hand+ * -written scalar `superseded_by: New Decision` as absent and show a replaced+ * note as live, while recall correctly treats it as a one-item list.+ */+export function vaultLifecycleReader(vaultRoot: string): LifecycleReader {+ return (relPath) => {+ if (!relPath || relPath.split("/").includes("..")) return null;+ const full = resolveNote(vaultRoot, relPath);+ if (full === null) return null;+ let text: string;+ try {+ text = readFileSync(full, "utf8");+ } catch {+ return null;+ }+ const fm = parseFrontmatter(text);+ const status = fm["status"];+ const lifecycle: NoteLifecycle = {+ ...(typeof status === "string" ? { status: status.trim().toLowerCase() } : {}),+ supersededBy: facetsOf(fm).superseded_by,+ };+ return lifecycle;+ };+}++/**+ * The marker a closed hit carries, or `null` when it is live.+ *+ * `superseded_by` wins over `status` because it names WHAT replaced the note,+ * and a search that surfaced the old decision without the new one is the case+ * this whole path exists to prevent.+ */+export function lifecycleMarker(lc: NoteLifecycle | null): string | null {+ if (!lc) return null;+ const replaced = (lc.supersededBy ?? []).filter((t) => String(t ?? "").trim() !== "");+ if (replaced.length) return `(superseded by: ${replaced.join(", ")})`;+ const status = lc.status ?? "";+ if (status && HISTORICAL_STATUS.has(status)) return `(status: ${status})`;+ return null;+}++/**+ * Stable partition: live hits first, closed ones after, relevance preserved+ * inside each group.+ *+ * The same shape recall applies to memories. Reordering by relevance alone puts+ * a corrected-away fact above the correction that replaced it, which is the one+ * thing supersession exists to prevent. Applied AFTER `limit`, so a closed note+ * never displaces a live one out of the set and is never pushed out of it+ * either.+ */+function partitionByLifecycle<T>(hits: T[], isClosed: (hit: T) => boolean): T[] {+ const live: T[] = [];+ const closed: T[] = [];+ for (const h of hits) (isClosed(h) ? closed : live).push(h);+ return [...live, ...closed];+}+// ---------------------------------------------------------------------------// The filter — pure, and the reason this file is split// ---------------------------------------------------------------------------@@ -124,11 +265,16 @@ const RESPONSE_MAX = 6000;* whose key is not in it is dropped and counted — counted, because a silent* drop is indistinguishable from an empty index, and the caller needs to tell* "nothing matched" apart from "nothing in scope".+ *+ * `lifecycle` is optional and omitted by the tests that are about the FILTER+ * alone. Given one, each permitted hit is marked and closed hits are ordered+ * after live ones; given none, the output is exactly what it always was.*/export function scopeResults(structured: unknown,allowed: ReadonlySet<string>,limit = 5,+ lifecycle?: LifecycleReader,): ScopedResult {// No structured results means no per-hit paths to filter on. qmd's// human-readable summary carries note paths too, so returning that instead@@ -152,9 +298,23 @@ export function scopeResults(};}+ // Read at most `limit` frontmatters, on the hits that survived the filter+ // and the cut. A hit the policy does not serve is never opened.+ const markers = new Map<QmdHit, string>();+ const ordered = lifecycle+ ? (() => {+ const marked = hits.map((h) => {+ const marker = lifecycleMarker(lifecycle(qmdRelPath(h.file)));+ if (marker) markers.set(h, marker);+ return h;+ });+ return partitionByLifecycle(marked, (h) => markers.has(h));+ })()+ : hits;+// `context` is dropped: qmd repeats an identical vault-level blurb on every// hit, and it was the single biggest consumer of the response budget.- const body = hits+ const body = ordered.map((h, i) => {const snippet = String(h.snippet ?? "").replace(/\s+/g, " ")@@ -162,7 +322,8 @@ export function scopeResults(.slice(0, SNIPPET_MAX);const where = `${h.file}${h.line ? `:${h.line}` : ""}`;const score = Math.round((h.score ?? 0) * 100);- return `[${i + 1}] ${where} (score ${score}%)\n ${h.title ?? ""}\n ${snippet}`;+ const marker = markers.get(h);+ return `[${i + 1}] ${where} (score ${score}%)${marker ? ` ${marker}` : ""}\n ${h.title ?? ""}\n ${snippet}`;}).join("\n\n").slice(0, RESPONSE_MAX);@@ -387,6 +548,7 @@ export async function qmdSearch(allowed: ReadonlySet<string>,query: string,limit = 5,+ lifecycle?: LifecycleReader,): Promise<ScopedResult> {try {await client.ready;@@ -402,7 +564,7 @@ export async function qmdSearch(minScore: 0.4,},})) as { structuredContent?: { results?: unknown } } | null;- return scopeResults(out?.structuredContent?.results, allowed, limit);+ return scopeResults(out?.structuredContent?.results, allowed, limit, lifecycle);} catch (e) {// qmd is optional in this template. A failure degrades this ONE call and// says so; it must never present as "the vault is empty".diff --git a/.claude/scripts/lib/mcp-server.ts b/.claude/scripts/lib/mcp-server.tsindex e0589b0..9aa560f 100644--- a/.claude/scripts/lib/mcp-server.ts+++ b/.claude/scripts/lib/mcp-server.ts@@ -27,7 +27,7 @@ import {vaultRelKeyRaw,} from "./mcp-exposure.ts";import { expandNote } from "./mcp-graph.ts";-import { qmdProbe, qmdSearch, type QmdClient } from "./mcp-qmd-client.ts";+import { qmdProbe, qmdSearch, vaultLifecycleReader, type QmdClient } from "./mcp-qmd-client.ts";import { callerProject, callerProjectSource, CALLER_VAR, isVaultItself, PROJECT_MARKER, sumAuditField, sanitize } from "./mcp-caller.ts";import { callerPlatforms, digestsFrom, resolvableNames, resolvableTargets } from "./mcp-memory-bridge.ts";import { captureNote, describeToolMarkup, toolMarkupRefusal } from "./mcp-capture.ts";@@ -288,7 +288,7 @@ export function createHandlers(deps: ServerDeps): Handlers {if (!query.trim()) return "(search needs a query)";const limit = Number(args.limit ?? 5);const allowed = allowedSearchPaths(ctx.vaultRoot, policy);- const r = await qmdSearch(qmd(), allowed, query, limit);+ const r = await qmdSearch(qmd(), allowed, query, limit, vaultLifecycleReader(ctx.vaultRoot));audit("search", { query, withheld: r.withheld, total: r.total, bytes: r.text.length });return r.text;}diff --git a/.claude/scripts/tests/mcp-qmd-client.test.ts b/.claude/scripts/tests/mcp-qmd-client.test.tsindex 8690922..ebc024a 100644--- a/.claude/scripts/tests/mcp-qmd-client.test.ts+++ b/.claude/scripts/tests/mcp-qmd-client.test.ts@@ -13,7 +13,7 @@import { spawn, type ChildProcess } from "node:child_process";import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -28,8 +28,11 @@ import {timeoutMessage,qmdProbe,probeBudget,+ vaultLifecycleReader,+ qmdRelPath,type QmdHit,type QmdClient,+ type LifecycleReader,} from "../lib/mcp-qmd-client.ts";import { waitFor } from "./_helpers.ts";@@ -284,6 +287,183 @@ describe("scoping results", () => {});});+// ---------------------------------------------------------------------------+// Lifecycle+// ---------------------------------------------------------------------------++describe("closed notes in search results", () => {+ /** Everything the fixture vault holds, as a caller scoped to `brain/` gets it. */+ const BRAIN = new Set([+ "brain/decisions.md",+ "brain/old-decision.md",+ "brain/2026-07-26-capture.md",+ "brain/reversed.md",+ "brain/scalar.md",+ ]);++ /**+ * A vault with the two notes a reversal leaves behind, plus the cases that+ * must NOT be demoted: a dated capture and a note carrying only+ * `superseded_by`. Written with spaces in the filenames on purpose, because+ * that is how the vault stores them and qmd is what reports the paths.+ */+ function fixtureVault(): string {+ const dir = mkdtempSync(join(tmpdir(), "qmd-lifecycle-"));+ mkdirSync(join(dir, "brain"), { recursive: true });+ const note = (name: string, fm: string) =>+ writeFileSync(join(dir, "brain", name), `---\n${fm}\n---\n\nbody\n`, "utf-8");+ note("Decisions.md", "status: active");+ note("Old Decision.md", "status: superseded");+ note("2026-07-26 Capture.md", "date: 2026-07-26");+ note("Reversed.md", 'superseded_by: ["New Decision"]');+ note("Scalar.md", "superseded_by: New Decision");+ return dir;+ }++ test("a live note outranks a closed one that scored higher, and the closed one is marked", () => {+ // The bug this fixes: the old decision scores best on text relevance and+ // comes back first, unlabelled, with nothing pointing at what replaced it.+ const dir = fixtureVault();+ try {+ const hits = [hit("myvault/brain/Old Decision.md", { score: 0.97 }), hit("myvault/brain/Decisions.md", { score: 0.81 })];+ const r = scopeResults(hits, BRAIN, 5, vaultLifecycleReader(dir));+ const liveAt = r.text.indexOf("brain/Decisions.md");+ const closedAt = r.text.indexOf("brain/Old Decision.md");+ assert.ok(liveAt >= 0 && closedAt >= 0, `both notes must be listed:\n${r.text}`);+ assert.ok(liveAt < closedAt, `the live note must be listed first:\n${r.text}`);+ assert.match(r.text, /\(status: superseded\)/);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("a dated note with no status is NOT demoted", () => {+ // `isHistoricalNote` would call this historical because of its name. That+ // is right for the correction sweep and wrong here: dated captures are+ // often exactly what a query is looking for.+ const dir = fixtureVault();+ try {+ const hits = [hit("myvault/brain/2026-07-26 Capture.md", { score: 0.9 }), hit("myvault/brain/Old Decision.md", { score: 0.4 })];+ const r = scopeResults(hits, BRAIN, 5, vaultLifecycleReader(dir));+ assert.ok(+ r.text.indexOf("2026-07-26 Capture.md") < r.text.indexOf("Old Decision.md"),+ `the capture keeps its rank ahead of a closed note:\n${r.text}`,+ );+ assert.ok(+ !/\[1\][^\n]*2026-07-26 Capture\.md[^\n]*\(status:/.test(r.text),+ `and the capture itself carries no marker:\n${r.text}`,+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("`superseded_by` alone marks and demotes, and names what replaced it", () => {+ const dir = fixtureVault();+ try {+ const hits = [hit("myvault/brain/Reversed.md", { score: 0.95 }), hit("myvault/brain/Decisions.md", { score: 0.6 })];+ const r = scopeResults(hits, BRAIN, 5, vaultLifecycleReader(dir));+ assert.match(r.text, /\(superseded by: New Decision\)/);+ assert.ok(+ r.text.indexOf("brain/Decisions.md") < r.text.indexOf("brain/Reversed.md"),+ `a superseded note must sort after a live one:\n${r.text}`,+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("relevance still decides the order INSIDE the live and closed groups", () => {+ const dir = fixtureVault();+ try {+ const hits = [+ hit("myvault/brain/Old Decision.md", { score: 0.95 }),+ hit("myvault/brain/Reversed.md", { score: 0.55 }),+ hit("myvault/brain/Decisions.md", { score: 0.9 }),+ ];+ const r = scopeResults(hits, BRAIN, 5, vaultLifecycleReader(dir));+ assert.ok(+ r.text.indexOf("Decisions.md") < r.text.indexOf("Old Decision.md") &&+ r.text.indexOf("Old Decision.md") < r.text.indexOf("Reversed.md"),+ `stable partition, relevance preserved within each group:\n${r.text}`,+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("a hit path as qmd reports it still finds the note it stands for", () => {+ // qmd normalises what it indexes, so the paths it reports are dashed+ // even when the note is stored as `Old Decision.md`. Every test above+ // passes the on-disk name, which means the fallback walk in+ // `resolveNote` — the path real searches take — was never exercised.+ // A miss there is silent in the worst way: the replaced note comes back+ // unmarked, which is indistinguishable from a live one.+ const dir = fixtureVault();+ try {+ const hits = [hit("myvault/brain/old-decision.md", { score: 0.97 }), hit("myvault/brain/decisions.md", { score: 0.81 })];+ const r = scopeResults(hits, BRAIN, 5, vaultLifecycleReader(dir));+ assert.match(r.text, /\(status: superseded\)/, `the dashed path must still be marked:\n${r.text}`);+ assert.ok(+ r.text.indexOf("brain/decisions.md") < r.text.indexOf("brain/old-decision.md"),+ `and must still sort after a live note:\n${r.text}`,+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("a scalar `superseded_by` marks the note the way recall reads it", () => {+ // `superseded_by: New Decision` is a hand-written scalar, and recall+ // treats it as a one-item list. A reader that only accepts an array sees+ // no claim at all and serves a replaced note as live.+ const dir = fixtureVault();+ try {+ const hits = [hit("myvault/brain/Scalar.md", { score: 0.95 }), hit("myvault/brain/Decisions.md", { score: 0.6 })];+ const r = scopeResults(hits, BRAIN, 5, vaultLifecycleReader(dir));+ assert.match(r.text, /\(superseded by: New Decision\)/);+ assert.ok(+ r.text.indexOf("brain/Decisions.md") < r.text.indexOf("brain/Scalar.md"),+ `a superseded note must sort after a live one:\n${r.text}`,+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("a note the policy does not serve is never opened", () => {+ // The reader is how the search path starts touching the filesystem. It+ // must not become a way to read a note `search` would not have returned.+ const opened: string[] = [];+ const reader: LifecycleReader = (relPath) => {+ opened.push(relPath);+ return null;+ };+ scopeResults([hit("myvault/people/Someone.md"), hit("myvault/brain/Gotchas.md")], ALLOWED, 5, reader);+ assert.deepEqual(opened, ["brain/Gotchas.md"]);+ });++ test("a closed note beyond the cut is neither promoted into the set nor dropped from it", () => {+ // The partition runs AFTER `limit`, so it reorders what was already+ // chosen and cannot change which notes were chosen.+ const dir = fixtureVault();+ try {+ const hits = [hit("myvault/brain/Old Decision.md", { score: 0.99 }), hit("myvault/brain/Decisions.md", { score: 0.8 })];+ const r = scopeResults(hits, BRAIN, 1, vaultLifecycleReader(dir));+ assert.ok(!r.text.includes("brain/Decisions.md"), `limit must still be one hit:\n${r.text}`);+ assert.match(r.text, /brain\/Old Decision\.md/);+ assert.match(r.text, /\(status: superseded\)/);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("without a reader the rendering is unchanged", () => {+ const r = scopeResults([hit("myvault/brain/Gotchas.md")], ALLOWED);+ assert.equal(r.text.includes("status:"), false);+ });+});+// ---------------------------------------------------------------------------// Liveness// ---------------------------------------------------------------------------