Decision watch: judges each completed turn (turn.complete) with the session's own model login, logs the verdict, and shows a FLAG or UNKNOWN. Adds /dw. Never…

A mod. It runs the decision watch on each completed turn (turn.complete) with this session's own model login. It replaces the Stop hook row. It never blocks a turn. A FLAG or UNKNOWN verdict shows in the session as a toast. An ALLOW verdict shows nothing. Each config notice shows as its own toast, marked Decision watch notice:.
turn.complete), the mod finds the transcript from the session id, read on each turn, and the cwd. The lookup waits at most 0.5 s and runs in the background. A lookup that passes the limit, or an id that cannot be read, logs a SKIP line and judges nothing.agentId set) is skipped. A turn with isAborted set, or a reason other than answer, is skipped with a SKIP line. A turn with no transcript logs a SKIP line.hooks/decision_watch.py in your Claude config folder, in two steps.--emit-prompt runs the cheap path. It prints a prompt only when a model call is due.--model-text or --model-error gives the verdict.$.env.get reads have no timer.key for the evidence it judged. The mod gives it back to phase 2 as --key after the reply. Evidence that moved between the two steps reads UNKNOWN. A phase 1 with no key reads UNKNOWN.verdict and notices as separate JSON fields. The mod does not parse joined text.NOTICE line or lines before the END line, which holds the verdict only. A verdict that is neither FLAG nor UNKNOWN is logged as NOT SHOWN. A failed toast is logged as TOAST FAILED, with the text it failed to show.\uXXXX.shadow.log (the file name is kept) in the state folder decision-watch-shadow, inside the config folder.CLAUDE_CONFIG_DIR/hooks/decision_watch.py. With no CLAUDE_CONFIG_DIR, the mod uses USERPROFILE or HOME, then .claude./dw each have their own state folder: decision-watch-shadow and decision-watch-dw. Each holds its own "already judged" cache. A background verdict does not mute /dw.python3 or python on PATH that is not the Windows Store stub. It asks the finder for one name at a time, because which and where.exe exit 1 when any name is missing, and a Mac has no python. It keeps that path until the mod reloads, and looks again after a run with it is rejected, times out, or exits non-zero with the file gone.The command runs the same judgment on the latest turn. It shows the timings, the result and each notice. It never shows the prompt. Before the first judged turn, it finds the transcript from the session id.
The last line is "Stops seen: N". N counts the STOP seen lines now in the log. The log keeps 500 lines, so N is at most 500.
/dw has its own cache. Run on the same turn twice, the second run says "nothing to say".
$.model.complete stops at timeoutMs. The request field is not in the host's type, so the mod does not rely on it. Its own timer enforces the 50 s limit. The host call may keep running after the timer.$.process.run kills the child at timeoutMs. The mod's timer frees the slot, but it does not kill the child. A hung python may keep running.--emit-prompt, --model-text, and --model-error.claude -p call. This is a hole: a wrong flag from a caller runs the old path.decision-watch-mod-limits (limits of the mod).Refresh the installed ~/.claude/hooks/decision_watch.py first. Replace it with this repo's hooks/decision_watch.py. An old copy ignores --emit-prompt, so each turn runs claude -p.
/plugin install decision-watch --marketplace shivinate7/claude-settings, then restart the session./dw. Check that the last line counts the turn.node mods/decision-watch/decision-watch.test.mjs runs the tests (stdlib only).claude plugin validate mods/decision-watch checks the mod.claude --plugin-dir mods/decision-watch, then /dw.hooks/register.mjs 363 lines1// decision-watch: runs the decision watch on each completed turn (hooks/decision_watch.py) with the session's
2// own model login, and writes the verdict to a log. A FLAG or UNKNOWN verdict shows in the session
3// with $.ui.toast. An ALLOW verdict shows nothing. Each config notice shows as its own toast, marked
4// as a notice (decision decision-watch-mod-limits). It never blocks and never changes the turn result.
5//
6// turn.complete returns next(e) after at most SEEN_WAIT_MS (500 ms), for the "STOP seen" line. The lookup and
7// the judging run in the background, one judge at a time. A subagent turn (agentId set) is skipped,
8// and so is a turn with isAborted or a reason other than "answer" (a SKIP line is logged). The
9// app's sec-default mod reroutes every classic.* event past user mods, so a classic.Stop
10// handler never ran; turn.* events pass. The event carries no transcript path, so the judge
11// finds it the way /dw does (deriveStop), from the session id read on each turn.
12// /dw runs the same judgment on the latest turn and shows the result.
13//
14// The python script has two phases: --emit-prompt prints the prompt when a model call is due,
15// then --model-text or --model-error finishes the verdict. This mod makes the model call between.
16// Phase 1 prints a "key" for the evidence it judged. Phase 2 gets it back as --key after the reply,
17// so evidence that moved between the phases reads UNKNOWN, never a silent ALLOW. No key reads UNKNOWN.
18// The script prints `verdict` and `notices` apart, so the mod never parses joined text.
19// The log holds the verdict line, the notices and timings, never the prompt.
20//
21// The host reads on(...) and $.noun.method(...) from source, so they are spelled literally.
22
23let lastStop; // the last Stop-shaped input built from a main-loop turn, for /dw
24let busy = false; // true while a background judge runs
25let foundPy; // the python path pickPython found, kept for the module's life; cleared when a run with it is rejected
26
27// The prefix of every UNKNOWN this mod makes itself; python's own UNKNOWN text comes through as printed.
28const UNKNOWN = "Decision watch: UNKNOWN, ";
29// The mark on a config notice toast. It never matches a FLAG or UNKNOWN verdict.
30const NOTICE = "Decision watch notice: ";
31const NOTHING = "nothing to say (no protected change, no model call)";
32const msg = (err) => String((err && err.message) || err).slice(0, 300);
33// $.model.complete returns {isAnswered, text, usage}. Accept a plain string too.
34const textOf = (r) => (typeof r === "string" ? r : String((r && r.text) ?? ""));
35
36export function register(on) {
37 on("session.start", async ($, e, next) => {
38 await $.command.register({
39 name: "dw",
40 description: "Run the decision watch on the latest turn with this session's own model login",
41 });
42 return next(e);
43 });
44
45 on("command.run", { command: "dw" }, async ($, e) => {
46 const lines = [];
47 try {
48 let stop = lastStop;
49 if (!stop) {
50 const d = await deriveStop($);
51 if (!d.found) throw new Error("no turn seen yet and no transcript found for this session");
52 stop = d.stop;
53 }
54 lines.push(`stop input: session ${stop.session_id}`);
55 const out = await judge($, stop, "dw");
56 lines.push(...out.trace, `RESULT: ${out.result}`, ...out.notices.map((n) => `NOTICE: ${n}`));
57 } catch (err) {
58 lines.push(`RESULT: UNKNOWN (mod error): ${msg(err)}`);
59 }
60 lines.push(`Stops seen: ${await stopsSeen($)}`);
61 return { text: lines.join("\n") };
62 });
63
64 // Background judge. The lookup, the "STOP seen" line and the judge start run off the return path. The
65 // handler waits at most SEEN_WAIT_MS for that "STOP seen" line, then returns next(e). One judge at a time:
66 // a turn that finds one running logs "SKIP busy". A turn that is not judged logs a SKIP line.
67 on("turn.complete", async ($, e, next) => {
68 if (!e.agentId) {
69 const work = (async () => {
70 if (e.isAborted || e.reason !== "answer") {
71 void log($, `SKIP no full answer | reason ${e.reason}, isAborted ${e.isAborted}`);
72 return;
73 }
74 let d;
75 try {
76 d = await deadline(deriveStop($), LOOKUP_MS);
77 } catch (err) {
78 void log($, `SKIP no session | ${msg(err)}`);
79 return;
80 }
81 await log($, `STOP seen ${d.stop.session_id}`);
82 if (!d.found) {
83 void log($, `SKIP no transcript ${d.stop.session_id} | ${d.stop.transcript_path}`);
84 return;
85 }
86 lastStop = d.stop;
87 if (busy) {
88 void log($, `SKIP busy ${d.stop.session_id}`);
89 } else {
90 busy = true;
91 void shadow($, d.stop).finally(() => {
92 busy = false;
93 });
94 }
95 })().catch(() => {});
96 await within(work, SEEN_WAIT_MS);
97 }
98 return next(e);
99 });
100}
101
102async function configDir($) {
103 const given = await $.env.get("CLAUDE_CONFIG_DIR");
104 if (given) return given;
105 const home = (await $.env.get("USERPROFILE")) || (await $.env.get("HOME"));
106 return `${home}/.claude`;
107}
108
109// The one lookup for a turn's transcript, used by turn.complete and /dw: rebuild transcript_path from the
110// session id and cwd the way the app names it. found says whether the file is there.
111async function deriveStop($) {
112 // The id is read per turn, never kept: a /clear gives a new id with no session.start.
113 const id = await $.session.id();
114 const cwd = await $.session.cwd();
115 const path = `${await configDir($)}/projects/${cwd.replace(/[^A-Za-z0-9]/g, "-")}/${id}.jsonl`;
116 return {
117 stop: { session_id: id, transcript_path: path, cwd, hook_event_name: "Stop", stop_hook_active: false },
118 found: await $.fs.exists(path),
119 };
120}
121
122// First python on PATH that is not the WindowsApps Store stub (settings.json's launcher does the same).
123// One name per finder call: where.exe and which both exit 1 when any name is missing, and a Mac has no python.
124async function pickPython($) {
125 for (const finder of [["where.exe"], ["which", "-a"]]) {
126 for (const name of ["python3", "python"]) {
127 try {
128 const r = await deadline($.process.run([...finder, name], { timeoutMs: FIND_MS }), FIND_MS + 1000);
129 const hit = r.stdout.split(/\r?\n/).map((s) => s.trim()).find((s) => s && !/WindowsApps/i.test(s));
130 if (r.exitCode === 0 && hit) return hit;
131 } catch {
132 // try the next name or finder
133 }
134 }
135 }
136 throw new Error("no python on PATH other than the WindowsApps stub");
137}
138
139// ASCII-only JSON: python -I may read stdin in a legacy code page, so escape every non-ASCII character.
140const asciiJson = (v) => JSON.stringify(v).replace(/[\u0080-\uffff]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
141
142// The background judge and /dw each get their own state folder, so neither mutes the other's
143// "already judged" cache.
144const stateDir = (cfg, who) => `${cfg}/decision-watch-${who}`;
145
146async function dwRun($, stop, extra, who) {
147 const cfg = await configDir($);
148 const t0 = Date.now();
149 const spawn = (py) =>
150 // The mod's own timer frees the slot if the host does not stop the child. It does not kill the child.
151 deadline($.process.run([py, "-I", `${cfg}/hooks/decision_watch.py`, ...extra], {
152 stdin: asciiJson(stop),
153 env: { CLAUDE_CONFIG_DIR: stateDir(cfg, who), DW_REAL_CONFIG_DIR: cfg },
154 timeoutMs: PY_MS,
155 }), PY_MS + 1000);
156 let r;
157 if (foundPy) {
158 const tried = foundPy;
159 try {
160 r = await spawn(tried);
161 // A non-zero exit from a file that is gone is a failed start too (the shell reports a missing file that way).
162 // A failed exists check counts as gone. The async wrapper turns a synchronous throw into a rejection, so r is kept.
163 if (r.exitCode !== 0 && !(await (async () => $.fs.exists(tried))().catch(() => false)) && foundPy === tried) foundPy = undefined;
164 } catch (err) {
165 // A rejected run (failed start or timeout) drops the cached path, so the next run looks again. This run is
166 // not repeated: a hung python would hold the slot twice as long. A python that exits non-zero resolves and keeps it.
167 if (foundPy === tried) foundPy = undefined;
168 throw err;
169 }
170 } else {
171 const py = await pickPython($);
172 r = await spawn(py);
173 foundPy = py;
174 }
175 return { ...r, ms: Date.now() - t0 };
176}
177
178// Two phases. Every failure is UNKNOWN, never a pass: the python side prints the same
179// "Decision watch: UNKNOWN ..." text for a model error it is handed with --model-error.
180async function judge($, stop, who) {
181 const trace = [];
182 const p1 = await dwRun($, stop, ["--emit-prompt"], who);
183 trace.push(`phase 1 (python, cheap path): exit ${p1.exitCode}, ${p1.ms} ms`);
184 if (p1.exitCode !== 0) return unknown(trace, `decision_watch exited ${p1.exitCode}: ${p1.stderr.slice(0, 200)}`);
185 const raw = p1.stdout.trim();
186 if (raw === "") return { trace, result: NOTHING, shown: "", notices: [] };
187 let out;
188 try {
189 out = JSON.parse(raw);
190 } catch {
191 return unknown(trace, `phase 1 output was not JSON: ${raw.slice(0, 200)}`);
192 }
193 if (!out.needs_model) {
194 const { verdict, notices } = partsOf(out);
195 const result = verdict ? `message from the cheap path: ${verdict}` : notices.length ? NOTHING : `message from the cheap path: ${raw.slice(0, 300)}`;
196 return { trace, result, shown: verdict, notices };
197 }
198 if (typeof out.key !== "string" || out.key === "") {
199 return unknown(trace, "phase 1 printed no key, so the reply cannot be tied to the evidence judged (an old decision_watch.py?)");
200 }
201
202 trace.push(`model due: ${out.model}, prompt ${out.prompt.length} chars`);
203 let args;
204 let modelFailed = false;
205 const t0 = Date.now();
206 try {
207 // The host's timeoutMs is unproven, so the mod enforces the limit itself: the race rejects, phase 2
208 // gets --model-error, and the one-judge slot frees. A late reply is dropped.
209 const reply = await deadline($.model.complete({ model: out.model, prompt: out.prompt, maxTokens: 512, timeoutMs: MODEL_MS }), MODEL_MS);
210 const text = textOf(reply);
211 if (text === "") throw new Error(`the model reply carried no text${reply && reply.reason ? ` (${reply.reason})` : ""}`);
212 trace.push(`model call: OK ${Date.now() - t0} ms, reply ${text.length} chars`);
213 args = ["--model-text", text.slice(0, 4000)];
214 } catch (err) {
215 modelFailed = true;
216 trace.push(`model call: FAIL ${Date.now() - t0} ms`);
217 args = ["--model-error", `model call: ${msg(err)}`];
218 }
219 const p2 = await dwRun($, stop, [...args, "--key", out.key], who);
220 trace.push(`phase 2 (python, verdict): exit ${p2.exitCode}, ${p2.ms} ms`);
221 if (p2.exitCode !== 0) return unknown(trace, `decision_watch exited ${p2.exitCode} in phase 2: ${p2.stderr.slice(0, 200)}`);
222 let parts = { verdict: "", notices: [] };
223 try {
224 if (p2.stdout.trim() !== "") parts = partsOf(JSON.parse(p2.stdout));
225 } catch {
226 return unknown(trace, `phase 2 output was not JSON: ${p2.stdout.slice(0, 200)}`);
227 }
228 if (parts.verdict === "" && modelFailed) return unknown(trace, "the model call failed and the script printed no verdict", parts.notices);
229 return { trace, result: parts.verdict === "" ? "ALLOW (silent)" : parts.verdict, shown: parts.verdict, notices: parts.notices };
230}
231
232// The script prints `verdict` and `notices` under a split flag. Output with no `notices` array
233// (a script that prints systemMessage only) is all verdict.
234function partsOf(o) {
235 if (Array.isArray(o.notices)) {
236 return { verdict: typeof o.verdict === "string" ? o.verdict : "", notices: o.notices.filter((n) => typeof n === "string" && n) };
237 }
238 return { verdict: typeof o.systemMessage === "string" ? o.systemMessage : "", notices: [] };
239}
240
241// A failure the mod itself sees is UNKNOWN, and it shows like the script's own UNKNOWN.
242function unknown(trace, why, notices = []) {
243 return { trace, result: `UNKNOWN: ${why}`, shown: UNKNOWN + why, notices };
244}
245
246async function shadow($, stop) {
247 await log($, `START ${stop.session_id}`);
248 let line;
249 let shown = "";
250 let notices = [];
251 try {
252 const out = await judge($, stop, "shadow");
253 // Each notice goes on its own log lines, before END, so the END cut at MAX_LINE never drops one.
254 // A longer notice is split over several lines with the same prefix. The pieces, joined, give the notice with
255 // its whitespace folded. A cut never splits a surrogate pair, and no piece after the first starts with a space,
256 // because log() would fold that space into the prefix. Whitespace at the very start of a notice is lost.
257 const prefix = `NOTICE ${stop.session_id} | NOTICE: `;
258 const room = Math.max(MAX_LINE - TIME_LEN - 1 - prefix.length, 100);
259 for (const n of out.notices) {
260 const text = n.replace(/\s+/g, " ");
261 let i = 0;
262 do {
263 let j = Math.min(i + room, text.length);
264 while (j < text.length && j > i + 1 && (text[j] === " " || /[\uDC00-\uDFFF]/.test(text[j]))) j--;
265 await log($, prefix + text.slice(i, j));
266 i = j;
267 } while (i < text.length);
268 }
269 line = `END ${stop.session_id} | ${out.trace.join(" | ")} | ${out.result}`;
270 shown = out.shown;
271 notices = out.notices;
272 } catch (err) {
273 line = `END ${stop.session_id} | MOD ERROR, reads as UNKNOWN: ${msg(err)}`;
274 shown = UNKNOWN + `the mod raised (${msg(err)})`;
275 }
276 await log($, line);
277 // A FLAG or UNKNOWN verdict toasts. An ALLOW verdict is silent. Each notice toasts on its own line.
278 if (/^Decision watch: (FLAG|UNKNOWN)/.test(shown)) {
279 await toast($, stop, shown);
280 } else if (shown) {
281 await log($, `NOT SHOWN ${stop.session_id} | not a FLAG or UNKNOWN | text: ${shown}`);
282 }
283 for (const n of notices) await toast($, stop, NOTICE + n);
284}
285
286async function toast($, stop, text) {
287 try {
288 await deadline(Promise.resolve($.ui.toast(text)), TOAST_MS);
289 } catch (err) {
290 await log($, `TOAST FAILED ${stop.session_id} | ${msg(err)} | text: ${text}`);
291 }
292}
293
294const MAX_LOG_LINES = 500;
295const MAX_LINE = 2000;
296const TIME_LEN = 24; // length of an ISO timestamp, the start of each log line
297const LOG_WAIT_MS = 2000;
298const LOOKUP_MS = 500; // the transcript lookup, off the return path
299const SEEN_WAIT_MS = 500; // the most the handler waits for the STOP seen line
300const MODEL_MS = 50000;
301const PY_MS = 30000; // each python run (unmeasured; split mode calls no model); the mod's timer adds 1 s
302const FIND_MS = 5000; // each finder call (one name); the mod's timer adds 1 s
303const TOAST_MS = 5000;
304
305// Like within, but a late promise rejects, so the caller can fail the step and free its slot.
306async function deadline(work, ms) {
307 let timer;
308 try {
309 return await Promise.race([work, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`no reply within ${ms} ms`)), ms); })]);
310 } finally {
311 clearTimeout(timer);
312 }
313}
314
315// Race a promise against a timer, and free the timer either way.
316async function within(work, ms) {
317 let timer;
318 try {
319 return await Promise.race([work, new Promise((resolve) => { timer = setTimeout(resolve, ms); })]);
320 } finally {
321 clearTimeout(timer);
322 }
323}
324
325async function logFile($) {
326 return `${stateDir(await configDir($), "shadow")}/shadow.log`;
327}
328
329// Writes go one at a time, so two lines never read the same old file. $.fs.write makes a missing folder.
330// The file keeps its newest MAX_LOG_LINES lines. A file the host will not read (too big) starts over.
331let logChain = Promise.resolve();
332function log($, line) {
333 const work = async () => {
334 try {
335 const file = await logFile($);
336 let old = [];
337 try {
338 if (await $.fs.exists(file)) old = String(await $.fs.read(file)).split("\n").filter(Boolean);
339 } catch {
340 old = [];
341 }
342 // Whitespace is folded, as guard_core.log_cut does, so no text can forge a second log line.
343 const next = `${new Date().toISOString()} ${line.replace(/\s+/g, " ")}`.slice(0, MAX_LINE);
344 await $.fs.write(file, [...old.slice(-(MAX_LOG_LINES - 1)), next].join("\n") + "\n");
345 } catch {
346 // the log never fails the Stop
347 }
348 };
349 const done = logChain.then(() => within(work(), LOG_WAIT_MS));
350 logChain = done;
351 return done;
352}
353
354async function stopsSeen($) {
355 try {
356 const file = await logFile($);
357 if (!(await $.fs.exists(file))) return 0;
358 return String(await $.fs.read(file)).split("\n").filter((l) => /^\S+ STOP seen /.test(l)).length;
359 } catch {
360 return "unknown";
361 }
362}
363