Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: hold the eager layer under Claude Code's hook output cap (#259)

Brenno Ferrari1b6f9fa0db1f
diff --git a/.claude/scripts/lib/active-hygiene.ts b/.claude/scripts/lib/active-hygiene.ts
index 3293174..81cc06b 100644
--- a/.claude/scripts/lib/active-hygiene.ts
+++ b/.claude/scripts/lib/active-hygiene.ts
@@ -620,7 +620,7 @@ export function newNoteClusterCandidate(
export function formatClusterHint(cluster: TopicCluster): string {
return [
- `πŸ—‚οΈ This note joins ${cluster.files.length - 1} loose sibling(s) in active/ sharing "${cluster.token}": ${cluster.files.join(", ")}.`,
+ `πŸ—‚οΈ This note joins ${cluster.files.length - 1} loose sibling(s) in active/ sharing "${cluster.token}": ${namesCapped(cluster.files)}.`,
"Convention: once a workstream has >1 note it gets a folder (active/<Topic>/, `git mv`, mirror the folder in archive/ later).",
"Token overlap is BLIND β€” judge whether these genuinely share context before grouping; if they don't, say so and move on.",
].join("\n");
@@ -647,6 +647,25 @@ export function scanActiveHygiene(
};
}
+/**
+ * How many entries a hygiene list prints before "… and N more". The flag's
+ * headline keeps the full count. Hygiene never degrades under the injection
+ * budget, so an uncapped list could fill the hook output cap by itself (#254).
+ */
+export const HYGIENE_LIST_CAP = 10;
+
+function listCapped<T>(items: readonly T[], render: (item: T) => string): string[] {
+ const lines = items.slice(0, HYGIENE_LIST_CAP).map(render);
+ if (items.length > HYGIENE_LIST_CAP) lines.push(` - … and ${items.length - HYGIENE_LIST_CAP} more`);
+ return lines;
+}
+
+/** A cluster's file names on one line, capped the same way. */
+export function namesCapped(names: readonly string[]): string {
+ const shown = names.slice(0, HYGIENE_LIST_CAP).join(", ");
+ return names.length > HYGIENE_LIST_CAP ? `${shown}, … and ${names.length - HYGIENE_LIST_CAP} more` : shown;
+}
+
/**
* Render the report as markdown lines for hook output. Returns [] when the
* vault is clean, so callers can skip emitting a section entirely.
@@ -676,7 +695,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
lines.push(
`⚠️ ${completedInActive.length} note(s) marked done but still in active/ β€” archive to archive/YYYY/ (ask the agent to run om-project-archive):`,
);
- for (const p of completedInActive) lines.push(` - ${p}`);
+ lines.push(...listCapped(completedInActive, (p) => ` - ${p}`));
}
if (ungroupedClusters.length > 0) {
@@ -684,9 +703,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
lines.push(
"⚠️ Loose active/ notes that look like one topic β€” consider a folder (active/<Topic>/):",
);
- for (const { token, files } of ungroupedClusters) {
- lines.push(` - "${token}": ${files.join(", ")}`);
- }
+ lines.push(...listCapped(ungroupedClusters, ({ token, files }) => ` - "${token}": ${namesCapped(files)}`));
}
if (oversizedNotes.length > 0) {
@@ -694,9 +711,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
lines.push(
`⚠️ ${oversizedNotes.length} note(s) past the ${MONOLITH_BYTES / 1000}KB organization threshold β€” do NOT trim content; SPLIT (domain notes / event-log satellites / a cluster folder, verbatim, one-liner index behind):`,
);
- for (const { path, sizeKb } of oversizedNotes) {
- lines.push(` - ${path} (${sizeKb}KB)`);
- }
+ lines.push(...listCapped(oversizedNotes, ({ path, sizeKb }) => ` - ${path} (${sizeKb}KB)`));
}
if (openLoops.length > 0) {
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.ts
index a5548b2..46c4e2b 100644
--- a/.claude/scripts/lib/session-start.ts
+++ b/.claude/scripts/lib/session-start.ts
@@ -6,6 +6,7 @@
import { basename, join, resolve } from "node:path";
+import { HOOK_OUTPUT_MAX_CHARS } from "./hook-io.ts";
import { escapeRegex } from "./regex.ts";
export function take(stdout: string, n: number): string {
@@ -20,29 +21,38 @@ export function take(stdout: string, n: number): string {
* 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.
+ * know. For the same reason it says when a configured budget was clamped to
+ * the hook output cap, and when the output was cut to fit it (#254). Called
+ * with one argument the output is byte-identical to before.
*/
export function formatInjectionSize(
bytes: number,
opts?: {
readonly budgetBytes?: number | undefined;
readonly collapsed?: readonly string[] | undefined;
+ /** The configured budget, when it was clamped to the hook output cap. */
+ readonly clampedFrom?: number | null | undefined;
+ /** True when the output was cut to fit the hook output cap. */
+ readonly cut?: boolean | undefined;
},
): string {
const safe = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
- const size = `${(safe / 1000).toFixed(1)}kB`;
+ const kb = (n: number) => `${(n / 1000).toFixed(1)}kB`;
+ const size = kb(safe);
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 clampedFrom = opts?.clampedFrom;
+ const clamp =
+ clampedFrom !== undefined && clampedFrom !== null ? ` (${kb(clampedFrom)} configured, held under the hook output cap)` : "";
+ let line = `_context injected: ${size} / ${kb(budget)} budget${clamp}`;
const collapsed = opts?.collapsed ?? [];
- if (collapsed.length === 0) {
- return `_context injected: ${size} / ${ceiling}_`;
- }
- return `_context injected: ${size} / ${ceiling} β€” collapsed: ${collapsed.join(", ")}_`;
+ if (collapsed.length > 0) line += ` β€” collapsed: ${collapsed.join(", ")}`;
+ if (opts?.cut === true) line += " β€” cut to fit the hook output cap";
+ return `${line}_`;
}
/**
@@ -185,6 +195,69 @@ export function parseInjectionBudget(manifestJson: string | null): number | null
return parsePositiveIntField(manifestJson, "eager_layer_budget_bytes");
}
+/** Room the closing meter line keeps beside the budgeted sections. */
+export const METER_HEADROOM = 400;
+
+/**
+ * The most the sections may spend. Claude Code caps a hook's plain stdout at
+ * 10,000 characters and, over it, injects a file path and the first 2,000
+ * characters instead, so a budget above the cap never binds: the session
+ * gets a preview and the meter at the end is the first thing lost (#254).
+ * The budget is in bytes, and a string's UTF-8 bytes are never fewer than
+ * its characters, so a byte ceiling also holds the character cap.
+ */
+export const INJECTION_CEILING_BYTES = HOOK_OUTPUT_MAX_CHARS - METER_HEADROOM;
+
+/**
+ * The budget actually enforced: the configured one, held under the ceiling.
+ * An unset budget gets the ceiling too, since a vault with no budget is the
+ * one most likely to pass the cap. `configured` is the manifest value when it
+ * was clamped, so the meter can say so; otherwise null.
+ */
+export function effectiveInjectionBudget(configured: number | null): {
+ readonly bytes: number;
+ readonly clampedFrom: number | null;
+} {
+ if (configured !== null && configured <= INJECTION_CEILING_BYTES) {
+ return { bytes: configured, clampedFrom: null };
+ }
+ return { bytes: INJECTION_CEILING_BYTES, clampedFrom: configured };
+}
+
+/** The line that replaces whatever a cut removed. */
+export const CUT_LINE = "… (cut to fit the hook output cap: the rest of this context was not injected)";
+
+/**
+ * The hook's whole stdout, held under Claude Code's output cap with the
+ * meter intact. The budget already holds the sections that can degrade;
+ * this is the backstop for the ones that never do (the date, open tasks,
+ * hygiene). Over the cap, the body is cut at a line boundary and the meter,
+ * built with `cut` set, still closes the output, so a cut is never silent.
+ *
+ * `meter` gets the UTF-8 size of the body it closes. The cut is sized with
+ * the uncut body's meter; the meter is then rebuilt for what was kept, and a
+ * smaller size never formats longer, so the rebuilt output still fits.
+ */
+export function fitHookOutput(
+ body: string,
+ meter: (cut: boolean, bodyBytes: number) => string,
+ cap: number = HOOK_OUTPUT_MAX_CHARS,
+): string {
+ const whole = `${body}\n${meter(false, Buffer.byteLength(body, "utf-8"))}\n`;
+ if (whole.length <= cap) return whole;
+ const room = cap - `\n${CUT_LINE}\n\n${meter(true, Buffer.byteLength(body, "utf-8"))}\n`.length;
+ // A meter that cannot fit beside any body is itself cut: never in practice
+ // (it is a few hundred characters), but the cap must hold for any input.
+ if (room < 0) return `${meter(true, 0).slice(0, Math.max(0, cap - 1))}\n`;
+ let head = body.slice(0, room);
+ const lastBreak = head.lastIndexOf("\n");
+ if (lastBreak >= 0) head = head.slice(0, lastBreak);
+ // No line to cut on: keep the partial line, minus any half of a surrogate pair.
+ else if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
+ const kept = `${head}\n${CUT_LINE}\n`;
+ return `${kept}\n${meter(true, Buffer.byteLength(kept, "utf-8"))}\n`;
+}
+
/** `listing_collapse_threshold` from the manifest; null when unset or invalid. */
export function parseListingCollapseThreshold(
manifestJson: string | null,
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index ac0ed51..dc7ffd0 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -45,6 +45,8 @@ import {
isMarkdownFilename,
collectOpenTasks,
applyInjectionBudget,
+ effectiveInjectionBudget,
+ fitHookOutput,
parseInjectionBudget,
parseListingCollapseThreshold,
shouldCollapseDir,
@@ -615,18 +617,21 @@ if (hygieneLines.length > 0) {
});
}
-// 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);
+// The eager layer is held under a byte budget, and the budget under Claude
+// Code's hook output cap: past the cap the session gets a 2,000-character
+// preview, so a larger budget never binds (#254). An unset or larger
+// manifest value is clamped, and the meter says so. fitHookOutput is the
+// backstop for the sections that never degrade.
+const budget = effectiveInjectionBudget(parseInjectionBudget(manifestJson));
+const budgeted = applyInjectionBudget(sections, budget.bytes);
-const body = budgeted.text + "\n";
process.stdout.write(
- body +
- "\n" +
- formatInjectionSize(Buffer.byteLength(body, "utf-8"), {
- budgetBytes: budgetBytes ?? undefined,
+ fitHookOutput(budgeted.text + "\n", (cut, bodyBytes) =>
+ formatInjectionSize(bodyBytes, {
+ budgetBytes: budget.bytes,
collapsed: budgeted.collapsed,
- }) +
- "\n",
+ clampedFrom: budget.clampedFrom,
+ cut,
+ }),
+ ),
);
diff --git a/.claude/scripts/tests/active-hygiene.test.ts b/.claude/scripts/tests/active-hygiene.test.ts
index e703ad6..0653076 100644
--- a/.claude/scripts/tests/active-hygiene.test.ts
+++ b/.claude/scripts/tests/active-hygiene.test.ts
@@ -17,12 +17,14 @@ import {
import { dirname, join } from "node:path";
import { tmpdir } from "node:os";
import {
+ HYGIENE_LIST_CAP,
MONOLITH_BYTES,
OPEN_LOOP_DAYS,
countOpenLoops,
formatActiveHygiene,
formatClusterHint,
formatMonolithHint,
+ namesCapped,
isMonolithExempt,
newNoteClusterCandidate,
parseMemoryRoot,
@@ -435,6 +437,37 @@ describe("scanActiveHygiene β€” detectors", () => {
assert.doesNotMatch(text, /om-intake/);
});
+ test("each previously uncapped hygiene list prints ten entries, then a count of the rest (#254)", () => {
+ const report = (n: number) =>
+ formatActiveHygiene({
+ completedInActive: Array.from({ length: n }, (_, i) => `work/active/Done ${i}.md`),
+ ungroupedClusters: Array.from({ length: n }, (_, i) => ({ token: `topic${i}`, files: ["a.md", "b.md"] })),
+ oversizedNotes: Array.from({ length: n }, (_, i) => ({ path: `notes/Big ${i}.md`, sizeKb: 30 })),
+ openLoops: [],
+ inboxPressure: null,
+ memoryInbox: null,
+ });
+ const atCap = report(HYGIENE_LIST_CAP);
+ assert.equal(atCap.filter((l) => l.startsWith(" - ")).length, 3 * HYGIENE_LIST_CAP);
+ assert.ok(!atCap.some((l) => l.includes("more")), "a full list at the cap gets no count line");
+
+ const over = report(HYGIENE_LIST_CAP + 1).join("\n");
+ assert.match(over, /11 note\(s\) marked done/, "the headline keeps the full count");
+ assert.match(over, /11 note\(s\) past the/);
+ assert.equal(over.match(/^ {3}- … and 1 more$/gm)?.length, 3, "one count line per list");
+ assert.doesNotMatch(over, /Done 10\.md|topic10|Big 10\.md/);
+ });
+
+ test("a cluster's file names are capped on its line and in the write-time hint (#254)", () => {
+ const files = Array.from({ length: HYGIENE_LIST_CAP + 3 }, (_, i) => `n${i}.md`);
+ assert.equal(namesCapped(files.slice(0, HYGIENE_LIST_CAP)), files.slice(0, HYGIENE_LIST_CAP).join(", "));
+ assert.match(namesCapped(files), /, n9\.md, … and 3 more$/);
+ const hint = formatClusterHint({ token: "topic", files });
+ assert.match(hint, /joins 12 loose sibling\(s\)/, "the count stays whole");
+ assert.match(hint, /… and 3 more\./);
+ assert.doesNotMatch(hint, /n10\.md/);
+ });
+
test("missing folders produce an empty report, not errors", () => {
const empty = mkdtempSync(join(tmpdir(), "active-hygiene-empty-"));
try {
diff --git a/.claude/scripts/tests/session-start.integration.test.ts b/.claude/scripts/tests/session-start.integration.test.ts
index 1f245dd..913e5bb 100644
--- a/.claude/scripts/tests/session-start.integration.test.ts
+++ b/.claude/scripts/tests/session-start.integration.test.ts
@@ -231,10 +231,10 @@ describe("session-start β€” listing collapse and injection budget", () => {
assert.match(listing, /projects[\\/]alpha[\\/]Note 0\.md/);
});
- test("no manifest budget β†’ plain meter, nothing collapsed (pre-budget behaviour)", () => {
+ test("no manifest budget β†’ the hook output ceiling is the budget (#254)", () => {
const { stdout } = runBig();
const last = stdout.split("\n").filter((l) => l.trim() !== "").pop() ?? "";
- assert.match(last, /^_context injected: \d+\.\dkB_$/);
+ assert.match(last, /^_context injected: \d+\.\dkB \/ 9\.1kB budget(?: β€” collapsed: [^_]+)?_$/);
});
test("a tight manifest budget degrades sections and NAMES them in the meter", () => {
@@ -263,13 +263,28 @@ describe("session-start β€” listing collapse and injection budget", () => {
}
});
- test("a generous budget collapses nothing but still reports the ceiling", () => {
+ test("a budget under the ceiling collapses nothing it does not need to and reports itself", () => {
const manifest = join(BIG_DIR, "vault-manifest.json");
- writeFileSync(manifest, JSON.stringify({ eager_layer_budget_bytes: 5_000_000 }));
+ writeFileSync(manifest, JSON.stringify({ eager_layer_budget_bytes: 9_000 }));
try {
const last =
runBig().stdout.split("\n").filter((l) => l.trim() !== "").pop() ?? "";
- assert.match(last, /^_context injected: \d+\.\dkB \/ 5000\.0kB budget_$/);
+ assert.match(last, /^_context injected: \d+\.\dkB \/ 9\.0kB budget_$/);
+ } finally {
+ rmSync(manifest, { force: true });
+ }
+ });
+
+ test("a budget above the hook output cap is clamped, and the meter says so (#254)", () => {
+ const manifest = join(BIG_DIR, "vault-manifest.json");
+ writeFileSync(manifest, JSON.stringify({ eager_layer_budget_bytes: 80_000 }));
+ try {
+ const last =
+ runBig().stdout.split("\n").filter((l) => l.trim() !== "").pop() ?? "";
+ assert.match(
+ last,
+ /^_context injected: \d+\.\dkB \/ 9\.1kB budget \(80\.0kB configured, held under the hook output cap\)(?: β€” collapsed: [^_]+)?_$/,
+ );
} finally {
rmSync(manifest, { force: true });
}
@@ -290,3 +305,61 @@ describe("session-start β€” listing collapse and injection budget", () => {
}
});
});
+
+/**
+ * Claude Code caps a hook's plain stdout at 10,000 characters; past it, the
+ * session gets a file path and the first 2,000 characters (#254). The output
+ * must fit whole, with the meter as its last line, whatever the vault holds.
+ */
+describe("session-start β€” the hook output cap", () => {
+ const CAP = 10_000;
+ const lastLine = (stdout: string) => stdout.split("\n").filter((l) => l.trim() !== "").pop() ?? "";
+
+ test("an ordinary vault of ~250 nested notes fits, the listing degrading first", () => {
+ // The shape that reproduced #254: nested project folders, each under
+ // the listing-collapse threshold, so nothing folds by count.
+ const dir = mkdtempSync(join(tmpdir(), "session-start-cap-"));
+ try {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ writeFileSync(join(dir, "brain", "North Star.md"), "---\ndescription: test\n---\n\n# North Star\n\n- placeholder\n");
+ for (let p = 0; p < 12; p++) {
+ for (const sub of ["notes", "decisions"]) {
+ mkdirSync(join(dir, "projects", `project-${p}`, sub), { recursive: true });
+ for (let i = 0; i < 10; i++) {
+ writeFileSync(
+ join(dir, "projects", `project-${p}`, sub, `Example project-${p} ${sub} note ${i}.md`),
+ "---\ndescription: x\n---\n",
+ );
+ }
+ }
+ }
+ writeFileSync(join(dir, "vault-manifest.json"), JSON.stringify({ eager_layer_budget_bytes: 80_000 }));
+ const { stdout, code, stderr } = spawnHook(SCRIPT, "", { CLAUDE_PROJECT_DIR: dir });
+ assert.equal(code, 0);
+ assert.equal(stderr, "");
+ assert.ok(stdout.length <= CAP, `stdout is ${stdout.length} characters`);
+ assert.match(lastLine(stdout), /^_context injected: .* β€” collapsed: Vault File Listing_$/);
+ } finally {
+ rmTemp(dir);
+ }
+ });
+
+ test("sections that never degrade cannot carry the output past the cap: it is cut, and the meter says so", () => {
+ // Open tasks never degrade. Ten long ones are over the cap on their own,
+ // with every degradable section already a pointer.
+ const dir = mkdtempSync(join(tmpdir(), "session-start-cut-"));
+ try {
+ const tasks = Array.from({ length: 10 }, (_, i) => `- [ ] task ${i} ${"x".repeat(1_500)}`).join("\n");
+ writeFileSync(join(dir, "Tasks.md"), `# Tasks\n\n${tasks}\n`);
+ const { stdout, code, stderr } = spawnHook(SCRIPT, "", { CLAUDE_PROJECT_DIR: dir });
+ assert.equal(code, 0);
+ assert.equal(stderr, "");
+ assert.ok(stdout.includes("task 0 "), "the fixture's tasks reached the output");
+ assert.ok(stdout.length <= CAP, `stdout is ${stdout.length} characters`);
+ assert.ok(stdout.includes("… (cut to fit the hook output cap"), "the cut is marked where it happened");
+ assert.match(lastLine(stdout), /^_context injected: .* β€” cut to fit the hook output cap_$/);
+ } finally {
+ rmTemp(dir);
+ }
+ });
+});
diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.ts
index 9e74e35..f99ea7e 100644
--- a/.claude/scripts/tests/session-start.test.ts
+++ b/.claude/scripts/tests/session-start.test.ts
@@ -23,6 +23,10 @@ import {
shouldCollapseDir,
formatCollapsedDir,
parseInjectionBudget,
+ effectiveInjectionBudget,
+ fitHookOutput,
+ INJECTION_CEILING_BYTES,
+ CUT_LINE,
parseListingCollapseThreshold,
DEFAULT_LISTING_COLLAPSE_THRESHOLD,
type BudgetSection,
@@ -1201,3 +1205,84 @@ describe("injectionMode", () => {
});
}
});
+
+describe("the injection budget under the hook output cap (#254)", () => {
+ test("the ceiling leaves the meter its headroom under the 9,500-character output cap", () => {
+ assert.equal(INJECTION_CEILING_BYTES, 9_100);
+ });
+
+ const cases: ReadonlyArray<readonly [number | null, number, number | null]> = [
+ [80_000, 9_100, 80_000], // the old default: clamped, and reported
+ [9_101, 9_100, 9_101], // one over: clamped
+ [9_100, 9_100, null], // exactly the ceiling: kept as configured
+ [4_000, 4_000, null], // under: kept
+ [null, 9_100, null], // unset: the ceiling, with nothing to report
+ ];
+ for (const [configured, bytes, clampedFrom] of cases) {
+ test(`effectiveInjectionBudget(${String(configured)}) β†’ ${bytes}${clampedFrom === null ? "" : " (clamped)"}`, () => {
+ assert.deepEqual(effectiveInjectionBudget(configured), { bytes, clampedFrom });
+ });
+ }
+
+ test("the meter names a clamp, a collapse and a cut, in that order", () => {
+ assert.equal(
+ formatInjectionSize(9_000, { budgetBytes: 9_100, clampedFrom: 80_000, collapsed: ["Vault File Listing"], cut: true }),
+ "_context injected: 9.0kB / 9.1kB budget (80.0kB configured, held under the hook output cap) β€” collapsed: Vault File Listing β€” cut to fit the hook output cap_",
+ );
+ assert.equal(formatInjectionSize(9_000, { budgetBytes: 9_100, clampedFrom: null }), "_context injected: 9.0kB / 9.1kB budget_");
+ });
+});
+
+describe("fitHookOutput", () => {
+ const meter = (cut: boolean, bytes: number) => `_meter ${bytes}${cut ? " cut" : ""}_`;
+
+ test("output under the cap is the body and the meter, unchanged", () => {
+ assert.equal(fitHookOutput("a\nb\n", meter, 100), "a\nb\n\n_meter 4_\n");
+ });
+
+ test("output over the cap is cut on a line, marked, and closed by the meter", () => {
+ const body = Array.from({ length: 200 }, (_, i) => `line ${i}`).join("\n") + "\n";
+ const out = fitHookOutput(body, meter, 500);
+ assert.ok(out.length <= 500, `output is ${out.length} characters`);
+ assert.ok(out.includes(`\n${CUT_LINE}\n`), "the cut is marked");
+ const lines = out.split("\n");
+ assert.match(lines.at(-2) ?? "", /^_meter \d+ cut_$/);
+ // Every kept line is a whole line of the body.
+ for (const l of lines.slice(0, lines.indexOf(CUT_LINE))) assert.match(l, /^line \d+$/);
+ });
+
+ test("the cut keeps as much as fits: an all-newline body lands one under the cap", () => {
+ // Every position is a line boundary, so the kept prefix is the longest
+ // the arithmetic allows; an off-by-one either way moves this length.
+ // A fixed-width meter, so a size with fewer digits cannot move it too.
+ const out = fitHookOutput("\n".repeat(2_000), (cut) => (cut ? "_m cut_" : "_m_"), 500);
+ assert.equal(out.length, 499);
+ });
+
+ test("a body with no line to cut on keeps the partial line, filling the cap exactly", () => {
+ const out = fitHookOutput("x".repeat(2_000), (cut) => (cut ? "_m cut_" : "_m_"), 500);
+ assert.equal(out.length, 500);
+ assert.ok(out.startsWith("x".repeat(100)), "the partial line is kept, not dropped");
+ });
+
+ test("a partial line never ends in half of a surrogate pair", () => {
+ // Each emoji is two UTF-16 units; one of the two parities lands mid-pair.
+ for (const cap of [500, 501]) {
+ const out = fitHookOutput("πŸ˜€".repeat(1_000), (cut) => (cut ? "_m cut_" : "_m_"), cap);
+ assert.ok(out.length <= cap);
+ assert.doesNotThrow(() => encodeURIComponent(out), `a lone surrogate at cap ${cap}`);
+ }
+ });
+
+ test("a meter longer than the cap is cut too: the cap holds for any input", () => {
+ const out = fitHookOutput("a\nb\n", () => "m".repeat(600), 500);
+ assert.ok(out.length <= 500, `output is ${out.length} characters`);
+ });
+
+ test("the meter reports the size of what was kept, not of the whole body", () => {
+ const body = "x\n".repeat(1_000);
+ const out = fitHookOutput(body, meter, 300);
+ const kept = out.slice(0, out.lastIndexOf("\n\n_meter") + 1);
+ assert.match(out, new RegExp(`_meter ${Buffer.byteLength(kept, "utf-8")} cut_\n$`));
+ });
+});
diff --git a/.claude/scripts/tests/stop-checklist.test.ts b/.claude/scripts/tests/stop-checklist.test.ts
index bf8384f..8a71dd1 100644
--- a/.claude/scripts/tests/stop-checklist.test.ts
+++ b/.claude/scripts/tests/stop-checklist.test.ts
@@ -249,16 +249,17 @@ describe("stop-checklist", () => {
assert.deepEqual(envelopeOf(reentry.stdout), {});
});
- test("a report too big for the hook output cap still fits, cut with a marker", () => {
- // Completed notes left in work/active/ are listed uncapped; four hundred
- // long names make a report several times the cap.
+ test("a long hygiene list is capped, so the report stays under the hook output cap (#254)", () => {
+ // Four hundred long names made a report several times the cap before
+ // hygiene lists were capped; the headline keeps the full count.
const names = Array.from({ length: 400 }, (_, i) => `A completed note with a deliberately long descriptive title ${i}.md`);
const root = vault("block-huge", ...names);
const { stdout } = run(stop("s-block-huge"), { vault: root });
assert.ok(stdout.length <= 9_500, `stdout is ${stdout.length} chars`);
- const envelope = envelopeOf(stdout);
- assert.equal(envelope["decision"], "block");
- assert.match(String(envelope["reason"]), /truncated to fit the hook output cap\)$/);
+ const reason = String(envelopeOf(stdout)["reason"]);
+ assert.match(reason, /⚠️ {2}400 note\(s\) marked done but still in active\//);
+ assert.match(reason, /^ {3}- … and 390 more$/m);
+ assert.doesNotMatch(reason, /truncated to fit/);
});
test("SessionEnd and a Stop without a session_id never block", () => {
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 009ea2f..b2d30e0 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -98,7 +98,9 @@ Because those memories are written from many repos and read by many repos, each
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 budget has a hard ceiling it cannot be raised past: Claude Code's hook output cap.** Claude Code caps a hook's plain stdout at 10,000 characters, with no setting to raise it. Over the cap, the session gets a file path and the first 2,000 characters, and Claude Code does not ask the model to read the rest. A budget above the cap never binds: nothing degrades, the meter on the last line is the first thing lost, and the meter the user reads still looks healthy (#254). So `session-start.ts` clamps any budget, set or unset, to the cap less room for the meter (9,100 bytes; bytes are never fewer than characters, so this holds the character cap too). When it clamps a configured value, the meter says so. The sections that never degrade (the date, open tasks, hygiene) could still pass the cap on their own, so the whole output is fitted as a backstop: cut on a line, marked where it was cut, the meter still last and saying "cut".
+
+**Within that ceiling, the budget is a runaway guard, not a squeeze.** The meter is the detector; the budget is the emergency brake. A ceiling low enough to bite in normal use degrades your context every session instead of catching a problem. If the budget starts firing, look at what grew. It can no longer be raised past the cap, so the fix is to make the section smaller or let it degrade to its pointer. Content a session must always have, in full, belongs in an instruction file (`CLAUDE.md` and its `@`-imports), which this cap does not apply to.
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.
@@ -201,7 +203,7 @@ sequenceDiagram
A few specific design choices are worth calling out:
-- **`SessionStart` injects, it does not load.** It builds a briefing (filename listing, North Star excerpt, git summary, open tasks aggregated from `work/active/` and the vault root) and hands it to the agent. Full note contents never flow through this hook. Its size is bounded by `eager_layer_budget_bytes` and reported by the meter on the last line of every injection, so the cost is visible rather than assumed. The open-tasks scan is filesystem-only so the hook never spawns the Obsidian CLI β€” that subprocess flashes the Electron app on macOS when no instance is running (#83).
+- **`SessionStart` injects, it does not load.** It builds a briefing (filename listing, North Star excerpt, git summary, open tasks aggregated from `work/active/` and the vault root) and hands it to the agent. Full note contents never flow through this hook. Its size is bounded by `eager_layer_budget_bytes`, held under Claude Code's 10,000-character hook output cap, and reported by the meter on the last line of every injection, so the cost is visible rather than assumed. The open-tasks scan is filesystem-only so the hook never spawns the Obsidian CLI β€” that subprocess flashes the Electron app on macOS when no instance is running (#83).
- **`UserPromptSubmit` classifies, it does not route.** It tags the prompt with hints like `ARCHITECTURE discussion` or `DECISION`; the agent decides where to file. Keeping the hook opinion-free means the routing logic lives in `CLAUDE.md`, which is editable per-user without touching scripts.
- **QMD refresh is shared, debounced, and detached.** Three hook entries fire the same refresh helper β€” `PostToolUse` (after `.md` writes), `PreCompact` (before transcript backup; writes tend to cluster before compaction), and `Stop` (after a response) β€” sharing one sentinel file so a burst of events produces at most one worker per debounce window. The actual indexing runs in `.claude/scripts/qmd-refresh-run.ts` as a detached, stdio-silent worker (`qmd update` β†’ `qmd embed` β†’ tail-chase `qmd update`), so the parent hook returns in milliseconds and nothing flows to the agent's context.
- **`PreCompact` also backs up the transcript.** In addition to kicking the QMD refresh, it copies the current session transcript out to `thinking/session-logs/` so long conversations remain recoverable after compaction.
diff --git a/CLAUDE.md b/CLAUDE.md
index 6a35a65..4a7f7f3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -440,7 +440,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 (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 |
+| 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 that fits Claude Code's 10,000-character hook output cap β€” 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.md b/README.md
index 45d5ae2..3f821dc 100644
--- a/README.md
+++ b/README.md
@@ -201,7 +201,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 β€” held under a byte budget, 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 that fits Claude Code's hook output cap, 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/` |
@@ -216,13 +216,13 @@ obsidian-mind does **not** dump your entire vault into context. It uses tiered l
| Tier | What | When | Cost |
|------|------|------|------|
-| **Always** | `CLAUDE.md` + SessionStart context (North Star excerpt, git summary, tasks, vault file listing) | Session start | capped by the manifest budget; the meter reports the real size every session |
+| **Always** | `CLAUDE.md` + SessionStart context (North Star excerpt, git summary, tasks, vault file listing) | Session start | capped by the manifest budget, itself held under Claude Code's 10,000-character hook output cap; the meter reports the real size every session |
| **On-demand** | QMD semantic search results | When the agent needs specific context | Targeted |
| **Triggered** | Classification routing hints | Every message | ~100 tokens |
| **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. 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.
+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`, and the budget is held under Claude Code's 10,000-character hook output cap whatever it is set to, because past the cap a session receives only a 2,000-character preview. 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 Agents
diff --git a/vault-manifest.json b/vault-manifest.json
index 3958601..346cdd8 100644
--- a/vault-manifest.json
+++ b/vault-manifest.json
@@ -13,7 +13,7 @@
"action items",
"what to watch"
],
- "eager_layer_budget_bytes": 80000,
+ "eager_layer_budget_bytes": 9100,
"listing_collapse_threshold": 12,
"memory_root": "memories",
"mcp_exposed_roots": [],