Skip to content

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

fix: emit SessionStart context as one JSON envelope on the hook path (#341)

Brenno Ferrari48ca6fced517
diff --git a/.claude/commands/om-vault-upgrade.md b/.claude/commands/om-vault-upgrade.md
index cffd0fd..30ba3df 100644
--- a/.claude/commands/om-vault-upgrade.md
+++ b/.claude/commands/om-vault-upgrade.md
@@ -74,7 +74,7 @@ ShardMind executes only through its terminal UI (`--json` works with `--dry-run`
### U3. Verify
1. `shardmind --json` reports the new version, with `update.kind` `up-to-date`. Its `files.modified` must be exactly the **ahead** files, plus any conflicts the user kept. A behind file listed there was frozen, so fix it before finishing.
-2. The hooks run: `echo '{}' | node --experimental-strip-types .claude/scripts/session-start.ts` exits 0 and prints the session context.
+2. The hooks run: `echo '{}' | node --experimental-strip-types .claude/scripts/session-start.ts` exits 0 and prints the session context, as one JSON object whose `hookSpecificOutput.additionalContext` carries it.
3. Report the **ahead** files to the user as upstream candidates. A local improvement every vault could use belongs upstream, where the next release carries it.
## Subagents
diff --git a/.claude/scripts/lib/hook-io.ts b/.claude/scripts/lib/hook-io.ts
index d4815f0..4c01b31 100644
--- a/.claude/scripts/lib/hook-io.ts
+++ b/.claude/scripts/lib/hook-io.ts
@@ -67,19 +67,42 @@ export function writeHookOutput(
// 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)));
+ const policies = policyResults && envelopeOverhead(hookEventName, policyResults) + minimum <= HOOK_OUTPUT_MAX_CHARS ? policyResults : [];
+ const context = fitEncoded(additionalContext, HOOK_OUTPUT_MAX_CHARS - envelopeOverhead(hookEventName, policies));
+ process.stdout.write(JSON.stringify(hookEnvelope(hookEventName, context, policies)));
+}
+
+const hookEnvelope = (hookEventName: string, additionalContext: string, policies: readonly PolicyResult[]) => ({
+ hookSpecificOutput:
+ policies.length > 0 ? { hookEventName, additionalContext, policyResults: policies } : { hookEventName, additionalContext },
+});
+
+/**
+ * The context a writeHookOutput envelope for `hookEventName` carries: what
+ * reaches the model. Throws, naming what it got, on stdout that is not one
+ * JSON object or not that event's envelope; for the tests and the delivery
+ * gate, which read the hook path as the agent does.
+ */
+export function parseHookContext(stdout: string, hookEventName: string): string {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(stdout);
+ } catch {
+ throw new Error(`hook stdout is not one JSON object: ${JSON.stringify(stdout.slice(0, 120))}`);
+ }
+ const out = (parsed as { hookSpecificOutput?: { hookEventName?: unknown; additionalContext?: unknown } } | null)?.hookSpecificOutput;
+ if (out?.hookEventName !== hookEventName || typeof out.additionalContext !== "string") {
+ throw new Error(`not a ${hookEventName} envelope: ${JSON.stringify(stdout.slice(0, 120))}`);
+ }
+ return out.additionalContext;
}
+/** What an envelope adds around its context, without the context's own two quotes. */
+const envelopeOverhead = (hookEventName: string, policies: readonly PolicyResult[] = []): number =>
+ JSON.stringify(hookEnvelope(hookEventName, "", policies)).length - 2;
+
/**
* Emit a message addressed to the *user* rather than to the model.
*
@@ -117,11 +140,48 @@ export const HOOK_OUTPUT_MAX_CHARS = 9_500;
* A limit a plain-text output is held under: its size, the unit it is
* measured in, and its name for the line that marks a cut.
*/
-export type OutputLimit = { readonly max: number; readonly unit: "chars" | "bytes"; readonly name: string };
+export type OutputLimit = { readonly max: number; readonly unit: "chars" | "bytes" | "json"; readonly name: string };
/** Claude Code's hook output cap, counted in UTF-16 units as Claude Code counts characters. */
export const HOOK_OUTPUT_LIMIT: OutputLimit = { max: HOOK_OUTPUT_MAX_CHARS, unit: "chars", name: "the hook output cap" };
+/**
+ * The cap for a context that goes out inside a `hookSpecificOutput` envelope
+ * (writeHookOutput), measured on its JSON-encoded form: what is left of the
+ * hook output cap once the envelope itself is counted. Claude Code caps the
+ * `additionalContext` string alone, but an agent whose cap is undocumented
+ * (Gemini, as of 2026-10-13) gets the whole stdout held under it (#340).
+ */
+export function envelopedLimit(hookEventName: string): OutputLimit {
+ // `"json"` sizes count the encoded string's own two quotes, which the
+ // overhead leaves out: the same split writeHookOutput fits with.
+ return { max: HOOK_OUTPUT_MAX_CHARS - envelopeOverhead(hookEventName), unit: "json", name: HOOK_OUTPUT_LIMIT.name };
+}
+
+/**
+ * The longest prefix of `text` whose JSON-encoded form, with `suffix` after
+ * it, is at most `max` characters. It never splits an emoji: JSON.stringify
+ * escapes a lone surrogate to six characters, so a cut inside a pair always
+ * costs more than keeping the whole pair, and the search keeps the longest
+ * prefix that fits.
+ */
+function longestEncodedPrefix(text: string, max: number, suffix = ""): string {
+ let lo = 0;
+ let hi = text.length;
+ while (lo < hi) {
+ const mid = Math.ceil((lo + hi) / 2);
+ if (JSON.stringify(text.slice(0, mid) + suffix).length <= max) lo = mid;
+ else hi = mid - 1;
+ }
+ return text.slice(0, lo);
+}
+
+/** How a limit in `unit` sizes text. */
+const sizeIn =
+ (unit: OutputLimit["unit"]) =>
+ (text: string): number =>
+ unit === "bytes" ? Buffer.byteLength(text, "utf-8") : unit === "json" ? JSON.stringify(text).length : text.length;
+
/** The line that replaces whatever a cut to `limit` removed. */
export const cutLine = (limit: OutputLimit): string => `… (truncated to fit ${limit.name})`;
@@ -130,21 +190,11 @@ const CUT_MARKER = `\n${cutLine(HOOK_OUTPUT_LIMIT)}`;
/**
* `text`, cut with a marker so that its JSON-encoded form is at most `max`
* characters. Escaping (`\n`, `\\`, quotes) is counted, which a cut on the
- * raw length would miss. It never splits an emoji: JSON.stringify escapes a
- * lone surrogate to six characters, so a cut inside a pair always costs more
- * than keeping the whole pair, and the search keeps the longest prefix that
- * fits.
+ * raw length would miss, and an emoji is never split (longestEncodedPrefix).
*/
export function fitEncoded(text: string, max: number): string {
if (JSON.stringify(text).length <= max) return text;
- let lo = 0;
- let hi = text.length;
- while (lo < hi) {
- const mid = Math.ceil((lo + hi) / 2);
- if (JSON.stringify(text.slice(0, mid) + CUT_MARKER).length <= max) lo = mid;
- else hi = mid - 1;
- }
- return text.slice(0, lo) + CUT_MARKER;
+ return longestEncodedPrefix(text, max, CUT_MARKER) + CUT_MARKER;
}
/**
@@ -156,35 +206,40 @@ export function fitEncoded(text: string, max: number): string {
* 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
+ * `meter` gets the size of the body it closes as `measure` sizes it: the
+ * limit's own unit unless the caller budgeted in another measure, so the
+ * meter reports the size its budget decided on. 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 fitWithMeter(
body: string,
- meter: (cut: boolean, bodyBytes: number) => string,
+ meter: (cut: boolean, bodySize: number) => string,
limit: OutputLimit = HOOK_OUTPUT_LIMIT,
+ measure: (text: string) => number = sizeIn(limit.unit),
): string {
- const size = (text: string) => (limit.unit === "bytes" ? Buffer.byteLength(text, "utf-8") : text.length);
+ const size = sizeIn(limit.unit);
// The longest prefix of `text` at most `n` units long, never half a character.
- const prefix = (text: string, n: number) =>
- limit.unit === "bytes"
- ? Buffer.from(text, "utf-8").subarray(0, n).toString("utf-8").replace(/\uFFFD+$/, "")
- : text.slice(0, n).replace(/[\uD800-\uDBFF]$/, "");
- const bodyBytes = Buffer.byteLength(body, "utf-8");
- const whole = `${body}\n${meter(false, bodyBytes)}\n`;
+ const prefix = (text: string, n: number) => {
+ if (limit.unit === "bytes") return Buffer.from(text, "utf-8").subarray(0, n).toString("utf-8").replace(/\uFFFD+$/, "");
+ if (limit.unit === "chars") return text.slice(0, n).replace(/[\uD800-\uDBFF]$/, "");
+ return longestEncodedPrefix(text, n);
+ };
+ const bodySize = measure(body);
+ const whole = `${body}\n${meter(false, bodySize)}\n`;
if (size(whole) <= limit.max) return whole;
const marker = cutLine(limit);
- const room = limit.max - size(`\n${marker}\n\n${meter(true, bodyBytes)}\n`);
+ const room = limit.max - size(`\n${marker}\n\n${meter(true, bodySize)}\n`);
// A meter that cannot fit beside any body is itself cut: never in practice
// (it is a few hundred characters), but the limit must hold for any input.
- if (room < 0) return `${prefix(meter(true, 0), Math.max(0, limit.max - 1))}\n`;
+ // The closing newline costs what it encodes to: two characters in json.
+ if (room < 0) return `${prefix(meter(true, 0), Math.max(0, limit.max - (size("\n") - size(""))))}\n`;
let head = prefix(body, room);
const lastBreak = head.lastIndexOf("\n");
// No line to cut on: keep the partial line.
if (lastBreak >= 0) head = head.slice(0, lastBreak);
const kept = `${head}\n${marker}\n`;
- return `${kept}\n${meter(true, Buffer.byteLength(kept, "utf-8"))}\n`;
+ return `${kept}\n${meter(true, measure(kept))}\n`;
}
/**
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.ts
index d43b119..1771680 100644
--- a/.claude/scripts/lib/session-start.ts
+++ b/.claude/scripts/lib/session-start.ts
@@ -6,7 +6,7 @@
import { basename, join, resolve } from "node:path";
-import { HOOK_OUTPUT_MAX_CHARS } from "./hook-io.ts";
+import { envelopedLimit } from "./hook-io.ts";
import { escapeRegex } from "./regex.ts";
export function take(stdout: string, n: number): string {
@@ -102,7 +102,12 @@ export type BudgetSection = {
export type BudgetLevel = {
readonly name: string;
readonly body?: string | undefined;
- readonly fit?: ((maxBytes: number) => string | null) | undefined;
+ /**
+ * The largest body this level can make that `fits`, or null. `fits` judges
+ * the whole render with that body in place, by the budget's own measure: a
+ * part's size does not add up to the whole's under every measure (#340).
+ */
+ readonly fit?: ((fits: (body: string) => boolean) => string | null) | undefined;
};
export type BudgetResult = {
@@ -151,8 +156,9 @@ function renderSections(sections: readonly BudgetSection[]): string {
export function applyInjectionBudget(
sections: readonly BudgetSection[],
budgetBytes: number,
+ measure: (text: string) => number = utf8Bytes,
): BudgetResult {
- const size = (s: readonly BudgetSection[]): number => Buffer.byteLength(renderSections(s), "utf-8");
+ const size = (s: readonly BudgetSection[]): number => measure(renderSections(s));
const name = (i: number): string => (sections[i]?.header ?? "").replace(/^#+\s*/, "");
// A section delivered at full whose body is itself a cut says so.
const cutOf = (delivered: readonly BudgetSection[]) =>
@@ -182,21 +188,13 @@ export function applyInjectionBudget(
for (const { s, i } of bestFirst) {
const rungs: readonly BudgetLevel[] = [{ name: "full", body: s.body }, ...(s.levels ?? [])];
for (const rung of rungs) {
- let body: string | null | undefined = rung.body;
- if (rung.fit !== undefined) {
- const empty = [...current];
- empty[i] = { ...s, body: "" };
- const room = budgetBytes - size(empty);
- body = room > 0 ? rung.fit(room) : null;
- }
- if (body === null || body === undefined || body === "") continue;
- const probe = [...current];
- probe[i] = { ...s, body };
- if (size(probe) <= budgetBytes) {
- current = probe;
- level.set(i, rung.name);
- break;
- }
+ const withBody = (body: string) => current.map((c, j) => (j === i ? { ...s, body } : c));
+ const fits = (body: string) => size(withBody(body)) <= budgetBytes;
+ const body = rung.fit !== undefined ? rung.fit(fits) : rung.body;
+ if (body === null || body === undefined || body === "" || !fits(body)) continue;
+ current = withBody(body);
+ level.set(i, rung.name);
+ break;
}
}
@@ -208,7 +206,7 @@ export function applyInjectionBudget(
.filter(({ i }) => level.get(i) !== "pointer" && level.get(i) !== "full")
.map(({ i }) => ({ section: name(i), level: level.get(i) as string }));
const text = renderSections(current);
- return { text, bytes: Buffer.byteLength(text, "utf-8"), collapsed, degraded, cut: cutOf(current) };
+ return { text, bytes: measure(text), collapsed, degraded, cut: cutOf(current) };
}
/**
@@ -276,16 +274,33 @@ export function parseInjectionBudget(manifestJson: string | null): number | null
/** Room the closing meter line keeps beside the budgeted sections. */
export const METER_HEADROOM = 400;
+/** A text's UTF-8 size: what a budget measures by default. */
+export const utf8Bytes = (text: string): number => Buffer.byteLength(text, "utf-8");
+
+/**
+ * A text's size as it goes out inside a JSON envelope (#340): its UTF-8 bytes
+ * or its JSON-encoded length, whichever is larger. Escaping (`\n`, quotes)
+ * grows ASCII text; multi-byte text is still held to its bytes, so no vault
+ * is measured more loosely than as plain stdout.
+ *
+ * On the hook path the budget, the ceiling, `BudgetResult.bytes` and the
+ * meter's kB are in this unit while keeping their byte names: the setting
+ * they answer to is `eager_layer_budget_bytes`, and this size is never below
+ * the byte count, so a figure read as bytes never understates.
+ */
+export const enveloped = (text: string): number => Math.max(utf8Bytes(text), JSON.stringify(text).length);
+
/**
- * The most the sections may spend. Claude Code caps a hook's plain stdout at
+ * The most the sections may spend. Claude Code caps a hook's context 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).
- * 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.
+ * The hook path sends the context inside a JSON envelope (#340), so the
+ * ceiling is what the envelope leaves of the hook output cap (which already
+ * keeps a margin under that 10,000), less the meter's headroom. The budget
+ * is measured as `enveloped`: never fewer than the encoded characters.
*/
-export const INJECTION_CEILING_BYTES = HOOK_OUTPUT_MAX_CHARS - METER_HEADROOM;
+export const INJECTION_CEILING_BYTES = envelopedLimit("SessionStart").max - METER_HEADROOM;
/** A budget the eager layer is held to, and the configured value when it was clamped. */
export type InjectionBudget = { readonly bytes: number; readonly clampedFrom?: number };
@@ -1039,14 +1054,14 @@ export function renderHeadlines(headlines: readonly string[]): string {
}
/**
- * The first N headlines that fit in `maxBytes`, with a line saying how many
+ * The first N headlines that `fits` accepts, with a line saying how many
* more there are. Null when not even one fits, or when all of them do (that
* is the `headlines` level, not this one).
*/
-export function topHeadlines(headlines: readonly string[], maxBytes: number): string | null {
+export function topHeadlines(headlines: readonly string[], fits: (body: string) => boolean): string | null {
for (let n = headlines.length - 1; n >= 1; n--) {
const body = `${renderHeadlines(headlines.slice(0, n))}\n_(+${headlines.length - n} more goals in brain/North Star.md)_`;
- if (Buffer.byteLength(body, "utf-8") <= maxBytes) return body;
+ if (fits(body)) return body;
}
return null;
}
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index e52d4d0..7e00eb8 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -54,10 +54,12 @@ import {
collectOpenTasks,
applyInjectionBudget,
effectiveInjectionBudget,
+ enveloped,
parseInjectionBudget,
parseInstructionBudget,
DEFAULT_INSTRUCTION_BUDGET_BYTES,
METER_HEADROOM,
+ utf8Bytes,
type InjectionBudget,
parseListingCollapseThreshold,
shouldCollapseDir,
@@ -83,7 +85,7 @@ import {
scanActiveHygiene,
} from "./lib/active-hygiene.ts";
-import { debug, fitWithMeter, HOOK_OUTPUT_LIMIT, type OutputLimit, readStdinJson } from "./lib/hook-io.ts";
+import { debug, envelopedLimit, fitWithMeter, type OutputLimit, readStdinJson, writeHookOutput } from "./lib/hook-io.ts";
import { REFRESH_SWITCH, refreshDisabled } from "./lib/qmd-refresh.ts";
import { readOmMod } from "./lib/om-mod.ts";
import { resolveProjectDir } from "./lib/project-dir.ts";
@@ -342,7 +344,7 @@ function northStarSection(priority: number): BudgetSection {
if (ladder.headlines.length > 0) {
levels.push(
{ name: "headlines", body: renderHeadlines(ladder.headlines) },
- { name: "top-N", fit: (room) => topHeadlines(ladder.headlines, room) },
+ { name: "top-N", fit: (fits) => topHeadlines(ladder.headlines, fits) },
);
}
return { header, body: ladder.full, priority, fallback: NORTH_STAR_POINTER, levels };
@@ -680,24 +682,33 @@ if (hygieneLines.length > 0) {
const budget: InjectionBudget = delivering
? { bytes: parseInstructionBudget(manifestJson) ?? DEFAULT_INSTRUCTION_BUDGET_BYTES }
: effectiveInjectionBudget(parseInjectionBudget(manifestJson));
-const budgeted = applyInjectionBudget(sections, budget.bytes);
+// On the hook path the context goes out inside a JSON envelope (#340): Gemini
+// parses a hook's stdout as JSON and reads context only from
+// hookSpecificOutput.additionalContext (per its hooks reference as of
+// 2026-10-13, not observed), and Claude Code accepts the same shape. So the
+// budget, the backstop cut and the meter's figure all use the encoded size.
+// A mod's deliver run stays plain text: it becomes an instruction file.
+const measure = delivering ? utf8Bytes : enveloped;
+const budgeted = applyInjectionBudget(sections, budget.bytes, measure);
const limit: OutputLimit = delivering
? { max: budget.bytes + METER_HEADROOM, unit: "bytes", name: "the instruction budget" }
- : HOOK_OUTPUT_LIMIT;
-
-process.stdout.write(
- fitWithMeter(
- budgeted.text + "\n",
- (cut, bodyBytes) =>
- formatInjectionSize(bodyBytes, {
- budgetBytes: budget.bytes,
- collapsed: budgeted.collapsed,
- degraded: budgeted.degraded,
- cutSections: budgeted.cut,
- clampedFrom: budget.clampedFrom,
- cut,
- cutTo: limit.name,
- }),
- limit,
- ),
+ : envelopedLimit("SessionStart");
+
+const context = fitWithMeter(
+ budgeted.text + "\n",
+ // Uncut, the size the budget judged, without the separator line added here.
+ (cut, bodySize) =>
+ formatInjectionSize(cut ? bodySize : budgeted.bytes, {
+ budgetBytes: budget.bytes,
+ collapsed: budgeted.collapsed,
+ degraded: budgeted.degraded,
+ cutSections: budgeted.cut,
+ clampedFrom: budget.clampedFrom,
+ cut,
+ cutTo: limit.name,
+ }),
+ limit,
+ measure,
);
+if (delivering) process.stdout.write(context);
+else writeHookOutput("SessionStart", context);
diff --git a/.claude/scripts/tests/_helpers.ts b/.claude/scripts/tests/_helpers.ts
index 3381145..c7179bd 100644
--- a/.claude/scripts/tests/_helpers.ts
+++ b/.claude/scripts/tests/_helpers.ts
@@ -33,6 +33,7 @@ import { spawnSync } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { parseHookContext } from "../lib/hook-io.ts";
import { REFRESH_SWITCH } from "../lib/qmd-refresh.ts";
const SENTINEL_DIR = mkdtempSync(join(tmpdir(), "om-test-sentinel-"));
@@ -50,6 +51,14 @@ export type RunResult = {
readonly code: number;
};
+/**
+ * The context a SessionStart hook-path run carried: its stdout is one JSON
+ * envelope, `{ hookSpecificOutput: { hookEventName: "SessionStart",
+ * additionalContext } }` (#340). Throws on anything else, so a test of the
+ * hook path can never pass on plain text.
+ */
+export const hookContext = (stdout: string): string => parseHookContext(stdout, "SessionStart");
+
export function runScript(
scriptPath: string,
stdin: string | object | null,
diff --git a/.claude/scripts/tests/budget-ladder.test.ts b/.claude/scripts/tests/budget-ladder.test.ts
index 56717bc..5258e96 100644
--- a/.claude/scripts/tests/budget-ladder.test.ts
+++ b/.claude/scripts/tests/budget-ladder.test.ts
@@ -17,6 +17,7 @@ import { fileURLToPath } from "node:url";
import {
applyInjectionBudget,
+ enveloped,
formatInjectionSize,
goalHeadline,
northStarLadder,
@@ -28,7 +29,7 @@ import {
NORTH_STAR_POINTER,
type BudgetSection,
} from "../lib/session-start.ts";
-import { runScript as spawnHook, rmTemp } from "./_helpers.ts";
+import { hookContext, runScript as spawnHook, rmTemp } from "./_helpers.ts";
const bytes = (s: string): number => Buffer.byteLength(s, "utf-8");
const render = (s: readonly BudgetSection[]): number =>
@@ -87,13 +88,16 @@ describe("applyInjectionBudget — the ladder", () => {
assert.deepEqual(overHeadlines.collapsed, ["North Star (current goals)"]);
});
- test("a `fit` level is handed exactly the room its body may take", () => {
+ test("a `fit` level's predicate accepts a body that fills the budget exactly, and not one byte more", () => {
const fixed: BudgetSection = { header: "", body: "x".repeat(10), priority: 0 };
- let handed = -1;
- const s = ns("F".repeat(500), [{ name: "top-N", fit: (room) => ((handed = room), "t".repeat(room)) }]);
+ const longest = (fits: (body: string) => boolean) => {
+ let n = 0;
+ while (fits("t".repeat(n + 1))) n++;
+ return n > 0 ? "t".repeat(n) : null;
+ };
+ const s = ns("F".repeat(500), [{ name: "top-N", fit: longest }]);
const r = applyInjectionBudget([fixed, s], 200);
- assert.equal(r.bytes, 200, "a body of exactly the room handed fills the budget to the byte");
- assert.equal(handed, 200 - render([fixed, { ...s, body: "" }]));
+ assert.equal(r.bytes, 200, "the longest body the predicate accepts fills the budget to the byte");
assert.deepEqual(r.degraded, [{ section: "North Star (current goals)", level: "top-N" }]);
});
@@ -233,11 +237,11 @@ describe("topHeadlines", () => {
const heads = ["one", "two", "three"];
test("the first N that fit, and how many more", () => {
const two = `${renderHeadlines(["one", "two"])}\n_(+1 more goals in brain/North Star.md)_`;
- assert.equal(topHeadlines(heads, bytes(two)), two);
- assert.equal(topHeadlines(heads, bytes(two) - 1), `${renderHeadlines(["one"])}\n_(+2 more goals in brain/North Star.md)_`);
+ assert.equal(topHeadlines(heads, (b) => bytes(b) <= bytes(two)), two);
+ assert.equal(topHeadlines(heads, (b) => bytes(b) <= bytes(two) - 1), `${renderHeadlines(["one"])}\n_(+2 more goals in brain/North Star.md)_`);
});
test("null when not one fits", () => {
- assert.equal(topHeadlines(heads, 5), null);
+ assert.equal(topHeadlines(heads, (b) => bytes(b) <= 5), null);
});
});
@@ -250,7 +254,9 @@ describe("session-start — #304's fixture on the hook path", () => {
const bullets = Array.from({ length: 30 }, (_, i) => `- [[Project ${i}]] — ${clause}${"More detail on how it is measured and what counts. ".repeat(5)}`);
writeFileSync(join(dir, "brain", "North Star.md"), `---\ndescription: d\n---\n# North Star\n\n## Current Focus\n\n${bullets.join("\n")}\n`);
writeFileSync(join(dir, "brain", "Gotchas.md"), "---\ndescription: pitfalls\n---\n# G\n");
- const { stdout, code } = spawnHook(resolve(dirname(fileURLToPath(import.meta.url)), "../session-start.ts"), { source: "startup" }, { CLAUDE_PROJECT_DIR: dir });
+ const run = spawnHook(resolve(dirname(fileURLToPath(import.meta.url)), "../session-start.ts"), { source: "startup" }, { CLAUDE_PROJECT_DIR: dir });
+ const { code } = run;
+ const stdout = hookContext(run.stdout);
assert.equal(code, 0);
const ns = stdout.slice(stdout.indexOf("### North Star"), stdout.indexOf("\n### ", stdout.indexOf("### North Star") + 5));
assert.match(ns, /- Project 0 — move the release build onto tagged artifacts/);
@@ -309,11 +315,13 @@ describe("North Star full level — no silent cut", () => {
try {
const tasks = Array.from({ length: 14 }, (_, i) => `- [ ] task ${i + 1}`).join("\n");
writeFileSync(join(dir, "Tasks.md"), `# Tasks\n\n${tasks}\n`);
- const { stdout, code } = spawnHook(
+ const run = spawnHook(
resolve(dirname(fileURLToPath(import.meta.url)), "../session-start.ts"),
{ source: "startup" },
{ CLAUDE_PROJECT_DIR: dir },
);
+ const { code } = run;
+ const stdout = hookContext(run.stdout);
assert.equal(code, 0);
const meter = stdout.trim().split("\n").pop() ?? "";
assert.match(meter, / — cut: Open Tasks \(10 of 14\)/, meter);
@@ -338,3 +346,71 @@ describe("North Star full level — no silent cut", () => {
);
});
});
+
+describe("the budget measures what goes out inside the JSON envelope (#340)", () => {
+ // Quotes and newlines escape to two characters each, so a section that fits
+ // a budget in bytes can be over it once encoded. Measured enveloped, the
+ // budget lets it fall back to its pointer instead of leaving the backstop
+ // to truncate the output mid-section.
+ const quoted: BudgetSection = { header: "### Quoted", body: '"'.repeat(5_000), priority: 10, fallback: "(pointer)" };
+
+ test("measured in bytes it fits whole; measured enveloped it falls back", () => {
+ assert.deepEqual(applyInjectionBudget([quoted], 6_000).collapsed, []);
+ assert.deepEqual(applyInjectionBudget([quoted], 6_000, enveloped).collapsed, ["Quoted"]);
+ });
+
+ test("enveloped never measures smaller than bytes, so multi-byte text is held as tightly as before", () => {
+ const cjk = "界".repeat(1_000);
+ assert.equal(enveloped(cjk), Buffer.byteLength(cjk, "utf-8"));
+ assert.ok(enveloped('a"b\nc') > Buffer.byteLength('a"b\nc', "utf-8"));
+ });
+});
+
+describe("a fitted rung sizes itself as the budget measures it (#340)", () => {
+ // North Star's top-N rung fits its body into the room the budget leaves.
+ // Fitted in raw bytes while the budget measures the encoded text, its body
+ // was always a little over once escaped, so the rung was never taken and
+ // the goals fell to their pointer.
+ test("under the enveloped measure, North Star still degrades to top-N rather than collapsing", () => {
+ const headlines = Array.from({ length: 40 }, (_, i) => `- goal ${i} keep the release pipeline building from tags`);
+ const fixed: BudgetSection = { header: "### Fixed", body: "f".repeat(2_000), priority: 1 };
+ const northStar: BudgetSection = {
+ header: "### North Star (current goals)",
+ body: headlines.join("\n"),
+ priority: 10,
+ fallback: "(pointer)",
+ levels: [{ name: "top-N", fit: (fits) => topHeadlines(headlines, fits) }],
+ };
+ for (const budget of [2_600, 2_800, 3_000]) {
+ const r = applyInjectionBudget([fixed, northStar], budget, enveloped);
+ assert.deepEqual(r.collapsed, [], `budget ${budget}: collapsed`);
+ assert.deepEqual(r.degraded, [{ section: "North Star (current goals)", level: "top-N" }], `budget ${budget}`);
+ }
+ });
+ test("top-N keeps every headline the whole render has room for, whatever the rest of it measures", () => {
+ // enveloped is max(bytes, json) of the WHOLE render, which is not the sum
+ // of its parts: multi-byte text elsewhere pays for this body's escapes.
+ const headlines = Array.from({ length: 60 }, (_, i) => `- goal ${i}`);
+ const fixed: BudgetSection = { header: "### Fixed", body: "語".repeat(700), priority: 1 };
+ const northStar = (body: string): BudgetSection => ({
+ header: "### North Star (current goals)",
+ body,
+ priority: 10,
+ fallback: "(pointer)",
+ levels: [{ name: "top-N", fit: (fits) => topHeadlines(headlines, fits) }],
+ });
+ const full = northStar(headlines.join("\n"));
+ const textOf = (body: string) => `### Fixed\n${fixed.body}\n\n### North Star (current goals)\n${body}`;
+ for (const budget of [2_400, 2_500, 2_600]) {
+ // The most headlines any top-N body could keep inside this budget.
+ let best = 0;
+ for (let n = 1; n < headlines.length; n++) {
+ const body = `${renderHeadlines(headlines.slice(0, n))}\n_(+${headlines.length - n} more goals in brain/North Star.md)_`;
+ if (enveloped(textOf(body)) <= budget) best = n;
+ }
+ assert.ok(best > 0, `budget ${budget} leaves room for at least one`);
+ const r = applyInjectionBudget([fixed, full], budget, enveloped);
+ assert.ok(r.text.includes(`(+${headlines.length - best} more goals`), `budget ${budget}: kept fewer than ${best}`);
+ }
+ });
+});
diff --git a/.claude/scripts/tests/delivery-gate.test.ts b/.claude/scripts/tests/delivery-gate.test.ts
index 60fcfd3..74aaa6a 100644
--- a/.claude/scripts/tests/delivery-gate.test.ts
+++ b/.claude/scripts/tests/delivery-gate.test.ts
@@ -11,6 +11,9 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import {
buildFixture,
+ contextOf,
+ flagConflict,
+ removeFixture,
countResults,
carries,
expectationTracker,
@@ -412,6 +415,12 @@ describe("delivery gate: self-test and environment", () => {
{ breakage: "startup-only" as const, verdicts: [v("at startup", startupOutcome), v("after /compact", "FAIL")] },
];
+ test("--self-test with --hooks-only is refused: the self-test breaks the mod, which --hooks-only never runs", () => {
+ assert.match(flagConflict(["--self-test", "--hooks-only"]) ?? "", /--self-test.*--hooks-only/);
+ assert.equal(flagConflict(["--hooks-only"]), null);
+ assert.equal(flagConflict(["--self-test"]), null);
+ });
+
test("the self-test passes only when every checkpoint fails and the startup-only control passes", () => {
assert.equal(selfTestOutcome(broken("PASS")).exitCode, 0);
assert.equal(selfTestOutcome(broken("FAIL")).exitCode, 1, "a control that failed means that copy never delivered");
@@ -471,6 +480,18 @@ describe("delivery gate: self-test and environment", () => {
}
});
+ test("contextOf reads the hook path's context out of its JSON envelope, and deliver as plain text (#340)", () => {
+ const vault = buildFixture("none", { withMod: false, notes: 0 });
+ try {
+ const hooked = contextOf(vault, false);
+ assert.match(lastLine(hooked), /^_context injected: /, "the expectation is the meter, not the envelope's closing brace");
+ assert.ok(!hooked.trimStart().startsWith("{"), "not the raw JSON");
+ assert.match(lastLine(contextOf(vault, true)), /^_context injected: /);
+ } finally {
+ removeFixture(vault);
+ }
+ });
+
test("expectedOf takes the last line, and the marker only when the context carries it", () => {
assert.deepEqual(expectedOf(`body GATE-MARK-1\n${METER}\n`, "GATE-MARK-1"), { line: METER, marker: "GATE-MARK-1" });
assert.deepEqual(expectedOf(`collapsed\n${METER}\n`, "GATE-MARK-1"), { line: METER, marker: null });
diff --git a/.claude/scripts/tests/hook-io.test.ts b/.claude/scripts/tests/hook-io.test.ts
index d0d053d..2cfd5c8 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, writeHookOutput, writeStopFeedback, writeSystemMessage, type PolicyResult } from "../lib/hook-io.ts";
+import { debug, envelopedLimit, fitEncoded, fitWithMeter, HOOK_OUTPUT_MAX_CHARS, parseHookContext, warn, writeHookOutput, writeStopFeedback, writeSystemMessage, type PolicyResult } from "../lib/hook-io.ts";
/**
* Replace process.stderr.write with a capturer that records calls and returns
@@ -194,6 +194,87 @@ describe("writeHookOutput — additionalContext fits the hook output cap (#254)"
});
});
+describe("envelopedLimit and fitWithMeter's json unit — a context sent inside the envelope (#340)", () => {
+ const meter = (cut: boolean) => (cut ? "_context injected: cut_" : "_context injected_");
+
+ test("a context fitted to the SessionStart limit stays within the cap once enveloped, meter last", () => {
+ // Newlines and quotes escape to two characters each: an ASCII body that
+ // fits the cap raw is over it once encoded, which a raw count would miss.
+ const body = Array.from({ length: 2_000 }, (_, i) => `- "item" ${i}\n`).join("");
+ const context = fitWithMeter(body, meter, envelopedLimit("SessionStart"));
+ const out = captureStdout(() => writeHookOutput("SessionStart", context));
+ assert.ok(out.length <= HOOK_OUTPUT_MAX_CHARS, `stdout is ${out.length} characters`);
+ const carried = (JSON.parse(out) as { hookSpecificOutput: { additionalContext: string } }).hookSpecificOutput.additionalContext;
+ assert.equal(carried, context, "writeHookOutput did not cut it again");
+ assert.match(carried, /_context injected: cut_\n$/);
+ });
+
+ test("a body that fits the limit raw but not encoded is cut, not passed whole", () => {
+ const limit = envelopedLimit("SessionStart");
+ // Every character a quote: raw it is under the limit, encoded about twice it.
+ const body = '"'.repeat(limit.max - 200);
+ const context = fitWithMeter(body, meter, limit);
+ assert.ok(JSON.stringify(context).length <= limit.max, `encoded ${JSON.stringify(context).length} of ${limit.max}`);
+ assert.match(context, /_context injected: cut_\n$/, "the cut is in the meter");
+ });
+
+ test("the meter is handed the size in the caller's measure, the one its budget decided on", () => {
+ const seen: number[] = [];
+ const encoded = (t: string) => JSON.stringify(t).length;
+ fitWithMeter('a"b\n', (_cut, size) => (seen.push(size), "_m_"), envelopedLimit("SessionStart"), encoded);
+ assert.deepEqual(seen, [encoded('a"b\n')], "not the UTF-8 bytes");
+ });
+
+ test("the json cut never splits an emoji", () => {
+ const body = "😀".repeat(6_000);
+ const context = fitWithMeter(body, meter, envelopedLimit("SessionStart"));
+ assert.doesNotMatch(context, /[\uD800-\uDBFF](?![\uDC00-\uDFFF])/, "a lone high surrogate");
+ assert.ok(JSON.stringify(context).length <= envelopedLimit("SessionStart").max);
+ });
+
+ test("an output exactly at the limit once encoded passes whole; one character more is cut", () => {
+ const limit = envelopedLimit("SessionStart");
+ // The whole output is `${body}\n${meter}\n`: solve for the body that lands
+ // on max, quotes (two encoded characters each) plus one "x" for an odd room.
+ const room = limit.max - 2 - (JSON.stringify(`\n${meter(false)}\n`).length - 2);
+ const body = "x".repeat(room % 2) + '"'.repeat(Math.floor(room / 2));
+ const whole = fitWithMeter(body, meter, limit);
+ assert.equal(JSON.stringify(whole).length, limit.max);
+ assert.match(whole, /_context injected_\n$/, "not cut");
+ assert.match(fitWithMeter(body + "x", meter, limit), /_context injected: cut_\n$/);
+ });
+
+ test("an emoji straddling the cut after an ASCII prefix is dropped whole, on every alignment", () => {
+ const limit = envelopedLimit("SessionStart");
+ for (let pad = 0; pad < 4; pad++) {
+ const body = "x".repeat(limit.max - 500 + pad) + "😀".repeat(400);
+ const context = fitWithMeter(body, meter, limit);
+ assert.doesNotMatch(context, /[\uD800-\uDBFF](?![\uDC00-\uDFFF])/, `a lone high surrogate at pad ${pad}`);
+ assert.ok(JSON.stringify(context).length <= limit.max, `pad ${pad}`);
+ }
+ });
+
+ test("a meter too long for the limit on its own is cut to the limit, its newline counted as encoded", () => {
+ for (const max of [10, 11, 20, 21]) {
+ const limit = { max, unit: "json" as const, name: "a tiny limit" };
+ const out = fitWithMeter("body", () => "m".repeat(100), limit);
+ assert.ok(JSON.stringify(out).length <= max, `max ${max}: encoded ${JSON.stringify(out).length}`);
+ }
+ });
+
+ test("without a measure, the meter is sized in the limit's own unit", () => {
+ const seen: number[] = [];
+ fitWithMeter('a"b\n', (_cut, size) => (seen.push(size), "_m_"), envelopedLimit("SessionStart"));
+ assert.deepEqual(seen, [JSON.stringify('a"b\n').length]);
+ });
+
+ test("CRLF bodies are measured as encoded, carriage returns included", () => {
+ const body = "line\r\n".repeat(3_000);
+ const context = fitWithMeter(body, meter, envelopedLimit("SessionStart"));
+ assert.ok(JSON.stringify(context).length <= envelopedLimit("SessionStart").max);
+ });
+});
+
describe("writeStopReportData", () => {
test("a report too large for one pipe write arrives whole", async () => {
const { spawnSync } = await import("node:child_process");
@@ -232,3 +313,22 @@ describe("writeStopReportData on a pipe that writes in parts", () => {
assert.throws(() => writeStopReportData({ key: "k", claims: [], agentText: "t" }, write), /closed/);
});
});
+
+describe("parseHookContext — the context a hook-path envelope carries (#340)", () => {
+ test("returns additionalContext from an envelope for the named event", () => {
+ const stdout = JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: "## Session Context\n" } });
+ assert.equal(parseHookContext(stdout, "SessionStart"), "## Session Context\n");
+ });
+
+ test("plain text is refused by name, not with a bare JSON SyntaxError", () => {
+ assert.throws(() => parseHookContext("## Session Context\n", "SessionStart"), /not one JSON object/);
+ });
+
+ test("an envelope for another event, or with no string context, is refused", () => {
+ const stop = JSON.stringify({ hookSpecificOutput: { hookEventName: "Stop", additionalContext: "x" } });
+ assert.throws(() => parseHookContext(stop, "SessionStart"), /not a SessionStart envelope/);
+ const empty = JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart" } });
+ assert.throws(() => parseHookContext(empty, "SessionStart"), /not a SessionStart envelope/);
+ assert.throws(() => parseHookContext("null", "SessionStart"), /not a SessionStart envelope/);
+ });
+});
diff --git a/.claude/scripts/tests/session-start.integration.test.ts b/.claude/scripts/tests/session-start.integration.test.ts
index 7517dfe..1c0f8e3 100644
--- a/.claude/scripts/tests/session-start.integration.test.ts
+++ b/.claude/scripts/tests/session-start.integration.test.ts
@@ -35,8 +35,11 @@ import {
} from "node:fs";
import { tmpdir } from "node:os";
import { HOOK_OUTPUT_MAX_CHARS } from "../lib/hook-io.ts";
-import { METER_HEADROOM } from "../lib/session-start.ts";
-import { runScript as spawnHook, rmTemp } from "./_helpers.ts";
+import { INJECTION_CEILING_BYTES, METER_HEADROOM } from "../lib/session-start.ts";
+
+/** The hook-path ceiling as the meter prints it, regex-escaped (derived: the envelope takes its share, #340). */
+const CEILING_KB = (INJECTION_CEILING_BYTES / 1000).toFixed(1).replace(".", "\\.");
+import { hookContext, runScript as spawnHook, rmTemp } from "./_helpers.ts";
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
const SCRIPT = resolve(SCRIPT_DIR, "../session-start.ts");
@@ -70,7 +73,15 @@ before(() => {
// `EPERM` thrown out of this hook after the assertions had already passed.
after(() => rmTemp(TMP_DIR));
-const runHook = () => spawnHook(SCRIPT, "", { CLAUDE_PROJECT_DIR: TMP_DIR });
+/**
+ * A hook-path run (#340): its stdout is one JSON envelope, so `stdout` here is
+ * the context it carried and `raw` what was printed. The cap applies to `raw`.
+ */
+const hookPath = (stdin: string | object, env: Record<string, string>) => {
+ const r = spawnHook(SCRIPT, stdin, env);
+ return { ...r, raw: r.stdout, stdout: hookContext(r.stdout) };
+};
+const runHook = () => hookPath("", { CLAUDE_PROJECT_DIR: TMP_DIR });
const REQUIRED_SECTIONS = [
"### Date",
@@ -95,6 +106,40 @@ describe("session-start — no detached qmd refresh under the switch (#337)", ()
});
});
+describe("session-start — the hook path prints one JSON envelope (#340)", () => {
+ // Gemini parses a hook's stdout as JSON and takes context only from
+ // hookSpecificOutput.additionalContext (per its hooks reference as of
+ // 2026-10-13, not observed); Claude Code accepts the same shape.
+ test("stdout is exactly one SessionStart envelope, whose additionalContext carries the context and the meter", () => {
+ const { raw, code } = runHook();
+ assert.equal(code, 0);
+ const parsed = JSON.parse(raw) as { hookSpecificOutput?: { hookEventName?: string; additionalContext?: string } };
+ assert.deepEqual(Object.keys(parsed), ["hookSpecificOutput"]);
+ assert.equal(parsed.hookSpecificOutput?.hookEventName, "SessionStart");
+ const context = parsed.hookSpecificOutput?.additionalContext ?? "";
+ assert.ok(context.includes("### Date"), "the context is inside the envelope");
+ assert.match(lastLine(context), /^_context injected: /, "the meter closes the context");
+ });
+
+ test("an empty folder, no vault files at all, still gets one well-formed envelope", () => {
+ const dir = mkdtempSync(join(tmpdir(), "session-start-empty-"));
+ try {
+ const { stdout, code } = hookPath({ source: "startup" }, { CLAUDE_PROJECT_DIR: dir });
+ assert.equal(code, 0);
+ assert.match(lastLine(stdout), /^_context injected: /);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("deliver stays plain text: the mod writes it into an instruction file", () => {
+ const { stdout, code } = spawnHook(SCRIPT, { source: "startup", om_mod: "deliver" }, { CLAUDE_PROJECT_DIR: TMP_DIR });
+ assert.equal(code, 0);
+ assert.ok(stdout.startsWith("## Session Context"), "plain Markdown, not JSON");
+ assert.throws(() => JSON.parse(stdout));
+ });
+});
+
describe("session-start — silence contract and structure", () => {
test("exits 0 with empty stderr on a minimal vault", () => {
const { code, stderr } = runHook();
@@ -217,7 +262,7 @@ describe("session-start — listing collapse and injection budget", () => {
after(() => rmTemp(BIG_DIR));
- const runBig = () => spawnHook(SCRIPT, "", { CLAUDE_PROJECT_DIR: BIG_DIR });
+ const runBig = () => hookPath("", { CLAUDE_PROJECT_DIR: BIG_DIR });
const listingOf = (stdout: string) =>
stdout.split("### Vault File Listing\n")[1]?.split("\n### ")[0] ?? "";
@@ -250,7 +295,7 @@ describe("session-start — listing collapse and injection budget", () => {
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 \/ 9\.1kB budget(?: — collapsed: [^_]+)?_$/);
+ assert.match(last, new RegExp(`^_context injected: \\d+\\.\\dkB / ${CEILING_KB}kB budget(?: — collapsed: [^_]+)?_$`));
});
test("a tight manifest budget degrades sections and NAMES them in the meter", () => {
@@ -299,7 +344,7 @@ describe("session-start — listing collapse and injection budget", () => {
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: [^_]+)?_$/,
+ new RegExp(`^_context injected: \\d+\\.\\dkB / ${CEILING_KB}kB budget \\(80\\.0kB configured, held under the hook output cap\\)(?: — collapsed: [^_]+)?_$`),
);
} finally {
rmSync(manifest, { force: true });
@@ -356,10 +401,10 @@ describe("session-start — the hook output cap", () => {
test("an ordinary vault of ~250 nested notes fits, the listing degrading first", () => {
const dir = nestedVault({ eager_layer_budget_bytes: 80_000 });
try {
- const { stdout, code, stderr } = spawnHook(SCRIPT, "", { CLAUDE_PROJECT_DIR: dir });
+ const { stdout, raw, code, stderr } = hookPath("", { CLAUDE_PROJECT_DIR: dir });
assert.equal(code, 0);
assert.equal(stderr, "");
- assert.ok(stdout.length <= CAP, `stdout is ${stdout.length} characters`);
+ assert.ok(raw.length <= CAP, `stdout is ${raw.length} characters`);
assert.match(lastLine(stdout), /^_context injected: .* — collapsed: Vault File Listing_$/);
} finally {
rmTemp(dir);
@@ -373,11 +418,11 @@ describe("session-start — the hook output cap", () => {
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 });
+ const { stdout, raw, code, stderr } = hookPath("", { 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(raw.length <= CAP, `stdout is ${raw.length} characters`);
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 {
@@ -430,7 +475,7 @@ describe("session-start — om_mod (a Claude Code mod)", () => {
test("without the flag the same run does write VAULT_PATH (the standdown check above can fail)", () => {
const envFile = join(TMP_DIR, "env-plain.sh");
writeFileSync(envFile, "");
- const { stdout } = spawnHook(SCRIPT, { source: "startup" }, { CLAUDE_PROJECT_DIR: TMP_DIR, CLAUDE_ENV_FILE: envFile });
+ const { stdout } = hookPath({ source: "startup" }, { CLAUDE_PROJECT_DIR: TMP_DIR, CLAUDE_ENV_FILE: envFile });
assert.ok(stdout.includes("### Date"));
assert.match(readFileSync(envFile, "utf-8"), /VAULT_PATH/);
});
@@ -447,8 +492,8 @@ describe("session-start — om_mod (a Claude Code mod)", () => {
assert.ok(delivered.stdout.includes("Example project-11 decisions note 9.md"), "the deepest listing entry is there");
// The same vault as hook output stays under the cap (#254), listing degraded.
- const hooked = spawnHook(SCRIPT, { source: "startup" }, { CLAUDE_PROJECT_DIR: dir });
- assert.ok(hooked.stdout.length <= HOOK_OUTPUT_MAX_CHARS);
+ const hooked = hookPath({ source: "startup" }, { CLAUDE_PROJECT_DIR: dir });
+ assert.ok(hooked.raw.length <= HOOK_OUTPUT_MAX_CHARS);
assert.match(lastLine(hooked.stdout), /collapsed: Vault File Listing/);
} finally {
rmTemp(dir);
@@ -469,13 +514,13 @@ describe("session-start — om_mod (a Claude Code mod)", () => {
const delivered = spawnHook(SCRIPT, { source: "compact", om_mod: "deliver" }, { CLAUDE_PROJECT_DIR: TMP_DIR }).stdout;
assert.ok(delivered.includes("### Vault File Listing"));
assert.ok(!delivered.includes("### Context Pointer"));
- const hooked = spawnHook(SCRIPT, { source: "compact" }, { CLAUDE_PROJECT_DIR: TMP_DIR }).stdout;
+ const hooked = hookPath({ source: "compact" }, { CLAUDE_PROJECT_DIR: TMP_DIR }).stdout;
assert.ok(hooked.includes("### Context Pointer"), "without the flag compact stays pointer mode");
});
test("an unknown om_mod value changes nothing: output identical to a run with no flag", () => {
- const plain = spawnHook(SCRIPT, { source: "startup" }, { CLAUDE_PROJECT_DIR: TMP_DIR });
- const unknown = spawnHook(SCRIPT, { source: "startup", om_mod: "silence" }, { CLAUDE_PROJECT_DIR: TMP_DIR });
+ const plain = hookPath({ source: "startup" }, { CLAUDE_PROJECT_DIR: TMP_DIR });
+ const unknown = hookPath({ source: "startup", om_mod: "silence" }, { CLAUDE_PROJECT_DIR: TMP_DIR });
assert.equal(unknown.code, 0);
assert.equal(unknown.stdout, plain.stdout);
assert.ok(plain.stdout.includes("### Date"));
diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.ts
index 1e3c941..2d83082 100644
--- a/.claude/scripts/tests/session-start.test.ts
+++ b/.claude/scripts/tests/session-start.test.ts
@@ -27,6 +27,7 @@ import {
DEFAULT_INSTRUCTION_BUDGET_BYTES,
effectiveInjectionBudget,
INJECTION_CEILING_BYTES,
+ METER_HEADROOM,
parseListingCollapseThreshold,
DEFAULT_LISTING_COLLAPSE_THRESHOLD,
type BudgetSection,
@@ -51,7 +52,7 @@ import {
collectOpenTasks,
} from "../lib/session-start.ts";
-import { cutLine, fitEncoded, fitWithMeter, HOOK_OUTPUT_LIMIT, HOOK_OUTPUT_MAX_CHARS, type OutputLimit } from "../lib/hook-io.ts";
+import { cutLine, envelopedLimit, fitEncoded, fitWithMeter, HOOK_OUTPUT_LIMIT, HOOK_OUTPUT_MAX_CHARS, type OutputLimit } from "../lib/hook-io.ts";
const CUT_LINE = cutLine(HOOK_OUTPUT_LIMIT);
import { rmTemp } from "./_helpers.ts";
@@ -1251,16 +1252,27 @@ describe("injectionMode", () => {
});
describe("the injection budget under the hook output cap (#254)", () => {
- test("the ceiling leaves the meter its headroom under the hook output cap", () => {
- assert.equal(INJECTION_CEILING_BYTES, 9_100);
+ test("the ceiling leaves the meter its headroom under the hook output cap, once the JSON envelope is counted (#340)", () => {
+ // The hook path sends the context inside an envelope, which takes its
+ // share of the cap: the ceiling must come from what the envelope leaves.
+ assert.equal(INJECTION_CEILING_BYTES, envelopedLimit("SessionStart").max - METER_HEADROOM);
+ // A ratchet on the value itself, so a wrong formula cannot pass by agreeing with itself.
+ assert.equal(INJECTION_CEILING_BYTES, 9_024);
});
+ test("the template's own manifest budget is under the ceiling: a fresh vault's meter never reports a clamp", () => {
+ const manifest = readFileSync(new URL("../../../vault-manifest.json", import.meta.url), "utf-8");
+ assert.equal(effectiveInjectionBudget(parseInjectionBudget(manifest)).clampedFrom, undefined);
+ });
+
+ const C = INJECTION_CEILING_BYTES;
+
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, undefined], // exactly the ceiling: kept as configured
+ [80_000, C, 80_000], // the old default: clamped, and reported
+ [C + 1, C, C + 1], // one over: clamped
+ [C, C, 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
+ [null, C, undefined], // unset: the ceiling, with nothing to report
];
for (const [configured, bytes, clampedFrom] of cases) {
test(`effectiveInjectionBudget(${String(configured)}) → ${bytes}${clampedFrom === undefined ? "" : " (clamped)"}`, () => {
@@ -1336,7 +1348,8 @@ describe("fitWithMeter", () => {
const body = "x\n".repeat(1_000);
const out = fitWithMeter(body, meter, chars(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$`));
+ // In the limit's own unit: characters here, so the marker's "…" counts once.
+ assert.match(out, new RegExp(`_meter ${kept.length} cut_\n$`));
});
test("a byte limit is measured in UTF-8 bytes, cuts on a line, and never splits a character", () => {
diff --git a/.github/scripts/delivery-gate.ts b/.github/scripts/delivery-gate.ts
index fd8af88..26bcafa 100644
--- a/.github/scripts/delivery-gate.ts
+++ b/.github/scripts/delivery-gate.ts
@@ -39,7 +39,7 @@
* Run it by hand on any Claude Code version before it is recommended, with a
* logged-in `claude`:
*
- * node --experimental-strip-types .github/scripts/delivery-gate.ts [--trusted-dir <dir>] [--file-issue] [--model opus] [--claude <bin>]
+ * node --experimental-strip-types .github/scripts/delivery-gate.ts [--trusted-dir <dir>] [--file-issue] [--hooks-only] [--model opus] [--claude <bin>]
*
* `--trusted-dir` loads the mod the way a user gets it: found in the vault's
* `.claude/skills/` after the workspace-trust prompt, which a headless session
@@ -50,6 +50,10 @@
*
* `--file-issue` opens a GitHub issue (with `gh`) when a checkpoint fails.
*
+ * `--hooks-only` runs only the sessions without the mod (the settings hooks
+ * alone), for a change that touches the hook path and not the mod's (#340).
+ * It cannot be combined with `--self-test`, which only runs the mod.
+ *
* `--self-test` runs two broken copies of the mod instead: one cuts its
* context to 2,000 characters everywhere, one delivers it whole only at
* startup. Every checkpoint must FAIL, except the startup-only copy's own
@@ -71,6 +75,7 @@ import { homedir, tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
+import { parseHookContext } from "../../.claude/scripts/lib/hook-io.ts";
import { isMainModule } from "../../.claude/scripts/lib/main-guard.ts";
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
@@ -612,7 +617,10 @@ export function contextOf(vault: string, deliver: boolean, source: "startup" | "
},
);
if (run.status !== 0) throw new Error(`session-start.ts failed: ${run.stderr}`);
- return run.stdout;
+ if (deliver) return run.stdout;
+ // The hook path prints one JSON envelope (#340): the context is its
+ // additionalContext, which is what reaches the model.
+ return parseHookContext(run.stdout, "SessionStart");
}
/** What a context makes a checkpoint expect: its last line, and the marker if the context carries it. */
@@ -793,6 +801,13 @@ const print = (label: string, verdicts: readonly Verdict[]) => {
}
};
+/** Why these flags cannot run together, or null when they can. */
+export function flagConflict(argv: readonly string[]): string | null {
+ return argv.includes("--self-test") && argv.includes("--hooks-only")
+ ? "--self-test breaks the mod, and --hooks-only runs no session with the mod: drop one of them."
+ : null;
+}
+
/** The self-test's expectation: every checkpoint fails, except the startup-only copy's own startup, its positive control. */
export function selfTestOutcome(runs: ReadonlyArray<{ readonly breakage: Breakage; readonly verdicts: readonly Verdict[] }>): {
exitCode: 0 | 1 | 2;
@@ -838,7 +853,13 @@ async function main(): Promise<void> {
const i = argv.indexOf(name);
return i >= 0 && argv[i + 1] ? argv[i + 1] : undefined;
};
+ const conflict = flagConflict(argv);
+ if (conflict) {
+ console.error(conflict);
+ process.exit(2);
+ }
const selfTest = argv.includes("--self-test");
+ const hooksOnly = argv.includes("--hooks-only");
const trustedDir = flag("--trusted-dir");
const base = { claude: flag("--claude") ?? "claude", model: flag("--model") ?? "opus", ...(trustedDir ? { trustedDir: resolve(trustedDir) } : {}) };
const version = spawnSync(base.claude, ["--version"], { encoding: "utf8" }).stdout?.trim() || "unknown version";
@@ -847,7 +868,7 @@ async function main(): Promise<void> {
process.exit(130);
});
const loading = trustedDir ? `found in the trusted folder ${resolve(trustedDir)}` : "loaded with --plugin-dir";
- console.log(`Delivery gate · ${version} · ${base.model} · the mod ${loading}${selfTest ? " · SELF-TEST" : ""}\n`);
+ console.log(`Delivery gate · ${version} · ${base.model} · ${hooksOnly ? "settings hooks only" : `the mod ${loading}`}${selfTest ? " · SELF-TEST" : ""}\n`);
if (selfTest) {
const runs: Array<{ breakage: Breakage; verdicts: Verdict[] }> = [];
@@ -864,7 +885,7 @@ async function main(): Promise<void> {
}
const verdicts: Verdict[] = [];
- for (const steps of plan(true)) verdicts.push(...(await runSession(steps, "none", { ...base, withMod: true })));
+ if (!hooksOnly) for (const steps of plan(true)) verdicts.push(...(await runSession(steps, "none", { ...base, withMod: true })));
for (const steps of plan(false)) verdicts.push(...(await runSession(steps, "none", { ...base, withMod: false })));
print("", verdicts);
const invalid = verdicts.filter((v) => v.outcome === "INVALID").length;
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index a3c8770..1847764 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -98,7 +98,7 @@ 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 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".
+**The budget has a hard ceiling it cannot be raised past: Claude Code's hook output cap.** Claude Code caps a hook's context 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 the JSON envelope and room for the meter (about 9,000; a section is sized as the larger of its UTF-8 bytes and its JSON-encoded length, 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 (`AGENTS.md`, plus `.claude/rules/` on Claude Code), which this cap does not apply to.
@@ -203,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`, 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. When the template's Claude Code mod delivers the same briefing as an instruction file instead, the hook stands down and the briefing is bounded by `eager_layer_instruction_budget_bytes`, since instruction files are not under the hook cap (#264). The same backstop holds there, in bytes: sections that never degrade are cut at the budget plus the meter's room, and the meter says "truncated to fit the instruction budget". 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. When the template's Claude Code mod delivers the same briefing as an instruction file instead, the hook stands down and the briefing is bounded by `eager_layer_instruction_budget_bytes`, since instruction files are not under the hook cap (#264). The same backstop holds there, in bytes: sections that never degrade are cut at the budget plus the meter's room, and the meter says "truncated to fit the instruction budget". On the hook path the briefing goes out as one JSON object, `{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":…}}`, for every agent (#340). Gemini parses a hook's stdout as JSON and takes context only from that field (per its hooks reference as of 2026-10-13, not observed), and Claude Code accepts the same shape, capping the `additionalContext` string rather than the raw stdout. Whether Codex and Grok take context from the envelope is unverified (TBC). So the budget and the backstop measure the JSON-encoded text (escaping counts), keeping the whole stdout under the cap for an agent whose cap is undocumented. The mod's `deliver` run stays plain text, since it becomes an instruction file. 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 `AGENTS.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.
- **`VAULT_QMD_REFRESH=off` switches the detached refresh off** (exactly `off`, as wiki-mind's copy reads it): no `qmd-refresh-run.ts` worker, and no detached `qmd update` or bootstrap from `SessionStart`. The debounce decision and its sentinel stamps still run. The test suite sets it in every test process and every hook a test runs. The test runner also stops and fails on any surviving worker whose command line names the run's temp folder, which every trailing worker's does; an immediate-path worker carries no path, so for those the switch is the guard (#337).
@@ -889,7 +889,7 @@ Step 2 is not documentation garnish. Measured: with the server wired and no repo
The same scripts serve three agents. Each agent has its own config file mapping equivalent lifecycle events to the shared scripts. The checklist runs on `Stop` for Claude Code and Codex (per response, deduped) and on `SessionEnd` for Gemini (at shutdown). The script branches on the documented event name and on what a payload field means, never on which agent sent it. Where agents spell one field differently, every spelling is read, so the field can never tell the agents apart: Grok's Stop sends the re-entry flag as `stopHookActive`, and the checklist reads it beside `stop_hook_active` (#323).
-Session-boundary output is JSON-or-nothing on all three agents. `stop-checklist.ts` emits `{}` when a Stop has nothing new to say. What the user sees is `systemMessage`, the one user-facing field all three agents share: on a Stop whose findings changed, a one-line-per-section summary, with the full report saved for the next prompt's `UserPromptSubmit` to hand to the agent unseen. Only when the report cannot be saved does it go out as Stop feedback, which Claude Code prints in full; whether Codex honours Stop feedback is unverified. SessionEnd (Gemini) has no next prompt, so there the full report is `systemMessage` only. `om-wrap-up` still owns the deliberate acting pass at the end of a session.
+Session-boundary output is JSON-or-nothing on all three agents. On the hook path `session-start.ts` prints one `hookSpecificOutput` envelope too, for every agent (#340). `stop-checklist.ts` emits `{}` when a Stop has nothing new to say. What the user sees is `systemMessage`, the one user-facing field all three agents share: on a Stop whose findings changed, a one-line-per-section summary, with the full report saved for the next prompt's `UserPromptSubmit` to hand to the agent unseen. Only when the report cannot be saved does it go out as Stop feedback, which Claude Code prints in full; whether Codex honours Stop feedback is unverified. SessionEnd (Gemini) has no next prompt, so there the full report is `systemMessage` only. `om-wrap-up` still owns the deliberate acting pass at the end of a session.
```mermaid
flowchart TB
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 95690c9..00c02b7 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -159,6 +159,8 @@ node --experimental-strip-types .github/scripts/delivery-gate.ts --trusted-dir <
node --experimental-strip-types .github/scripts/delivery-gate.ts --trusted-dir <that folder> --file-issue # then: every checkpoint PASS
```
+For a change to the hook path alone (the settings hooks, not the mod), `--hooks-only` runs just the sessions without the mod; it cannot be combined with `--self-test`, which breaks the mod.
+
A self-test that does not exit 0 means the gate is broken: fix it before trusting a normal run. A normal run that fails files an issue with `--file-issue`, and that version is not recommended until it is resolved. What counts as PASS, FAIL and INVALID, the exit codes, and why each `/compact` and `/clear` changes the vault first are documented at the top of `.github/scripts/delivery-gate.ts`.
## Questions?
diff --git a/vault-manifest.json b/vault-manifest.json
index 8bfabe2..2f37d0a 100644
--- a/vault-manifest.json
+++ b/vault-manifest.json
@@ -13,7 +13,7 @@
"action items",
"what to watch"
],
- "eager_layer_budget_bytes": 9100,
+ "eager_layer_budget_bytes": 9000,
"eager_layer_instruction_budget_bytes": 20000,
"listing_collapse_threshold": 12,
"memory_root": "memories",