The harness's session hooks (sandman recall/report/take, docket), house-rule guards, the five-hour window clock and the sandman shift band.

The harness's Claude Code mod: it runs the session hooks that settings.json used to wire, guards tool calls against the house rules, keeps the five-hour window clock, logs corrections to the trail, and puts the sandman shift above the prompt.
$HOME/.local/bin through $.process.run; a --hook call gets the settings hook's stdin JSON (the classic.<Event> event's e) on stdin, and its output is read as a command hook's: a JSON reply adds its hookSpecificOutput.additionalContext or nothing, other stdout adds itself. A missing binary, a timeout or a non-zero exit is a dim $.ui.log line and adds nothing; no exit code blocks.| event | runs | returns |
|---|---|---|
classic.SessionStart | sandman recall --hook, docket --hook, sandman report --hook, 10 s each, and the dead-session sweep (docket list --json, then a docket resolve per stale thread, 5 s each), concurrently | the chain's result plus each one's context, in that order, as additionalContext |
classic.UserPromptSubmit | docket --hook, 10 s | docket's pull as additionalContext |
classic.Stop | docket --hook, 10 s | the chain's result untouched |
classic.Notification (agent_needs_input, idle_prompt, permission_prompt) | docket --hook, 10 s | the chain's result untouched |
classic.SessionEnd | sandman take --hook, 1.5 s — the SessionEnd budget — and concurrently docket list --json, then docket resolve <id> --reason "session ended" per notification thread of the session, 0.75 s each | the chain's result untouched |
The SessionEnd resolve closes the session's notification problem — its title the first line of its first message, trimmed and cut at 120 characters, as docket's Notification derives it, and no line of any message a Stop's failed: or needs input: directive (later notifications append to it) — by id: an idle_prompt fires after the turn's last Stop, so docket's own close on Stop never reaches it, and docket --hook ignores SessionEnd (verified 2026-10-19 · docket src/verbs/hook.rs, probe under $DOCKET_ROOT). A --key resolve would also close the failed: problem (body the whole message) and needs input: decision docket's Stop opens under the same session:<id> key, a second after it opened them — every claude -p run ends in SessionEnd — so those are left for the owner. A killed session fires no SessionEnd, so the SessionStart sweep closes what such sessions left: it reads the live session ids from ~/.claude/sessions/<pid>.json (sessionId; the <pid>.<hash>.key files beside them are skipped), runs docket list --json, and docket resolve <id> --reason "session gone" for every notification-born problem thread (its title the first line of its first message, trimmed and cut at 120 characters, as docket's Notification derives it, and no line of any message a Stop's failed: or needs input: directive (later notifications append to it)) keyed session:<id> whose id is not live, adding no context. A headless claude -p session never registers, so a problem docket's Stop opened for one on a failed: message (its body the whole message, not the title) is never swept. An unreadable registry, or one not listing this session, skips the sweep: the format changed and absence is no evidence (verified 2026-10-19 · Claude Code 2.1.304, ~/.claude/sessions/<pid>.json observed).
A classic.* hook's result carries additionalContext on SessionStart, UserPromptSubmit and Stop, not on Notification or SessionEnd (verified 2026-10-14 · Claude Code 2.1.296 ClassicResultFields). Under managed settings an installed mod's classic.* hooks do not run (verified 2026-10-14 · claude plugin validate).
pkill -f/--full, tree discard — git checkout … --/./-f/--force/--pathspec-from-file, git switch -f/--force/--discard-changes, git restore (not -h/--help) unless --staged/-S without --worktree/-W, git read-tree -u/--reset, and a git -c/--config-env setting alias.… or include.…/includeIf.… (any case, harmless aliases too), which can hide any guarded command; config set through GIT_CONFIG_* variables or a saved alias is not seen — git reset --hard (abbreviated to --ha), git push --force (to --forc)/-f (bundled too: -fu)/--force-with-lease (to --force-w)/+<refspec>, each quoted or not, git stash (not list/show/-h/--help) or git clean (not with -n/--dry-run) at a command position, and a Write/Edit to a *.yml path, are denied with the house rule as the reason, and each denial is trailed: sandman trail append --kind guard. Backslash-newline continuations are joined first. A command position is a line start or follows ;, &, |, (, {, $( or an -exec/-execdir/-ok/-okdir word (find's, though any command's counts), past any VAR=value, keyword (if/elif/while/until/then/do/else/!) or wrapper (builtin, command, doas, env, eval, exec, mise x/exec, nice, nohup, sh/bash/zsh/dash/ksh, sudo, time, timeout, xargs), a wrapper's options (-u me, -c '…'; -- takes no value), tool@version words (mise x node@22 --) and bare numbers (timeout 5) included; the command word may be quoted, \-escaped or path-qualified ("git", \git, /usr/bin/git); git's global options (-C <path>, quoted or not, -c, -P, --git-dir <dir>) may stand before the subcommand, and a flag counts only before the command's next ;, &, | or line end. The match is textual: a forbidden command quoted after any of those separators inside an argument is denied too. An agent.spawn with no model (forks aside) is pinned to opus.session.start and on every session.measure, the five_hour entry of $.session.usage().rateLimits is written to $CLAUDE_WINDOW_FILE, else $XDG_STATE_HOME/claude/window.json, else ~/.local/state/claude/window.json, as {"at","five_hour":{"resets_at","used_percentage"},"session_id"}, resets_at in unix seconds — the statusline's format, read by sandman shift clock. $.fs.write is not atomic, so the file goes to window.json.<session>.tmp and /bin/mv -f renames it; a failed write or mv is a $.ui.log line. No write without both figures, with a percentage outside 0–100, or when the stored window is live (resets within 6 h) and ahead — a later resets_at, or the same with a higher used_percentage — the statusline's rule, so a reload's session.start in an idle session never rolls the clock back. The statusline's directory lock is beyond the mod API, so a write racing it can still land. (verified 2026-10-14 · code.claude.com/docs/en/plugins/mods/reference, Mods API methods)⟳ <shift> · <theme> · <repo> · <time to handoff> · last: <kind> <rationale>. Read every 15 s from ~/.sandman/shifts/current.json (shift, theme, repo, handoff_by) and the last line of today's (UTC) trail file ~/.sandman/trail/<yyyy>/<mm>/<dd>.jsonl. Either may be missing; with neither, or while a survey shows, the band is left to the engine. Interactive sessions only.claude -p, plugin or notification prompt) that matches ^no(?:[,.!\s]|$), don't/dont, never, stop, i said, wrong or not what i (case-insensitive) runs sandman trail append --kind correction --rationale <first 200 chars> --ref session:<id>, plus --shift $SANDMAN_SHIFT when set. A prompt of three or more tokens whose token set has Jaccard ≥ 0.8 with an earlier prompt of the session is appended instead with the rationale repeated instruction: …. Skipped, and kept out of the repeat comparison: a prompt over 400 characters, one starting # (a shift or breath brief, a pasted document), and the opening prompt of a claude --bg session — dispatch's brief. That prompt reaches the mod as a composer prompt of an interactive terminal session; the one signal telling it apart is the daemon's CLAUDE_CODE_SESSION_KIND=bg (verified 2026-10-14 · Claude Code 2.1.299, probe mod under --bg and interactive). The prompt always continues unchanged./shift runs sandman shift status, /docket docket list, /trail [n] sandman trail log cut to its last n lines (10 by default). Output is a $.ui.log line Claude never reads; all three run mid-turn.The harness repo is a marketplace (.claude-plugin/marketplace.json); once per machine:
claude plugin marketplace add ~/.grove/code/jgeschwendt/claude/main
claude plugin install perpetual@jgeschwendt
The install enables it under enabledPlugins in the user settings.json — this repo's, through the ~/.claude link — so every session loads it, claude --bg shifts included. The install is a versioned copy, not the trunk: installed_plugins.json pins installPath to ~/.claude/plugins/cache/jgeschwendt/perpetual/<version>, taken at install, so a trunk edit is not live until it ships — each change bumps version in .claude-plugin/plugin.json, and goes live after claude plugin update perpetual@jgeschwendt on a pulled trunk (verified 2026-10-19 · the 0.2.0 copy from a97f0ee lacked later fixes).
claude plugin validate plugins/perpetual --strict
claude plugin test plugins/perpetual
The tests stub $.process.run beneath the mod, so no binary runs; HOME is stubbed to /home/test.
hooks/perpetual.mjs 365 lines1// perpetual: the harness's session hooks, guards and window clock, plus the shift band.
2
3/** prompts that read as the person correcting the session */
4const CORRECTION =
5 /^no(?:[,.!\s]|$)|\bdon'?t\b|\bi said\b|\bnever\b|\bnot what i\b|\bstop\b|\bwrong\b/i;
6
7/** an optional quote, backslash or directory before a command word: `"git"`, `\git`, `/usr/bin/git` */
8const W = String.raw`[\\'"]?(?:[\w./~-]*\/)?`;
9/**
10 * one piece of a word: a quoted string, a backtick, `(…)` or `{…}` group (`$(pwd)`, `${HOME}`, `{}`), or a character
11 * no command position follows — each piece parses one way, and none runs past a separator unquoted, so a long
12 * spaceless line (minified JS, a query string) is scanned once, not once per `;`
13 */
14const V = String.raw`(?:"[^"]*"|'[^']*'|\`[^\`]*\`|\([^()]*\)|\{[^{}]*\}|[^\s;&|(){}\`"'])`;
15/** a statement keyword or a wrapper that runs the command after it, shells (`bash -c`) and `eval` included */
16const PRE = String.raw`(?:if|elif|while|until|then|do|else|!|${W}(?:builtin|command|doas|env|eval|exec|mise\s+(?:x|exec)|nice|nohup|(?:ba|da|k|z)?sh|sudo|time|timeout|xargs))(?=\s)`;
17/** a `tool@version` word (`mise x node@22 --`): never a value, so it parses one way */
18const TOOL = String.raw`(?![-\d])[\w./:+-]+@${V}*`;
19/**
20 * a command word at a command position: line start, after `;`, `&`, `|`, `(` or `{`, or after an
21 * `-exec`/`-execdir`/`-ok`/`-okdir` word (`find`'s; any command's counts), then any `VAR=value` or PRE, a PRE taking options (`--`, `-u me`: a
22 * value is never a PRE, a `VAR=`, a TOOL, nor leads with `-` or a digit, and `--` takes none, so each word parses one way;
23 * an option is never `-exec`, so each run of options ends at the next one, which starts its own),
24 * TOOLs and bare numbers (`timeout 5`)
25 */
26const AT = String.raw`(?:^|[;&|({]|\s-(?:exec|ok)(?:dir)?(?=\s))\s*(?:${PRE}(?:[^\S\n]+(?:-(?!(?:exec|ok)(?:dir)?\s)(?:-(?=\s)|(?!-\s)${V}+(?:[^\S\n]+(?![-\d]|${PRE}|${TOOL}|\w+=)${V}+)?)|${TOOL}|\d${V}*))*[^\S\n]+|\w+=${V}*[^\S\n]+)*${W}`;
27/** the rest of one command: up to a separator or the end of the line */
28const ARGS = String.raw`[^;&|\n]*`;
29/**
30 * `git`, closing quote and all, and its global options, then the subcommand's opening quote (`git "stash"`): `-C <path>`, quoted or not, `-c k=v`, a lone letter (`-P`), any
31 * long option with `=` only, a value-taking one also with a separate value (`--git-dir <dir>`) — a
32 * separate value for every `--opt` would read `git --no-pager show stash@{0}` as `stash`, and backtrack exponentially
33 */
34const GIT = String.raw`git['"]?(?:\s+-[Cc]\s+${V}+|\s+-[abd-zABD-Z]\b|\s+--(?:git-dir|work-tree|namespace|super-prefix|config-env)\s+(?!-)${V}+|\s+--[\w-]+(?:=${V}+)?)*\s+['"]?`;
35/** Bash commands the house rules forbid, each after a command position, with the rule that forbids it */
36const GUARDS = [
37 [
38 String.raw`pkill\b['"]?${ARGS}\s(?:-[a-z]*f|--full\b)`,
39 "pkill -f matches every process's full argv — kill by resolved PID: `lsof -ti :<port>` or `pgrep -x <name>`, inspect, then `kill <pid>`",
40 ],
41 [
42 // a `-c`/`--config-env` alias or include (any case: git lowercases the section) is denied outright, since it can name any of these
43 String.raw`${GIT}(?:(?:-c\s+|--config-env[=\s]\s*)['"]?(?:[Aa][Ll][Ii][Aa][Ss]|[Ii][Nn][Cc][Ll][Uu][Dd][Ee](?:[Ii][Ff])?)\.|checkout\b${ARGS}\s(?:(?:--(?:f\w*)?|\.)(?=[\s'";&|)]|$)|['"]?--pathspec-fr|-[dlmpqt]*f)|switch\b${ARGS}\s(?:--(?:di[\w-]*|force(?![\w-]))|-[dmqt]*f)|restore(?![\w-])(?!\s+(?:-h|--help)\b)(?:${ARGS}\s(?:--w\w*|-[mpqS]*W)|(?!${ARGS}\s(?:--st\w*|-[mpqW]*S)))|read-tree(?![\w-])${ARGS}\s(?:--res|-[imnqv]*u))`,
44 "never mutate to inspect — `git checkout --`/`.`/`-f`/`--pathspec-from-file`, `git switch -f`, a worktree `git restore`, `git read-tree -u`/`--reset` and a `git -c alias.…` that can hide any of them discard every uncommitted change to the path, co-resident work included; undo your own edit by re-editing",
45 ],
46 [
47 String.raw`${GIT}reset\b${ARGS}\s--ha(?:rd?)?\b`,
48 "never mutate to inspect — `git reset --hard` discards the working tree; commit, or fast-forward with `git update-ref`",
49 ],
50 [
51 String.raw`${GIT}push\b${ARGS}\s['"]?(?:--forc(?:e(?:-w[\w-]*)?)?(?:=\S*)?|-[a-zA-Z]*f[a-zA-Z]*|\+\S+)(?=[\s'";&|)]|$)`,
52 "never force-push — push a new branch or a new commit instead",
53 ],
54 [
55 String.raw`${GIT}stash\b(?!['"]?\s+(?:list|show|-h|--help)\b)`,
56 "never `git stash` — the stash stack is shared across worktrees and sessions; set work aside with a WIP commit",
57 ],
58 [
59 String.raw`${GIT}clean\b(?!${ARGS}\s(?:-[dfiqxX]*n|--d))`,
60 "never mutate to inspect — `git clean` deletes untracked files, co-resident work included",
61 ],
62];
63/** every guard in one pass, so a long command is walked once, not once per guard; the capture names the guard */
64const GUARD = new RegExp(`${AT}(?:${GUARDS.map(([pattern]) => `(${pattern})`).join("|")})`, "m");
65const HOOK_MS = 10000;
66const TAKE_MS = 1500;
67
68const state = { prompts: [] };
69
70/** Appends one trail event; a failure is logged, never raised. */
71async function append($, kind, rationale) {
72 const argv = ["trail", "append", "--kind", kind, "--rationale", rationale];
73 argv.push("--ref", `session:${await $.session.id()}`);
74 const shift = await $.env.get("SANDMAN_SHIFT");
75 if (shift) argv.push("--shift", shift);
76 await run($, "sandman", argv, { timeoutMs: 5000 });
77}
78
79/** Minutes until `handoff_by`, as `1h05m left` or `handoff due` once past; unparseable, itself. */
80function clockOf(handoffBy, now) {
81 if (!handoffBy) return undefined;
82 const due = Date.parse(handoffBy);
83 if (Number.isNaN(due)) return handoffBy;
84 if (due <= now) return "handoff due";
85 const minutes = Math.ceil((due - now) / 60000);
86 const h = Math.floor(minutes / 60);
87 return h > 0 ? `${h}h${String(minutes % 60).padStart(2, "0")}m left` : `${minutes}m left`;
88}
89
90/**
91 * Runs a settings-hook binary on the event's stdin JSON, as a command hook would, and resolves
92 * to the context it adds: `hookSpecificOutput.additionalContext` of a JSON reply, or plain stdout.
93 */
94async function hook($, bin, args, e, timeoutMs = HOOK_MS) {
95 const out = (await run($, bin, args, { stdin: JSON.stringify(e), timeoutMs }))?.trim();
96 const context = /^\{[^]*\}$/.test(out) ? parse(out)?.hookSpecificOutput?.additionalContext : out;
97 return typeof context === "string" && context ? [context] : [];
98}
99
100const homeOf = async ($) => (state.home ??= (await $.env.get("HOME")) ?? "");
101
102function parse(text) {
103 try {
104 const value = JSON.parse(text);
105 return value && typeof value === "object" ? value : null;
106 } catch {
107 return null;
108 }
109}
110
111/** Re-reads the shift file and today's trail tail, then asks for a redraw. */
112async function refresh($) {
113 const home = await homeOf($);
114 const day = new Date(await $.clock.now()).toISOString().slice(0, 10).replaceAll("-", "/");
115 const shiftText = await $.fs.read(`${home}/.sandman/shifts/current.json`).catch(() => "");
116 const trailText = await $.fs.read(`${home}/.sandman/trail/${day}.jsonl`).catch(() => "");
117 state.shift = parse(shiftText);
118 state.last = parse(trailText.trimEnd().split("\n").at(-1));
119 $.ui.invalidate("ui.render");
120}
121
122/**
123 * Runs `~/.local/bin/<bin>`; resolves to its stdout, or `undefined` after a dim log line when it
124 * cannot start, times out or exits non-zero. Never raises: no binary may break a session.
125 */
126async function run($, bin, args, init) {
127 const name = [bin, ...args.slice(0, 2)].join(" ");
128 try {
129 const { exitCode, stderr, stdout } = await $.process.run(
130 [`${await homeOf($)}/.local/bin/${bin}`, ...args],
131 init,
132 );
133 if (exitCode === 0) return stdout;
134 $.ui.log(`perpetual: ${name} exited ${exitCode}: ${stderr.trim().split("\n")[0]}`);
135 } catch (error) {
136 $.ui.log(`perpetual: ${name} failed: ${error}`);
137 }
138}
139
140/** Runs a binary for a command and logs what it printed. */
141async function show($, bin, args, shape = (stdout) => stdout.trim()) {
142 const stdout = await run($, bin, args);
143 if (stdout !== undefined) $.ui.log(shape(stdout) || "(empty)");
144 return {};
145}
146
147/**
148 * Resolves the open notification `problem` threads (docket's Notification: the title the first message's first line,
149 * trimmed and cut at 120 chars,
150 * no message line a Stop's `failed:` or `needs input:` — later notifications append) keyed `session:<id>` where
151 * `ends(id)`, by id: docket's Stop keys a `failed:` problem (its body the whole message)
152 * and a `needs input:` decision under the same key, and those stay for the owner. The list, then the
153 * resolves, get `timeoutMs` each.
154 */
155async function close($, ends, reason, timeoutMs) {
156 const init = { timeoutMs };
157 const threads = parse(await run($, "docket", ["list", "--json"], init));
158 await Promise.all(
159 (Array.isArray(threads) ? threads : [])
160 .filter(
161 (thread) =>
162 thread.kind === "problem" &&
163 thread.key?.startsWith("session:") &&
164 ends(thread.key.slice(8)) &&
165 [...(thread.messages[0]?.body ?? "").split("\n")[0].trim()]
166 .slice(0, 120)
167 .join("")
168 .trimEnd() === thread.title &&
169 !thread.messages.some((message) =>
170 /^[\s\u0085]*(failed|needs input):/m.test(message.body),
171 ),
172 )
173 .map((thread) => run($, "docket", ["resolve", thread.id, "--reason", reason], init)),
174 );
175}
176
177/**
178 * Closes the notification threads of sessions absent from Claude Code's live registry,
179 * `~/.claude/sessions/<pid>.json` (`sessionId`): a killed session fires no SessionEnd. Skipped unless the
180 * registry reads and lists this session — else its format changed and absence is no evidence. With the
181 * registry reads the sweep can hold SessionStart ≈10 s; it adds no context.
182 */
183async function sweep($) {
184 const dir = `${await homeOf($)}/.claude/sessions`;
185 const live = new Set();
186 for (const { name } of await $.fs.list(dir).catch(() => []))
187 if (name.endsWith(".json"))
188 live.add(parse(await $.fs.read(`${dir}/${name}`).catch(() => ""))?.sessionId);
189 if (live.has(await $.session.id()))
190 await close($, (id) => !live.has(id), "session gone", HOOK_MS / 2);
191 return [];
192}
193
194/**
195 * Persists the five-hour window to `$CLAUDE_WINDOW_FILE`, else `$XDG_STATE_HOME/claude/window.json`,
196 * else `~/.local/state/claude/window.json`, for `sandman shift clock`: written to a per-session `.tmp`
197 * then renamed with `mv`, since `$.fs.write` is not atomic. Skipped without both figures, with a
198 * percentage outside 0–100, or when the stored window is live (resets within 6 h) and ahead — a later
199 * reset, or the same with more used — the statusline's rule, so an idle session's stale reading at a
200 * reload never rolls the clock back. The statusline's directory lock is beyond the mod API, so a
201 * concurrent write can still interleave.
202 */
203async function window($) {
204 const five = (await $.session.usage()).rateLimits.find((limit) => limit.kind === "five_hour");
205 const resets_at = Math.floor(Date.parse(five?.resetsAt) / 1000);
206 const used = five?.percentUsed;
207 if (Number.isNaN(resets_at) || !(typeof used === "number" && used >= 0 && used <= 100)) return;
208 const root = (await $.env.get("XDG_STATE_HOME")) || `${await homeOf($)}/.local/state`;
209 const path = (await $.env.get("CLAUDE_WINDOW_FILE")) || `${root}/claude/window.json`;
210 const now = await $.clock.now();
211 const prior = parse(await $.fs.read(path).catch(() => ""))?.five_hour;
212 const lead = prior?.resets_at - Math.floor(now / 1000);
213 if (
214 lead >= 1 &&
215 lead <= 21600 &&
216 (prior.resets_at - resets_at || prior.used_percentage - used) > 0
217 )
218 return;
219 const id = await $.session.id();
220 const at = new Date(now).toISOString().replace(/\.\d+Z$/, "Z");
221 const five_hour = { resets_at, used_percentage: used };
222 try {
223 await $.fs.write(`${path}.${id}.tmp`, JSON.stringify({ at, five_hour, session_id: id }));
224 const { exitCode, stderr } = await $.process.run(["/bin/mv", "-f", `${path}.${id}.tmp`, path]);
225 if (exitCode) throw `mv exited ${exitCode}: ${stderr.trim()}`;
226 } catch (error) {
227 $.ui.log(`perpetual: window.json write failed: ${error}`);
228 }
229}
230
231/** Runs side-effect hooks beside the chain beneath and returns its result untouched. */
232async function beside(next, e, runs) {
233 return (await Promise.all([next(e), ...runs]))[0];
234}
235
236/** Runs context hooks beside the chain beneath and adds what they print, in order. */
237async function context(next, e, runs) {
238 const [result, ...contexts] = await Promise.all([next(e), ...runs]);
239 const additionalContext = [...(result.additionalContext ?? []), ...contexts.flat()];
240 return additionalContext.length ? { ...result, additionalContext } : result;
241}
242
243/** @type {import('claude-code').Register} */
244export const register = (on) => {
245 on("agent.spawn", ($, e, next) => next(e.model || e.fork ? e : { ...e, model: "opus" }));
246
247 // the notification types docket opens a thread for
248 on(
249 "classic.Notification",
250 { notification_type: ["agent_needs_input", "idle_prompt", "permission_prompt"] },
251 ($, e, next) => beside(next, e, [hook($, "docket", ["--hook"], e)]),
252 );
253
254 // an ended session waits on no one: its idle or permission notification fired after the last Stop,
255 // so docket's Stop never resolved it, and docket's hook has no SessionEnd; a `failed:` or `needs input:`
256 // thread under the same key still waits on the owner. The list and resolve split the 1.5 s budget
257 on("classic.SessionEnd", ($, e, next) =>
258 beside(next, e, [
259 hook($, "sandman", ["take", "--hook"], e, TAKE_MS),
260 close($, (id) => id === e.session_id, "session ended", TAKE_MS / 2),
261 ]),
262 );
263
264 on("classic.SessionStart", ($, e, next) =>
265 context(next, e, [
266 hook($, "sandman", ["recall", "--hook"], e),
267 hook($, "docket", ["--hook"], e),
268 hook($, "sandman", ["report", "--hook"], e),
269 sweep($),
270 ]),
271 );
272
273 on("classic.Stop", ($, e, next) => beside(next, e, [hook($, "docket", ["--hook"], e)]));
274
275 on("classic.UserPromptSubmit", ($, e, next) =>
276 context(next, e, [hook($, "docket", ["--hook"], e)]),
277 );
278
279 on("command.run", { command: "docket" }, ($) => show($, "docket", ["list"]));
280
281 on("command.run", { command: "shift" }, ($) => show($, "sandman", ["shift", "status"]));
282
283 on("command.run", { command: "trail" }, ($, e) => {
284 const n = Number.parseInt(e.args, 10);
285 const count = n > 0 ? n : 10;
286 return show($, "sandman", ["trail", "log"], (stdout) =>
287 stdout.trimEnd().split("\n").slice(-count).join("\n"),
288 );
289 });
290
291 on("prompt.submit", async ($, e, next) => {
292 // the owner's live words only: a `claude -p` shift brief's "never …" is no correction, nor is a long or `# `
293 // prompt (a brief, a pasted document), nor a `claude --bg` session's opening prompt — dispatch's brief, which
294 // arrives as a composer prompt of an interactive terminal session; only the daemon's env tells it apart
295 if (e.origin.kind !== "composer") return next(e);
296 const isOpening = !state.isOpened;
297 state.isOpened = true;
298 if (e.text.length > 400 || e.text.startsWith("# ")) return next(e);
299 if (isOpening && (await $.env.get("CLAUDE_CODE_SESSION_KIND")) === "bg") return next(e);
300 const tokens = new Set(e.text.toLowerCase().match(/[\p{L}\p{N}']+/gu));
301 // a repeat: three or more tokens, Jaccard ≥ 0.8 with an earlier prompt
302 const isRepeat =
303 tokens.size >= 3 &&
304 state.prompts.some((seen) => {
305 const shared = [...seen].filter((token) => tokens.has(token)).length;
306 return shared / (seen.size + tokens.size - shared) >= 0.8;
307 });
308 state.prompts.push(tokens);
309 const head = e.text.slice(0, 200);
310 if (isRepeat) await append($, "correction", `repeated instruction: ${head}`);
311 else if (CORRECTION.test(e.text)) await append($, "correction", head);
312 return next(e);
313 }).catch(($, e, next) => next(e)); // observe-only: a failed capture never holds the prompt
314
315 on("session.measure", async ($, e, next) => (await window($), next(e)));
316
317 on("session.start", async ($, e, next) => {
318 for (const [name, description, argumentHint] of [
319 ["docket", "Lists the docket's threads (log only)."],
320 ["shift", "Shows the current sandman shift (log only)."],
321 ["trail", "Shows the last n trail events, 10 by default (log only).", "[n]"],
322 ])
323 await $.command.register({ argumentHint, description, immediate: true, name });
324 await window($);
325 if (e.isInteractive) {
326 await refresh($);
327 state.timer?.cancel();
328 state.timer = $.clock.every(15000, () => refresh($));
329 }
330 return next(e);
331 });
332
333 on("tool.call", { tool: "Bash" }, async ($, e, next) => {
334 const command = e.command.replace(/\\\r?\n/g, " ");
335 const reason = GUARDS[GUARD.exec(command)?.slice(1).findIndex(Boolean)]?.[1];
336 if (!reason) return next(e);
337 await append($, "guard", `${reason}: ${e.command.slice(0, 200)}`);
338 return { deny: `perpetual: ${reason}.` };
339 });
340
341 on("tool.call", { tool: ["Edit", "Write"] }, async ($, e, next) => {
342 if (!/\.yml$/i.test(e.file_path)) return next(e);
343 const reason = "YAML files end in `.yaml`, never `.yml` — rename on touch";
344 await append($, "guard", `${reason}: ${e.file_path}`);
345 return { deny: `perpetual: ${reason}.` };
346 });
347
348 on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
349 const { last, shift } = state;
350 if (e.props.hasSurvey || (!shift && !last)) return next(e);
351 const parts = [
352 shift?.shift,
353 shift?.theme,
354 shift?.repo,
355 clockOf(shift?.handoff_by, await $.clock.now()),
356 last && `last: ${[last.kind, last.rationale].filter(Boolean).join(" ")}`,
357 ].filter(Boolean);
358 const width = Math.max(1, e.props.bodyColumns);
359 let line = `⟳ ${parts.join(" · ")}`.replace(/\s+/g, " ");
360 if (line.length > width) line = `${line.slice(0, width - 1)}…`;
361 const { Text } = $.ui.resolve(e);
362 return h(Text, { dimColor: true, wrap: "truncate-end" }, line);
363 });
364};
365