A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: hold every hook writer under the output cap, with one cut routine (#260)
Brenno Ferrari2773cfb76962
diff --git a/.claude/scripts/lib/active-hygiene.ts b/.claude/scripts/lib/active-hygiene.tsindex 81cc06b..2aa6cf7 100644--- a/.claude/scripts/lib/active-hygiene.ts+++ b/.claude/scripts/lib/active-hygiene.ts@@ -654,16 +654,21 @@ export function scanActiveHygiene(*/export const HYGIENE_LIST_CAP = 10;+/** The first HYGIENE_LIST_CAP items, and the "… and N more" tail when any were left out. */+function capped<T>(items: readonly T[]): { readonly shown: readonly T[]; readonly more: string | null } {+ const rest = items.length - HYGIENE_LIST_CAP;+ return { shown: items.slice(0, HYGIENE_LIST_CAP), more: rest > 0 ? `… and ${rest} more` : null };+}+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;+ const { shown, more } = capped(items);+ return more === null ? shown.map(render) : [...shown.map(render), ` - ${more}`];}/** 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;+ const { shown, more } = capped(names);+ return more === null ? shown.join(", ") : [...shown, more].join(", ");}/**diff --git a/.claude/scripts/lib/hook-io.ts b/.claude/scripts/lib/hook-io.tsindex effd667..0bf5f15 100644--- a/.claude/scripts/lib/hook-io.ts+++ b/.claude/scripts/lib/hook-io.ts@@ -63,14 +63,21 @@ export function writeHookOutput(additionalContext: string,policyResults?: readonly PolicyResult[],): void {- process.stdout.write(- JSON.stringify({- hookSpecificOutput:- policyResults && policyResults.length > 0- ? { hookEventName, additionalContext, policyResults }- : { hookEventName, additionalContext },- }),- );+ // The whole stdout fits the cap, like every writer here (#254): the+ // context gets what the envelope and any policy results leave. Policy+ // results that cannot fit beside even the cut marker are dropped rather+ // than carried over the cap (three raw paths can be 12 KB on Linux).+ const envelope = (context: string, policies: readonly PolicyResult[]) => ({+ hookSpecificOutput:+ policies.length > 0+ ? { hookEventName, additionalContext: context, policyResults: policies }+ : { hookEventName, additionalContext: context },+ });+ const overhead = (policies: readonly PolicyResult[]) => JSON.stringify(envelope("", policies)).length - 2;+ // The smallest context fitEncoded can return is the marker, quotes included.+ const minimum = JSON.stringify(CUT_MARKER).length;+ const policies = policyResults && overhead(policyResults) + minimum <= HOOK_OUTPUT_MAX_CHARS ? policyResults : [];+ process.stdout.write(JSON.stringify(envelope(fitEncoded(additionalContext, HOOK_OUTPUT_MAX_CHARS - overhead(policies)), policies)));}/**@@ -126,6 +133,43 @@ export function fitEncoded(text: string, max: number): string {return text.slice(0, lo) + CUT_MARKER;}+/** The line that replaces whatever a plain-text cut removed: the same words as fitEncoded's marker. */+export const CUT_LINE = CUT_MARKER.trimStart();++/**+ * A plain-text hook's whole stdout, held under Claude Code's output cap with+ * its closing meter intact: the plain-stdout counterpart of fitEncoded.+ * SessionStart's budget already holds the sections that can degrade; this is+ * the backstop for the ones that never do (the date, open tasks, hygiene)+ * (#254). The length is counted in UTF-16 units, never fewer than the+ * characters Claude Code counts. 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 bodyBytes = Buffer.byteLength(body, "utf-8");+ const whole = `${body}\n${meter(false, bodyBytes)}\n`;+ if (whole.length <= cap) return whole;+ const room = cap - `\n${CUT_LINE}\n\n${meter(true, bodyBytes)}\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)).replace(/[\uD800-\uDBFF]$/, "")}\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`;+}+/*** A Stop that hands `reason` to the agent now and gives it another turn* (#256). The user reads the same text: Claude Code prints a block's reasondiff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.tsindex 46c4e2b..4704c82 100644--- a/.claude/scripts/lib/session-start.ts+++ b/.claude/scripts/lib/session-start.ts@@ -22,7 +22,7 @@ export function take(stdout: string, n: number): string {* 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. 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+ * the hook output cap, and when the output was truncated to fit it (#254). Called* with one argument the output is byte-identical to before.*/export function formatInjectionSize(@@ -31,8 +31,8 @@ export function formatInjectionSize(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 clampedFrom?: number | undefined;+ /** True when the output was truncated to fit the hook output cap. */readonly cut?: boolean | undefined;},): string {@@ -46,12 +46,11 @@ export function formatInjectionSize(}const clampedFrom = opts?.clampedFrom;- const clamp =- clampedFrom !== undefined && clampedFrom !== null ? ` (${kb(clampedFrom)} configured, held under the hook output cap)` : "";+ const clamp = clampedFrom === undefined ? "" : ` (${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) line += ` — collapsed: ${collapsed.join(", ")}`;- if (opts?.cut === true) line += " — cut to fit the hook output cap";+ if (opts?.cut === true) line += " — truncated to fit the hook output cap";return `${line}_`;}@@ -203,60 +202,27 @@ export const METER_HEADROOM = 400;* 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.+ * HOOK_OUTPUT_MAX_CHARS already keeps a margin under that 10,000. 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.+ * one most likely to pass the cap. `clampedFrom` is the manifest value when+ * it was clamped, so the meter can say so, and absent otherwise.*/export function effectiveInjectionBudget(configured: number | null): {readonly bytes: number;- readonly clampedFrom: number | null;+ readonly clampedFrom?: number;} {- if (configured !== null && configured <= INJECTION_CEILING_BYTES) {- return { bytes: configured, clampedFrom: null };- }+ if (configured === null) return { bytes: INJECTION_CEILING_BYTES };+ if (configured <= INJECTION_CEILING_BYTES) return { bytes: configured };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(diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.tsindex dc7ffd0..3b2a419 100644--- a/.claude/scripts/session-start.ts+++ b/.claude/scripts/session-start.ts@@ -46,7 +46,6 @@ import {collectOpenTasks,applyInjectionBudget,effectiveInjectionBudget,- fitHookOutput,parseInjectionBudget,parseListingCollapseThreshold,shouldCollapseDir,@@ -66,7 +65,7 @@ import {scanActiveHygiene,} from "./lib/active-hygiene.ts";-import { readStdinJson } from "./lib/hook-io.ts";+import { fitHookOutput, readStdinJson } from "./lib/hook-io.ts";import { resolveProjectDir } from "./lib/project-dir.ts";type HookInput = { readonly source?: unknown };diff --git a/.claude/scripts/tests/hook-io.test.ts b/.claude/scripts/tests/hook-io.test.tsindex aac5dfa..7a1fca0 100644--- a/.claude/scripts/tests/hook-io.test.ts+++ b/.claude/scripts/tests/hook-io.test.ts@@ -7,7 +7,7 @@import { test, describe, afterEach } from "node:test";import assert from "node:assert/strict";-import { debug, fitEncoded, HOOK_OUTPUT_MAX_CHARS, warn, writeStopBlock, writeSystemMessage } from "../lib/hook-io.ts";+import { debug, fitEncoded, HOOK_OUTPUT_MAX_CHARS, warn, writeHookOutput, writeStopBlock, writeSystemMessage, type PolicyResult } from "../lib/hook-io.ts";/*** Replace process.stderr.write with a capturer that records calls and returns@@ -150,3 +150,44 @@ describe("writeSystemMessage — the output fits", () => {assert.equal(captureStdout(() => writeSystemMessage("hello")), '{"systemMessage":"hello"}');});});++describe("writeHookOutput — additionalContext fits the hook output cap (#254)", () => {+ test("a huge context is cut with the marker, and the whole stdout fills the cap exactly", () => {+ const out = captureStdout(() => writeHookOutput("PostToolUse", "x".repeat(20_000)));+ assert.equal(out.length, HOOK_OUTPUT_MAX_CHARS);+ const context = (JSON.parse(out) as { hookSpecificOutput: { additionalContext: string } }).hookSpecificOutput.additionalContext;+ assert.match(context, /truncated to fit the hook output cap\)$/);+ });++ test("policy results take their share of the cap, not more of it", () => {+ const policy: PolicyResult[] = Array.from({ length: 3 }, (_, i) => ({ policy_id: `rule-${i}`, path: `notes/${"y".repeat(300)}.md`, classification: "misplaced", action: "warn" }));+ const out = captureStdout(() => writeHookOutput("PostToolUse", "x".repeat(20_000), policy));+ assert.equal(out.length, HOOK_OUTPUT_MAX_CHARS);+ assert.equal((JSON.parse(out) as { hookSpecificOutput: { policyResults: unknown[] } }).hookSpecificOutput.policyResults.length, 3);+ });++ test("at every policy size near the edge, the whole stdout stays within the cap", () => {+ // Sweeps the boundary where the context's room is about the marker's size,+ // which a single large fixture cannot reach.+ const shell = JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: "", policyResults: [{ policy_id: "r", path: "", classification: "c", action: "warn" }] } }).length;+ for (let pathLen = HOOK_OUTPUT_MAX_CHARS - shell - 80; pathLen <= HOOK_OUTPUT_MAX_CHARS - shell + 5; pathLen++) {+ const policy: PolicyResult[] = [{ policy_id: "r", path: "p".repeat(pathLen), classification: "c", action: "warn" }];+ const out = captureStdout(() => writeHookOutput("PostToolUse", "x".repeat(20_000), policy));+ assert.ok(out.length <= HOOK_OUTPUT_MAX_CHARS, `policy path ${pathLen}: stdout is ${out.length} characters`);+ }+ });++ test("policy results too large to fit beside any context are dropped, never carried over the cap", () => {+ const policy: PolicyResult[] = Array.from({ length: 3 }, (_, i) => ({ policy_id: `rule-${i}`, path: `notes/${"y".repeat(4_000)}.md`, classification: "misplaced", action: "warn" }));+ const out = captureStdout(() => writeHookOutput("PostToolUse", "x".repeat(20_000), policy));+ assert.ok(out.length <= HOOK_OUTPUT_MAX_CHARS, `stdout is ${out.length} characters`);+ const parsed = JSON.parse(out) as { hookSpecificOutput: { additionalContext: string; policyResults?: unknown[] } };+ assert.equal(parsed.hookSpecificOutput.policyResults, undefined);+ assert.match(parsed.hookSpecificOutput.additionalContext, /truncated to fit the hook output cap\)$/);+ });++ test("a short context is written unchanged", () => {+ const out = captureStdout(() => writeHookOutput("PostToolUse", "hello"));+ assert.equal(out, '{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"hello"}}');+ });+});diff --git a/.claude/scripts/tests/session-start.integration.test.ts b/.claude/scripts/tests/session-start.integration.test.tsindex 913e5bb..6167cdf 100644--- a/.claude/scripts/tests/session-start.integration.test.ts+++ b/.claude/scripts/tests/session-start.integration.test.ts@@ -33,6 +33,7 @@ import {writeFileSync,} from "node:fs";import { tmpdir } from "node:os";+import { HOOK_OUTPUT_MAX_CHARS } from "../lib/hook-io.ts";import { runScript as spawnHook, rmTemp } from "./_helpers.ts";const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));@@ -312,7 +313,7 @@ describe("session-start — listing collapse and injection budget", () => {* 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 CAP = HOOK_OUTPUT_MAX_CHARS;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", () => {@@ -356,8 +357,8 @@ describe("session-start — the hook output cap", () => {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_$/);+ assert.ok(stdout.includes("… (truncated to fit the hook output cap)"), "the cut is marked where it happened");+ assert.match(lastLine(stdout), /^_context injected: .* — truncated 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.tsindex f99ea7e..3752106 100644--- a/.claude/scripts/tests/session-start.test.ts+++ b/.claude/scripts/tests/session-start.test.ts@@ -24,9 +24,7 @@ import {formatCollapsedDir,parseInjectionBudget,effectiveInjectionBudget,- fitHookOutput,INJECTION_CEILING_BYTES,- CUT_LINE,parseListingCollapseThreshold,DEFAULT_LISTING_COLLAPSE_THRESHOLD,type BudgetSection,@@ -51,6 +49,7 @@ import {collectOpenTasks,} from "../lib/session-start.ts";+import { CUT_LINE, fitHookOutput, HOOK_OUTPUT_MAX_CHARS } from "../lib/hook-io.ts";import { rmTemp } from "./_helpers.ts";describe("take", () => {@@ -1207,29 +1206,29 @@ 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", () => {+ test("the ceiling leaves the meter its headroom under the hook output cap", () => {assert.equal(INJECTION_CEILING_BYTES, 9_100);});- const cases: ReadonlyArray<readonly [number | null, number, number | null]> = [+ const cases: ReadonlyArray<readonly [number | null, number, number | undefined]> = [[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+ [9_100, 9_100, undefined], // exactly the ceiling: kept as configured+ [4_000, 4_000, undefined], // under: kept+ [null, 9_100, undefined], // 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(`effectiveInjectionBudget(${String(configured)}) → ${bytes}${clampedFrom === undefined ? "" : " (clamped)"}`, () => {+ assert.deepEqual(effectiveInjectionBudget(configured), clampedFrom === undefined ? { bytes } : { 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_",+ "_context injected: 9.0kB / 9.1kB budget (80.0kB configured, held under the hook output cap) — collapsed: Vault File Listing — truncated to fit the hook output cap_",);- assert.equal(formatInjectionSize(9_000, { budgetBytes: 9_100, clampedFrom: null }), "_context injected: 9.0kB / 9.1kB budget_");+ assert.equal(formatInjectionSize(9_000, { budgetBytes: 9_100 }), "_context injected: 9.0kB / 9.1kB budget_");});});@@ -1274,6 +1273,14 @@ describe("fitHookOutput", () => {}});+ test("an oversized meter is cut without leaving half of a surrogate pair", () => {+ for (const cap of [500, 501]) {+ const out = fitHookOutput("x".repeat(2_000), () => "😀".repeat(600), 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`);@@ -1286,3 +1293,43 @@ describe("fitHookOutput", () => {assert.match(out, new RegExp(`_meter ${Buffer.byteLength(kept, "utf-8")} cut_\n$`));});});++describe("the eager layer end to end under the cap (#254)", () => {+ test("sections totalling 30,000 characters degrade, fit, and the meter names what collapsed", () => {+ // The issue's own test: the budget, the fit and the meter together. The+ // budget alone brings this one under the cap, so no cut happens.+ const sections: BudgetSection[] = [+ { header: "### Date", body: "Friday", priority: 0 },+ { header: "### North Star", body: "n".repeat(6_000), priority: 30, fallback: "(pointer)" },+ { header: "### Brain Topics", body: "b".repeat(9_000), priority: 40, fallback: "(pointer)" },+ { header: "### Vault File Listing", body: "l".repeat(15_000), priority: 50, fallback: "(pointer)" },+ ];+ const budget = effectiveInjectionBudget(80_000);+ const budgeted = applyInjectionBudget(sections, budget.bytes);+ const out = fitHookOutput(budgeted.text + "\n", (cut, bytes) =>+ formatInjectionSize(bytes, { budgetBytes: budget.bytes, collapsed: budgeted.collapsed, clampedFrom: budget.clampedFrom, cut }),+ );+ assert.ok(out.length <= HOOK_OUTPUT_MAX_CHARS, `output is ${out.length} characters`);+ assert.ok(!out.includes(CUT_LINE), "the budget was enough; nothing was cut");+ const meter = out.trimEnd().split("\n").at(-1) ?? "";+ assert.match(meter, /— collapsed: Vault File Listing, Brain Topics_$/);+ assert.match(meter, /\(80\.0kB configured, held under the hook output cap\)/);+ assert.ok(out.includes("n".repeat(6_000)), "North Star fits once the larger sections give way");+ });++ test("when sections that never degrade pass the cap after every collapse, the fit cuts and the meter says both", () => {+ const sections: BudgetSection[] = [+ { header: "### Open Tasks", body: Array.from({ length: 40 }, (_, i) => `- [ ] task ${i} ${"t".repeat(300)}`).join("\n"), priority: 0 },+ { header: "### Vault File Listing", body: "l".repeat(15_000), priority: 50, fallback: "(pointer)" },+ ];+ const budget = effectiveInjectionBudget(null);+ const budgeted = applyInjectionBudget(sections, budget.bytes);+ const out = fitHookOutput(budgeted.text + "\n", (cut, bytes) =>+ formatInjectionSize(bytes, { budgetBytes: budget.bytes, collapsed: budgeted.collapsed, cut }),+ );+ assert.ok(out.length <= HOOK_OUTPUT_MAX_CHARS, `output is ${out.length} characters`);+ assert.ok(out.includes(`\n${CUT_LINE}\n`), "the cut is marked");+ const meter = out.trimEnd().split("\n").at(-1) ?? "";+ assert.match(meter, /— collapsed: Vault File Listing — truncated to fit the hook output cap_$/);+ });+});diff --git a/.claude/scripts/tests/stop-checklist.test.ts b/.claude/scripts/tests/stop-checklist.test.tsindex 8a71dd1..39164ec 100644--- a/.claude/scripts/tests/stop-checklist.test.ts+++ b/.claude/scripts/tests/stop-checklist.test.ts@@ -22,6 +22,7 @@import { test, describe, before, after } from "node:test";import assert from "node:assert/strict";+import { HOOK_OUTPUT_MAX_CHARS } from "../lib/hook-io.ts";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { fileURLToPath } from "node:url";@@ -255,7 +256,7 @@ describe("stop-checklist", () => {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`);+ assert.ok(stdout.length <= HOOK_OUTPUT_MAX_CHARS, `stdout is ${stdout.length} chars`);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);diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex b2d30e0..960d872 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -98,7 +98,7 @@ Because those memories are written from many repos and read by many repos, eachSession 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 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".+**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 it was "truncated to fit the hook output cap".**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.diff --git a/README.ja.md b/README.ja.mdindex 4704dc1..aabfed1 100644--- a/README.ja.md+++ b/README.ja.md@@ -194,7 +194,7 @@ QMDは**3つの小さなモデルをローカルで**実行します。設定す| フック | タイミング | 内容 ||------|------|------|-| 🚀 SessionStart | 起動/再開時 | QMD再インデックス+セルフヒール、North Starフォーカス・アクティブプロジェクト・最近の変更・タスク・ファイル一覧・ボールト衛生フラグを注入 — 全体はバイトバジェットで抑えられ、最終行は注入サイズメーター |+| 🚀 SessionStart | 起動/再開時 | QMD再インデックス+セルフヒール、North Starフォーカス・アクティブプロジェクト・最近の変更・タスク・ファイル一覧・ボールト衛生フラグを注入 — 全体はClaude Codeのフック出力上限に収まるバイトバジェットで抑えられ、最終行は注入サイズメーター || 💬 UserPromptSubmit | 全メッセージ | コンテンツを分類(意思決定、インシデント、実績、1on1、アーキテクチャ、人物、プロジェクト更新)してルーティングヒントを注入 || ✍️ PostToolUse | `.md`書き込み後 | フロントマター+ウィキリンクの検証、誤配置メモリファイルのブロック、肥大ノート(削るのではなく分割)と書き込み時トピッククラスタのフラグ || 💾 PreCompact | コンテキスト圧縮前 | セッション記録を`thinking/session-logs/`にバックアップ |@@ -209,13 +209,13 @@ obsidian-mindはボールト全体をコンテキストに読み込み**ませ| 階層 | 内容 | タイミング | コスト ||------|------|------------|--------|-| **常時** | `CLAUDE.md` + SessionStartコンテキスト(North Star抜粋、git概要、タスク、ボールトファイル一覧) | セッション開始時 | マニフェストのバジェットが上限。実サイズは毎セッション末尾のメーターが表示 |+| **常時** | `CLAUDE.md` + SessionStartコンテキスト(North Star抜粋、git概要、タスク、ボールトファイル一覧) | セッション開始時 | マニフェストのバジェットが上限(それ自体もClaude Codeの10,000文字のフック出力上限の内側に抑えられる)。実サイズは毎セッション末尾のメーターが表示 || **オンデマンド** | QMDセマンティック検索結果 | エージェントが特定のコンテキストを必要とした時 | 対象のみ || **トリガー** | 分類ルーティングヒント | 毎メッセージ | ~100トークン || **トリガー** | PostToolUse検証 | `.md`書き込み後 | ~200トークン || **まれ** | ファイル全体の読み込み | 明示的に必要な場合のみ | 可変 |-SessionStartは**軽量なコンテキスト**を読み込みます — 主要ファイルからの短い抜粋、ファイル名、git概要のみで、ノート全体は読み込みません。エージェントはQMDで意味検索してからファイルを読むため、関連する情報のみを取得します。分類フックはメッセージごとに軽量なNode呼び出し1回です。検証フックはMarkdown書き込み時のみ発火し、除外パスはスキップします。 ボールトが成長しても注入層を正直に保つ5つの仕組み: **ソース認識注入**(resume/compact時は揮発セクションのみ再注入 — 静的な大部分はすでに会話内にある)、全注入の最終行に付く**注入サイズメーター**、メーターが計測する値を実際に強制する**注入バジェット**(上限を超えると失っても影響の小さいセクションからポインタに縮退し、縮退したものはメーターに必ず名前が出る — 黙って失われる方が肥大化より悪いため)、書き込みごとの**フック起動は1プロセスのみ**(QMDリフレッシュは検証フックに同乗)、**一覧の折りたたみ**(ノート数のしきい値を超えたフォルダは1行のカウント表示に畳まれるので、誰も設定し忘れたフォルダ経由でボールトが上限を超えて育つことはない)。バジェットとしきい値はどちらも `vault-manifest.json` で調整できます。+SessionStartは**軽量なコンテキスト**を読み込みます — 主要ファイルからの短い抜粋、ファイル名、git概要のみで、ノート全体は読み込みません。エージェントはQMDで意味検索してからファイルを読むため、関連する情報のみを取得します。分類フックはメッセージごとに軽量なNode呼び出し1回です。検証フックはMarkdown書き込み時のみ発火し、除外パスはスキップします。 ボールトが成長しても注入層を正直に保つ5つの仕組み: **ソース認識注入**(resume/compact時は揮発セクションのみ再注入 — 静的な大部分はすでに会話内にある)、全注入の最終行に付く**注入サイズメーター**、メーターが計測する値を実際に強制する**注入バジェット**(上限を超えると失っても影響の小さいセクションからポインタに縮退し、縮退したものはメーターに必ず名前が出る — 黙って失われる方が肥大化より悪いため)、書き込みごとの**フック起動は1プロセスのみ**(QMDリフレッシュは検証フックに同乗)、**一覧の折りたたみ**(ノート数のしきい値を超えたフォルダは1行のカウント表示に畳まれるので、誰も設定し忘れたフォルダ経由でボールトが上限を超えて育つことはない)。バジェットとしきい値はどちらも `vault-manifest.json` で調整できます。ただしバジェットは設定値にかかわらずClaude Codeの10,000文字のフック出力上限の内側に抑えられます。上限を超えると、セッションには2,000文字のプレビューしか届かないためです。### 🌐 他のエージェントでの利用diff --git a/README.ko.md b/README.ko.mdindex b187559..8e95513 100644--- a/README.ko.md+++ b/README.ko.md@@ -194,7 +194,7 @@ QMD는 **세 개의 작은 모델을 로컬에서** 실행하므로, 설정할 A| 훅 | 시점 | 동작 ||------|------|------|-| 🚀 SessionStart | 시작/재개 시 | QMD 재인덱싱+셀프힐, North Star 포커스·활성 작업·최근 변경사항·작업·파일 목록·볼트 위생 플래그 주입 — 전체는 바이트 예산으로 제한되고, 마지막 줄은 주입 크기 미터 |+| 🚀 SessionStart | 시작/재개 시 | QMD 재인덱싱+셀프힐, North Star 포커스·활성 작업·최근 변경사항·작업·파일 목록·볼트 위생 플래그 주입 — 전체는 Claude Code의 훅 출력 상한에 맞는 바이트 예산으로 제한되고, 마지막 줄은 주입 크기 미터 || 💬 UserPromptSubmit | 매 메시지마다 | 콘텐츠 분류(의사결정, 인시던트, 성과, 1:1, 아키텍처, 인물, 프로젝트 업데이트) 및 라우팅 힌트 주입 || ✍️ PostToolUse | `.md` 작성 후 | 프론트매터+위키링크 검증, 잘못 배치된 메모리 파일 차단, 비대 노트(줄이지 말고 분할)와 작성 시점 토픽 클러스터 플래그 || 💾 PreCompact | 컨텍스트 압축 전 | 세션 트랜스크립트를 `thinking/session-logs/`에 백업 |@@ -209,13 +209,13 @@ obsidian-mind는 전체 볼트를 컨텍스트에 로드하지 **않습니다**.| 계층 | 내용 | 시점 | 비용 ||------|------|------|------|-| **항상** | `CLAUDE.md` + SessionStart 컨텍스트 (North Star 발췌, git 요약, 작업, 볼트 파일 목록) | 세션 시작 시 | 매니페스트 예산이 상한. 실제 크기는 매 세션 마지막 줄의 미터가 보고 |+| **항상** | `CLAUDE.md` + SessionStart 컨텍스트 (North Star 발췌, git 요약, 작업, 볼트 파일 목록) | 세션 시작 시 | 매니페스트 예산이 상한 (예산 자체도 Claude Code의 10,000자 훅 출력 상한 안으로 제한됨). 실제 크기는 매 세션 마지막 줄의 미터가 보고 || **온디맨드** | QMD 시맨틱 검색 결과 | 에이전트가 특정 컨텍스트 필요 시 | 대상만 || **트리거** | 분류 라우팅 힌트 | 매 메시지 | ~100 토큰 || **트리거** | PostToolUse 검증 | `.md` 작성 후 | ~200 토큰 || **드물게** | 전체 파일 읽기 | 명시적으로 필요한 경우만 | 가변 |-SessionStart는 **가벼운 컨텍스트**를 로드합니다 — 주요 파일의 짧은 발췌, 파일명, git 요약만 로드하며 전체 노트 내용은 읽지 않습니다. 에이전트는 QMD를 통해 의미 기반 검색 후 파일을 읽으므로 관련 정보만 가져옵니다. 분류 훅은 메시지당 가벼운 Node 호출 1회입니다. 검증 훅은 마크다운 쓰기 시에만 실행되며 제외된 경로는 건너뜁니다. 볼트가 커져도 주입 계층을 정직하게 유지하는 다섯 가지 메커니즘: **소스 인식 주입** (resume/compact 시 휘발성 섹션만 재주입 — 정적인 대부분은 이미 대화에 있음), 모든 주입의 마지막 줄에 붙는 **주입 크기 미터**, 미터가 측정한 값을 실제로 강제하는 **주입 예산** (상한을 넘으면 잃어도 되는 섹션부터 포인터로 축소되고, 축소된 섹션 이름은 미터에 반드시 표시됨 — 조용한 손실이 비대화보다 나쁘기 때문), 쓰기당 **훅 프로세스 1회** (QMD 리프레시가 검증 훅에 동승), **목록 접기** (노트 수 임계값을 넘는 폴더는 한 줄 카운트로 접히므로, 아무도 설정하지 않은 폴더를 통해 볼트가 상한을 넘어 자랄 수 없음). 예산과 임계값 모두 `vault-manifest.json` 에서 조정할 수 있습니다.+SessionStart는 **가벼운 컨텍스트**를 로드합니다 — 주요 파일의 짧은 발췌, 파일명, git 요약만 로드하며 전체 노트 내용은 읽지 않습니다. 에이전트는 QMD를 통해 의미 기반 검색 후 파일을 읽으므로 관련 정보만 가져옵니다. 분류 훅은 메시지당 가벼운 Node 호출 1회입니다. 검증 훅은 마크다운 쓰기 시에만 실행되며 제외된 경로는 건너뜁니다. 볼트가 커져도 주입 계층을 정직하게 유지하는 다섯 가지 메커니즘: **소스 인식 주입** (resume/compact 시 휘발성 섹션만 재주입 — 정적인 대부분은 이미 대화에 있음), 모든 주입의 마지막 줄에 붙는 **주입 크기 미터**, 미터가 측정한 값을 실제로 강제하는 **주입 예산** (상한을 넘으면 잃어도 되는 섹션부터 포인터로 축소되고, 축소된 섹션 이름은 미터에 반드시 표시됨 — 조용한 손실이 비대화보다 나쁘기 때문), 쓰기당 **훅 프로세스 1회** (QMD 리프레시가 검증 훅에 동승), **목록 접기** (노트 수 임계값을 넘는 폴더는 한 줄 카운트로 접히므로, 아무도 설정하지 않은 폴더를 통해 볼트가 상한을 넘어 자랄 수 없음). 예산과 임계값 모두 `vault-manifest.json` 에서 조정할 수 있으며, 예산은 설정값과 관계없이 Claude Code의 10,000자 훅 출력 상한 안으로 제한됩니다. 상한을 넘으면 세션에는 2,000자 미리보기만 전달되기 때문입니다.### 🌐 다른 에이전트와 사용하기diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 40992cc..e6eac6e 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -194,7 +194,7 @@ QMD **在本地运行三个小模型**,因此不需要配置 API 密钥,没| 钩子 | 触发时机 | 功能 ||------|---------|------|-| 🚀 SessionStart | 启动/恢复时 | QMD 重新索引+自愈,注入北极星焦点、活跃工作、最近变更、任务、文件列表、仓库卫生标志 — 整体受字节预算约束,末行为注入大小计量 |+| 🚀 SessionStart | 启动/恢复时 | QMD 重新索引+自愈,注入北极星焦点、活跃工作、最近变更、任务、文件列表、仓库卫生标志 — 整体受字节预算约束(预算本身限制在 Claude Code 的钩子输出上限之内),末行为注入大小计量 || 💬 UserPromptSubmit | 每条消息 | 对内容分类(决策、事件、成就、1:1、架构、人员、项目更新)并注入路由提示 || ✍️ PostToolUse | 写入 `.md` 后 | 验证 frontmatter+wikilinks,拦截误放的记忆文件,标记过大笔记(拆分而非删减)与写入时的主题集群 || 💾 PreCompact | 上下文压缩前 | 将会话记录备份到 `thinking/session-logs/` |@@ -209,13 +209,13 @@ obsidian-mind **不会**将整个 vault 加载到上下文中。它使用分层| 层级 | 内容 | 时机 | 成本 ||------|------|------|------|-| **始终** | `CLAUDE.md` + SessionStart 上下文(北极星摘要、git 摘要、任务、vault 文件列表) | 会话启动时 | 以清单中的预算为上限;每次会话末尾的计量器报告实际大小 |+| **始终** | `CLAUDE.md` + SessionStart 上下文(北极星摘要、git 摘要、任务、vault 文件列表) | 会话启动时 | 以清单中的预算为上限(预算本身限制在 Claude Code 10,000 字符的钩子输出上限之内);每次会话末尾的计量器报告实际大小 || **按需** | QMD 语义搜索结果 | Agent 需要特定上下文时 | 精准定向 || **触发** | 分类路由提示 | 每条消息 | ~100 tokens || **触发** | PostToolUse 验证 | `.md` 写入后 | ~200 tokens || **罕见** | 完整文件读取 | 仅在明确需要时 | 可变 |-SessionStart 加载**轻量级上下文** — 关键文件的简短摘要、文件名和 git 摘要,而非完整笔记内容。Agent 通过 QMD 进行语义搜索后再读取文件,因此只获取相关内容。分类钩子每条消息仅执行一次轻量级 Node 调用。验证钩子仅在 markdown 写入时触发,跳过排除的路径。 五个机制让注入层随仓库增长仍保持诚实:**来源感知注入**(resume/compact 时只重新注入易变部分——静态大块已在会话中)、每次注入末行的**注入大小计量**、真正强制执行计量结果的**注入预算**(超出上限时,最容易舍弃的部分降级为指针,且计量行会逐一列出被降级的部分——因为悄无声息的丢失比膨胀更糟)、每次写入**仅一次钩子进程**(QMD 刷新搭载在验证钩子上)、**列表折叠**(笔记数超过阈值的文件夹折叠为一行计数,因此仓库不会通过某个没人想到要配置的文件夹突破上限)。预算与阈值均可在 `vault-manifest.json` 中调整。+SessionStart 加载**轻量级上下文** — 关键文件的简短摘要、文件名和 git 摘要,而非完整笔记内容。Agent 通过 QMD 进行语义搜索后再读取文件,因此只获取相关内容。分类钩子每条消息仅执行一次轻量级 Node 调用。验证钩子仅在 markdown 写入时触发,跳过排除的路径。 五个机制让注入层随仓库增长仍保持诚实:**来源感知注入**(resume/compact 时只重新注入易变部分——静态大块已在会话中)、每次注入末行的**注入大小计量**、真正强制执行计量结果的**注入预算**(超出上限时,最容易舍弃的部分降级为指针,且计量行会逐一列出被降级的部分——因为悄无声息的丢失比膨胀更糟)、每次写入**仅一次钩子进程**(QMD 刷新搭载在验证钩子上)、**列表折叠**(笔记数超过阈值的文件夹折叠为一行计数,因此仓库不会通过某个没人想到要配置的文件夹突破上限)。预算与阈值均可在 `vault-manifest.json` 中调整,但无论如何设置,预算都会被限制在 Claude Code 10,000 字符的钩子输出上限之内——超过上限时,会话只能收到 2,000 字符的预览。### 🌐 与其他 Agent 配合使用