Skip to content

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

feat: add om_mod flags to session-start and stop-checklist (#269)

Brenno Ferrari9bb66e28fb70
diff --git a/.claude/scripts/lib/hook-io.ts b/.claude/scripts/lib/hook-io.ts
index 9ac5866..d4815f0 100644
--- a/.claude/scripts/lib/hook-io.ts
+++ b/.claude/scripts/lib/hook-io.ts
@@ -113,7 +113,19 @@ export function writeSystemMessage(message: string): void {
*/
export const HOOK_OUTPUT_MAX_CHARS = 9_500;
-const CUT_MARKER = "\n… (truncated to fit the hook output cap)";
+/**
+ * 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 };
+
+/** 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 line that replaces whatever a cut to `limit` removed. */
+export const cutLine = (limit: OutputLimit): string => `… (truncated to fit ${limit.name})`;
+
+const CUT_MARKER = `\n${cutLine(HOOK_OUTPUT_LIMIT)}`;
/**
* `text`, cut with a marker so that its JSON-encoded form is at most `max`
@@ -135,40 +147,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.
+ * A plain-text output, held under `limit` 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), under the hook output cap or,
+ * delivered by a mod, under the instruction budget in bytes. Over the limit,
+ * 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(
+export function fitWithMeter(
body: string,
meter: (cut: boolean, bodyBytes: number) => string,
- cap: number = HOOK_OUTPUT_MAX_CHARS,
+ limit: OutputLimit = HOOK_OUTPUT_LIMIT,
): string {
+ const size = (text: string) => (limit.unit === "bytes" ? Buffer.byteLength(text, "utf-8") : text.length);
+ // 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`;
- if (whole.length <= cap) return whole;
- const room = cap - `\n${CUT_LINE}\n\n${meter(true, bodyBytes)}\n`.length;
+ if (size(whole) <= limit.max) return whole;
+ const marker = cutLine(limit);
+ const room = limit.max - size(`\n${marker}\n\n${meter(true, bodyBytes)}\n`);
// 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);
+ // (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`;
+ 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);
- // 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`;
+ const kept = `${head}\n${marker}\n`;
return `${kept}\n${meter(true, Buffer.byteLength(kept, "utf-8"))}\n`;
}
@@ -227,3 +242,28 @@ export function writeSilentHookOutput(): void {
/* stdout gone — nothing to report it to */
}
}
+
+/**
+ * The Stop report as data, for the obsidian-mind mod's own run
+ * (`om_mod: "report"`, lib/om-mod.ts). Not a hook envelope: the mod parses it
+ * and decides what the user and the agent see.
+ *
+ * Written whole: writeSync can return after part of a large buffer on a pipe,
+ * and can fail with EAGAIN when the pipe is full, so it loops until every
+ * byte is out, retrying a full pipe. Any other failure throws: the mod treats
+ * a run that printed no usable report as failed and lets the settings hook
+ * run in its place, which a silently truncated report would not trigger.
+ */
+export function writeStopReportData(
+ report: { readonly key: string; readonly claims: readonly string[]; readonly agentText: string },
+ write: (buffer: Buffer, offset: number, length: number) => number = (buffer, offset, length) => writeSync(1, buffer, offset, length),
+): void {
+ const bytes = Buffer.from(JSON.stringify({ report }), "utf8");
+ for (let offset = 0; offset < bytes.length; ) {
+ try {
+ offset += write(bytes, offset, bytes.length - offset);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EAGAIN") throw error;
+ }
+ }
+}
diff --git a/.claude/scripts/lib/om-mod.ts b/.claude/scripts/lib/om-mod.ts
new file mode 100644
index 0000000..c94ad7f
--- /dev/null
+++ b/.claude/scripts/lib/om-mod.ts
@@ -0,0 +1,40 @@
+/**
+ * The instruction a Claude Code mod passes to a hook script on the event
+ * itself (#264).
+ *
+ * A mod wraps each settings-hook event as `classic.<Event>` and runs before
+ * the settings hooks beneath it; what it passes to `next()` is exactly what
+ * those hooks read on stdin. So when the template's mod takes an event over,
+ * it calls `next({ ...e, om_mod: "standdown" })` and the script exits without
+ * output or side effects, and when it wants the script's output for a
+ * channel of its own, it runs the script itself with `deliver` or `report`.
+ *
+ * The flag is the switch because it fails safe: it exists only on an event
+ * whose mod hook actually ran. A mod that throws before `next`, crashed, was
+ * blocked by policy or never loaded passes the original event down, and the
+ * script runs exactly as it does without a mod. Codex and Gemini never load
+ * mods, so they never send it. An environment variable would not have that
+ * property: it outlives a mod that died, and the scripts would stand down
+ * with nothing delivering.
+ *
+ * Each script honours only the modes meant for it and ignores the rest,
+ * including any unknown value, so a typo or a newer mod degrades to today's
+ * behaviour rather than to silence.
+ */
+
+/**
+ * - `standdown`: the mod delivers this event; print nothing and do nothing, except what only a hook process can do (session-start exports VAULT_PATH to CLAUDE_ENV_FILE, which the mod's run never receives).
+ * - `deliver`: the mod delivers this output as an instruction file, not as
+ * hook output, so the hook-output cap does not apply.
+ * - `report`: return the Stop report as data for the mod to present.
+ */
+export type OmMod = "standdown" | "deliver" | "report";
+
+const OM_MODS: ReadonlySet<string> = new Set<OmMod>(["standdown", "deliver", "report"]);
+
+/** The `om_mod` instruction on a hook's parsed input, or null when absent or unknown. */
+export function readOmMod(input: unknown): OmMod | null {
+ if (input === null || typeof input !== "object") return null;
+ const value = (input as { readonly om_mod?: unknown }).om_mod;
+ return typeof value === "string" && OM_MODS.has(value) ? (value as OmMod) : null;
+}
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.ts
index 4704c82..3dad494 100644
--- a/.claude/scripts/lib/session-start.ts
+++ b/.claude/scripts/lib/session-start.ts
@@ -32,8 +32,10 @@ export function formatInjectionSize(
readonly collapsed?: readonly string[] | undefined;
/** The configured budget, when it was clamped to the hook output cap. */
readonly clampedFrom?: number | undefined;
- /** True when the output was truncated to fit the hook output cap. */
+ /** True when the output was truncated to fit its limit. */
readonly cut?: boolean | undefined;
+ /** The limit a cut was to; the hook output cap when unset. */
+ readonly cutTo?: string | undefined;
},
): string {
const safe = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
@@ -50,7 +52,7 @@ export function formatInjectionSize(
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 += " — truncated to fit the hook output cap";
+ if (opts?.cut === true) line += ` — truncated to fit ${opts.cutTo ?? "the hook output cap"}`;
return `${line}_`;
}
@@ -208,21 +210,36 @@ export const METER_HEADROOM = 400;
*/
export const INJECTION_CEILING_BYTES = HOOK_OUTPUT_MAX_CHARS - 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 };
+
/**
* 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. `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;
-} {
+export function effectiveInjectionBudget(configured: number | null): InjectionBudget {
if (configured === null) return { bytes: INJECTION_CEILING_BYTES };
if (configured <= INJECTION_CEILING_BYTES) return { bytes: configured };
return { bytes: INJECTION_CEILING_BYTES, clampedFrom: configured };
}
+/**
+ * The budget when a Claude Code mod delivers the eager layer as an
+ * instruction file (`om_mod: "deliver"`, #264), unless the manifest sets
+ * `eager_layer_instruction_budget_bytes`. Instruction files are not under the
+ * hook-output cap, so INJECTION_CEILING_BYTES does not apply there. The layer
+ * still gets a deliberate size, because it is paid in every session and by
+ * every general-purpose subagent: about 5,000 tokens.
+ */
+export const DEFAULT_INSTRUCTION_BUDGET_BYTES = 20_000;
+
+/** `eager_layer_instruction_budget_bytes` from the manifest; null when unset or invalid. */
+export function parseInstructionBudget(manifestJson: string | null): number | null {
+ return parsePositiveIntField(manifestJson, "eager_layer_instruction_budget_bytes");
+}
+
/** `listing_collapse_threshold` from the manifest; null when unset or invalid. */
export function parseListingCollapseThreshold(
diff --git a/.claude/scripts/lib/stop-report.ts b/.claude/scripts/lib/stop-report.ts
index 70312e6..62da41d 100644
--- a/.claude/scripts/lib/stop-report.ts
+++ b/.claude/scripts/lib/stop-report.ts
@@ -3,11 +3,22 @@
* report for the agent. Why two, and how the full one travels: lib/stop-handoff.ts.
*/
-/** What both framings close with, so the two cannot drift apart on it. */
+/** What every framing closes with, so they cannot drift apart on it. */
const STANDING_RULES = "Never move or delete notes without asking, and do not recite the report back.";
+/** The choice both next-prompt framings hand the agent, and the rules after it. */
+const DECIDE = `then decide what the report calls for: act on what bears on the current work, ask the user when something needs their call, or leave it unmentioned if nothing needs doing. ${STANDING_RULES}`;
+
/** Framing for the agent, which reads the report alongside the user's next message. */
-export const AGENT_PREFACE = `Stop hook report, handed over with this message: when your previous response ended, these findings were new or changed since the last report this session. The user saw only a one-line summary of each section. Deal with the user's message first, then decide what the report calls for: act on what bears on the current work, ask the user when something needs their call, or leave it unmentioned if nothing needs doing. ${STANDING_RULES}`;
+export const AGENT_PREFACE = `Stop hook report, handed over with this message: when your previous response ended, these findings were new or changed since the last report this session. The user saw only a one-line summary of each section. Deal with the user's message first, ${DECIDE}`;
+
+/**
+ * Framing for the agent under the obsidian-mind mod (`om_mod: "report"`), whose
+ * delivery differs: the user saw one line under an earlier answer, the report
+ * rides a later prompt (not always the next one), and that prompt may be the
+ * mod's own notice rather than the user's.
+ */
+export const MOD_PREFACE = `Stop hook report, handed over with this message: when one of your earlier responses this session ended, these findings were new or changed since the last report. The user saw one line naming them under that response. Deal with this message first (it may be the user's, or a vault notice from the obsidian-mind plugin), ${DECIDE}`;
/** The closing line of the summary: where the detail went. */
export const SUMMARY_TRAILER = "The full report reaches the agent with your next message.";
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index 3b2a419..9a96d3a 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -8,6 +8,14 @@
* vault markdown file listing.
*
* Also persists VAULT_PATH to CLAUDE_ENV_FILE when Claude Code provides it.
+ *
+ * Under the template's Claude Code mod (#264, lib/om-mod.ts) the mod
+ * delivers this output as an instruction file: it runs this script with
+ * `om_mod: "deliver"` (always the full layer, held to
+ * `eager_layer_instruction_budget_bytes` rather than the hook-output cap) and
+ * flags the event it passes down with `om_mod: "standdown"`, on which this
+ * hook exits before any output or side effect. Without the mod, nothing
+ * sends the flag.
*/
import {
@@ -47,6 +55,10 @@ import {
applyInjectionBudget,
effectiveInjectionBudget,
parseInjectionBudget,
+ parseInstructionBudget,
+ DEFAULT_INSTRUCTION_BUDGET_BYTES,
+ METER_HEADROOM,
+ type InjectionBudget,
parseListingCollapseThreshold,
shouldCollapseDir,
formatCollapsedDir,
@@ -65,7 +77,8 @@ import {
scanActiveHygiene,
} from "./lib/active-hygiene.ts";
-import { fitHookOutput, readStdinJson } from "./lib/hook-io.ts";
+import { fitWithMeter, HOOK_OUTPUT_LIMIT, type OutputLimit, readStdinJson } from "./lib/hook-io.ts";
+import { readOmMod } from "./lib/om-mod.ts";
import { resolveProjectDir } from "./lib/project-dir.ts";
type HookInput = { readonly source?: unknown };
@@ -95,7 +108,6 @@ async function readHookInput(): Promise<HookInput | null> {
return result;
}
const hookInput = await readHookInput();
-const mode = injectionMode(hookInput?.source);
function readManifestRaw(): string | null {
try {
@@ -106,7 +118,6 @@ function readManifestRaw(): string | null {
}
const cwd = resolveProjectDir(process.cwd());
-process.chdir(cwd);
// Persist vault path for any downstream shell consumers (Claude Code feature).
// The whole line comes from formatEnvExport so quoting is not a step anyone
@@ -122,6 +133,21 @@ if (envFile) {
}
}
+// A Claude Code mod that delivers this layer itself flags the event it
+// passes down (lib/om-mod.ts): stand down before every other side effect,
+// since the mod's own run of this script performs them. The export above is
+// the exception: Claude Code gives CLAUDE_ENV_FILE to hook processes only, so
+// the mod's run never sees it and this run is the only one that can write it.
+// `deliver` is the mod's run: the output becomes an instruction file, which
+// compaction keeps whole, so it is always the full layer and is not held
+// under the hook-output cap.
+const omMod = readOmMod(hookInput);
+if (omMod === "standdown") process.exit(0);
+const delivering = omMod === "deliver";
+const mode = delivering ? "full" : injectionMode(hookInput?.source);
+
+process.chdir(cwd);
+
// Manifest is read once and reused: QMD's named index, the infrastructure
// allowlist for openTasks(), and any future manifest-driven sections all
// derive from the same source. Both helpers tolerate a null source so a
@@ -619,18 +645,30 @@ if (hygieneLines.length > 0) {
// The eager layer is held under a byte budget, and the budget under Claude
// Code's hook output cap: past the cap the session gets a 2,000-character
// preview, so a larger budget never binds (#254). An unset or larger
-// manifest value is clamped, and the meter says so. fitHookOutput is the
-// backstop for the sections that never degrade.
-const budget = effectiveInjectionBudget(parseInjectionBudget(manifestJson));
+// manifest value is clamped, and the meter says so. fitWithMeter is the
+// backstop for the sections that never degrade. Delivered by a mod as an
+// instruction file, the layer is under no hook cap: it gets its own budget,
+// and the backstop holds the whole file to that budget plus the meter's
+// headroom, in bytes, as the hook path holds its budget under the cap.
+const budget: InjectionBudget = delivering
+ ? { bytes: parseInstructionBudget(manifestJson) ?? DEFAULT_INSTRUCTION_BUDGET_BYTES }
+ : effectiveInjectionBudget(parseInjectionBudget(manifestJson));
const budgeted = applyInjectionBudget(sections, budget.bytes);
+const limit: OutputLimit = delivering
+ ? { max: budget.bytes + METER_HEADROOM, unit: "bytes", name: "the instruction budget" }
+ : HOOK_OUTPUT_LIMIT;
process.stdout.write(
- fitHookOutput(budgeted.text + "\n", (cut, bodyBytes) =>
- formatInjectionSize(bodyBytes, {
- budgetBytes: budget.bytes,
- collapsed: budgeted.collapsed,
- clampedFrom: budget.clampedFrom,
- cut,
- }),
+ fitWithMeter(
+ budgeted.text + "\n",
+ (cut, bodyBytes) =>
+ formatInjectionSize(bodyBytes, {
+ budgetBytes: budget.bytes,
+ collapsed: budgeted.collapsed,
+ clampedFrom: budget.clampedFrom,
+ cut,
+ cutTo: limit.name,
+ }),
+ limit,
),
);
diff --git a/.claude/scripts/stop-checklist.ts b/.claude/scripts/stop-checklist.ts
index 2fb7e3f..682c700 100644
--- a/.claude/scripts/stop-checklist.ts
+++ b/.claude/scripts/stop-checklist.ts
@@ -39,6 +39,12 @@
* (lib/hook-io.ts).
* The documented event name is the only branch — no agent sniffing and no
* agent-specific argument.
+ *
+ * Under the template's Claude Code mod (#264, lib/om-mod.ts) the mod presents
+ * the report itself: it runs this script with `om_mod: "report"` to get the
+ * report as data, and flags the Stop it passes down with
+ * `om_mod: "standdown"`, on which this hook writes the empty envelope and
+ * does nothing else. Without the mod, nothing sends the flag.
*/
import { readFileSync } from "node:fs";
@@ -48,11 +54,13 @@ import {
readStdinJson,
writeSilentHookOutput,
writeStopFeedback,
+ writeStopReportData,
writeSystemMessage,
} from "./lib/hook-io.ts";
+import { readOmMod } from "./lib/om-mod.ts";
import { triggerDebouncedRefresh } from "./lib/qmd-refresh.ts";
import { HANDOFF_DIR, pruneHandoffs, writeHandoff } from "./lib/stop-handoff.ts";
-import { AGENT_PREFACE, FEEDBACK_PREFACE, FEEDBACK_TRAILER, stopSummary } from "./lib/stop-report.ts";
+import { AGENT_PREFACE, FEEDBACK_PREFACE, FEEDBACK_TRAILER, MOD_PREFACE, stopSummary } from "./lib/stop-report.ts";
import {
formatActiveHygiene,
hygieneClaims,
@@ -87,12 +95,20 @@ type HookInput = {
};
const input = await readStdinJson<HookInput>();
+// The mod presents this Stop (lib/om-mod.ts): the empty envelope, no state,
+// no handoff, no refresh. The mod's own `report` run does the refresh.
+const omMod = readOmMod(input);
+if (omMod === "standdown") {
+ writeSilentHookOutput();
+ process.exit(0);
+}
// Re-entry (the Stop after a turn some Stop hook forced, or a secondary
// agent's): say nothing, which keeps a forced turn from looping, spawn no second refresh,
// but still emit the empty envelope rather than zero bytes — see
// writeSilentHookOutput for why "sometimes silent, sometimes JSON" is the
// weaker contract.
-if (input?.stop_hook_active === true) {
+// The mod's `report` run is not a re-entry: the mod decides when to ask.
+if (input?.stop_hook_active === true && omMod !== "report") {
writeSilentHookOutput();
process.exit(0);
}
@@ -152,13 +168,18 @@ const VOLATILE_FIELDS = new Set(["sizeKb", "ageDays", "oldestDays"]);
const sessionId = input?.session_id;
const isStop = input?.hook_event_name === "Stop";
const hasSession = typeof sessionId === "string" && sessionId !== "";
-const show =
- !isStop || !hasSession || claimChanged(STATE_PATH, sessionId, reportKey({ checklist, report }, VOLATILE_FIELDS));
+const key = reportKey({ checklist, report }, VOLATILE_FIELDS);
+const claims = hygieneClaims(report);
-if (!show) writeSilentHookOutput();
+if (omMod === "report") {
+ // The mod's own run (lib/om-mod.ts): the report as data. The mod draws the
+ // line, hands the agent the report and decides when it changed, so no
+ // state is claimed and nothing is handed over here. `key` is the report's
+ // identity, the same one the Stop dedupe below compares.
+ writeStopReportData({ key, claims, agentText: `${MOD_PREFACE}\n\n${message}` });
+} else if (isStop && hasSession && !claimChanged(STATE_PATH, sessionId, key)) writeSilentHookOutput();
else if (isStop && hasSession) {
// The summary now, the full report with the next prompt; Stop feedback if it cannot be saved.
- const claims = hygieneClaims(report);
try {
pruneHandoffs(HANDOFF_DIR, Date.now());
writeHandoff(HANDOFF_DIR, sessionId, `${AGENT_PREFACE}\n\n${message}`);
diff --git a/.claude/scripts/tests/hook-io.test.ts b/.claude/scripts/tests/hook-io.test.ts
index 324e6c9..d0d053d 100644
--- a/.claude/scripts/tests/hook-io.test.ts
+++ b/.claude/scripts/tests/hook-io.test.ts
@@ -193,3 +193,42 @@ describe("writeHookOutput — additionalContext fits the hook output cap (#254)"
assert.equal(out, '{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"hello"}}');
});
});
+
+describe("writeStopReportData", () => {
+ test("a report too large for one pipe write arrives whole", async () => {
+ const { spawnSync } = await import("node:child_process");
+ const lib = new URL("../lib/hook-io.ts", import.meta.url).href;
+ const agentText = "x".repeat(2_000_000);
+ const script = `import { writeStopReportData } from ${JSON.stringify(lib)}; writeStopReportData({ key: "k", claims: ["c"], agentText: "x".repeat(${agentText.length}) });`;
+ const run = spawnSync(process.execPath, ["--disable-warning=ExperimentalWarning", "--experimental-strip-types", "--input-type=module", "-e", script], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
+ assert.equal(run.status, 0, run.stderr);
+ const parsed = JSON.parse(run.stdout) as { report: { agentText: string } };
+ assert.equal(parsed.report.agentText.length, agentText.length);
+ });
+});
+
+describe("writeStopReportData on a pipe that writes in parts", () => {
+ test("short writes and a full pipe still deliver every byte, in order", async () => {
+ const { writeStopReportData } = await import("../lib/hook-io.ts");
+ const out: Buffer[] = [];
+ let calls = 0;
+ const write = (buffer: Buffer, offset: number, length: number): number => {
+ calls++;
+ if (calls === 2) throw Object.assign(new Error("full"), { code: "EAGAIN" });
+ const n = Math.min(length, 7);
+ out.push(buffer.subarray(offset, offset + n));
+ return n;
+ };
+ writeStopReportData({ key: "k", claims: ["a claim"], agentText: "the full report, longer than one short write" }, write);
+ const parsed = JSON.parse(Buffer.concat(out).toString("utf8")) as { report: { agentText: string } };
+ assert.equal(parsed.report.agentText, "the full report, longer than one short write");
+ });
+
+ test("any failure but a full pipe throws, so the mod falls back", async () => {
+ const { writeStopReportData } = await import("../lib/hook-io.ts");
+ const write = (): number => {
+ throw Object.assign(new Error("closed"), { code: "EPIPE" });
+ };
+ assert.throws(() => writeStopReportData({ key: "k", claims: [], agentText: "t" }, write), /closed/);
+ });
+});
diff --git a/.claude/scripts/tests/om-mod.test.ts b/.claude/scripts/tests/om-mod.test.ts
new file mode 100644
index 0000000..1edb7d9
--- /dev/null
+++ b/.claude/scripts/tests/om-mod.test.ts
@@ -0,0 +1,33 @@
+/**
+ * readOmMod reads the instruction a Claude Code mod passes on a hook's event
+ * (#264). Anything it does not recognise must read as "no instruction", so a
+ * typo or a newer mod degrades to the hook's normal behaviour, never to
+ * silence.
+ */
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { readOmMod } from "../lib/om-mod.ts";
+
+describe("readOmMod", () => {
+ test("each known mode is read back", () => {
+ assert.equal(readOmMod({ om_mod: "standdown" }), "standdown");
+ assert.equal(readOmMod({ om_mod: "deliver" }), "deliver");
+ assert.equal(readOmMod({ om_mod: "report" }), "report");
+ });
+
+ test("an event without the field is no instruction", () => {
+ assert.equal(readOmMod({ hook_event_name: "Stop", session_id: "s" }), null);
+ });
+
+ test("an unknown or mistyped value is no instruction", () => {
+ for (const value of ["Standdown", "stand-down", "", "silence", 1, true, null, ["standdown"], { mode: "standdown" }]) {
+ assert.equal(readOmMod({ om_mod: value }), null, `om_mod: ${JSON.stringify(value)}`);
+ }
+ });
+
+ test("input that is not an object is no instruction", () => {
+ for (const input of [null, undefined, "standdown", 0, []]) {
+ assert.equal(readOmMod(input), null, `input: ${JSON.stringify(input)}`);
+ }
+ });
+});
diff --git a/.claude/scripts/tests/session-start.integration.test.ts b/.claude/scripts/tests/session-start.integration.test.ts
index 6167cdf..4fdc76c 100644
--- a/.claude/scripts/tests/session-start.integration.test.ts
+++ b/.claude/scripts/tests/session-start.integration.test.ts
@@ -29,11 +29,13 @@ import { dirname, join, resolve } from "node:path";
import {
mkdtempSync,
mkdirSync,
+ readFileSync,
rmSync,
writeFileSync,
} 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";
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
@@ -312,29 +314,35 @@ describe("session-start — listing collapse and injection budget", () => {
* session gets a file path and the first 2,000 characters (#254). The output
* must fit whole, with the meter as its last line, whatever the vault holds.
*/
+const lastLine = (stdout: string) => stdout.split("\n").filter((l) => l.trim() !== "").pop() ?? "";
+
+/**
+ * ~250 nested notes: the shape that reproduced #254. Nested project folders,
+ * each under the listing-collapse threshold, so nothing folds by count and
+ * the listing alone passes the hook cap.
+ */
+function nestedVault(manifest: Record<string, unknown> = {}): string {
+ const dir = mkdtempSync(join(tmpdir(), "session-start-nested-"));
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ writeFileSync(join(dir, "brain", "North Star.md"), "---\ndescription: test\n---\n\n# North Star\n\n- placeholder\n");
+ for (let p = 0; p < 12; p++) {
+ for (const sub of ["notes", "decisions"]) {
+ mkdirSync(join(dir, "projects", `project-${p}`, sub), { recursive: true });
+ for (let i = 0; i < 10; i++) {
+ writeFileSync(join(dir, "projects", `project-${p}`, sub, `Example project-${p} ${sub} note ${i}.md`), "---\ndescription: x\n---\n");
+ }
+ }
+ }
+ writeFileSync(join(dir, "vault-manifest.json"), JSON.stringify(manifest));
+ return dir;
+}
+
describe("session-start — the hook output cap", () => {
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", () => {
- // The shape that reproduced #254: nested project folders, each under
- // the listing-collapse threshold, so nothing folds by count.
- const dir = mkdtempSync(join(tmpdir(), "session-start-cap-"));
+ const dir = nestedVault({ eager_layer_budget_bytes: 80_000 });
try {
- mkdirSync(join(dir, "brain"), { recursive: true });
- writeFileSync(join(dir, "brain", "North Star.md"), "---\ndescription: test\n---\n\n# North Star\n\n- placeholder\n");
- for (let p = 0; p < 12; p++) {
- for (const sub of ["notes", "decisions"]) {
- mkdirSync(join(dir, "projects", `project-${p}`, sub), { recursive: true });
- for (let i = 0; i < 10; i++) {
- writeFileSync(
- join(dir, "projects", `project-${p}`, sub, `Example project-${p} ${sub} note ${i}.md`),
- "---\ndescription: x\n---\n",
- );
- }
- }
- }
- writeFileSync(join(dir, "vault-manifest.json"), JSON.stringify({ eager_layer_budget_bytes: 80_000 }));
const { stdout, code, stderr } = spawnHook(SCRIPT, "", { CLAUDE_PROJECT_DIR: dir });
assert.equal(code, 0);
assert.equal(stderr, "");
@@ -363,4 +371,114 @@ describe("session-start — the hook output cap", () => {
rmTemp(dir);
}
});
+
+ test("deliver holds sections that never degrade to its own budget, in bytes: cut, and the meter says so", () => {
+ // Three bytes per character, so the output is under the budget in
+ // characters and over it in bytes: a character count would pass it.
+ const dir = mkdtempSync(join(tmpdir(), "session-start-deliver-cut-"));
+ try {
+ writeFileSync(join(dir, "vault-manifest.json"), JSON.stringify({ eager_layer_instruction_budget_bytes: 12_000 }));
+ const tasks = Array.from({ length: 10 }, (_, i) => `- [ ] task ${i} ${"界".repeat(500)}`).join("\n");
+ writeFileSync(join(dir, "Tasks.md"), `# Tasks\n\n${tasks}\n`);
+ const { stdout, code, stderr } = spawnHook(SCRIPT, { source: "startup", om_mod: "deliver" }, { CLAUDE_PROJECT_DIR: dir });
+ assert.equal(code, 0);
+ assert.equal(stderr, "");
+ assert.ok(stdout.includes("task 0 "), "the fixture's tasks reached the output");
+ const bytes = Buffer.byteLength(stdout, "utf-8");
+ assert.ok(bytes <= 12_000 + METER_HEADROOM, `stdout is ${bytes} bytes`);
+ // Cut on a line boundary, so up to one task line (about 1.5 KB) short of the limit.
+ assert.ok(bytes > 12_000 + METER_HEADROOM - 1_600, `the budget was used, not undercut: ${bytes} bytes`);
+ assert.ok(!stdout.includes("\uFFFD"), "no character was split");
+ assert.ok(stdout.includes("… (truncated to fit the instruction budget)"), "the cut is marked where it happened");
+ assert.match(lastLine(stdout), /^_context injected: .* \/ 12\.0kB budget( — collapsed: .*)? — truncated to fit the instruction budget_$/);
+ } finally {
+ rmTemp(dir);
+ }
+ });
+});
+
+/**
+ * A Claude Code mod that delivers the eager layer itself passes `om_mod` on
+ * the event (#264, lib/om-mod.ts). `standdown` must leave no trace at all;
+ * `deliver` is the mod's own run, whose output becomes an instruction file:
+ * always the full layer, held to its own budget, never cut to the hook cap.
+ */
+describe("session-start — om_mod (a Claude Code mod)", () => {
+ test("standdown prints nothing, yet still exports VAULT_PATH: only a hook process gets CLAUDE_ENV_FILE", () => {
+ const envFile = join(TMP_DIR, "env-standdown.sh");
+ writeFileSync(envFile, "");
+ const { stdout, stderr, code } = spawnHook(SCRIPT, { source: "startup", om_mod: "standdown" }, { CLAUDE_PROJECT_DIR: TMP_DIR, CLAUDE_ENV_FILE: envFile });
+ assert.equal(code, 0);
+ assert.equal(stderr, "");
+ assert.equal(stdout, "", "the mod delivers this event; the hook must add nothing");
+ assert.match(readFileSync(envFile, "utf-8"), /VAULT_PATH/, "the mod's run cannot write the env file, so this run must");
+ });
+
+ 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 });
+ assert.ok(stdout.includes("### Date"));
+ assert.match(readFileSync(envFile, "utf-8"), /VAULT_PATH/);
+ });
+
+ test("deliver is not cut to the hook-output cap: the layer arrives whole, against its own budget", () => {
+ // Different values, so reading the wrong field cannot pass.
+ const dir = nestedVault({ eager_layer_budget_bytes: 9_000, eager_layer_instruction_budget_bytes: 80_000 });
+ try {
+ const delivered = spawnHook(SCRIPT, { source: "startup", om_mod: "deliver" }, { CLAUDE_PROJECT_DIR: dir });
+ assert.equal(delivered.code, 0);
+ assert.equal(delivered.stderr, "");
+ assert.ok(delivered.stdout.length > HOOK_OUTPUT_MAX_CHARS, `delivered ${delivered.stdout.length} characters`);
+ assert.match(lastLine(delivered.stdout), /^_context injected: \d+\.\dkB \/ 80\.0kB budget_$/, "nothing collapsed, nothing clamped, meter last");
+ 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);
+ assert.match(lastLine(hooked.stdout), /collapsed: Vault File Listing/);
+ } finally {
+ rmTemp(dir);
+ }
+ });
+
+ test("deliver without a configured instruction budget uses the default", () => {
+ const dir = nestedVault();
+ try {
+ const { stdout } = spawnHook(SCRIPT, { source: "startup", om_mod: "deliver" }, { CLAUDE_PROJECT_DIR: dir });
+ assert.match(lastLine(stdout), /\/ 20\.0kB budget/);
+ } finally {
+ rmTemp(dir);
+ }
+ });
+
+ test("deliver is the full layer even on compact: an instruction file has no pointer mode", () => {
+ 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;
+ 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 });
+ assert.equal(unknown.code, 0);
+ assert.equal(unknown.stdout, plain.stdout);
+ assert.ok(plain.stdout.includes("### Date"));
+ });
+
+ test("standdown exits before every other side effect: it never reaches the project directory", () => {
+ // Every side effect but the VAULT_PATH export (the QMD preflight and
+ // spawn, the scans) comes after the chdir into the project directory. A
+ // missing directory makes that chdir throw, so only a run that left
+ // before it exits clean.
+ const missing = join(TMP_DIR, "no-such-vault");
+ const plain = spawnHook(SCRIPT, { source: "startup" }, { CLAUDE_PROJECT_DIR: missing });
+ assert.notEqual(plain.code, 0, "without the flag the run reaches the chdir and fails");
+ const stood = spawnHook(SCRIPT, { source: "startup", om_mod: "standdown" }, { CLAUDE_PROJECT_DIR: missing });
+ assert.equal(stood.code, 0);
+ assert.equal(stood.stdout, "");
+ assert.equal(stood.stderr, "");
+ });
});
diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.ts
index 3752106..31b4a4f 100644
--- a/.claude/scripts/tests/session-start.test.ts
+++ b/.claude/scripts/tests/session-start.test.ts
@@ -23,6 +23,8 @@ import {
shouldCollapseDir,
formatCollapsedDir,
parseInjectionBudget,
+ parseInstructionBudget,
+ DEFAULT_INSTRUCTION_BUDGET_BYTES,
effectiveInjectionBudget,
INJECTION_CEILING_BYTES,
parseListingCollapseThreshold,
@@ -49,7 +51,8 @@ import {
collectOpenTasks,
} from "../lib/session-start.ts";
-import { CUT_LINE, fitHookOutput, HOOK_OUTPUT_MAX_CHARS } from "../lib/hook-io.ts";
+import { cutLine, 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";
describe("take", () => {
@@ -1167,6 +1170,25 @@ describe("manifest budget fields", () => {
assert.equal(parseListingCollapseThreshold('{"eager_layer_budget_bytes":25}'), null);
});
+ test("parseInstructionBudget reads its own field, with the same validation", () => {
+ assert.equal(parseInstructionBudget('{"eager_layer_instruction_budget_bytes":40000}'), 40_000);
+ assert.equal(parseInstructionBudget('{"eager_layer_budget_bytes":40000}'), null);
+ assert.equal(parseInstructionBudget('{"eager_layer_instruction_budget_bytes":0}'), null);
+ assert.equal(parseInstructionBudget('{"eager_layer_instruction_budget_bytes":"40000"}'), null);
+ assert.equal(parseInstructionBudget(null), null);
+ });
+
+ test("the instruction-file default is above the hook-output ceiling, or delivering would gain nothing", () => {
+ assert.ok(DEFAULT_INSTRUCTION_BUDGET_BYTES > INJECTION_CEILING_BYTES);
+ });
+
+ test("the shipped manifest states the same instruction budget the code falls back to", () => {
+ // The manifest shows users the key; the constant covers a vault whose
+ // manifest omits it. They are one default, so they must not drift apart.
+ const manifest = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../../../vault-manifest.json"), "utf-8");
+ assert.equal(parseInstructionBudget(manifest), DEFAULT_INSTRUCTION_BUDGET_BYTES);
+ });
+
test("the shipped default threshold is a positive integer", () => {
assert.ok(Number.isInteger(DEFAULT_LISTING_COLLAPSE_THRESHOLD));
assert.ok(DEFAULT_LISTING_COLLAPSE_THRESHOLD > 0);
@@ -1232,16 +1254,17 @@ describe("the injection budget under the hook output cap (#254)", () => {
});
});
-describe("fitHookOutput", () => {
+describe("fitWithMeter", () => {
+ const chars = (max: number): OutputLimit => ({ ...HOOK_OUTPUT_LIMIT, max });
const meter = (cut: boolean, bytes: number) => `_meter ${bytes}${cut ? " cut" : ""}_`;
test("output under the cap is the body and the meter, unchanged", () => {
- assert.equal(fitHookOutput("a\nb\n", meter, 100), "a\nb\n\n_meter 4_\n");
+ assert.equal(fitWithMeter("a\nb\n", meter, chars(100)), "a\nb\n\n_meter 4_\n");
});
test("output over the cap is cut on a line, marked, and closed by the meter", () => {
const body = Array.from({ length: 200 }, (_, i) => `line ${i}`).join("\n") + "\n";
- const out = fitHookOutput(body, meter, 500);
+ const out = fitWithMeter(body, meter, chars(500));
assert.ok(out.length <= 500, `output is ${out.length} characters`);
assert.ok(out.includes(`\n${CUT_LINE}\n`), "the cut is marked");
const lines = out.split("\n");
@@ -1254,12 +1277,12 @@ describe("fitHookOutput", () => {
// Every position is a line boundary, so the kept prefix is the longest
// the arithmetic allows; an off-by-one either way moves this length.
// A fixed-width meter, so a size with fewer digits cannot move it too.
- const out = fitHookOutput("\n".repeat(2_000), (cut) => (cut ? "_m cut_" : "_m_"), 500);
+ const out = fitWithMeter("\n".repeat(2_000), (cut) => (cut ? "_m cut_" : "_m_"), chars(500));
assert.equal(out.length, 499);
});
test("a body with no line to cut on keeps the partial line, filling the cap exactly", () => {
- const out = fitHookOutput("x".repeat(2_000), (cut) => (cut ? "_m cut_" : "_m_"), 500);
+ const out = fitWithMeter("x".repeat(2_000), (cut) => (cut ? "_m cut_" : "_m_"), chars(500));
assert.equal(out.length, 500);
assert.ok(out.startsWith("x".repeat(100)), "the partial line is kept, not dropped");
});
@@ -1267,7 +1290,7 @@ describe("fitHookOutput", () => {
test("a partial line never ends in half of a surrogate pair", () => {
// Each emoji is two UTF-16 units; one of the two parities lands mid-pair.
for (const cap of [500, 501]) {
- const out = fitHookOutput("😀".repeat(1_000), (cut) => (cut ? "_m cut_" : "_m_"), cap);
+ const out = fitWithMeter("😀".repeat(1_000), (cut) => (cut ? "_m cut_" : "_m_"), chars(cap));
assert.ok(out.length <= cap);
assert.doesNotThrow(() => encodeURIComponent(out), `a lone surrogate at cap ${cap}`);
}
@@ -1275,23 +1298,46 @@ 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);
+ const out = fitWithMeter("x".repeat(2_000), () => "😀".repeat(600), chars(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);
+ const out = fitWithMeter("a\nb\n", () => "m".repeat(600), chars(500));
assert.ok(out.length <= 500, `output is ${out.length} characters`);
});
test("the meter reports the size of what was kept, not of the whole body", () => {
const body = "x\n".repeat(1_000);
- const out = fitHookOutput(body, meter, 300);
+ const 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$`));
});
+
+ test("a byte limit is measured in UTF-8 bytes, cuts on a line, and never splits a character", () => {
+ const limit: OutputLimit = { max: 500, unit: "bytes", name: "a test budget" };
+ // Three bytes per character: 400 characters fit a character cap of 500, not this one.
+ const body = Array.from({ length: 40 }, () => "界".repeat(10)).join("\n") + "\n";
+ const out = fitWithMeter(body, meter, limit);
+ assert.ok(Buffer.byteLength(out, "utf-8") <= 500, `output is ${Buffer.byteLength(out, "utf-8")} bytes`);
+ assert.ok(out.includes(`\n${cutLine(limit)}\n`), "the cut is marked with the limit's name");
+ const lines = out.split("\n");
+ for (const l of lines.slice(0, lines.indexOf(cutLine(limit)))) assert.equal(l, "界".repeat(10));
+ });
+
+ test("a byte limit with no line to cut on keeps whole characters only", () => {
+ for (const max of [500, 501, 502]) {
+ const out = fitWithMeter("界".repeat(1_000), (cut) => (cut ? "_m cut_" : "_m_"), { max, unit: "bytes", name: "a test budget" });
+ assert.ok(Buffer.byteLength(out, "utf-8") <= max);
+ assert.ok(!out.includes("\uFFFD"), `a split character at ${max}`);
+ }
+ });
+
+ test("the hook limit's cut line is the one fitEncoded uses", () => {
+ assert.ok(fitEncoded("x".repeat(100), 60).endsWith(`\n${CUT_LINE}`));
+ });
});
describe("the eager layer end to end under the cap (#254)", () => {
@@ -1306,7 +1352,7 @@ describe("the eager layer end to end under the cap (#254)", () => {
];
const budget = effectiveInjectionBudget(80_000);
const budgeted = applyInjectionBudget(sections, budget.bytes);
- const out = fitHookOutput(budgeted.text + "\n", (cut, bytes) =>
+ const out = fitWithMeter(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`);
@@ -1324,7 +1370,7 @@ describe("the eager layer end to end under the cap (#254)", () => {
];
const budget = effectiveInjectionBudget(null);
const budgeted = applyInjectionBudget(sections, budget.bytes);
- const out = fitHookOutput(budgeted.text + "\n", (cut, bytes) =>
+ const out = fitWithMeter(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`);
diff --git a/.claude/scripts/tests/stop-checklist.test.ts b/.claude/scripts/tests/stop-checklist.test.ts
index 85d00dc..809b639 100644
--- a/.claude/scripts/tests/stop-checklist.test.ts
+++ b/.claude/scripts/tests/stop-checklist.test.ts
@@ -20,11 +20,11 @@
* substring that appears inside the JSON either way.
*/
-import { test, describe, before, after } from "node:test";
+import { test, describe, before, after, beforeEach } from "node:test";
import assert from "node:assert/strict";
import { HOOK_OUTPUT_MAX_CHARS } from "../lib/hook-io.ts";
import { takeHandoff } from "../lib/stop-handoff.ts";
-import { AGENT_PREFACE, FEEDBACK_PREFACE, FEEDBACK_TRAILER, SUMMARY_TRAILER } from "../lib/stop-report.ts";
+import { AGENT_PREFACE, FEEDBACK_PREFACE, FEEDBACK_TRAILER, MOD_PREFACE, SUMMARY_TRAILER } from "../lib/stop-report.ts";
import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
@@ -77,7 +77,13 @@ function freshState(): string {
*/
function run(
stdin: string | object | null,
- opts: { readonly state?: string; readonly vault?: string; readonly handoffDir?: string; readonly keep?: boolean } = {},
+ opts: {
+ readonly state?: string;
+ readonly vault?: string;
+ readonly handoffDir?: string;
+ readonly keep?: boolean;
+ readonly env?: Readonly<Record<string, string>>;
+ } = {},
) {
handoffCounter += 1;
const handoffDir = opts.handoffDir ?? join(TMP_DIR, `handoff-${handoffCounter}`);
@@ -86,6 +92,7 @@ function run(
STOP_CHECKLIST_STATE: opts.state ?? freshState(),
STOP_HANDOFF_DIR: handoffDir,
...(opts.vault ? { CLAUDE_PROJECT_DIR: opts.vault } : {}),
+ ...opts.env,
});
// What the agent receives: the report Stop saved for the next prompt.
const sid = typeof stdin === "object" && stdin !== null ? (stdin as { session_id?: unknown }).session_id : undefined;
@@ -486,3 +493,86 @@ describe("stop-checklist", () => {
);
});
});
+
+/**
+ * Under the template's Claude Code mod (#264, lib/om-mod.ts) the mod presents
+ * the Stop report. `standdown` on the Stop it passes down must leave no trace;
+ * `report` is the mod's own run and returns the report as data, claiming no
+ * state and handing nothing over, because the mod owns both.
+ */
+describe("stop-checklist — om_mod (a Claude Code mod)", () => {
+ const flagged = (session_id: string, om_mod: string) => ({ ...stop(session_id), om_mod });
+ // The shared sentinel is fresh, so every refresh this file triggers is
+ // debounced: nothing is spawned, and with HOOK_DEBUG=1 the call still
+ // shows on stderr. That makes "was the refresh triggered?" observable.
+ const DEBUG = { HOOK_DEBUG: "1" };
+ const refreshed = (stderr: string) => stderr.includes("stop-checklist: debounced");
+ // Re-touch the shared sentinel before each test: it was written once in
+ // before(), and on a slow runner the tests above can outlast the 30s
+ // debounce window, which would turn "debounced" into a real spawn.
+ beforeEach(() => writeFileSync(SENTINEL, ""));
+
+ test("standdown writes the empty envelope and touches no state, no handoff, no refresh", () => {
+ const root = vault("ommod-standdown", "Done.md");
+ const state = freshState();
+ const dir = join(TMP_DIR, "handoff-ommod-standdown");
+ const result = run(flagged("s-standdown", "standdown"), { vault: root, state, handoffDir: dir, keep: true, env: DEBUG });
+ assert.equal(result.code, 0);
+ assert.equal(result.stdout, "{}");
+ assert.equal(existsSync(state), false, "no dedupe state claimed");
+ assert.equal(existsSync(dir), false, "no report saved for the next prompt");
+ assert.equal(refreshed(result.stderr), false, "the mod's report run does the refresh");
+ });
+
+ test("the same Stop without the flag does claim state, hand the report over and refresh (the checks above can fail)", () => {
+ const root = vault("ommod-plain", "Done.md");
+ const state = freshState();
+ const result = run(stop("s-plain"), { vault: root, state, env: DEBUG });
+ assert.equal(existsSync(state), true);
+ assert.ok(result.handed?.includes("work/active/Done.md"));
+ assert.equal(refreshed(result.stderr), true);
+ });
+
+ test("report returns the report as data, refreshes, and claims no state and hands nothing over", () => {
+ const root = vault("ommod-report", "Done.md");
+ const state = freshState();
+ const dir = join(TMP_DIR, "handoff-ommod-report");
+ const result = run(flagged("s-report", "report"), { vault: root, state, handoffDir: dir, keep: true, env: DEBUG });
+ assert.equal(result.code, 0);
+ const { report } = envelopeOf(result.stdout) as { report: { key: string; claims: string[]; agentText: string } };
+ assert.deepEqual(Object.keys(report).sort(), ["agentText", "claims", "key"], "data only: the mod draws its own line");
+ assert.match(report.key, /^[0-9a-f]{16,}$/);
+ assert.ok(report.claims.length > 0, "the drift is a claim");
+ assert.ok(report.agentText.startsWith(`${MOD_PREFACE}\n\n`), "the mod's report carries the mod's framing, not the settings hook's");
+ assert.match(report.agentText, /work\/active\/Done\.md/);
+ assert.equal(existsSync(state), false, "the mod decides when the report changed");
+ assert.equal(existsSync(dir), false, "the mod hands the report over");
+ assert.equal(refreshed(result.stderr), true, "the mod's run replaces the hook's, refresh included");
+ });
+
+ test("report answers even on a re-entry event: the mod decides when to ask", () => {
+ const root = vault("ommod-reentry", "Done.md");
+ const result = run({ ...flagged("s-reentry", "report"), stop_hook_active: true }, { vault: root });
+ const envelope = envelopeOf(result.stdout) as { report?: { agentText: string } };
+ assert.ok(envelope.report, `expected a report, got ${result.stdout}`);
+ assert.match(envelope.report.agentText, /work\/active\/Done\.md/);
+ });
+
+ test("report's key is the report's identity: stable for the same findings, different when they change", () => {
+ const root = vault("ommod-key", "Done.md");
+ const keyOf = () => (envelopeOf(run(flagged("s-key", "report"), { vault: root }).stdout) as { report: { key: string } }).report.key;
+ const first = keyOf();
+ assert.equal(keyOf(), first);
+ completeNote(root, "Also Done.md");
+ assert.notEqual(keyOf(), first);
+ });
+
+ test("an unknown om_mod value changes nothing: output identical to a Stop with no flag", () => {
+ const root = vault("ommod-unknown", "Done.md");
+ const plain = run(stop("s-unknown"), { vault: root });
+ const unknown = run(flagged("s-unknown", "silence"), { vault: root });
+ assert.equal(unknown.stdout, plain.stdout);
+ assert.equal(unknown.handed, plain.handed);
+ assert.ok(plain.handed?.includes("work/active/Done.md"));
+ });
+});
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 402cb05..a457820 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -122,7 +122,7 @@ The hook scripts, subagent prompts, command definitions, and vault conventions a
| Which files are user content? | `user_content_roots[]`, `scaffold{}` |
| What frontmatter is required for each note type? | `frontmatter_required{}` |
| Which notes does the `om` server serve, and where do memories live? | `mcp_exposed_roots[]`, `mcp_never_expose[]`, `memory_root`, `mcp_inbox` |
-| How much context may the eager layer spend? | `eager_layer_budget_bytes`, `listing_collapse_threshold` |
+| How much context may the eager layer spend? | `eager_layer_budget_bytes` (as hook output, held under the 10,000-char hook cap), `eager_layer_instruction_budget_bytes` (when the mod delivers it as an instruction file), `listing_collapse_threshold` |
| Which model does a `reason` spawn run on? | `reason.model` — unset means the user's own CLI default |
The `qmd_index` field is the most load-bearing. **Five independent callers** read it, and they fail *silently* when they disagree — one writes to a store another never reads, which surfaces only as "0 documents" or as an empty search:
@@ -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. 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". The open-tasks scan is filesystem-only so the hook never spawns the Obsidian CLI — that subprocess flashes the Electron app on macOS when no instance is running (#83).
- **`UserPromptSubmit` classifies, it does not route.** It tags the prompt with hints like `ARCHITECTURE discussion` or `DECISION`; the agent decides where to file. Keeping the hook opinion-free means the routing logic lives in `CLAUDE.md`, which is editable per-user without touching scripts.
- **QMD refresh is shared, debounced, and detached.** Three hook entries fire the same refresh helper — `PostToolUse` (after `.md` writes), `PreCompact` (before transcript backup; writes tend to cluster before compaction), and `Stop` (after a response) — sharing one sentinel file so a burst of events produces at most one worker per debounce window. The actual indexing runs in `.claude/scripts/qmd-refresh-run.ts` as a detached, stdio-silent worker (`qmd update` → `qmd embed` → tail-chase `qmd update`), so the parent hook returns in milliseconds and nothing flows to the agent's context.
- **`PreCompact` also backs up the transcript.** In addition to kicking the QMD refresh, it copies the current session transcript out to `thinking/session-logs/` so long conversations remain recoverable after compaction.
@@ -1002,7 +1002,7 @@ The design makes these changes easy:
| Change which notes `om` serves | `vault-manifest.json` → `mcp_exposed_roots` / `mcp_never_expose`, or tag a note `private` |
| Move the memory store | Rename the folder in Obsidian — discovery finds it and `health` reports the drift; pin it with `memory_root` to be explicit |
| Add a new `om` tool | A declaration in `.claude/scripts/lib/mcp-tools.ts` + a case in `mcp-server.ts` — the description is what the model reads when deciding to call it |
-| Change what the eager layer may spend | `vault-manifest.json` → `eager_layer_budget_bytes`, `listing_collapse_threshold` |
+| Change what the eager layer may spend | `vault-manifest.json` → `eager_layer_budget_bytes` (hook path), `eager_layer_instruction_budget_bytes` (mod path), `listing_collapse_threshold` |
The design is hostile to these changes (on purpose):
diff --git a/vault-manifest.json b/vault-manifest.json
index 1260303..c7d6eb3 100644
--- a/vault-manifest.json
+++ b/vault-manifest.json
@@ -14,6 +14,7 @@
"what to watch"
],
"eager_layer_budget_bytes": 9100,
+ "eager_layer_instruction_budget_bytes": 20000,
"listing_collapse_threshold": 12,
"memory_root": "memories",
"mcp_exposed_roots": [],