Planning mode guidelines and context injection

Planning mode guidelines and context injection for Claude Code.
plan:review: reviews how an implementation diverged from its approved plan, dispatching a clean-context agent over the plan and the diff to surface drift and follow-upshooks/gate.ts: gates ExitPlanMode, denying an unchanged plan resubmission, a patch that keeps nearly every line of a plan the gate just denied, and a plan over 10k characters, re-arming while a rework stays over the threshold up to two fires per sessionmod/register.ts:references/guidelines.md to the first full plan-mode reminder of the main conversation, and again after a compaction. Every request made in plan mode carries that reminder, however plan mode was reached, so one hook covers a prompt, EnterPlanMode, and a mode toggle. Subagent reminders are skipped.references/delegation.md as tool-result context the first time a Write or Edit takes the plan file to half the gate's limit without a Delegation heading, once per plan file.Write or Edit that leaves the plan file over the gate's limit, so a draft is trimmed before it reaches ExitPlanMode. It keys on the plan file the reminder names, so a custom plansDirectory is covered.Write or Edit to the plan file named in the plan-mode reminder, shows its size as a share of the gate's limit in the status line once it reaches 90% (plan: 10.2k (102%), rounded down), counting string.length the way the gate does, and clears it when a plan is approved. hooks/gate.test.ts pins its limit to the gate's.mod-events it logs plan.inject and plan.delegation for each injection (ok: false when the reference could not be read), plan.count for each count, plan.crossed whenever the count moves over or back under the limit, and plan.present for each ExitPlanMode with its size and whether it went through.evals/gate/: mines every recorded presentation for hooks/replay.test.ts, which replays the corpus through the gate and fails on decisions that moved against a saved baselineThe PreToolUse gate hook keeps per-session state under /tmp/claude/<session_id>/ and runs three checks in order. It denies a resubmission whose text is unchanged from the last presentation. It denies a resubmission that keeps nearly every line of a presentation the gate itself denied and introduces at least one new one, which catches a denied plan patched past the gate, by a line swap or a plain append. A presentation the gate passed went to the user, so the next one answers their feedback and may grow by what they asked for. It denies a plan over 10k characters, the same limit the injected guidelines state, re-arming while a rework remains over the threshold, capped at two fires per session so a deny loop is impossible.
Every check denies, including the two that read as advice. A PreToolUse hook's permissionDecision: "ask" is inert on ExitPlanMode: the tool runs its own plan-approval prompt, and the harness drops the hook's permissionDecisionReason and systemMessage alike, so neither the user nor the transcript sees them. deny is the only decision that carries a reason back. Each denial is recoverable in one step, since the model reworks the plan and presents again, and the size check spends its marker on first use. hooks/fixtures/re-presents.json holds presentation sequences recorded from real sessions. gate.test.ts replays them one process per presentation and snapshots the permissionDecision alongside the rule, so a check that stops deciding surfaces as a changed snapshot rather than as silence.
A missing session id or a plan that is not a string fails open silently, since neither is a fault. Anything else, an unusable state directory or a crash mid-decision, prints to stderr and exits 1: the presentation still goes through, and the failure is visible rather than reading as a plan that passed every check.
Each denial reason states the fix directly: rework against the feedback or the denial, move detail to sidecar files, or split the plan.
plan:review reads the approved plan from the file Claude Code writes under ~/.claude/plans/ and injects into the session on plan exit. It dispatches a clean-context agent that diffs the plan against the branch's base (resolved from the open PR, not assumed to be main) using the rubric in skills/review/references/divergence.md.
bun test plugins/plan
bun scripts/mod-test.ts planmod/register.ts 197 lines1import type { On } from "claude-code";
2
3// The plan gate denies a plan whose `plan.length`, in UTF-16 code units, exceeds this.
4export const LIMIT = 10_000;
5const SHOWN_FROM = LIMIT * 0.9;
6
7function percent(chars: number): number {
8 return Math.floor((chars * 100) / LIMIT);
9}
10
11// Both figures round down so a plan under the limit never reads 10k or 100%.
12export function statusText(chars: number): string | undefined {
13 if (chars < SHOWN_FROM) return undefined;
14 return `${Math.floor(chars / 100) / 10}k (${percent(chars)}%)`;
15}
16
17export const SIDECAR_GUIDANCE =
18 "Move supporting detail into <plan>-<topic>.md files the plan links " +
19 "(<plan>-decisions.md is the common one), or split the work into smaller plans.";
20
21// Sent after every write that leaves the plan over the limit, so a draft is trimmed before
22// the gate denies it at ExitPlanMode.
23export function overText(chars: number): string {
24 return `This plan file is ${chars} characters, over the ${LIMIT}-character presentation limit. ${SIDECAR_GUIDANCE}`;
25}
26
27// A plan this large has slices worth delegating, so it gets the delegation guidance.
28export const DELEGATION_FROM = LIMIT / 2;
29const DELEGATION_HEADING = /^#{1,6}\s+Delegation\b/m;
30
31function basename(path: string): string {
32 return path.slice(path.lastIndexOf("/") + 1);
33}
34
35export function register(on: On): void {
36 let planFile: string | undefined;
37 let planning = false;
38 let shown = false;
39 let wasOver = false;
40 // Once per conversation: the guidelines stay in context until a compaction.
41 let injected = false;
42 let delegated = false;
43
44 on("session.start", ($, e, next) => {
45 void $.modEvents.emit({ mod: "plan", event: "session.start" });
46 return next(e);
47 });
48
49 // /clear and /resume start a new conversation without a session.start.
50 on("session.end", ($, e, next) => {
51 if (e.reason !== "clear" && e.reason !== "resume") return next(e);
52 planning = false;
53 planFile = undefined;
54 wasOver = false;
55 injected = false;
56 delegated = false;
57 if (shown) {
58 shown = false;
59 $.ui.status(undefined);
60 }
61 return next(e);
62 });
63
64 on("session.compact", async ($, e, next) => {
65 const result = await next(e);
66 if (e.agentId === undefined && result.skip === undefined) injected = false;
67 return result;
68 }).catch(($, e, next) => next(e));
69
70 // The plan-mode reminder names the session's plan file, so sidecars beside it don't count.
71 // Its full wording opens every planning session and follows every compaction, whichever
72 // way plan mode was reached, so the guidelines ride on the first one.
73 on("prompt.attachment", { type: "plan_mode" }, async ($, e, next) => {
74 if (e.agentId !== undefined) return next(e);
75 planning = true;
76 const path = e.detail?.planFilePath;
77 if (path !== undefined && path !== planFile) {
78 planFile = path;
79 wasOver = false;
80 delegated = false;
81 }
82 const result = await next(e);
83 if (injected || e.detail?.reminder !== "full" || result.text === null) return result;
84 injected = true;
85 let guidelines: string;
86 try {
87 guidelines = await $.fs.read(`${$.plugin.root}/references/guidelines.md`);
88 } catch {
89 void $.modEvents.emit({ mod: "plan", event: "inject", ok: false });
90 return result;
91 }
92 void $.modEvents.emit({ mod: "plan", event: "inject", ok: true });
93 return { text: `${result.text}\n\n${guidelines}` };
94 }).catch(($, e, next) => next(e));
95
96 // Plan mode can end without ExitPlanMode, as when the user cycles out of it.
97 on("prompt.attachment", { type: "plan_mode_exit" }, ($, e, next) => {
98 if (e.agentId !== undefined) return next(e);
99 planning = false;
100 if (shown) {
101 shown = false;
102 $.ui.status(undefined);
103 }
104 return next(e);
105 });
106
107 on("tool.call", { tool: ["Write", "Edit"] }, async ($, e, next) => {
108 const result = await next(e);
109 if (!planning || e.file_path !== planFile || result.deny !== undefined || result.isError)
110 return result;
111
112 let plan: string;
113 try {
114 plan = await $.fs.read(e.file_path);
115 } catch {
116 if (shown) {
117 shown = false;
118 $.ui.status(undefined);
119 }
120 return result;
121 }
122
123 const chars = plan.length;
124 const over = chars > LIMIT;
125 const file = basename(e.file_path);
126 const text = statusText(chars);
127 if (text !== undefined || shown) $.ui.status(text);
128 shown = text !== undefined;
129 await $.modEvents.emit({
130 mod: "plan",
131 event: "count",
132 detail: { file, chars, limit: LIMIT, over, tool: e.tool },
133 });
134 if (over !== wasOver) {
135 await $.modEvents.emit({
136 mod: "plan",
137 event: "crossed",
138 detail: { file, chars, limit: LIMIT, direction: over ? "over" : "under" },
139 });
140 }
141 wasOver = over;
142
143 const notes = over ? [overText(chars)] : [];
144 if (!delegated && chars >= DELEGATION_FROM && !DELEGATION_HEADING.test(plan)) {
145 delegated = true;
146 try {
147 notes.unshift(await $.fs.read(`${$.plugin.root}/references/delegation.md`));
148 await $.modEvents.emit({
149 mod: "plan",
150 event: "delegation",
151 ok: true,
152 detail: { file, chars },
153 });
154 } catch {
155 await $.modEvents.emit({
156 mod: "plan",
157 event: "delegation",
158 ok: false,
159 detail: { file, chars },
160 });
161 }
162 }
163 return notes.length === 0
164 ? result
165 : { ...result, context: [...(result.context ?? []), ...notes] };
166 }).catch(($, e, next) => next(e));
167
168 on("tool.call", { tool: "ExitPlanMode" }, async ($, e, next) => {
169 const result = await next(e);
170 const denied = result.deny !== undefined || result.isError === true;
171 if (!denied) planning = false;
172 if (!denied && shown) {
173 shown = false;
174 $.ui.status(undefined);
175 }
176 if (planFile === undefined) return result;
177
178 let chars: number;
179 try {
180 chars = (await $.fs.read(planFile)).length;
181 } catch {
182 if (shown) {
183 shown = false;
184 $.ui.status(undefined);
185 }
186 return result;
187 }
188 await $.modEvents.emit({
189 mod: "plan",
190 event: "present",
191 ok: !denied,
192 detail: { file: basename(planFile), chars, limit: LIMIT, over: chars > LIMIT },
193 });
194 return result;
195 }).catch(($, e, next) => next(e));
196}
197