A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
feat: hold the SessionStart eager layer under a byte budget (#147)
Brenno Ferrari266fa39c0cfd
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.tsindex 9b57d57..d13960b 100644--- a/.claude/scripts/lib/session-start.ts+++ b/.claude/scripts/lib/session-start.ts@@ -16,10 +16,180 @@ export function take(stdout: string, n: number): string {* Injection-size meter line: eager-layer bloat becomes visible the day it* starts. kB = 1000 bytes, one decimal. Negative/NaN guard to 0.0kB — the* meter must never be the thing that breaks the hook.+ *+ * With a budget, the meter also reports the ceiling and names any section+ * that was collapsed to stay under it. Silence about a collapse would be+ * worse than the bloat: a session would silently lose context and never+ * know. Called with one argument the output is byte-identical to before.*/-export function formatInjectionSize(bytes: number): string {+export function formatInjectionSize(+ bytes: number,+ opts?: {+ readonly budgetBytes?: number | undefined;+ readonly collapsed?: readonly string[] | undefined;+ },+): string {const safe = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;- return `_context injected: ${(safe / 1000).toFixed(1)}kB_`;+ const size = `${(safe / 1000).toFixed(1)}kB`;++ const budget = opts?.budgetBytes;+ if (budget === undefined || !Number.isFinite(budget) || budget <= 0) {+ return `_context injected: ${size}_`;+ }++ const ceiling = `${(budget / 1000).toFixed(1)}kB budget`;+ const collapsed = opts?.collapsed ?? [];+ if (collapsed.length === 0) {+ return `_context injected: ${size} / ${ceiling}_`;+ }+ return `_context injected: ${size} / ${ceiling} — collapsed: ${collapsed.join(", ")}_`;+}++/**+ * One assembled section of the eager layer, with what it costs and what it+ * degrades to when the injection is over budget.+ *+ * `priority` orders SURRENDER, not importance: the highest number is given+ * up first. A section with no `fallback` is load-bearing and never dropped+ * (identity, the date header) regardless of priority.+ */+export type BudgetSection = {+ /** Section heading, e.g. "### Vault File Listing". Empty for preamble. */+ readonly header: string;+ readonly body: string;+ readonly priority: number;+ readonly fallback?: string | undefined;+};++export type BudgetResult = {+ readonly text: string;+ readonly bytes: number;+ /** Headers (heading markup stripped) that were degraded, in drop order. */+ readonly collapsed: readonly string[];+};++function renderSections(sections: readonly BudgetSection[]): string {+ return sections+ .map((s) => (s.header === "" ? s.body : `${s.header}\n${s.body}`))+ .join("\n\n");+}++/**+ * Hold the eager layer under a byte ceiling by degrading the cheapest-to-lose+ * sections to their pointers, highest `priority` first, until it fits.+ *+ * Why bytes and not lines: the pre-existing caps in this file (`take`,+ * `formatActiveWork`, `collectOpenTasks`) are all LINE caps, and a line cap+ * cannot bound an injection — shortening entries just slides the window+ * deeper and refills it. Only a byte budget actually holds.+ *+ * Degradation is never silent truncation: a section is replaced whole by its+ * fallback pointer, so the content is missing but its existence is not.+ *+ * A non-finite or non-positive budget is a no-op — as with the size meter,+ * the budget must never be the thing that breaks the hook.+ */+export function applyInjectionBudget(+ sections: readonly BudgetSection[],+ budgetBytes: number,+): BudgetResult {+ const render = (s: readonly BudgetSection[]): BudgetResult => ({+ text: renderSections(s),+ bytes: Buffer.byteLength(renderSections(s), "utf-8"),+ collapsed: [],+ });++ if (!Number.isFinite(budgetBytes) || budgetBytes <= 0) return render(sections);++ let current = [...sections];+ if (render(current).bytes <= budgetBytes) return render(current);++ // Candidates are only those that can degrade, surrendered worst-first.+ const order = current+ .map((s, i) => ({ s, i }))+ .filter(({ s }) => s.fallback !== undefined && s.fallback !== s.body)+ .sort((a, b) => b.s.priority - a.s.priority || a.i - b.i);++ const collapsed: string[] = [];+ for (const { i } of order) {+ const target = current[i];+ if (target === undefined) continue;+ current[i] = { ...target, body: target.fallback ?? target.body };+ collapsed.push(target.header.replace(/^#+\s*/, ""));+ if (Buffer.byteLength(renderSections(current), "utf-8") <= budgetBytes) break;+ }++ const text = renderSections(current);+ return { text, bytes: Buffer.byteLength(text, "utf-8"), collapsed };+}++/**+ * Collapse a FLAT directory holding more than `threshold` notes to a single+ * count line.+ *+ * Replaces a hardcoded folder list: a fixed list only ever collapses the+ * folders someone remembered to name, so a vault grows past the ceiling+ * through whichever directory nobody listed. A threshold cannot go stale as+ * a vault evolves.+ *+ * `hasSubdirs` is the guard that makes this safe. Collapsing on recursive+ * subtree count folds whole TREES — `projects/`, `brain/`, `work/` all+ * vanish behind one line and the vault's shape becomes invisible, which is+ * far worse than the bytes it saves. The signal we actually want is flat+ * bulk: a folder of same-shaped sibling notes (people, archives, captures)+ * whose names are retrievable on demand. Structure is navigation and is+ * kept; flat bulk is noise and is folded. Anything the threshold declines+ * to fold is still caught by the byte budget — two mechanisms, two jobs.+ */+export const DEFAULT_LISTING_COLLAPSE_THRESHOLD = 12;++export function shouldCollapseDir(+ noteCount: number,+ threshold: number,+ alwaysCollapse: readonly string[],+ posixPath: string,+ hasSubdirs: boolean,+): boolean {+ if (alwaysCollapse.includes(posixPath)) return true;+ if (hasSubdirs) return false;+ if (!Number.isFinite(threshold) || threshold <= 0) return false;+ return noteCount > threshold;+}++/** The one-line stand-in for a collapsed directory. Shape predates the threshold. */+export function formatCollapsedDir(posixPath: string, noteCount: number): string {+ return `./${posixPath}/ — ${noteCount} notes (listing collapsed — Glob or QMD on demand)`;+}++function parsePositiveIntField(+ manifestJson: string | null,+ field: string,+): number | null {+ if (manifestJson === null) return null;+ try {+ const parsed = JSON.parse(manifestJson) as unknown;+ if (parsed !== null && typeof parsed === "object" && field in parsed) {+ const value = (parsed as Record<string, unknown>)[field];+ if (typeof value === "number" && Number.isInteger(value) && value > 0) {+ return value;+ }+ }+ } catch {+ /* malformed manifest → treat as missing */+ }+ return null;+}++/** `eager_layer_budget_bytes` from the manifest; null when unset or invalid. */+export function parseInjectionBudget(manifestJson: string | null): number | null {+ return parsePositiveIntField(manifestJson, "eager_layer_budget_bytes");+}++/** `listing_collapse_threshold` from the manifest; null when unset or invalid. */+export function parseListingCollapseThreshold(+ manifestJson: string | null,+): number | null {+ return parsePositiveIntField(manifestJson, "listing_collapse_threshold");}/**diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.tsindex f19ffc3..2b21da0 100644--- a/.claude/scripts/session-start.ts+++ b/.claude/scripts/session-start.ts@@ -42,6 +42,13 @@ import {isInfraFilename,isMarkdownFilename,collectOpenTasks,+ applyInjectionBudget,+ parseInjectionBudget,+ parseListingCollapseThreshold,+ shouldCollapseDir,+ formatCollapsedDir,+ DEFAULT_LISTING_COLLAPSE_THRESHOLD,+ type BudgetSection,} from "./lib/session-start.ts";import {buildQmdCommand,@@ -403,12 +410,38 @@ const SKIP_PREFIXES: readonly string[] = [".claude",];-// High-volume dirs the listing collapses to one count line (#107): the-// archive grows forever and its enumeration is orientation noise — Glob-// or QMD reach it on demand.-const COLLAPSED_DIRS: readonly string[] = ["work/archive"];+// Dirs that collapse to one count line regardless of size (#107): the+// archive is orientation noise whether it holds 3 notes or 300 — Glob or+// QMD reach it on demand. Everything else collapses by SIZE instead, via+// the threshold below, so a vault cannot grow past the ceiling through+// whichever folder nobody remembered to list here.+const ALWAYS_COLLAPSED_DIRS: readonly string[] = ["work/archive"];-function countMd(dir: string): number {+const listingCollapseThreshold =+ parseListingCollapseThreshold(manifestJson) ??+ DEFAULT_LISTING_COLLAPSE_THRESHOLD;++/**+ * One traversal that carries its own subtree count, so the collapse decision+ * costs nothing extra. (A separate recursive counter would re-walk every+ * subtree the listing walk already visited.)+ *+ * The count reflects what the listing WOULD have printed — skipped prefixes+ * are excluded — so a collapsed line never claims notes the expanded listing+ * would not have shown.+ */+type WalkResult = {+ readonly lines: readonly string[];+ readonly count: number;+ readonly hasSubdirs: boolean;+};++/**+ * Count-only recursion for directories that are collapsing regardless of+ * size. Building their descendant lines just to discard them is wasted work+ * on a large archive, so the always-collapse branch counts without walking.+ */+function countMdOnly(dir: string): number {let entries: Dirent[];try {entries = readdirSync(dir, { withFileTypes: true });@@ -417,87 +450,147 @@ function countMd(dir: string): number {}let n = 0;for (const e of entries) {- const full = join(dir, e.name);- if (e.isDirectory()) n += countMd(full);+ const posix = (dir === "." ? e.name : join(dir, e.name)).replaceAll("\\", "/");+ if (isSkippedPath(posix, SKIP_PREFIXES)) continue;+ if (e.isDirectory()) n += countMdOnly(posix);else if (e.isFile() && isMarkdownFilename(e.name)) n += 1;}return n;}-function listMd(): string[] {- const results: string[] = [];- function walk(dir: string): void {- let entries: Dirent[];- try {- entries = readdirSync(dir, { withFileTypes: true });- } catch {- return;- }- for (const e of entries) {- const full = dir === "." ? e.name : join(dir, e.name);- if (isSkippedPath(full, SKIP_PREFIXES)) continue;- if (e.isDirectory()) {- const posix = full.replaceAll("\\", "/");- if (COLLAPSED_DIRS.includes(posix)) {- results.push(- `./${posix}/ — ${countMd(full)} notes (listing collapsed — Glob or QMD on demand)`,- );- continue;- }- walk(full);- } else if (e.isFile() && isMarkdownFilename(e.name)) results.push(`./${full}`);+function walkMd(dir: string): WalkResult {+ let entries: Dirent[];+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ return { lines: [], count: 0, hasSubdirs: false };+ }+ const lines: string[] = [];+ let count = 0;+ let hasSubdirs = false;+ for (const e of entries) {+ // Normalise to posix BEFORE the skip check: `isSkippedPath` matches on+ // `prefix + "/"`, so a Windows `\` separator would let nested paths+ // under a skipped prefix through.+ const full = (dir === "." ? e.name : join(dir, e.name)).replaceAll("\\", "/");+ if (isSkippedPath(full, SKIP_PREFIXES)) continue;+ if (e.isDirectory()) {+ hasSubdirs = true;+ const posix = full;+ // Always-collapse dirs never render their descendants — count only.+ if (ALWAYS_COLLAPSED_DIRS.includes(posix)) {+ const n = countMdOnly(full);+ count += n;+ lines.push(formatCollapsedDir(posix, n));+ continue;+ }+ const sub = walkMd(full);+ count += sub.count;+ if (+ shouldCollapseDir(+ sub.count,+ listingCollapseThreshold,+ ALWAYS_COLLAPSED_DIRS,+ posix,+ sub.hasSubdirs,+ )+ ) {+ lines.push(formatCollapsedDir(posix, sub.count));+ } else {+ lines.push(...sub.lines);+ }+ } else if (e.isFile() && isMarkdownFilename(e.name)) {+ lines.push(`./${full}`);+ count += 1;}}- walk(".");- return results.sort();+ return { lines, count, hasSubdirs };+}++function listMd(): string[] {+ return [...walkMd(".").lines].sort();}// Source-aware assembly (#107): on resume/compact the static bulk (North// Star, brain index, file listing) is already in-conversation — a pointer// replaces it, and only the volatile sections (recent changes, tasks,// active work, hygiene, QMD notes) re-inject.-const sections = [- "## Session Context",- "",- "### Date",- formatDateHeader(new Date()),- "",+// `priority` orders SURRENDER under budget, highest first. Sections with no+// fallback are load-bearing and never degrade. The listing goes first: it is+// the section that grows with every note and is fully reconstructible with+// one Glob. Hygiene never degrades — it is small and it is actionable.+const PRIORITY = {+ LOAD_BEARING: 0,+ HYGIENE: 5,+ VOLATILE: 10,+ RECENT_CHANGES: 20,+ NORTH_STAR: 30,+ BRAIN_INDEX: 40,+ FILE_LISTING: 50,+} as const;++const sections: BudgetSection[] = [+ { header: "", body: "## Session Context", priority: PRIORITY.LOAD_BEARING },+ {+ header: "### Date",+ body: formatDateHeader(new Date()),+ priority: PRIORITY.LOAD_BEARING,+ },];if (mode === "full") {sections.push(- "### North Star (current goals)",- northStar(),- "",- "### Brain Topics (read on demand)",- brainIndex(),- "",+ {+ header: "### North Star (current goals)",+ body: northStar(),+ priority: PRIORITY.NORTH_STAR,+ fallback: "(Over budget — re-read brain/North Star.md on demand.)",+ },+ {+ header: "### Brain Topics (read on demand)",+ body: brainIndex(),+ priority: PRIORITY.BRAIN_INDEX,+ fallback: "(Over budget — list brain/ on demand.)",+ },);}sections.push(- "### Recent Changes (last 48h)",- recentChanges(),- "",- "### Open Tasks",- openTasks(),- "",- "### Active Work",- activeWork(),+ {+ header: "### Recent Changes (last 48h)",+ body: recentChanges(),+ priority: PRIORITY.RECENT_CHANGES,+ fallback: "(Over budget — run git log on demand.)",+ },+ { header: "### Open Tasks", body: openTasks(), priority: PRIORITY.VOLATILE },+ { header: "### Active Work", body: activeWork(), priority: PRIORITY.VOLATILE },);if (mode === "full") {- sections.push("", "### Vault File Listing", listMd().join("\n"));+ sections.push({+ header: "### Vault File Listing",+ body: listMd().join("\n"),+ priority: PRIORITY.FILE_LISTING,+ fallback: "(Over budget — Glob or QMD the vault on demand.)",+ });} else {- sections.push(- "",- "### Context Pointer",- "(Re-entry via resume/compact — North Star, brain index, and the file listing were injected at session start and are unchanged; re-read on demand.)",- );+ sections.push({+ header: "### Context Pointer",+ body: "(Re-entry via resume/compact — North Star, brain index, and the file listing were injected at session start and are unchanged; re-read on demand.)",+ priority: PRIORITY.LOAD_BEARING,+ });}if (qmdSelfHealNote !== null) {- sections.push("", "### QMD Self-Heal", qmdSelfHealNote);+ sections.push({+ header: "### QMD Self-Heal",+ body: qmdSelfHealNote,+ priority: PRIORITY.LOAD_BEARING,+ });}if (qmdVersionNote !== null) {- sections.push("", "### QMD Version", qmdVersionNote);+ sections.push({+ header: "### QMD Version",+ body: qmdVersionNote,+ priority: PRIORITY.LOAD_BEARING,+ });}// Hygiene drift flags (#98/#103/#106): silent when the vault is clean, so@@ -511,10 +604,25 @@ const hygieneLines = formatActiveHygiene(),);if (hygieneLines.length > 0) {- sections.push("", "### Vault Hygiene (drift detected)", hygieneLines.join("\n"));+ sections.push({+ header: "### Vault Hygiene (drift detected)",+ body: hygieneLines.join("\n"),+ priority: PRIORITY.HYGIENE,+ });}-const body = sections.join("\n") + "\n";+// The eager layer is held under a byte ceiling. Unset budget = measure only,+// which is the pre-budget behaviour, so an un-migrated vault is unaffected.+const budgetBytes = parseInjectionBudget(manifestJson);+const budgeted = applyInjectionBudget(sections, budgetBytes ?? 0);++const body = budgeted.text + "\n";process.stdout.write(- body + "\n" + formatInjectionSize(Buffer.byteLength(body, "utf-8")) + "\n",+ body ++ "\n" ++ formatInjectionSize(Buffer.byteLength(body, "utf-8"), {+ budgetBytes: budgetBytes ?? undefined,+ collapsed: budgeted.collapsed,+ }) ++ "\n",);diff --git a/.claude/scripts/tests/session-start.integration.test.ts b/.claude/scripts/tests/session-start.integration.test.tsindex 1f1e17b..7dfc235 100644--- a/.claude/scripts/tests/session-start.integration.test.ts+++ b/.claude/scripts/tests/session-start.integration.test.ts@@ -168,3 +168,139 @@ describe("session-start — openTasks aggregation", () => {}});});++/**+ * The eager layer must stay bounded as a vault grows. These run against a+ * SEPARATE oversized vault so the fixtures above stay minimal.+ */+describe("session-start — listing collapse and injection budget", () => {+ let BIG_DIR = "";++ before(() => {+ BIG_DIR = mkdtempSync(join(tmpdir(), "session-start-budget-"));+ mkdirSync(join(BIG_DIR, "brain"), { recursive: true });+ writeFileSync(+ join(BIG_DIR, "brain", "North Star.md"),+ "---\ndescription: test\n---\n\n# North Star\n\n- placeholder\n",+ );+ // 40 notes in one folder — well past the default threshold.+ mkdirSync(join(BIG_DIR, "people"), { recursive: true });+ for (let i = 0; i < 40; i++) {+ writeFileSync(+ join(BIG_DIR, "people", `Person ${String(i).padStart(2, "0")}.md`),+ "---\ndescription: x\n---\n\n# p\n",+ );+ }+ // 3 notes — comfortably under it.+ mkdirSync(join(BIG_DIR, "strategy"), { recursive: true });+ for (let i = 0; i < 3; i++) {+ writeFileSync(join(BIG_DIR, "strategy", `Doc ${i}.md`), "---\ndescription: x\n---\n");+ }+ // A TREE well past the threshold: 30 notes, but spread over subdirs.+ // It must stay expanded — folding it would hide the vault's shape.+ for (const p of ["alpha", "beta", "gamma"]) {+ mkdirSync(join(BIG_DIR, "projects", p), { recursive: true });+ for (let i = 0; i < 10; i++) {+ writeFileSync(+ join(BIG_DIR, "projects", p, `Note ${i}.md`),+ "---\ndescription: x\n---\n",+ );+ }+ }+ });++ after(() => {+ if (BIG_DIR) {+ rmSync(BIG_DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });+ }+ });++ const runBig = () => spawnHook(SCRIPT, "", { CLAUDE_PROJECT_DIR: BIG_DIR });+ const listingOf = (stdout: string) =>+ stdout.split("### Vault File Listing\n")[1]?.split("\n### ")[0] ?? "";++ test("a directory over the threshold collapses; one under it stays expanded", () => {+ const { stdout, code, stderr } = runBig();+ assert.equal(code, 0);+ assert.equal(stderr, "");+ const listing = listingOf(stdout);+ assert.match(+ listing,+ /\.\/people\/ — 40 notes \(listing collapsed/,+ "a 40-note folder must fold to one count line",+ );+ assert.doesNotMatch(listing, /Person 07/, "collapsed folders enumerate nothing");+ assert.match(listing, /strategy[\\/]Doc 1\.md/, "a 3-note folder stays expanded");+ });++ test("a 30-note TREE stays expanded — structure is navigation, not bulk", () => {+ const listing = listingOf(runBig().stdout);+ assert.doesNotMatch(+ listing,+ /\.\/projects\/ — \d+ notes/,+ "a directory with subdirectories must never collapse on size",+ );+ assert.match(listing, /projects[\\/]beta[\\/]Note 4\.md/);+ // Its flat leaves are still folded — 10 notes is under the default 12.+ assert.match(listing, /projects[\\/]alpha[\\/]Note 0\.md/);+ });++ test("no manifest budget → plain meter, nothing collapsed (pre-budget behaviour)", () => {+ const { stdout } = runBig();+ const last = stdout.split("\n").filter((l) => l.trim() !== "").pop() ?? "";+ assert.match(last, /^_context injected: \d+\.\dkB_$/);+ });++ test("a tight manifest budget degrades sections and NAMES them in the meter", () => {+ const manifest = join(BIG_DIR, "vault-manifest.json");+ writeFileSync(manifest, JSON.stringify({ eager_layer_budget_bytes: 400 }));+ try {+ const { stdout, code, stderr } = runBig();+ assert.equal(code, 0);+ assert.equal(stderr, "", "the budget must never break the silence contract");++ const last = stdout.split("\n").filter((l) => l.trim() !== "").pop() ?? "";+ assert.match(+ last,+ /^_context injected: \d+\.\dkB \/ 0\.4kB budget — collapsed: .+_$/,+ `meter must report the ceiling and name what it dropped, got: ${last}`,+ );+ // The listing is the first thing surrendered.+ assert.match(last, /collapsed: Vault File Listing/);+ assert.match(listingOf(stdout), /Over budget/, "dropped body is a pointer, not silence");+ // Degrading is never truncation: the header survives so the session+ // knows the section exists and can go get it.+ assert.ok(stdout.includes("### Vault File Listing"));+ assert.ok(stdout.includes("### Date"), "load-bearing sections are untouched");+ } finally {+ rmSync(manifest, { force: true });+ }+ });++ test("a generous budget collapses nothing but still reports the ceiling", () => {+ const manifest = join(BIG_DIR, "vault-manifest.json");+ writeFileSync(manifest, JSON.stringify({ eager_layer_budget_bytes: 5_000_000 }));+ try {+ const last =+ runBig().stdout.split("\n").filter((l) => l.trim() !== "").pop() ?? "";+ assert.match(last, /^_context injected: \d+\.\dkB \/ 5000\.0kB budget_$/);+ } finally {+ rmSync(manifest, { force: true });+ }+ });++ test("manifest threshold overrides the default", () => {+ const manifest = join(BIG_DIR, "vault-manifest.json");+ writeFileSync(manifest, JSON.stringify({ listing_collapse_threshold: 2 }));+ try {+ const listing = listingOf(runBig().stdout);+ assert.match(+ listing,+ /\.\/strategy\/ — 3 notes \(listing collapsed/,+ "a threshold of 2 must fold the 3-note folder that the default kept",+ );+ } finally {+ rmSync(manifest, { force: true });+ }+ });+});diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.tsindex ac322b4..4f7472a 100644--- a/.claude/scripts/tests/session-start.test.ts+++ b/.claude/scripts/tests/session-start.test.ts@@ -13,6 +13,13 @@ import {formatDateHeader,formatInjectionSize,injectionMode,+ applyInjectionBudget,+ shouldCollapseDir,+ formatCollapsedDir,+ parseInjectionBudget,+ parseListingCollapseThreshold,+ DEFAULT_LISTING_COLLAPSE_THRESHOLD,+ type BudgetSection,formatActiveWork,formatRecentChanges,isSkippedPath,@@ -658,6 +665,196 @@ describe("formatInjectionSize", () => {assert.equal(formatInjectionSize(bytes), expected);});}++ test("an unset budget keeps the pre-budget line byte-identical", () => {+ assert.equal(formatInjectionSize(58_400, {}), "_context injected: 58.4kB_");+ });+ test("a budget with nothing collapsed reports the ceiling", () => {+ assert.equal(+ formatInjectionSize(30_000, { budgetBytes: 40_000 }),+ "_context injected: 30.0kB / 40.0kB budget_",+ );+ });+ test("collapsed sections are NAMED — a silent loss is worse than the bloat", () => {+ assert.equal(+ formatInjectionSize(39_800, {+ budgetBytes: 40_000,+ collapsed: ["Vault File Listing", "Brain Topics (read on demand)"],+ }),+ "_context injected: 39.8kB / 40.0kB budget — collapsed: Vault File Listing, Brain Topics (read on demand)_",+ );+ });+ test("a nonsense budget degrades to the plain meter, never throws", () => {+ for (const b of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {+ assert.equal(+ formatInjectionSize(1_000, { budgetBytes: b }),+ "_context injected: 1.0kB_",+ );+ }+ });+});++describe("applyInjectionBudget", () => {+ const mk = (+ header: string,+ body: string,+ priority: number,+ fallback?: string,+ ): BudgetSection =>+ fallback === undefined+ ? { header, body, priority }+ : { header, body, priority, fallback };++ test("under budget → untouched, nothing collapsed", () => {+ const s = [mk("### A", "short", 10, "(dropped)")];+ const r = applyInjectionBudget(s, 10_000);+ assert.equal(r.text, "### A\nshort");+ assert.deepEqual(r.collapsed, []);+ });++ test("renders header+body joined by a blank line (pre-budget shape)", () => {+ const r = applyInjectionBudget(+ [mk("", "## Session Context", 0), mk("### Date", "2026-07-24", 0)],+ 10_000,+ );+ assert.equal(r.text, "## Session Context\n\n### Date\n2026-07-24");+ });++ test("surrenders the HIGHEST priority first", () => {+ const s = [+ mk("### Keep", "x".repeat(50), 10, "(k)"),+ mk("### Drop", "y".repeat(50), 90, "(d)"),+ ];+ const r = applyInjectionBudget(s, 80);+ assert.deepEqual(r.collapsed, ["Drop"]);+ assert.match(r.text, /### Drop\n\(d\)/);+ assert.ok(+ !r.text.includes("y"),+ "the dropped body must be replaced WHOLE, not truncated — no residue",+ );+ assert.ok(r.text.includes("x".repeat(50)), "the lower-priority section survives");+ });++ test("keeps surrendering until it fits, in descending priority", () => {+ const s = [+ mk("### Third", "c".repeat(100), 10, "(c)"),+ mk("### First", "a".repeat(100), 50, "(a)"),+ mk("### Second", "b".repeat(100), 30, "(b)"),+ ];+ // 335 B intact; 238 after First collapses; 141 after Second. A 150 B+ // ceiling therefore lands exactly two collapses deep and stops.+ const r = applyInjectionBudget(s, 150);+ assert.deepEqual(r.collapsed, ["First", "Second"]);+ assert.ok(r.text.includes("c".repeat(100)), "the lowest priority is still intact");+ });++ test("a section without a fallback is load-bearing and never degrades", () => {+ const s = [mk("### Identity", "z".repeat(500), 99)];+ const r = applyInjectionBudget(s, 10);+ assert.deepEqual(r.collapsed, []);+ assert.ok(r.text.includes("z".repeat(500)), "identity survives an impossible budget");+ assert.ok(r.bytes > 10, "over budget is reported honestly, not faked");+ });++ test("stops once it fits — does not over-collapse", () => {+ const s = [+ mk("### Big", "a".repeat(200), 50, "(a)"),+ mk("### Also", "b".repeat(60), 40, "(b)"),+ ];+ const r = applyInjectionBudget(s, 100);+ assert.deepEqual(r.collapsed, ["Big"], "second section kept once the first freed enough");+ });++ test("a nonsense budget is a no-op, never throws", () => {+ const s = [mk("### A", "x".repeat(999), 10, "(short)")];+ for (const b of [0, -5, Number.NaN]) {+ const r = applyInjectionBudget(s, b);+ assert.deepEqual(r.collapsed, []);+ assert.ok(r.text.includes("x".repeat(999)));+ }+ });++ test("bytes are measured in UTF-8, not UTF-16 code units", () => {+ // Four 3-byte chars: 12 bytes, but only 4 .length units. A budget of 8+ // must therefore collapse — the bug this guards is measuring .length.+ const s = [mk("", "日本語版", 50, "x")];+ const r = applyInjectionBudget(s, 8);+ assert.deepEqual(r.collapsed, [""]);+ });+});++describe("shouldCollapseDir", () => {+ const flat = false;+ const tree = true;++ test("collapses a flat folder strictly above the threshold, not at it", () => {+ assert.equal(shouldCollapseDir(12, 12, [], "people", flat), false);+ assert.equal(shouldCollapseDir(13, 12, [], "people", flat), true);+ });++ test("NEVER collapses a folder with subdirectories, however large", () => {+ // The regression this locks: collapsing on recursive subtree count+ // folded `projects/`, `brain/` and `work/` into three lines and made+ // the vault's shape invisible. Structure is navigation; only flat+ // bulk is noise.+ assert.equal(shouldCollapseDir(9_999, 12, [], "projects", tree), false);+ });++ test("an always-collapse dir folds regardless of size OR structure", () => {+ // work/archive is year-foldered, so the subdir guard would spare it;+ // the explicit list is what makes semantic exceptions still work.+ assert.equal(+ shouldCollapseDir(1, 999, ["work/archive"], "work/archive", tree),+ true,+ );+ });++ test("matching is on the posix path, so nesting is respected", () => {+ assert.equal(shouldCollapseDir(1, 999, ["reference/cv"], "cv", flat), false);+ });++ test("a nonsense threshold collapses nothing by size", () => {+ for (const t of [0, -1, Number.NaN]) {+ assert.equal(shouldCollapseDir(9_999, t, [], "people", flat), false);+ }+ });+});++describe("formatCollapsedDir", () => {+ test("keeps the pre-threshold line shape verbatim", () => {+ assert.equal(+ formatCollapsedDir("work/archive", 42),+ "./work/archive/ — 42 notes (listing collapsed — Glob or QMD on demand)",+ );+ });+});++describe("manifest budget fields", () => {+ const cases: ReadonlyArray<readonly [string | null, number | null]> = [+ ['{"eager_layer_budget_bytes":40000}', 40_000],+ ['{"eager_layer_budget_bytes":0}', null], // non-positive → unset+ ['{"eager_layer_budget_bytes":-1}', null],+ ['{"eager_layer_budget_bytes":"40000"}', null], // string → unset+ ['{"eager_layer_budget_bytes":1.5}', null], // non-integer → unset+ ["{}", null],+ ["not json", null],+ [null, null],+ ];+ for (const [json, expected] of cases) {+ test(`parseInjectionBudget(${String(json)}) → ${String(expected)}`, () => {+ assert.equal(parseInjectionBudget(json), expected);+ });+ }++ test("parseListingCollapseThreshold reads its own field", () => {+ assert.equal(parseListingCollapseThreshold('{"listing_collapse_threshold":25}'), 25);+ assert.equal(parseListingCollapseThreshold('{"eager_layer_budget_bytes":25}'), null);+ });++ test("the shipped default threshold is a positive integer", () => {+ assert.ok(Number.isInteger(DEFAULT_LISTING_COLLAPSE_THRESHOLD));+ assert.ok(DEFAULT_LISTING_COLLAPSE_THRESHOLD > 0);+ });});describe("resolveIndexStorePath", () => {diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 3211d0c..89e42ea 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -75,7 +75,13 @@ All durable knowledge lives in the vault, inside `brain/` topic notes. The agent### 3. Progressive disclosure-`SessionStart` injects ~2K tokens of lightweight context (North Star excerpt, git summary, tasks, file listing). Full note contents are pulled on demand via QMD semantic search. A full file read is a last resort, not a default. This keeps session cost flat regardless of vault size.+`SessionStart` injects a small block of lightweight context (North Star excerpt, git summary, tasks, file listing). Full note contents are pulled on demand via QMD semantic search. A full file read is a last resort, not a default.++Session cost stays flat regardless of vault size because it is **enforced**, not merely intended. Two of those inputs grow with the vault — the file listing grows with every note, the North Star excerpt with every status edit — so without a ceiling the eager layer drifts upward a little every day and nobody notices until a session is paying for it. A byte budget holds the total; over it, the cheapest-to-lose sections degrade to pointers, worst-priority first, and the closing size meter names each one it dropped. Line-based caps cannot do this job: shortening entries under a line cap just slides the window deeper and refills it. Budget and listing-collapse threshold are set in `vault-manifest.json`.++**The budget is a runaway guard, not a squeeze — set it above everything worth injecting.** The meter is the detector; the budget is only the emergency brake. A ceiling low enough to bite in normal use degrades your context every session instead of catching a problem, and the two failures are not symmetric: a ceiling set too high still leaves the drift visible in the meter every session, while one set too low silently removes context you never learn you were missing. If the budget starts firing, the right response is usually to raise it and look at what grew — not to accept running degraded.++The same asymmetry decides *what* may degrade. Rank the eager layer by **value density, not size**: filenames are the cheapest bytes (one Glob rebuilds them), so the listing surrenders first. Anything irreplaceable — identity, personal context, correctness guards — carries no fallback and is never traded for plumbing. Optimizing this layer means removing **duplication**, not **information**, which is exactly why re-entry via resume/compact drops the static bulk: it is already in the conversation, so omitting it loses nothing.### 4. Agent-agnostic corediff --git a/CLAUDE.md b/CLAUDE.mdindex 1eaa02c..0ff1229 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -321,7 +321,7 @@ Five lifecycle hooks in `.claude/settings.json`:| Hook | When | What ||------|------|------|-| SessionStart | On startup/resume | QMD re-index + self-heal, inject North Star, active work, recent changes, tasks, file listing, vault-hygiene drift flags (completed-not-archived, ungrouped clusters, 25KB oversize, stale open loops, meetings-inbox pressure); ends with an injection-size meter line |+| SessionStart | On startup/resume | QMD re-index + self-heal, inject North Star, active work, recent changes, tasks, file listing (folders past a note-count threshold collapse to one line), vault-hygiene drift flags (completed-not-archived, ungrouped clusters, 25KB oversize, stale open loops, meetings-inbox pressure); the whole injection is held under a byte budget — over it, low-priority sections degrade to pointers and the closing injection-size meter names each one it dropped || UserPromptSubmit | Every message | Classifies content (decision, incident, win, 1:1, architecture, person, project update) and injects routing hints || PostToolUse | After writing `.md` | Validates frontmatter + wikilinks, blocks misplaced memory files, flags notes crossing the 25KB organization threshold (split, don't trim) and write-time topic clusters || PreCompact | Before context compaction | Backs up session transcript to `thinking/session-logs/` |diff --git a/README.ja.md b/README.ja.mdindex 7813e8d..a3279dc 100644--- a/README.ja.md+++ b/README.ja.md@@ -175,7 +175,7 @@ qmd --index obsidian-mind embed # 多数の新規ノート後| フック | タイミング | 内容 ||------|------|------|-| 🚀 SessionStart | 起動/再開時 | QMD再インデックス+セルフヒール、North Starフォーカス・アクティブプロジェクト・最近の変更・タスク・ファイル一覧・ボールト衛生フラグを注入 — 最終行は注入サイズメーター |+| 🚀 SessionStart | 起動/再開時 | QMD再インデックス+セルフヒール、North Starフォーカス・アクティブプロジェクト・最近の変更・タスク・ファイル一覧・ボールト衛生フラグを注入 — 全体はバイトバジェットで抑えられ、最終行は注入サイズメーター || 💬 UserPromptSubmit | 全メッセージ | コンテンツを分類(意思決定、インシデント、実績、1on1、アーキテクチャ、人物、プロジェクト更新)してルーティングヒントを注入 || ✍️ PostToolUse | `.md`書き込み後 | フロントマター+ウィキリンクの検証、誤配置メモリファイルのブロック、肥大ノート(削るのではなく分割)と書き込み時トピッククラスタのフラグ || 💾 PreCompact | コンテキスト圧縮前 | セッション記録を`thinking/session-logs/`にバックアップ |@@ -196,7 +196,7 @@ obsidian-mindはボールト全体をコンテキストに読み込み**ませ| **トリガー** | PostToolUse検証 | `.md`書き込み後 | ~200トークン || **まれ** | ファイル全体の読み込み | 明示的に必要な場合のみ | 可変 |-SessionStartは**軽量なコンテキスト**を読み込みます — 主要ファイルからの短い抜粋、ファイル名、git概要のみで、ノート全体は読み込みません。エージェントはQMDで意味検索してからファイルを読むため、関連する情報のみを取得します。分類フックはメッセージごとに軽量なNode呼び出し1回です。検証フックはMarkdown書き込み時のみ発火し、除外パスはスキップします。 ボールトが成長しても注入層を正直に保つ4つの仕組み: **ソース認識注入**(resume/compact時は揮発セクションのみ再注入 — 静的な大部分はすでに会話内にある)、全注入の最終行に付く**注入サイズメーター**、書き込みごとの**フック起動は1プロセスのみ**(QMDリフレッシュは検証フックに同乗)、**一覧の折りたたみ**(アーカイブは1行のカウント表示に)。+SessionStartは**軽量なコンテキスト**を読み込みます — 主要ファイルからの短い抜粋、ファイル名、git概要のみで、ノート全体は読み込みません。エージェントはQMDで意味検索してからファイルを読むため、関連する情報のみを取得します。分類フックはメッセージごとに軽量なNode呼び出し1回です。検証フックはMarkdown書き込み時のみ発火し、除外パスはスキップします。 ボールトが成長しても注入層を正直に保つ5つの仕組み: **ソース認識注入**(resume/compact時は揮発セクションのみ再注入 — 静的な大部分はすでに会話内にある)、全注入の最終行に付く**注入サイズメーター**、メーターが計測する値を実際に強制する**注入バジェット**(上限を超えると失っても影響の小さいセクションからポインタに縮退し、縮退したものはメーターに必ず名前が出る — 黙って失われる方が肥大化より悪いため)、書き込みごとの**フック起動は1プロセスのみ**(QMDリフレッシュは検証フックに同乗)、**一覧の折りたたみ**(ノート数のしきい値を超えたフォルダは1行のカウント表示に畳まれるので、誰も設定し忘れたフォルダ経由でボールトが上限を超えて育つことはない)。バジェットとしきい値はどちらも `vault-manifest.json` で調整できます。### 🌐 他のエージェントでの利用diff --git a/README.ko.md b/README.ko.mdindex d867605..a183a75 100644--- a/README.ko.md+++ b/README.ko.md@@ -175,7 +175,7 @@ qmd --index obsidian-mind embed # 많은 신규 노트 후| 훅 | 시점 | 동작 ||------|------|------|-| 🚀 SessionStart | 시작/재개 시 | QMD 재인덱싱+셀프힐, North Star 포커스·활성 작업·최근 변경사항·작업·파일 목록·볼트 위생 플래그 주입 — 마지막 줄은 주입 크기 미터 |+| 🚀 SessionStart | 시작/재개 시 | QMD 재인덱싱+셀프힐, North Star 포커스·활성 작업·최근 변경사항·작업·파일 목록·볼트 위생 플래그 주입 — 전체는 바이트 예산으로 제한되고, 마지막 줄은 주입 크기 미터 || 💬 UserPromptSubmit | 매 메시지마다 | 콘텐츠 분류(의사결정, 인시던트, 성과, 1:1, 아키텍처, 인물, 프로젝트 업데이트) 및 라우팅 힌트 주입 || ✍️ PostToolUse | `.md` 작성 후 | 프론트매터+위키링크 검증, 잘못 배치된 메모리 파일 차단, 비대 노트(줄이지 말고 분할)와 작성 시점 토픽 클러스터 플래그 || 💾 PreCompact | 컨텍스트 압축 전 | 세션 트랜스크립트를 `thinking/session-logs/`에 백업 |@@ -196,7 +196,7 @@ obsidian-mind는 전체 볼트를 컨텍스트에 로드하지 **않습니다**.| **트리거** | PostToolUse 검증 | `.md` 작성 후 | ~200 토큰 || **드물게** | 전체 파일 읽기 | 명시적으로 필요한 경우만 | 가변 |-SessionStart는 **가벼운 컨텍스트**를 로드합니다 — 주요 파일의 짧은 발췌, 파일명, git 요약만 로드하며 전체 노트 내용은 읽지 않습니다. 에이전트는 QMD를 통해 의미 기반 검색 후 파일을 읽으므로 관련 정보만 가져옵니다. 분류 훅은 메시지당 가벼운 Node 호출 1회입니다. 검증 훅은 마크다운 쓰기 시에만 실행되며 제외된 경로는 건너뜁니다. 볼트가 커져도 주입 계층을 정직하게 유지하는 네 가지 메커니즘: **소스 인식 주입** (resume/compact 시 휘발성 섹션만 재주입 — 정적인 대부분은 이미 대화에 있음), 모든 주입의 마지막 줄에 붙는 **주입 크기 미터**, 쓰기당 **훅 프로세스 1회** (QMD 리프레시가 검증 훅에 동승), **목록 접기** (아카이브는 한 줄 카운트로 접힘).+SessionStart는 **가벼운 컨텍스트**를 로드합니다 — 주요 파일의 짧은 발췌, 파일명, git 요약만 로드하며 전체 노트 내용은 읽지 않습니다. 에이전트는 QMD를 통해 의미 기반 검색 후 파일을 읽으므로 관련 정보만 가져옵니다. 분류 훅은 메시지당 가벼운 Node 호출 1회입니다. 검증 훅은 마크다운 쓰기 시에만 실행되며 제외된 경로는 건너뜁니다. 볼트가 커져도 주입 계층을 정직하게 유지하는 다섯 가지 메커니즘: **소스 인식 주입** (resume/compact 시 휘발성 섹션만 재주입 — 정적인 대부분은 이미 대화에 있음), 모든 주입의 마지막 줄에 붙는 **주입 크기 미터**, 미터가 측정한 값을 실제로 강제하는 **주입 예산** (상한을 넘으면 잃어도 되는 섹션부터 포인터로 축소되고, 축소된 섹션 이름은 미터에 반드시 표시됨 — 조용한 손실이 비대화보다 나쁘기 때문), 쓰기당 **훅 프로세스 1회** (QMD 리프레시가 검증 훅에 동승), **목록 접기** (노트 수 임계값을 넘는 폴더는 한 줄 카운트로 접히므로, 아무도 설정하지 않은 폴더를 통해 볼트가 상한을 넘어 자랄 수 없음). 예산과 임계값 모두 `vault-manifest.json` 에서 조정할 수 있습니다.### 🌐 다른 에이전트와 사용하기diff --git a/README.md b/README.mdindex de2ddba..0901634 100644--- a/README.md+++ b/README.md@@ -182,7 +182,7 @@ Five lifecycle hooks handle routing automatically:| Hook | When | What ||------|------|------|-| 🚀 SessionStart | On startup/resume | QMD re-index + self-heal, inject North Star focus, active work, recent changes, tasks, file listing, vault-hygiene drift flags — ending with an injection-size meter |+| 🚀 SessionStart | On startup/resume | QMD re-index + self-heal, inject North Star focus, active work, recent changes, tasks, file listing, vault-hygiene drift flags — held under a byte budget, ending with an injection-size meter || 💬 UserPromptSubmit | Every message | Classifies content (decision, incident, win, 1:1, architecture, person, project update) and injects routing hints || ✍️ PostToolUse | After writing `.md` | Validates frontmatter + wikilinks, blocks misplaced memory files, flags oversized notes (split, don't trim) and write-time topic clusters || 💾 PreCompact | Before context compaction | Backs up session transcript to `thinking/session-logs/` |@@ -203,7 +203,7 @@ obsidian-mind does **not** dump your entire vault into context. It uses tiered l| **Triggered** | PostToolUse validation | After `.md` writes | ~200 tokens || **Rare** | Full file reads | Only when explicitly needed | Variable |-SessionStart loads **lightweight context** — small excerpts from key files, filenames, and git summary — not full note contents. Four mechanisms keep the eager layer honest as the vault grows: **source-aware injection** (resume/compact re-inject only volatile sections — the static bulk is already in-conversation), an **injection-size meter** as the last line of every injection (you always see what context costs), a **single hook spawn per write** (the QMD refresh rides the validation hook), and **listing collapse** (the archive folds to one count line). The agent queries by meaning via QMD before reading files, so it pulls only what's relevant. The classification hook is one lightweight Node call per message. The validation hook only fires on markdown writes and skips excluded paths.+SessionStart loads **lightweight context** — small excerpts from key files, filenames, and git summary — not full note contents. Five mechanisms keep the eager layer honest as the vault grows: **source-aware injection** (resume/compact re-inject only volatile sections — the static bulk is already in-conversation), an **injection-size meter** as the last line of every injection (you always see what context costs), an **injection budget** that enforces what the meter measures (over the ceiling, the cheapest-to-lose sections degrade to pointers — and the meter names every one it dropped, because a silent loss is worse than the bloat), a **single hook spawn per write** (the QMD refresh rides the validation hook), and **listing collapse** (any folder past a note-count threshold folds to one count line, so a vault can't outgrow the ceiling through whichever folder nobody thought to configure). Both the budget and the threshold are tunable in `vault-manifest.json`. The agent queries by meaning via QMD before reading files, so it pulls only what's relevant. The classification hook is one lightweight Node call per message. The validation hook only fires on markdown writes and skips excluded paths.### 🌐 Using with Other Agentsdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 8691dea..9f8abbc 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -175,7 +175,7 @@ qmd --index obsidian-mind embed # 大量新笔记后| 钩子 | 触发时机 | 功能 ||------|---------|------|-| 🚀 SessionStart | 启动/恢复时 | QMD 重新索引+自愈,注入北极星焦点、活跃工作、最近变更、任务、文件列表、仓库卫生标志 — 末行为注入大小计量 |+| 🚀 SessionStart | 启动/恢复时 | QMD 重新索引+自愈,注入北极星焦点、活跃工作、最近变更、任务、文件列表、仓库卫生标志 — 整体受字节预算约束,末行为注入大小计量 || 💬 UserPromptSubmit | 每条消息 | 对内容分类(决策、事件、成就、1:1、架构、人员、项目更新)并注入路由提示 || ✍️ PostToolUse | 写入 `.md` 后 | 验证 frontmatter+wikilinks,拦截误放的记忆文件,标记过大笔记(拆分而非删减)与写入时的主题集群 || 💾 PreCompact | 上下文压缩前 | 将会话记录备份到 `thinking/session-logs/` |@@ -196,7 +196,7 @@ obsidian-mind **不会**将整个 vault 加载到上下文中。它使用分层| **触发** | PostToolUse 验证 | `.md` 写入后 | ~200 tokens || **罕见** | 完整文件读取 | 仅在明确需要时 | 可变 |-SessionStart 加载**轻量级上下文** — 关键文件的简短摘要、文件名和 git 摘要,而非完整笔记内容。Agent 通过 QMD 进行语义搜索后再读取文件,因此只获取相关内容。分类钩子每条消息仅执行一次轻量级 Node 调用。验证钩子仅在 markdown 写入时触发,跳过排除的路径。 四个机制让注入层随仓库增长仍保持诚实:**来源感知注入**(resume/compact 时只重新注入易变部分——静态大块已在会话中)、每次注入末行的**注入大小计量**、每次写入**仅一次钩子进程**(QMD 刷新搭载在验证钩子上)、**列表折叠**(归档折叠为一行计数)。+SessionStart 加载**轻量级上下文** — 关键文件的简短摘要、文件名和 git 摘要,而非完整笔记内容。Agent 通过 QMD 进行语义搜索后再读取文件,因此只获取相关内容。分类钩子每条消息仅执行一次轻量级 Node 调用。验证钩子仅在 markdown 写入时触发,跳过排除的路径。 五个机制让注入层随仓库增长仍保持诚实:**来源感知注入**(resume/compact 时只重新注入易变部分——静态大块已在会话中)、每次注入末行的**注入大小计量**、真正强制执行计量结果的**注入预算**(超出上限时,最容易舍弃的部分降级为指针,且计量行会逐一列出被降级的部分——因为悄无声息的丢失比膨胀更糟)、每次写入**仅一次钩子进程**(QMD 刷新搭载在验证钩子上)、**列表折叠**(笔记数超过阈值的文件夹折叠为一行计数,因此仓库不会通过某个没人想到要配置的文件夹突破上限)。预算与阈值均可在 `vault-manifest.json` 中调整。### 🌐 与其他 Agent 配合使用diff --git a/vault-manifest.json b/vault-manifest.jsonindex ffa5577..f06acc5 100644--- a/vault-manifest.json+++ b/vault-manifest.json@@ -13,6 +13,8 @@"action items","what to watch"],+ "eager_layer_budget_bytes": 80000,+ "listing_collapse_threshold": 12,"qmd_context": "Engineer's work vault built on obsidian-mind. Active projects and archive, 1:1 notes, incidents, brag log with quarterly evidence, competency map, people and teams, decisions and patterns in brain/, reference docs and runbooks. Multi-agent (Claude Code, Codex, Gemini) with lifecycle hooks and QMD semantic search. Ground for 'what did I ship?' reviews, project status, and personal knowledge management.","infrastructure": ["CLAUDE.md",