reads every Bash call, fork spawn and Write before it runs: a Write over a tracked file the session never read, a floor command, a system, overwrite, prune or…

🎞️ the frame: a place where most of the machine's setup lives as data.
<a href="https://github.com/dvakatsiienko/frame/actions/workflows/ci.yml"><img src="https://raw.githubusercontent.com/dvakatsiienko/frame/badges/ci.svg" alt="ci"></a> <img src="assets/badges/tests.svg" alt="tests"> <img src="assets/badges/renovate.svg" alt="renovate"> <img src="assets/badges/node.svg" alt="node"> <img src="assets/badges/pnpm.svg" alt="pnpm"> <img src="assets/badges/skills.svg" alt="skills"> <img src="assets/badges/mirrored.svg" alt="mirrored">
<img src="assets/banner.svg" align="left" width="100%" alt="frame — the inventory of one mac"> <img src="assets/mac.svg" align="right" width="36%" alt="an 80s mac showing ~ frame">
home/ is ~home/.claude/ is the claude code setup every session reads: memories, rules, skills (plugin-x), hooks, output styles, and sline, the statusline. cclio/ is the coordinator's home, the session that plans and routes work to background coders. x/ is x, the agent-first cli in go + charm: one verb registry, json for agents and boards for humans (x lane commits and pushes from a sandboxed worktree). hotkeys/ maps every keyboard chord on the machine and serves chords, the map's app. x-speak (a schedule/ daemon) reads the selected text aloud on F4 (with nothing selected it pauses / resumes, as ⇧F4 always does) and stops on F5, rewriting ids, versions, paths and code into something a voice can say; speak/ is its voice admin (pnpm speak:admin).
<img src="home/.claude/sline/showcase/sline.svg" width="100%" alt="sline, the statusline, as a session climbs from fresh to heavy">
chords is a keyboard map app: every key binding on every modifier layer, how often each one fires, and which keys are still free. powered by launchd daemon that counts key presses.
<img src="hotkeys/chords/showcase.png" width="100%" alt="chords: the hyper layer on a NuPhy Air75, each bound key with its app and press count">
the mirror links dotfiles and configs. a path under home/ is the same path under ~. the link map is derived by walking the tree, so adding a file to home/ auto-tracks it.
pnpm frame:link # status
pnpm frame:link apply # link everything not linked yet
pnpm frame:link register ~/.foo # move a file into the mirror and link it back
pnpm frame:link untrack ~/.gitconfig # hand a file back to ~
<img src="assets/frame-link.gif" width="720" alt="pnpm frame:link, ending on everything mirrored">
the mac's setup is kept as data, because data does not rot and scripts do: the Brewfile, the macos defaults, the duti file bindings, and the launchd jobs under schedule/.
pnpm macos:setup # brew bundle, macos defaults, duti, vim-plug
on a fresh machine, install the command line tools first — the clone itself needs git, and macos ships only a shim that opens the install dialog. then clone to ~/frame and run the seed, or hand it to an agent («seed this mac from frame»):
xcode-select --install # stop 0: the dialog, ~2 min
git clone https://github.com/dvakatsiienko/frame ~/frame && cd ~/frame
script/seed.sh # command line tools → brew → fnm, pnpm, node → pnpm i → macos:setup → sline → claude cli → frame:link apply
script/seed.sh --claude # the same, with ~/.claude linked
script/seed.sh --without-appstore # skip the app store apps and their sign-in
script/seed.sh --dry-run # what it would do, nothing changed
one status line per step, safe to re-run. it stops with needs your hands: … (exit 2) where only a human can act — the command line tools dialog, the homebrew password, files in the way of a link, the app store and 1password sign-ins — and the next run picks up from there. when it ends, open a new terminal: a shell opened before the seed never sources the zsh stubs it wrote.
hooks/register.ts 930 lines1import type { EngineInterface, Register } from 'claude-code';
2
3import { briefPaths } from './rules/brief.ts';
4import type { Brief, Context, Refusal } from './rules/command.ts';
5import { trashedPaths } from './rules/hazard.ts';
6import { hints, slowHint, slowShapes } from './rules/hint.ts';
7import { hasNotes, notedKey, notesEdits } from './rules/notes.ts';
8import { overwrittenPaths, writtenPaths } from './rules/overwrite.ts';
9import { rewrite } from './rules/rewrite.ts';
10import { SPEC_DOOR, SPEC_WHY, isSpecMissing } from './rules/spec.ts';
11import {
12 addedPaths,
13 check,
14 foregroundClaude,
15 installDirs,
16 mergeWord,
17 message,
18 namesWhole,
19 rawLinear,
20 rawPluginUpdate,
21 removedTrees,
22} from './rules.ts';
23
24// x-mod-guard: every Bash call is read before it runs; a floor command or a hazard shape is refused with its door.
25// each refusal and each escape is kept in $.store as one `event:` key, with per-day counts a halt reads.
26
27export type GuardEvent = {
28 at: number;
29 sid: string;
30 name?: string;
31 command: string;
32 // warned: a warn-only rule fired and the call ran
33 kind: 'refused' | 'escaped' | 'warned';
34 door: string;
35 target: string;
36 // why it was refused, the line x-mod-stash shows unfolded; an escape names every rule it stepped past
37 why: string;
38 // the rule that fired; an escape names every rule it stepped past, comma-joined
39 rule: string;
40};
41
42type Tally = { refused: number; escaped: number; warned?: number };
43// rules: the same tally split by the rule that fired, so noise and real catches separate
44export type DayCount = Tally & { rules?: Record<string, Tally> };
45
46const EVENT = 'event:';
47const KEEP = 50;
48const DAY = 'day:';
49const DAYS = 30;
50const SHOWN = 160;
51// a cclio session's own code edits: the 8th gets one note that a bigger job belongs to a helper
52const CODE_FILE = /\.(ts|tsx|go|sh|py|swift)$/;
53const EDITS = { key: 'edits', plugin: 'x-mod-guard' } as const;
54const EDIT_LIMIT = 8;
55const DELEGATE_NOTE =
56 "x-mod-guard: 8 code edits in this cclio session — a bigger job goes to a helper (~137k base) instead of this thread's context";
57const FAILED =
58 'x-mod-guard: the check failed or ran out of time, so this call is refused (fail closed). retry it once; if it repeats, tell cclio';
59// a fork carries the whole parent context; the line says what of it the fork needs
60const WHY_FORK = /^\s*why-fork:\s*\S/m;
61const FORK_DOOR =
62 'a fresh agent with a self-contained brief, or helper for a mechanical job';
63const FORK_WHY = 'a fork carries the whole parent context (~220k tokens)';
64const FORK_REFUSED = `x-mod-guard stopped this fork. instead: ${FORK_DOOR}. why: ${FORK_WHY}. a fork that truly needs that context says so in a prompt line: why-fork: <what parent context it needs>`;
65// an Agent prompt naming a ticket id, a backticked path or file, or one of matt's skills is a brief (FRM-392); the id
66// shape copies brief.go's ticketID, which a mod cannot import. a SendMessage is never checked: reports name skills and
67// example paths on purpose, and the verifier's verdict was refused three times live (13:40)
68const BRIEF_SIGN =
69 /\b(?:FRM|BYT|DOT)-\d+\b|`[^`\n]*\/[^`\n]*`|`[\w.@~-]+\.[a-z]{1,5}`|\bmattpocock-skills:|\bmatt's `?[a-z]/;
70// of x brief check's findings only a missing path and a skill's user quiz refuse; a quoted code term is a message's own
71const BRIEF_REFUSES = /^line \d+: (?:path|quiz) .+$/gm;
72// a relative path the session's repo lacks may live in another repo, which an absolute or ~/ path names (dima's o66)
73const RELATIVE_MISS = /^line \d+: path (?![/~])/;
74
75// the findings that stop a brief, or none; it throws when x breaks, and the spawn goes then (fail open, unlike the
76// floor): this runs on every Agent of every session, cclio's included
77async function briefFindings($: EngineInterface, text: string) {
78 if (!BRIEF_SIGN.test(text)) return [];
79 const repo = await $.session.root().catch(() => $.session.cwd());
80 const run = await $.process.run(
81 ['x', 'brief', 'check', '/dev/stdin', '--repo', repo, '--json'],
82 { stdin: text, timeoutMs: 8000 },
83 );
84 const out = JSON.parse(run.stdout) as { error?: unknown };
85 return typeof out.error === 'string'
86 ? (out.error.match(BRIEF_REFUSES) ?? [])
87 : [];
88}
89
90// what x brief check stamps: sha256 over the file's raw bytes, under $X_STATE or ~/.local/state/x (x/go/brief.go)
91async function readBrief(
92 $: EngineInterface,
93 path: string,
94 home: string | undefined,
95): Promise<Brief> {
96 const { base64 } = await $.fs.read(path, { as: 'bytes' });
97 const bytes = Uint8Array.from(atob(base64), (ch) => ch.charCodeAt(0));
98 const sum = [
99 ...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)),
100 ]
101 .map((b) => b.toString(16).padStart(2, '0'))
102 .join('');
103 const state = (await $.env.get('X_STATE')) || `${home}/.local/state/x`;
104 return {
105 isCoder: new TextDecoder().decode(bytes).includes('/x:crew-coder'),
106 isStamped: await $.fs.exists(`${state}/briefs/${sum}.json`),
107 };
108}
109
110// backlog finds its project from the root up; a task file is `<id> - <title>.md` under `.backlog/tasks` or `backlog/tasks`
111async function isTaskNoted(
112 $: EngineInterface,
113 root: string,
114 id: string,
115 home: string | undefined,
116) {
117 const prefix = `${id.toLowerCase()} - `;
118 for (let dir = root; dir && dir !== '/' && dir !== home; ) {
119 for (const tasks of [`${dir}/.backlog/tasks`, `${dir}/backlog/tasks`]) {
120 const names = await $.fs.list(tasks).catch(() => undefined);
121 if (!names) continue;
122 const file = names.find((n) =>
123 n.name.toLowerCase().startsWith(prefix),
124 );
125 if (!file) return false;
126 return hasNotes(await $.fs.read(`${tasks}/${file.name}`));
127 }
128 dir = dir.slice(0, dir.lastIndexOf('/'));
129 }
130 return false;
131}
132
133// a session's entry in cc's registry: the name ListAgents shows, and `bg` for a background session
134async function registryEntry($: EngineInterface, sid: string) {
135 const dir = `${await $.env.get('HOME')}/.claude/sessions`;
136 for (const f of await $.fs.list(dir).catch(() => [])) {
137 if (!f.name.endsWith('.json')) continue;
138 const raw = await $.fs.read(`${dir}/${f.name}`).catch(() => '');
139 if (!raw.includes(sid)) continue;
140 try {
141 const v = JSON.parse(raw) as {
142 sessionId?: unknown;
143 name?: unknown;
144 kind?: unknown;
145 };
146 if (v.sessionId === sid)
147 return {
148 isBg: v.kind === 'bg',
149 name: typeof v.name === 'string' ? v.name : undefined,
150 };
151 } catch {}
152 }
153 return undefined;
154}
155
156async function sessionName($: EngineInterface, sid: string) {
157 return (await registryEntry($, sid))?.name;
158}
159
160// one key per event, so parallel sessions never overwrite each other; the oldest past KEEP are dropped
161async function record(
162 $: EngineInterface,
163 event: Omit<GuardEvent, 'at' | 'sid' | 'name'>,
164) {
165 const sid = await $.session.id();
166 const at = await $.clock.now();
167 // one line on the band, whatever the command's shape
168 const line = event.command.replace(/\s+/g, ' ').trim();
169 const value: GuardEvent = {
170 ...event,
171 at,
172 command: line.length > SHOWN ? `${line.slice(0, SHOWN)}…` : line,
173 name: await sessionName($, sid),
174 sid,
175 };
176 // the band's record only: a store failure never turns a verdict into a refusal
177 try {
178 await $.store.set(`${EVENT}${at}:${sid}`, value);
179 const keys = await $.store.keys();
180 const events = keys.filter((k) => k.startsWith(EVENT));
181 for (const old of events.slice(0, Math.max(0, events.length - KEEP)))
182 await $.store.delete(old);
183 await count($, keys, at, sid, event).catch(() => undefined);
184 } catch (err) {
185 $.ui.log(`x-mod-guard: the event was not kept: ${err}`);
186 }
187}
188
189const tally = (was: Tally | undefined, kind: GuardEvent['kind']): Tally => ({
190 escaped: (was?.escaped ?? 0) + (kind === 'escaped' ? 1 : 0),
191 refused: (was?.refused ?? 0) + (kind === 'refused' ? 1 : 0),
192 ...(kind === 'warned' || was?.warned
193 ? { warned: (was?.warned ?? 0) + (kind === 'warned' ? 1 : 0) }
194 : {}),
195});
196
197// a new refusing rule ships warn-only: the call runs and the model reads what would have been refused, until the rule's
198// verifier says clean and it leaves this set (dima's o70, after FRM-392's guard refused plain reports live)
199const WARN_ONLY: ReadonlySet<string> = new Set([
200 'frozen-lockfile',
201 'notes-replace',
202 'raw-plugin-update',
203 'spec',
204]);
205// the store's `rule-mode:<rule>` = «enforce» turns a listed rule on early; nothing in the store can make a rule warn —
206// any session writes that store, and a «warn» there switched the floor off for every session (verifier, 15:08)
207async function isWarnOnly($: EngineInterface, rule: string) {
208 if (!WARN_ONLY.has(rule)) return false;
209 return (
210 (await $.store.get(`rule-mode:${rule}`).catch(() => undefined)) !==
211 'enforce'
212 );
213}
214const wouldRefuse = (rule: string, text: string) =>
215 `x-mod-guard would refuse this (rule ${rule}, warn-only until its verifier says clean): ${text}`;
216
217// the local day, `yyyy-mm-dd`
218function day(at: number) {
219 const d = new Date(at);
220 const two = (n: number) => String(n).padStart(2, '0');
221 return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())}`;
222}
223
224// one `day:<yyyy-mm-dd>:<session>` key per session a day, so a halt counts the whole day past the KEEP kept events; a count past DAYS is dropped
225async function count(
226 $: EngineInterface,
227 keys: string[],
228 at: number,
229 sid: string,
230 { kind, rule }: Pick<GuardEvent, 'kind' | 'rule'>,
231) {
232 const key = `${DAY}${day(at)}:${sid}`;
233 const was = (await $.store.get(key)) as DayCount | undefined;
234 const rules = { ...was?.rules };
235 for (const r of new Set(rule.split(', '))) rules[r] = tally(rules[r], kind);
236 await $.store.set(key, {
237 ...tally(was, kind),
238 rules,
239 } satisfies DayCount);
240 const oldest = `${DAY}${day(at - DAYS * 86_400_000)}`;
241 for (const old of keys)
242 if (old.startsWith(DAY) && old < oldest) await $.store.delete(old);
243}
244
245// x-mod-holds' store file: a session's first edit of a file holds it, and a Bash write by another session is refused here,
246// by the one Bash parser. the release checks are holds' own: a holder idle 30 min, a dead pid, a landed hold clean in git
247const HOLDS_FILE = /^x-mod-holds_.*\.json$/;
248// stash's 🎛️ «guard verdicts» knob lives in stash's own store file; silent drops the rewrite, hint and delegate notes, never a
249// refusal or a would-refuse (FRM-391 slice 06, dima's o11) — read-only, the store is one file per plugin
250const STASH_FILE = /^x-mod-stash_.*\.json$/;
251async function isSilent($: EngineInterface, home: string | undefined) {
252 const dir = `${home}/.claude/plugins/store`;
253 for (const f of await $.fs.list(dir).catch(() => [])) {
254 if (!STASH_FILE.test(f.name)) continue;
255 try {
256 const v = JSON.parse(await $.fs.read(`${dir}/${f.name}`));
257 if (v?.['guard-silent'] === true) return true;
258 } catch {}
259 }
260 return false;
261}
262const HOLD = 'hold:';
263const IDLE_MS = 30 * 60 * 1000;
264type Hold = { at: number; file: string; landed?: boolean };
265type Holder = { pid?: number; start?: string; idleSince: number | null };
266
267// twin dirname — a copy lives in x-mod-holds; the twins lint keeps them equal
268const dirname = (file: string) => file.slice(0, file.lastIndexOf('/')) || '/';
269// twin end
270
271// twin real-path — a copy lives in x-mod-holds; the twins lint keeps them equal
272// the key is lowercased on every platform: APFS is case-insensitive and the mod cannot ask which os it runs on
273async function realPath($: EngineInterface, file: string) {
274 const resolve = (p: string) =>
275 $.fs.stat(p, { resolve: true }).then(
276 (s) => s.realPath,
277 () => undefined,
278 );
279 const direct = await resolve(file);
280 if (direct) return { file: direct, key: direct.toLowerCase() };
281 // a new file has no real path yet; its nearest existing folder does
282 let dir = dirname(file);
283 let real = await resolve(dir);
284 while (!real && dir !== '/') {
285 dir = dirname(dir);
286 real = await resolve(dir);
287 }
288 const full = `${real ?? dir}${file.slice(dir.length)}`;
289 return { file: full, key: full.toLowerCase() };
290}
291// twin end
292
293// twin holder-gone — a copy lives in x-mod-holds; the twins lint keeps them equal
294// a holder that ended, went idle or died holds nothing
295async function isGone(
296 $: EngineInterface,
297 holder: Holder | undefined,
298 now: number,
299) {
300 if (!holder) return true;
301 if (holder.idleSince !== null && now - holder.idleSince >= IDLE_MS)
302 return true;
303 if (holder.pid && holder.start) {
304 const ps = await $.process.run([
305 'ps',
306 '-o',
307 'lstart=',
308 '-p',
309 String(holder.pid),
310 ]);
311 // a reused pid starts at another time
312 if (ps.stdout.trim() !== holder.start) return true;
313 }
314 return false;
315}
316// twin end
317
318async function heldBy(
319 $: EngineInterface,
320 command: string,
321 cwd: string,
322 ctx: Context,
323): Promise<string | undefined> {
324 const paths = writtenPaths(command, cwd, ctx);
325 if (!paths.length) return undefined;
326 const dir = `${ctx.home}/.claude/plugins/store`;
327 const held: Record<string, unknown> = {};
328 for (const f of await $.fs.list(dir).catch(() => [])) {
329 if (!HOLDS_FILE.test(f.name)) continue;
330 try {
331 Object.assign(
332 held,
333 JSON.parse(await $.fs.read(`${dir}/${f.name}`)),
334 );
335 } catch {}
336 }
337 const sid = await $.session.id();
338 const now = await $.clock.now();
339 for (const path of paths) {
340 const real = await realPath($, path);
341 for (const [key, value] of Object.entries(held)) {
342 if (!key.startsWith(HOLD)) continue;
343 const cut = key.indexOf(':', HOLD.length);
344 const holder = key.slice(HOLD.length, cut);
345 if (key.slice(cut + 1) !== real.key || holder === sid) continue;
346 const hold = value as Hold;
347 if (
348 await isReleased(
349 $,
350 held[`holder:${holder}`] as Holder | undefined,
351 hold,
352 now,
353 )
354 )
355 continue;
356 const mins = Math.round((now - hold.at) / 60000);
357 return `x-mod-holds: ${path} is held by session ${holder.slice(0, 8)}, which took it ${mins} min ago. wait, or ask it to commit the file.`;
358 }
359 }
360 return undefined;
361}
362
363async function isReleased(
364 $: EngineInterface,
365 holder: Holder | undefined,
366 hold: Hold,
367 now: number,
368) {
369 if (await isGone($, holder, now)) return true;
370 if (!hold.landed) return false;
371 const git = await $.process
372 .run(['git', 'status', '--porcelain', '--', hold.file], {
373 cwd: hold.file.slice(0, hold.file.lastIndexOf('/')) || '/',
374 })
375 .catch(() => null);
376 return git?.exitCode !== 0 || git.stdout.trim() === '';
377}
378
379const isUnder = (path: string, dir: string) =>
380 path === dir || path.startsWith(`${dir}/`);
381
382const SEEN = { key: 'seen', plugin: 'x-mod-guard' } as const;
383// dima's last prompt typed at the composer or sent over the bridge: a peer's message, a notification, a plugin's or an
384// sdk turn never lands here, and only this plugin writes $.state, so no tool call can forge it
385const PROMPT = { key: 'prompt', plugin: 'x-mod-guard' } as const;
386const TYPED_BY_DIMA = new Set(['composer', 'bridge']);
387// a --bg session's spawn prompt arrives as `composer` and dima's typing there as `bridge` (measured 2026-10-09, FRM-358),
388// so in a bg session only the bridge is his
389const TYPED_BY_DIMA_IN_BG = new Set(['bridge']);
390const UNPROVEN_DOOR =
391 'ask dima; his own next prompt naming each target as a word lets the # dima-ok marker through (a bare symbol like . or & only as «dima-ok: <target>»). a bg session counts only what dima types into it himself; ask cclio to get him there';
392const UNPROVEN_WHY =
393 "a # dima-ok marker counts only when dima's last typed prompt names its target";
394// a live mod's hooks reload into every session on save, so while its own tests are red a half-done edit there breaks the fleet
395// (FRM-350: Bash down fleet-wide for ~5 min); the fix goes through a scratch copy and lands only once it is green
396const LIVE_RED_DOOR =
397 'edit a scratch copy: `x mods edit pull <file>`, then `x mods edit push`, which lands it only when the mod validates and tests green';
398
399// the live mod dir a path sits under `hooks/` of, from CLAUDE_CODE_PLUGIN_DIRS; real paths on both sides, so a symlinked
400// route into the tree counts too
401async function liveModOf($: EngineInterface, path: string) {
402 const home = await $.env.get('HOME');
403 const dirs = (await $.env.get('CLAUDE_CODE_PLUGIN_DIRS')) ?? '';
404 const real = async (p: string) =>
405 $.fs.stat(p, { resolve: true }).then(
406 (s) => s.realPath ?? p,
407 () => p,
408 );
409 const file = await real(path);
410 for (const entry of dirs.split(':').filter(Boolean)) {
411 const dir = entry.replace(/^~(?=\/|$)/, home ?? '~');
412 if (file.startsWith(`${await real(dir)}/hooks/`)) return dir;
413 }
414 return undefined;
415}
416
417// every prompt's origin and fields, the last 20 across sessions, so a probe reads what a session really saw (FRM-358):
418// whether dima's typing can be told from a machine's is a measurement, never a guess from the types
419const ORIGINS = 'origins';
420async function logOrigin(
421 $: EngineInterface,
422 e: {
423 text: string;
424 origin: { kind: string };
425 turnId?: string;
426 wait: boolean;
427 attachments?: readonly unknown[];
428 context?: readonly string[];
429 },
430) {
431 const was = ((await $.store.get(ORIGINS)) ?? []) as {
432 text?: string;
433 }[];
434 // whole code points, and no half pair left from an older cut: a lone surrogate leaves the store file unreadable to jq
435 const whole = (s: string) =>
436 [...s].filter((c) => c.length === 2 || !/[\ud800-\udfff]/.test(c));
437 const head = (s: string) => whole(s).slice(0, 80).join('');
438 const row = {
439 at: await $.clock.now(),
440 attachments: e.attachments?.length ?? 0,
441 context: e.context?.map(head),
442 origin: e.origin,
443 sid: await $.session.id().catch(() => undefined),
444 text: head(e.text),
445 turnId: e.turnId,
446 wait: e.wait,
447 };
448 // a row an older build cut mid-pair is mended on the next write
449 const kept = was.map((r) =>
450 typeof r.text === 'string' ? { ...r, text: head(r.text) } : r,
451 );
452 await $.store.set(ORIGINS, [row, ...kept].slice(0, 20));
453}
454
455const UNREAD_DOOR = 'Read the file first, then Write';
456const UNREAD_WHY = 'a Write replaces a tracked file this session never read';
457
458async function isTracked($: EngineInterface, path: string) {
459 if (!(await $.fs.exists(path))) return false;
460 const cut = path.lastIndexOf('/');
461 // a slow or locked repo fails open on this lookup only: the Write runs as cc would run it
462 const ls = await $.process
463 .run(
464 ['git', 'ls-files', '--error-unmatch', '--', path.slice(cut + 1)],
465 { cwd: path.slice(0, cut) || '/' },
466 )
467 .catch(() => null);
468 return ls?.exitCode === 0;
469}
470
471// a tree cclio may drop unasked: no `.scratch/` plan inside, and every commit its HEAD reaches is on a branch;
472// a lookup that fails counts as unclean, so the remove asks
473async function isCleanTree($: EngineInterface, tree: string) {
474 if (await $.fs.exists(`${tree}/.scratch`)) return false;
475 const orphans = await $.process
476 .run(
477 [
478 'git',
479 'rev-list',
480 '-n',
481 '1',
482 'HEAD',
483 '--not',
484 '--branches',
485 '--remotes',
486 ],
487 { cwd: tree },
488 )
489 .catch(() => null);
490 return !!orphans && orphans.exitCode === 0 && orphans.stdout.trim() === '';
491}
492
493// a manifest the working tree changed since HEAD: `CI=1 pnpm install` would freeze the lockfile against it
494async function isManifestChanged($: EngineInterface, dir: string) {
495 const r = await $.process
496 .run(['git', 'diff', '--name-only', 'HEAD'], { cwd: dir })
497 .catch(() => null);
498 if (!r || r.exitCode !== 0) return false;
499 return r.stdout
500 .split('\n')
501 .some((f) =>
502 /(^|\/)(package\.json|pnpm-workspace\.yaml)$/.test(f.trim()),
503 );
504}
505
506// parallel Reads in one step each add their path: a write that lost the race reads again
507async function markSeen($: EngineInterface, path: string) {
508 for (let tries = 0; tries < 3; tries++) {
509 const { value = [], version } = await $.state.get(SEEN);
510 if (value.includes(path)) return;
511 const { isSet } = await $.state.set(SEEN, [...value, path], {
512 ifVersion: version,
513 });
514 if (isSet) return;
515 }
516}
517
518// the disk facts the pure rules need, looked up in one round: each rule names the paths it asks about, this answers
519// them; a rule that needs a new fact adds its question here and its field to Context
520async function lookUp(
521 $: EngineInterface,
522 command: string,
523 cwd: string,
524 ctx: Context,
525): Promise<Context> {
526 const missing = new Set<string>();
527 for (const path of addedPaths(command, cwd, ctx))
528 if (!(await $.fs.exists(path))) missing.add(path);
529 const kinds: NonNullable<Context['kinds']> = new Map();
530 for (const path of [
531 ...overwrittenPaths(command, cwd, ctx),
532 ...trashedPaths(command, cwd, ctx),
533 ])
534 if (await $.fs.exists(path))
535 kinds.set(path, (await $.fs.stat(path)).kind);
536 const cleanTrees = new Set<string>();
537 for (const tree of removedTrees(command, cwd, ctx))
538 if (await isCleanTree($, tree)) cleanTrees.add(tree);
539 const briefs = new Map<string, Brief>();
540 for (const path of briefPaths(command, cwd, ctx))
541 if (await $.fs.exists(path))
542 briefs.set(path, await readBrief($, path, ctx.home));
543 const manifestDirs = new Set<string>();
544 for (const dir of installDirs(command, cwd, ctx))
545 if (await isManifestChanged($, dir)) manifestDirs.add(dir);
546 const notedTasks = new Set<string>();
547 for (const edit of notesEdits(command, cwd, ctx))
548 if (await isTaskNoted($, edit.root, edit.id, ctx.home))
549 notedTasks.add(notedKey(edit));
550 return { briefs, cleanTrees, kinds, manifestDirs, missing, notedTasks };
551}
552
553// a foreground Bash that held the session over a minute is remembered by its shapes; the next foreground run of one
554// reads a hint toward run_in_background (dima's o113: the 2-minute gates of 10-14 added up)
555const SLOW = 'slow:';
556const SLOW_MS = 60_000;
557async function rememberSlow(
558 $: EngineInterface,
559 shapes: string[],
560 took: number,
561) {
562 if (took < SLOW_MS) return;
563 for (const shape of shapes)
564 await $.store.set(SLOW + shape, { ms: took }).catch(() => undefined);
565}
566async function slowSeen($: EngineInterface, shapes: string[]) {
567 const seen: string[] = [];
568 for (const shape of shapes) {
569 const was = (await $.store.get(SLOW + shape).catch(() => undefined)) as
570 | { ms: number }
571 | undefined;
572 if (was) seen.push(slowHint(shape, Math.round(was.ms / 1000)));
573 }
574 return seen;
575}
576
577export const register: Register = (on) => {
578 // a Monitor's command is a shell command too
579 on('tool.call', { tool: /^(Bash|Monitor)$/ }, async ($, e, next) => {
580 // the input is the model's: a command that is not a string is the tool's to refuse
581 if (e.tool !== 'Bash' && e.tool !== 'Monitor') return next(e);
582 const typed = e.command;
583 if (typeof typed !== 'string') return next(e);
584 // a shape with one right spelling is fixed, then the fixed command is what every rule reads
585 const { command, notes } = rewrite(typed);
586 const cwd = await $.session.cwd();
587 const home = await $.env.get('HOME');
588 const root = await $.session.root().catch(() => cwd);
589 const ctx: Context = {
590 home,
591 isCclio: isUnder(root, `${home}/frame/cclio`),
592 jobDir: await $.env.get('CLAUDE_JOB_DIR'),
593 };
594 const verdict = check(command, cwd, {
595 ...ctx,
596 ...(await lookUp($, command, cwd, ctx)),
597 });
598 // a worktree session whose shell `cd`ed out (`cd ~/frame && …`) is refused for the wrong tree; the root still names its own
599 const drift =
600 root.includes('/.claude/worktrees/') &&
601 cwd !== root &&
602 !cwd.startsWith(`${root}/`)
603 ? `this worktree session's shell left its tree for ${cwd}: cd ${root}, or EnterWorktree(path: "${root}")`
604 : undefined;
605 const deny = (text: string) => ({
606 deny: drift ? `${text} — ${drift}` : text,
607 });
608 // the model typed the old command: it is told what changed, or it reads a surprise
609 const go = async () => {
610 const isForeground =
611 e.tool === 'Bash' && e.run_in_background !== true;
612 const shapes = isForeground ? slowShapes(command, cwd) : [];
613 const slow = await slowSeen($, shapes);
614 const started = await $.clock.now().catch(() => undefined);
615 const result = await next(notes.length ? { ...e, command } : e);
616 const ended = await $.clock.now().catch(() => undefined);
617 if (started !== undefined && ended !== undefined)
618 await rememberSlow($, shapes, ended - started);
619 if (result.deny !== undefined) return deny(result.deny);
620 const isQuiet = await isSilent($, ctx.home);
621 const context = [
622 ...(notes.length && !isQuiet
623 ? [
624 `x-mod-guard rewrote this call before it ran: ${notes.join('; ')}. it ran: ${command}`,
625 ]
626 : []),
627 ...(drift && result.isError ? [drift] : []),
628 ...(isQuiet ? [] : hints(command, cwd, ctx)),
629 ...(isQuiet ? [] : slow),
630 ];
631 if (!context.length) return result;
632 return {
633 ...result,
634 context: [...(result.context ?? []), ...context],
635 };
636 };
637 // every Bash refusal goes through here: recorded, then refused — or, for a rule in WARN_ONLY, run with the
638 // would-refuse note the model reads
639 const enforce = async (
640 r: Pick<Refusal, 'door' | 'rule' | 'targets' | 'why'>,
641 denial: string,
642 note = denial,
643 ) => {
644 const isWarn = await isWarnOnly($, r.rule);
645 await record($, {
646 command,
647 door: r.door,
648 kind: isWarn ? 'warned' : 'refused',
649 rule: r.rule,
650 target: r.targets[0] ?? '',
651 why: r.why,
652 });
653 if (!isWarn) return deny(denial);
654 const ran = await go();
655 return ran.deny !== undefined
656 ? ran
657 : {
658 ...ran,
659 context: [
660 ...(ran.context ?? []),
661 wouldRefuse(r.rule, note),
662 ],
663 };
664 };
665 // a file another live session holds (x-mod-holds) is refused before any other rule; holds has no escape
666 const held = await heldBy($, command, cwd, ctx).catch(() => undefined);
667 if (held) return deny(held);
668 // a refusal, never a warning, so it stays out of WARN_ONLY: a warn would fire after the block it means to
669 // prevent (dima's o102)
670 const fg =
671 e.tool === 'Bash' && e.run_in_background !== true
672 ? foregroundClaude(command, cwd)
673 : undefined;
674 if (fg)
675 return enforce(
676 fg,
677 `nothing in this command ran — x-mod-guard stopped this one command. instead: ${fg.door}. why: ${fg.why}.`,
678 );
679 // a member's raw linear read or comment, as typed (before the api rewrite), names its x linear door; cclio's runs (FRM-398)
680 const raw = rawLinear(typed, cwd);
681 if (raw) {
682 const sid = await $.session.id().catch(() => undefined);
683 const name = sid ? await sessionName($, sid) : undefined;
684 if (
685 name !== undefined &&
686 name.replaceAll(/[\s\u200d]/g, '') !== '🦉cclio'
687 ) {
688 const said = `x-mod-guard stopped this one command. instead: ${raw.door}. why: ${raw.why}.`;
689 return enforce(
690 raw,
691 `nothing in this command ran — ${said}`,
692 said,
693 );
694 }
695 }
696 // a raw plugin update names x plugin bump, every session's door (FRM-389 exit 7); warn-only until its verifier
697 const bump = rawPluginUpdate(typed, cwd);
698 if (bump) {
699 const said = `x-mod-guard stopped this one command. instead: ${bump.door}. why: ${bump.why}.`;
700 return enforce(bump, `nothing in this command ran — ${said}`, said);
701 }
702 // a refusal, never in WARN_ONLY: a warn would run the merge it means to stop (dima's o102, FRM-423)
703 const word = mergeWord(typed, cwd);
704 if (word) {
705 const { value: prompt = '' } = await $.state.get(PROMPT);
706 const unproven = word.targets.filter(
707 (t) => !namesWhole(prompt, t) && !namesWhole(prompt, `#${t}`),
708 );
709 if (unproven.length) {
710 const said = `x-mod-guard stopped this one command. instead: ${word.door}. why: ${word.why} (rule dima-ok-flag); it does not name: ${unproven.join(' ')}.`;
711 return enforce(
712 { ...word, targets: unproven },
713 `nothing in this command ran — ${said}`,
714 said,
715 );
716 }
717 }
718 if (verdict.kind === 'run') return go();
719 if (verdict.kind === 'refused')
720 return enforce(verdict.refusal, message(verdict.refusal));
721 // the marker is only a claim: dima's own last prompt must name every target the refusals named
722 const { value: said = '' } = await $.state.get(PROMPT);
723 const unproven = [
724 ...new Set(verdict.refusals.flatMap((r) => r.targets)),
725 ].filter((t) => !namesWhole(said, t));
726 if (unproven.length) {
727 await record($, {
728 command,
729 door: UNPROVEN_DOOR,
730 kind: 'refused',
731 rule: 'dima-ok-unproven',
732 target: unproven[0] ?? '',
733 why: UNPROVEN_WHY,
734 });
735 return deny(
736 `nothing in this command ran — x-mod-guard stopped it. instead: ${UNPROVEN_DOOR}. why: ${UNPROVEN_WHY}; it does not name: ${unproven.join(' ')}`,
737 );
738 }
739 await record($, {
740 command,
741 door: verdict.refusals.map((r) => r.door).join('; '),
742 kind: 'escaped',
743 rule: [...new Set(verdict.refusals.map((r) => r.rule))].join(', '),
744 target: verdict.targets.join(', '),
745 why: verdict.refusals.map((r) => r.why).join('; '),
746 });
747 $.ui.log(`x-mod-guard: ran on dima-ok: ${verdict.targets.join(', ')}`);
748 return go();
749 }).catch(() => ({ deny: FAILED }));
750
751 on(
752 'tool.call',
753 { tool: /^(Edit|Write|MultiEdit)$/ },
754 async ($, e, next) => {
755 const result = await next(e);
756 const path = 'file_path' in e ? e.file_path : undefined;
757 if (
758 result.deny !== undefined ||
759 typeof path !== 'string' ||
760 !CODE_FILE.test(path)
761 )
762 return result;
763 try {
764 const home = await $.env.get('HOME');
765 // the session's root, never its cwd: a cclio cd'd into ~/frame is still cclio, a coder cd'd into cclio is not
766 const root = await $.session
767 .root()
768 .catch(() => $.session.cwd());
769 if (!isUnder(root, `${home}/frame/cclio`)) return result;
770 const n = ((await $.state.get(EDITS)).value ?? 0) + 1;
771 await $.state.set(EDITS, n);
772 if (n !== EDIT_LIMIT || (await isSilent($, home)))
773 return result;
774 return {
775 ...result,
776 context: [...(result.context ?? []), DELEGATE_NOTE],
777 };
778 } catch {
779 return result;
780 }
781 },
782 );
783
784 // an Edit or Write under a live mod's hooks/ waits for that mod's own tests to be green
785 on(
786 'tool.call',
787 { tool: /^(Edit|MultiEdit|Write)$/ },
788 async ($, e, next) => {
789 const path = 'file_path' in e ? e.file_path : undefined;
790 if (typeof path !== 'string') return next(e);
791 const mod = await liveModOf($, path);
792 if (!mod) return next(e);
793 const run = await $.process.run(['claude', 'plugin', 'test', mod], {
794 timeoutMs: 60_000,
795 });
796 if (run.exitCode === 0) return next(e);
797 const name = mod.split('/').filter(Boolean).at(-1) ?? mod;
798 const why = `${name}'s plugin test is red, and a save under its hooks/ reloads into every live session`;
799 await record($, {
800 command: `${e.tool} ${path}`,
801 door: LIVE_RED_DOOR,
802 kind: 'refused',
803 rule: 'live-hook-red',
804 target: path,
805 why,
806 });
807 return {
808 deny: `x-mod-guard stopped this ${e.tool}. instead: ${LIVE_RED_DOOR}. why: ${why}: ${path}`,
809 };
810 },
811 ).catch(() => ({ deny: FAILED }));
812
813 // a Write over a tracked file this session never saw replaces what it never read; a Read, Edit or Write marks it seen
814 on(
815 'tool.call',
816 { tool: /^(Read|Edit|MultiEdit|Write)$/ },
817 async ($, e, next) => {
818 const path = 'file_path' in e ? e.file_path : undefined;
819 if (typeof path !== 'string') return next(e);
820 const real = await $.fs.stat(path, { resolve: true }).then(
821 (s) => s.realPath ?? path,
822 () => path,
823 );
824 const { value: seen = [] } = await $.state.get(SEEN);
825 if (
826 e.tool === 'Write' &&
827 !seen.includes(real) &&
828 (await isTracked($, real))
829 ) {
830 await record($, {
831 command: `Write ${path}`,
832 door: UNREAD_DOOR,
833 kind: 'refused',
834 rule: 'write-unread',
835 target: path,
836 why: UNREAD_WHY,
837 });
838 return {
839 deny: `x-mod-guard stopped this Write. instead: ${UNREAD_DOOR}. why: ${UNREAD_WHY}: ${path}`,
840 };
841 }
842 const result = await next(e);
843 if (result.deny === undefined && !result.isError)
844 // bookkeeping only: the call already ran, so a failed mark never turns it into a refusal
845 await markSeen($, real).catch(() => undefined);
846 return result;
847 },
848 ).catch(() => ({ deny: FAILED }));
849
850 // fail open: a message is never stopped by a broken check
851 on('tool.call', { tool: 'SendMessage' }, async ($, e, next) => {
852 const { message, to } = e as { message?: unknown; to?: unknown };
853 if (
854 typeof to !== 'string' ||
855 typeof message !== 'string' ||
856 !isSpecMissing(to, message)
857 )
858 return next(e);
859 const isWarn = await isWarnOnly($, 'spec').catch(() => true);
860 await record($, {
861 command: `SendMessage → ${to}: ${message}`,
862 door: SPEC_DOOR,
863 kind: isWarn ? 'warned' : 'refused',
864 rule: 'spec',
865 target: to,
866 why: SPEC_WHY,
867 }).catch(() => undefined);
868 if (!isWarn)
869 return {
870 deny: `x-mod-guard stopped this message. instead: ${SPEC_DOOR}. why: ${SPEC_WHY}`,
871 };
872 const sent = await next(e);
873 return sent.deny !== undefined
874 ? sent
875 : {
876 ...sent,
877 context: [
878 ...(sent.context ?? []),
879 wouldRefuse('spec', `${SPEC_WHY}; ${SPEC_DOOR}`),
880 ],
881 };
882 });
883
884 on('prompt.submit', async ($, e, next) => {
885 if (TYPED_BY_DIMA.has(e.origin.kind)) {
886 const sid = await $.session.id().catch(() => undefined);
887 const isBg = sid
888 ? ((await registryEntry($, sid).catch(() => undefined))?.isBg ??
889 false)
890 : false;
891 if ((isBg ? TYPED_BY_DIMA_IN_BG : TYPED_BY_DIMA).has(e.origin.kind))
892 await $.state.set(PROMPT, e.text).catch(() => undefined);
893 }
894 await logOrigin($, e).catch(() => undefined);
895 return next(e);
896 });
897
898 on('agent.spawn', async ($, e, next) => {
899 const found = await briefFindings($, e.prompt).catch(() => []);
900 if (found.length) {
901 const why = found.join('; ');
902 // a spawn takes no note, so a warn-only rule is seen in the kept events alone
903 const isWarn = await isWarnOnly($, 'brief');
904 await record($, {
905 command: `Agent: ${e.description}`,
906 door: 'fix what x brief check names',
907 kind: isWarn ? 'warned' : 'refused',
908 rule: 'brief',
909 target: found[0] ?? '',
910 why,
911 }).catch(() => undefined);
912 if (isWarn) return next(e);
913 return {
914 deny: `x-mod-guard stopped this brief. instead: fix what x brief check names, then spawn again${found.some((f) => RELATIVE_MISS.test(f)) ? '; a path from another repo: write it absolute or ~/' : ''}. why: ${why}`,
915 };
916 }
917 if (!e.fork || WHY_FORK.test(e.prompt)) return next(e);
918 const isWarn = await isWarnOnly($, 'fork');
919 await record($, {
920 command: `fork: ${e.description}`,
921 door: FORK_DOOR,
922 kind: isWarn ? 'warned' : 'refused',
923 rule: 'fork',
924 target: 'why-fork',
925 why: FORK_WHY,
926 });
927 return isWarn ? next(e) : { deny: FORK_REFUSED };
928 }).catch(() => ({ deny: FAILED }));
929};
930hooks/rules/brief.ts 60 lines1import { parse } from '../shell.ts';
2import {
3 type Command,
4 type Context,
5 type Refusal,
6 commands,
7 operands,
8 resolve,
9} from './command.ts';
10
11const CODER = '/x:crew-coder';
12const INLINE = 'inline-brief';
13// a `claude --bg` call's brief file: the one `$(cat <path>)`, `cat <path> |` or `< <path>` reads
14function spawnBrief(c: Command, ctx: Context) {
15 if (c.name !== 'claude' || !c.args.some((w) => w.text === '--bg'))
16 return undefined;
17 const dir = resolve(c.dir, '/', ctx);
18 const text =
19 c.feeders.flatMap((f) =>
20 f.name === 'cat' ? operands(f.args) : [],
21 )[0] ?? c.reads[0];
22 return {
23 dir,
24 file: text ? { path: resolve(text, dir, ctx), text } : undefined,
25 };
26}
27// the brief files every coder spawn in the command reads, for the caller to hash and look up
28export function briefPaths(command: string, cwd: string, ctx: Context = {}) {
29 return commands(parse(command), cwd).flatMap((c) => {
30 const path = spawnBrief(c, ctx)?.file?.path;
31 return path ? [path] : [];
32 });
33}
34// a coder spawn runs only on a brief whose bytes passed x brief check
35export function brief(c: Command, ctx: Context): Refusal | undefined {
36 const spawn = spawnBrief(c, ctx);
37 if (!spawn) return undefined;
38 const { dir, file } = spawn;
39 const isNamed = c.args.some((w) => w.text.includes(CODER));
40 if (!file)
41 return isNamed
42 ? {
43 door: `write the brief to a file, run x brief check <path> --repo ${dir}, then spawn with "$(cat <path>)"`,
44 rule: 'brief',
45 targets: [INLINE],
46 why: 'x-mod-guard can check a brief only in a file, and a coder brief must pass x brief check',
47 }
48 : undefined;
49 const found = ctx.briefs?.get(file.path);
50 if (!(isNamed || found?.isCoder) || found?.isStamped) return undefined;
51 return {
52 door: `x brief check ${file.path} --repo ${dir}, fix what it names, then spawn again`,
53 rule: 'brief',
54 targets: [file.text],
55 why: found
56 ? 'the brief has no clean x brief check stamp for its current bytes'
57 : 'the brief file is missing',
58 };
59}
60hooks/rules/command.ts 262 lines1import type { Parsed, Sep, Word } from '../shell.ts';
2
3// a refusal names its door; an escape marker must name every one of its targets
4export type Refusal = {
5 rule: string;
6 why: string;
7 door: string;
8 targets: string[];
9};
10// what the rules read off the machine: the job's own dir, home, and the added paths found missing
11// kinds: what each written-over or trashed path found on disk is
12export type Context = {
13 jobDir?: string;
14 home?: string;
15 missing?: Set<string>;
16 kinds?: Map<string, 'file' | 'dir' | 'other'>;
17 briefs?: Map<string, Brief>;
18 // the session is cclio's: it cleans its fleet's scratch trees and branches on its own
19 isCclio?: boolean;
20 // the trees looked up and found safe to drop: no `.scratch/`, no commit only their HEAD reaches
21 cleanTrees?: Set<string>;
22 // the dirs whose working tree changed a package.json or pnpm-workspace.yaml since HEAD (FRM-393)
23 manifestDirs?: Set<string>;
24 // the backlog tasks a `--notes` edit names whose file already holds notes, keyed by notes.ts's notedKey
25 notedTasks?: Set<string>;
26};
27// a spawn's brief file as found on disk: whether it names the coder skill, and whether x brief check stamped its bytes
28export type Brief = { isCoder: boolean; isStamped: boolean };
29export type Verdict =
30 | { kind: 'run' }
31 | { kind: 'refused'; refusal: Refusal }
32 | { kind: 'escaped'; refusals: Refusal[]; targets: string[] };
33// wrappers: the peeled heads (`sudo`, `env`); writes: the targets of its `>` redirects; reads: of its `<`
34type Peeled = {
35 name: string;
36 args: Word[];
37 assigns: string[];
38 wrappers: string[];
39 writes: string[];
40 appends: string[];
41 reads: string[];
42 // where its stdout lands when redirected: `>`, `1>`, `&>` and their `>>`, `/dev/null` included
43 stdouts: string[];
44};
45// feeders: the commands whose output reaches this one, through `$( … )` or a pipe
46export type Command = Peeled & { sep: Sep; dir: string; feeders: Peeled[] };
47export const VAULT = 'iCloud~md~obsidian';
48// each wrapper, and its options that take the next word as their value
49const WRAPPERS = new Map<string, string[]>([
50 ['builtin', []],
51 ['command', []],
52 ['doas', ['-u']],
53 ['env', ['-u', '-C', '-S']],
54 ['exec', ['-a']],
55 ['nice', ['-n']],
56 ['nohup', []],
57 ['sudo', ['-u', '-g', '-U', '-C', '-h', '-p', '-r', '-t', '-D']],
58 ['time', []],
59 ['timeout', ['-s', '-k', '--signal', '--kill-after']],
60 ['xargs', ['-I', '-n', '-P', '-L', '-s', '-d', '-E', '-J', '-R']],
61]);
62const KEYWORDS = new Set([
63 'if',
64 'then',
65 'else',
66 'elif',
67 'do',
68 'while',
69 'until',
70 '!',
71 '{',
72 '}',
73]);
74export const SD_VALUE = new Set(['-n', '--max-replacements', '-f', '--flags']);
75const REDIRECT = /^\d*(>>?|<|&>>?)&?$/;
76const REDIRECT_JOINED = /^\d*(>>?|<|&>>?)&?\S/;
77export const basename = (p: string) => p.split('/').filter(Boolean).pop() ?? p;
78export const isFlag = (w: string) => w.startsWith('-') && w !== '-';
79// `-rf` holds f; a long flag is matched whole
80export function hasFlag(args: Word[], long: string[], short = '') {
81 return args.some(
82 ({ text: t }) =>
83 long.includes(t) ||
84 long.some((l) => t.startsWith(`${l}=`)) ||
85 (!!short &&
86 /^-[A-Za-z]+$/.test(t) &&
87 [...short].some((c) => t.includes(c))),
88 );
89}
90export function operands(args: Word[]) {
91 const out: string[] = [];
92 let isRest = false;
93 for (const { text } of args) {
94 if (isRest) out.push(text);
95 else if (text === '--') isRest = true;
96 else if (!isFlag(text)) out.push(text);
97 }
98 return out;
99}
100// a `>` that truncates its target; `>>` appends and `>&` names a descriptor
101const TRUNCATE = /^\d*&?>$/;
102const TRUNCATE_JOINED = /^\d*&?>([^>&].*)$/;
103const READ = /^\d*<$/;
104const READ_JOINED = /^\d*<([^<&>].*)$/;
105// the paths a redirect names, apart (`> f`) or joined (`>f`)
106function redirected(words: Word[], apart: RegExp, joined: RegExp) {
107 return words.flatMap((w, i) => {
108 const path = apart.test(w.text)
109 ? words[i + 1]?.text
110 : w.text.match(joined)?.[1];
111 return path ? [path] : [];
112 });
113}
114const writes = (words: Word[]) =>
115 redirected(words, TRUNCATE, TRUNCATE_JOINED).filter(
116 (to) => !to.startsWith('/dev/'),
117 );
118export const reads = (words: Word[]) => redirected(words, READ, READ_JOINED);
119const STDOUT = /^[1&]?>>?$/;
120const STDOUT_JOINED = /^[1&]?>>?([^>&].*)$/;
121const stdouts = (words: Word[]) => redirected(words, STDOUT, STDOUT_JOINED);
122function dropRedirects(words: Word[]) {
123 const out: Word[] = [];
124 for (let i = 0; i < words.length; i++) {
125 const t = words[i]?.text ?? '';
126 if (REDIRECT.test(t)) i++;
127 else if (!REDIRECT_JOINED.test(t)) out.push(words[i] as Word);
128 }
129 return out;
130}
131// a command with its assignments, shell keywords and wrappers peeled off
132export function peel(raw: Word[]): Peeled {
133 let words = dropRedirects(raw);
134 const assigns: string[] = [];
135 const wrappers: string[] = [];
136 for (;;) {
137 const head = words[0]?.text ?? '';
138 if (KEYWORDS.has(head)) {
139 words = words.slice(1);
140 continue;
141 }
142 if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(head)) {
143 assigns.push(head);
144 words = words.slice(1);
145 continue;
146 }
147 const values = WRAPPERS.get(basename(head));
148 if (!values) break;
149 wrappers.push(basename(head));
150 words = words.slice(1);
151 while (isFlag(words[0]?.text ?? '')) {
152 const flag = words[0]?.text ?? '';
153 words = words.slice(values.includes(flag) ? 2 : 1);
154 }
155 // timeout's duration
156 if (basename(head) === 'timeout') words = words.slice(1);
157 }
158 const [first, ...args] = words;
159 return {
160 appends: redirected(raw, APPEND, APPEND_JOINED),
161 args,
162 assigns,
163 name: first ? basename(first.text) : '',
164 reads: reads(raw),
165 stdouts: stdouts(raw),
166 wrappers,
167 writes: writes(raw),
168 };
169}
170// each segment as the command it runs, `cd` followed
171export function commands(parsed: Parsed, cwd: string): Command[] {
172 const out: Command[] = [];
173 let dir = cwd;
174 const peeled = parsed.segments.map((s) => ({ ...peel(s.words), s }));
175 peeled.forEach(({ s, ...c }, k) => {
176 if (!c.name) return;
177 const piped: Peeled[] = [];
178 for (let j = k - 1; j >= 0 && peeled[j]?.s.sep === '|'; j--)
179 piped.push(peeled[j] as Peeled);
180 const feeders = [...s.subst.map((x) => peel(x.words)), ...piped];
181 if (c.name === 'cd') {
182 const to = c.args[0]?.text ?? '~';
183 dir = /^[/~$]/.test(to) ? to : `${dir}/${to}`;
184 }
185 out.push({ ...c, dir, feeders, sep: s.sep });
186 });
187 return out;
188}
189// git's own options before the subcommand; `-c` values kept, since two of them are floor
190export function gitParts(args: Word[]) {
191 const configs: string[] = [];
192 let at: string | undefined;
193 let i = 0;
194 for (; i < args.length; i++) {
195 const t = args[i]?.text ?? '';
196 if (t === '-c') configs.push(args[++i]?.text ?? '');
197 else if (t === '-C') at = args[++i]?.text;
198 else if (t === '--git-dir' || t === '--work-tree') i++;
199 else if (!isFlag(t)) break;
200 }
201 return {
202 at,
203 configs,
204 sub: args[i]?.text ?? '',
205 subArgs: args.slice(i + 1),
206 };
207}
208export const or = (list: string[], fallback: string) =>
209 list.length ? list : [fallback];
210export const TRASH = 'trash <path> — recoverable from the macos trash';
211export const STASH =
212 'git stash -u — it sets the work aside and keeps it recoverable';
213// the one door that is a person: nothing safe does the job
214export const ASK = 'no safe door here — ask cclio, naming the target';
215export const NEVER =
216 'fix what the hook or the signer refused, then run it without the flag';
217export const LANE = 'x lane commit — it commits named paths only';
218// a path as the shell would land it: the job dir and ~ filled in, `.` and `..` walked; a path still holding a `$` stays unresolved
219export function resolve(path: string, dir: string, ctx: Context) {
220 const filled = path
221 .replace(
222 /^\$\{?CLAUDE_JOB_DIR\}?(?=\/|$)/,
223 ctx.jobDir ?? '$CLAUDE_JOB_DIR',
224 )
225 .replace(/^(~|\$\{?HOME\}?)(?=\/|$)/, ctx.home ?? '~');
226 const whole = filled.startsWith('/') ? filled : `${dir}/${filled}`;
227 const out: string[] = [];
228 for (const part of whole.split('/')) {
229 if (!part || part === '.') continue;
230 if (part === '..') out.pop();
231 else out.push(part);
232 }
233 return `/${out.join('/')}`;
234}
235// the dir a git command works in: its `-C`, else the dir its `cd`s left
236export function gitDir(c: Command, ctx: Context) {
237 const dir = resolve(c.dir, '/', ctx);
238 const { at } = gitParts(c.args);
239 return at === undefined ? dir : resolve(at, dir, ctx);
240}
241// a git add's pathspecs as typed and where they land; globs, magic and unexpanded words are git's to read
242export function adds(c: Command, ctx: Context) {
243 if (c.name !== 'git') return [];
244 const { sub, subArgs } = gitParts(c.args);
245 if (sub !== 'add') return [];
246 const dir = gitDir(c, ctx);
247 return operands(subArgs)
248 .filter((o) => !/[*?[$]/.test(o) && !o.startsWith(':'))
249 .map((text) => ({ path: resolve(text, dir, ctx), text }));
250}
251// a resolved path under the session's own `$CLAUDE_JOB_DIR/tmp`
252export function isJobTmp(path: string, ctx: Context) {
253 return (
254 !!ctx.jobDir &&
255 path.startsWith(`${resolve(`${ctx.jobDir}/tmp`, '/', ctx)}/`)
256 );
257}
258// every file a command writes, resolved: `>` and `>>` targets, `tee`, `sd` and `sed -i` files, python's `open(…, 'w')`.
259// x-mod-holds' files are checked against it; a path held in a variable is not read
260const APPEND = /^\d*&?>>$/;
261const APPEND_JOINED = /^\d*&?>>([^&].*)$/;
262hooks/rules/hazard.ts 175 lines1import { parse } from '../shell.ts';
2import {
3 ASK,
4 type Command,
5 type Context,
6 type Refusal,
7 VAULT,
8 commands,
9 hasFlag,
10 operands,
11 or,
12 resolve,
13} from './command.ts';
14
15// frame and bytes: the two repos `x lane push` serves
16export function isOwnRepo(dir: string, ctx: Context) {
17 if (!ctx.home) return false;
18 return [`${ctx.home}/frame`, `${ctx.home}/projects/bytes`].some(
19 (r) => dir === r || dir.startsWith(`${r}/`),
20 );
21}
22const ROOT_STEP = 'hand dima the step — these are his, in System Settings';
23const PRUNE = 'leave the prune to dima — name it in your report';
24const LINEAR = 'linear closes, never deletes — cancel it (state Canceled)';
25const DELETE = new Set(['delete', 'rm', 'remove']);
26// `~`, a dir above it, a dir right under it, or the obsidian vault root and above
27function isTopDir(path: string, ctx: Context) {
28 const home = ctx.home;
29 if (path === '/' || !home) return path === '/';
30 if (path === home || home.startsWith(`${path}/`)) return true;
31 if (path.slice(0, path.lastIndexOf('/')) === home) return true;
32 const parts = path.split('/');
33 const at = parts.indexOf(VAULT);
34 return at >= 0 && parts.length - at <= 3;
35}
36// what a `trash` would take, so lookUp can stat each: a regular file is never a top dir
37export function trashedPaths(command: string, cwd: string, ctx: Context = {}) {
38 return commands(parse(command), cwd).flatMap((c) =>
39 c.name === 'trash'
40 ? operands(c.args)
41 .filter((o) => !o.includes('$'))
42 .map((o) => resolve(o, resolve(c.dir, '/', ctx), ctx))
43 : [],
44 );
45}
46// past the floor: system state, prunes, remote deletes, a top dir or a whole defaults domain, and sudo
47export function hazard(c: Command, ctx: Context): Refusal | undefined {
48 const ops = operands(c.args);
49 const dir = resolve(c.dir, '/', ctx);
50 const system = (what: string, targets: string[], door = ASK): Refusal => ({
51 door,
52 rule: 'system',
53 targets,
54 why: `${what} changes the machine past undoing`,
55 });
56 if (c.name === 'diskutil' && /^erase/i.test(ops[0] ?? ''))
57 return system(`diskutil ${ops[0]}`, or(ops.slice(1), 'diskutil'));
58 const device = c.args.find(
59 (w) =>
60 w.text.startsWith('of=/dev/') &&
61 !/^of=\/dev\/(null|std)/.test(w.text),
62 );
63 if (c.name === 'dd' && device)
64 return system('dd onto a device', [device.text.slice(3)]);
65 if (/^(mkfs|newfs)/.test(c.name)) return system(c.name, or(ops, c.name));
66 if (
67 (c.name === 'chmod' || c.name === 'chown') &&
68 hasFlag(c.args, ['--recursive'], 'R')
69 ) {
70 const home = ops.filter((o) => {
71 const p = resolve(o, dir, ctx);
72 return (
73 p === '/' || p === ctx.home || !!ctx.home?.startsWith(`${p}/`)
74 );
75 });
76 if (home.length)
77 return system(
78 `${c.name} -R over home`,
79 home,
80 `${c.name} the one path you mean, never -R over ~`,
81 );
82 }
83 if (c.name === 'csrutil' && ops[0] && ops[0] !== 'status')
84 return system(`csrutil ${ops[0]}`, [ops[0]], ROOT_STEP);
85 const gatekeeper = c.args.find(
86 (w) => w.text === '--master-disable' || w.text === '--global-disable',
87 );
88 if (c.name === 'spctl' && gatekeeper)
89 return system('spctl', [gatekeeper.text], ROOT_STEP);
90 if (c.name === 'tccutil' && ops[0] === 'reset')
91 return system('tccutil reset', or(ops.slice(1), 'reset'), ROOT_STEP);
92
93 const prune = (what: string, target: string): Refusal => ({
94 door: PRUNE,
95 rule: 'prune',
96 targets: [target],
97 why: `${what} drops what dima may still want`,
98 });
99 if (c.name === 'brew' && ops[0] === 'cleanup')
100 return prune('brew cleanup', 'cleanup');
101 if (c.name === 'pnpm' && ops[0] === 'store' && ops[1] === 'prune')
102 return prune('pnpm store prune', 'prune');
103 if (c.name === 'docker' && ops[0] === 'system' && ops[1] === 'prune')
104 return prune('docker system prune', 'prune');
105 if (c.name === 'crontab' && hasFlag(c.args, [], 'r'))
106 return prune('crontab -r', '-r');
107
108 const remote = (what: string, targets: string[], door = ASK): Refusal => ({
109 door,
110 rule: 'remote-delete',
111 targets,
112 why: `${what} deletes on the remote, past any trash`,
113 });
114 if (
115 c.name === 'gh' &&
116 (ops[0] === 'repo' || ops[0] === 'release') &&
117 /^delete/.test(ops[1] ?? '')
118 )
119 return remote(`gh ${ops[0]} ${ops[1]}`, or(ops.slice(2), ops[0]));
120 const vercelAt = ops.slice(0, 2).findIndex((o) => DELETE.has(o));
121 if (c.name === 'vercel' && vercelAt >= 0)
122 return remote(
123 `vercel ${ops.slice(0, vercelAt + 1).join(' ')}`,
124 or(ops.slice(vercelAt + 1), 'vercel'),
125 );
126 if (c.name === 'op' && DELETE.has(ops[1] ?? ''))
127 return remote(`op ${ops[0]} ${ops[1]}`, or(ops.slice(2), 'op'));
128 if (c.name === 'security' && /^delete-/.test(ops[0] ?? ''))
129 return remote(`security ${ops[0]}`, [ops[0] ?? 'security']);
130 if (c.name === 'linear' && ops[0] === 'issue' && DELETE.has(ops[1] ?? ''))
131 return remote('linear issue delete', or(ops.slice(2), 'issue'), LINEAR);
132 if (
133 ['curl', 'linear', 'xh', 'http'].includes(c.name) &&
134 c.args.some((w) => /\bissueDelete\b/.test(w.text))
135 )
136 return remote('an issueDelete mutation', ['issueDelete'], LINEAR);
137
138 const top =
139 c.name === 'trash'
140 ? ops.filter((o) => {
141 if (o.includes('$')) return false;
142 const path = resolve(o, dir, ctx);
143 return ctx.kinds?.get(path) !== 'file' && isTopDir(path, ctx);
144 })
145 : [];
146 if (top.length)
147 return {
148 door: 'trash the files inside it, by name',
149 rule: 'top-dir',
150 targets: top,
151 why: 'trash of a top dir takes everything under it at once',
152 };
153 const isGlobal = hasFlag(c.args, ['-g', '-globalDomain']);
154 if (
155 c.name === 'defaults' &&
156 ops[0] === 'delete' &&
157 ops.length - 1 < (isGlobal ? 1 : 2)
158 )
159 return {
160 door: 'defaults delete <domain> <key> — one key, never the whole domain',
161 rule: 'top-dir',
162 targets: or(ops.slice(1), isGlobal ? '-g' : 'delete'),
163 why: 'defaults delete of a domain drops every preference the app has',
164 };
165 const root = c.wrappers.find((w) => w === 'sudo' || w === 'doas');
166 if (root)
167 return {
168 door: 'run it without sudo, or hand dima the command in a copy fence',
169 rule: 'sudo',
170 targets: [root],
171 why: `${root} changes system state as root`,
172 };
173 return undefined;
174}
175hooks/rules/hint.ts 209 lines1import { parse } from '../shell.ts';
2import {
3 type Command,
4 type Context,
5 commands,
6 gitDir,
7 gitParts,
8 hasFlag,
9 operands,
10 resolve,
11} from './command.ts';
12import { isOwnRepo } from './hazard.ts';
13import { writtenPaths } from './overwrite.ts';
14
15const PR_HINT =
16 'x-mod-guard hint: `x gh pr <n>` reads a pr — its checks and all three comment feeds, newest first — in one call';
17const LANE_HINT =
18 'x-mod-guard hint: `x lane commit <msg file> -- <paths>` formats and stages exactly those paths, then commits them';
19// gh's --jq runs gojq built into gh, not the system jq: a program proven with jq can read differently inside gh
20// (BYT-95/96 retros, FRM-394; was a fleet-hazards line)
21const JQ_HINT =
22 'x-mod-guard hint: `gh --jq` runs gojq, not jq — prove the program through gh itself, or pipe `gh --json …` into `jq`';
23// PK-67 (the 10-11 halt flush): a scripted replace into a repo file skips the format and hold hooks Edit fires (5 slips
24// on 10-11); zsh's echo reads backslash escapes inside json (two verifiers); `claude -p` in a `while read` loop eats the
25// loop's stdin (the 15:41 dima-caught)
26const EDIT_HINT =
27 'x-mod-guard hint: a hand edit to a repo file goes through `Edit` — it fires the format and hold hooks a scripted replace skips; a bulk change across many files may stay one script';
28const ECHO_JSON_HINT =
29 "x-mod-guard hint: zsh's `echo` reads `\\n` and other escapes inside json — print it with `printf '%s\\n'` or build it with `jq -n`";
30const LOOP_HINT =
31 "x-mod-guard hint: `claude -p` inside `while read` eats the loop's stdin — end it with `</dev/null`";
32// rg skips dot dirs: a «0 left» proof over frame missed 4 live pointers under home/.claude (PK-139, 2026-10-14)
33const RG_HINT =
34 'x-mod-guard hint: `rg` skips dot dirs like `home/.claude` — add `--hidden` when the search must reach them';
35// rg's options that take the next word, and the ones that carry the pattern so no positional one comes first
36const RG_VALUE = new Set([
37 '-e',
38 '--regexp',
39 '-f',
40 '--file',
41 '-g',
42 '--glob',
43 '--iglob',
44 '-t',
45 '--type',
46 '-T',
47 '--type-not',
48 '-A',
49 '-B',
50 '-C',
51 '--after-context',
52 '--before-context',
53 '--context',
54 '-m',
55 '--max-count',
56 '--max-depth',
57 '-d',
58 '-r',
59 '--replace',
60 '-M',
61 '--max-columns',
62 '-j',
63 '--threads',
64 '--sort',
65 '--sortr',
66 '--encoding',
67 '-E',
68]);
69const RG_PATTERN = new Set(['-e', '--regexp', '-f', '--file']);
70function rgPaths(args: Command['args']) {
71 const words: string[] = [];
72 let isPatternGiven = false;
73 let isRest = false;
74 for (let i = 0; i < args.length; i++) {
75 const t = args[i]?.text ?? '';
76 if (isRest || !t.startsWith('-')) words.push(t);
77 else if (t === '--') isRest = true;
78 else if (RG_VALUE.has(t)) {
79 isPatternGiven ||= RG_PATTERN.has(t);
80 i++;
81 } else if (/^--(regexp|file)=/.test(t)) isPatternGiven = true;
82 }
83 return isPatternGiven ? words : words.slice(1);
84}
85// an rg rooted where dot dirs live below it (frame, frame/home, ~): a path naming a dot dir outright is searched
86function rgMissesDots(c: Command, ctx: Context) {
87 if (
88 hasFlag(c.args, ['--hidden'], '.') ||
89 c.args.some((w) => /^-u{2,}$/.test(w.text))
90 )
91 return false;
92 const dir = resolve(c.dir, '/', ctx);
93 const paths = rgPaths(c.args);
94 // no path and a pipe or a $( ) feeding it: rg reads stdin and searches no folder
95 if (!paths.length && c.feeders.length) return false;
96 const roots = paths.length ? paths.map((p) => resolve(p, dir, ctx)) : [dir];
97 const frame = `${ctx.home}/frame`;
98 return roots.some(
99 (r) => r === frame || r === `${frame}/home` || r === ctx.home,
100 );
101}
102const REPLACERS = new Set(['sd', 'sed', 'python', 'python3']);
103const isJsonish = (text: string) => /^\s*[[{].*["\\]/s.test(text);
104const isGhJq = (args: Command['args']) =>
105 args.some(
106 (w) =>
107 w.text === '--jq' || w.text.startsWith('--jq=') || w.text === '-q',
108 );
109const PULLS = /(^|\/)pulls(\/|$|\?)/;
110// a gh api call with a body or a method other than GET writes, and x gh pr covers only reads
111function isPullsRead(args: Command['args']) {
112 const method = args.findIndex(
113 (w) => w.text === '-X' || w.text === '--method',
114 );
115 const isGet = method < 0 || args[method + 1]?.text.toUpperCase() === 'GET';
116 return (
117 isGet &&
118 !hasFlag(args, ['--field', '--raw-field', '--input'], 'fF') &&
119 operands(args).some((o) => PULLS.test(o))
120 );
121}
122// a hint, never a rewrite: the raw command runs as typed, one context line names the x verb that covers it
123export function hints(command: string, cwd: string, ctx: Context) {
124 const found = new Set<string>();
125 const all = commands(parse(command), cwd);
126 if (
127 all.some((c) => REPLACERS.has(c.name)) &&
128 writtenPaths(command, cwd, ctx).some((p) => isOwnRepo(p, ctx))
129 )
130 found.add(EDIT_HINT);
131 if (
132 /\bwhile\b[^;\n]*\bread\b/.test(command) &&
133 all.some(
134 (c) =>
135 c.name === 'claude' &&
136 c.args.some((w) => w.text === '-p' || w.text === '--print'),
137 ) &&
138 !/<\s*\/dev\/null/.test(command)
139 )
140 found.add(LOOP_HINT);
141 for (const c of all) {
142 if (c.name === 'echo' && operands(c.args).some(isJsonish))
143 found.add(ECHO_JSON_HINT);
144 const [sub, verb] = c.args.map((w) => w.text);
145 if (
146 c.name === 'gh' &&
147 ((sub === 'pr' && (verb === 'view' || verb === 'checks')) ||
148 (sub === 'api' && isPullsRead(c.args.slice(1))))
149 )
150 found.add(PR_HINT);
151 if (c.name === 'gh' && isGhJq(c.args)) found.add(JQ_HINT);
152 if (c.name === 'rg' && ctx.home && rgMissesDots(c, ctx))
153 found.add(RG_HINT);
154 if (c.name === 'git') {
155 const git = gitParts(c.args).sub;
156 if (
157 (git === 'add' || git === 'commit') &&
158 isOwnRepo(gitDir(c, ctx), ctx)
159 )
160 found.add(LANE_HINT);
161 }
162 }
163 return [...found];
164}
165
166// the shapes a command runs, `name first-operand`, for the slow-call memory: the quick readers and shell glue carry
167// none, so a slow `go test ./...` is remembered and the `cd` in front of it is not
168const QUICK = new Set([
169 'cd',
170 'echo',
171 'printf',
172 'cat',
173 'ls',
174 'head',
175 'tail',
176 'rg',
177 'grep',
178 'jq',
179 'sed',
180 'awk',
181 'tee',
182 'true',
183 'test',
184 'wc',
185 'sort',
186 'uniq',
187 'cut',
188 'tr',
189 'export',
190 'set',
191 'sleep',
192 'date',
193 'trash',
194 'mkdir',
195 'cp',
196 'mv',
197]);
198export function slowShapes(command: string, cwd: string) {
199 const shapes = new Set<string>();
200 for (const c of commands(parse(command), cwd)) {
201 if (!c.name || QUICK.has(c.name)) continue;
202 const first = operands(c.args)[0];
203 shapes.add(first ? `${c.name} ${first}` : c.name);
204 }
205 return [...shapes];
206}
207export const slowHint = (shape: string, seconds: number) =>
208 `x-mod-guard hint: \`${shape}\` held the foreground ${seconds} s last time — run it with run_in_background: true and keep working until it notifies`;
209hooks/rules/notes.ts 55 lines1import { parse } from '../shell.ts';
2import {
3 type Command,
4 type Context,
5 type Refusal,
6 commands,
7 hasFlag,
8 operands,
9 resolve,
10} from './command.ts';
11
12// `backlog task edit <id> --notes` replaces the task's notes whole, so a note already there is wiped without a word
13// (PK-150); `--append-notes` keeps it
14export type NotesEdit = { id: string; root: string };
15
16function notesEdit(c: Command, ctx: Context): NotesEdit | undefined {
17 const [verb, sub, id] = operands(c.args);
18 if (c.name !== 'backlog' || verb !== 'task' || sub !== 'edit' || !id)
19 return undefined;
20 if (!hasFlag(c.args, ['--notes'])) return undefined;
21 const cwd = c.assigns
22 .find((a) => a.startsWith('BACKLOG_CWD='))
23 ?.slice('BACKLOG_CWD='.length);
24 const dir = resolve(c.dir, '/', ctx);
25 return { id, root: cwd ? resolve(cwd, dir, ctx) : dir };
26}
27
28// what lookUp reads off disk for each edit: the key the rule finds in ctx.notedTasks
29export const notedKey = (e: NotesEdit) => `${e.root}\n${e.id.toLowerCase()}`;
30
31export function notesEdits(command: string, cwd: string, ctx: Context = {}) {
32 return commands(parse(command), cwd).flatMap((c) => {
33 const e = notesEdit(c, ctx);
34 return e ? [e] : [];
35 });
36}
37
38// a task file's notes block holds text
39export function hasNotes(task: string) {
40 return /<!-- SECTION:NOTES:BEGIN -->\s*(?!<!-- SECTION:NOTES:END -->)\S/.test(
41 task,
42 );
43}
44
45export function notes(c: Command, ctx: Context): Refusal | undefined {
46 const e = notesEdit(c, ctx);
47 if (!e || !ctx.notedTasks?.has(notedKey(e))) return undefined;
48 return {
49 door: `backlog task edit ${e.id} --append-notes <text>`,
50 rule: 'notes-replace',
51 targets: ['--notes'],
52 why: `--notes replaces the notes ${e.id} already holds, a silent wipe`,
53 };
54}
55hooks/rules/overwrite.ts 139 lines1import { type Word, parse } from '../shell.ts';
2import {
3 type Command,
4 type Context,
5 type Refusal,
6 SD_VALUE,
7 basename,
8 commands,
9 hasFlag,
10 isFlag,
11 isJobTmp,
12 operands,
13 or,
14 resolve,
15} from './command.ts';
16
17// an mv or cp's dest, then the file each source lands on when that dest is a dir
18export function landings(c: Command, ctx: Context) {
19 const ops = operands(c.args);
20 const dest = ops.at(-1);
21 if (ops.length < 2 || dest === undefined) return [];
22 const to = resolve(dest, resolve(c.dir, '/', ctx), ctx);
23 return [
24 { path: to, text: dest },
25 ...ops
26 .slice(0, -1)
27 .map((src) => ({ path: `${to}/${basename(src)}`, text: dest })),
28 ];
29}
30// the paths a command may write over, for the caller to look up on disk
31export function overwrittenPaths(
32 command: string,
33 cwd: string,
34 ctx: Context = {},
35) {
36 return commands(parse(command), cwd).flatMap((c) => {
37 const dir = resolve(c.dir, '/', ctx);
38 const moved =
39 c.name === 'mv' || c.name === 'cp'
40 ? landings(c, ctx).map((l) => l.path)
41 : [];
42 return [...c.writes.map((w) => resolve(w, dir, ctx)), ...moved];
43 });
44}
45export function writtenPaths(command: string, cwd: string, ctx: Context = {}) {
46 const out: string[] = [];
47 for (const m of command.matchAll(
48 /open\(\s*['"]([^'"]+)['"]\s*,\s*['"][wax]/g,
49 ))
50 if (m[1]) out.push(resolve(m[1], cwd, ctx));
51 const parsed = parse(command);
52 for (const c of commands(parsed, cwd)) {
53 const dir = resolve(c.dir, '/', ctx);
54 const named = [...c.writes, ...c.appends];
55 const ops = operands(c.args);
56 if (c.name === 'tee') named.push(...ops);
57 if (c.name === 'sd') named.push(...sdFiles(c.args));
58 if (c.name === 'sed') named.push(...sedFiles(c.args));
59 for (const n of named)
60 if (n && !n.startsWith('/dev/') && !n.includes('$'))
61 out.push(resolve(n, dir, ctx));
62 }
63 return [...new Set(out)];
64}
65// sd's files follow its find and replace; a flag in SD_VALUE eats the word after it
66function sdFiles(args: Word[]) {
67 const out: string[] = [];
68 let isRest = false;
69 for (let i = 0; i < args.length; i++) {
70 const t = args[i]?.text ?? '';
71 if (isRest) out.push(t);
72 else if (t === '--') isRest = true;
73 else if (SD_VALUE.has(t)) i++;
74 else if (!isFlag(t)) out.push(t);
75 }
76 return out.slice(2);
77}
78// sed edits in place only with -i; macOS spells it `-i ''`, and -e or -f carries the script
79function sedFiles(args: Word[]) {
80 if (!args.some((a) => /^(-i|--in-place)/.test(a.text))) return [];
81 const kept = args.filter(
82 (a, i) => !(a.text === '' && args[i - 1]?.text === '-i'),
83 );
84 const isScripted = kept.some((a) => /^-[ef]$/.test(a.text));
85 const files: string[] = [];
86 for (let i = 0; i < kept.length; i++) {
87 const t = kept[i]?.text ?? '';
88 if (/^-[ef]$/.test(t)) i++;
89 else if (!isFlag(t)) files.push(t);
90 }
91 return isScripted ? files : files.slice(1);
92}
93// the file a `>`, an mv, a cp -f or a cp /dev/null would empty or replace; the job's own tmp is its scratch to write over
94// a claude session's own scratchpad holds only what that session wrote (PK-138: 8 refusals in 14 days, and the >>
95// workaround glued two commit messages)
96const SCRATCHPAD =
97 /^(\/private)?\/tmp\/claude-\d+\/[^/]+\/[0-9a-f-]{36}\/scratchpad\/[^/]/;
98export function overwrite(c: Command, ctx: Context): Refusal | undefined {
99 const dir = resolve(c.dir, '/', ctx);
100 const isFile = (p: string) =>
101 ctx.kinds?.get(p) === 'file' &&
102 !isJobTmp(p, ctx) &&
103 !SCRATCHPAD.test(p);
104 const written = c.writes.filter((w) => isFile(resolve(w, dir, ctx)));
105 if (written.length)
106 return {
107 door: '>> to append, a new path, or the Write tool after reading the file',
108 rule: 'overwrite',
109 targets: written,
110 why: 'a > redirect empties the file before the command runs',
111 };
112 const isNull = c.name === 'cp' && operands(c.args)[0] === '/dev/null';
113 const isForced =
114 c.name === 'mv' ||
115 (c.name === 'cp' && hasFlag(c.args, ['--force'], 'f'));
116 const isKept = hasFlag(c.args, ['--no-clobber'], 'ni');
117 if (!(isNull || isForced) || isKept) return undefined;
118 const [to, ...into] = landings(c, ctx);
119 if (!to) return undefined;
120 if (
121 !isFile(to.path) &&
122 !(ctx.kinds?.get(to.path) === 'dir' && into.some((l) => isFile(l.path)))
123 )
124 return undefined;
125 if (isNull)
126 return {
127 door: 'the Write tool after reading the file',
128 rule: 'overwrite',
129 targets: [to.text],
130 why: 'cp /dev/null empties the file',
131 };
132 return {
133 door: `${c.name} -n, or trash the old file first`,
134 rule: 'overwrite',
135 targets: [to.text],
136 why: `${c.name} replaces the file already there, silently`,
137 };
138}
139hooks/rules/rewrite.ts 89 lines1import { type Segment, type Word, parse } from '../shell.ts';
2import { peel } from './command.ts';
3
4// zsh reads `[[ a == b ]]`'s operator as syntax, never as a path
5const TEST_OPERATORS = new Set(['=', '==', '=~']);
6type Edit = { at: number; from: string; to: string; why: string };
7// a shape with one right spelling, fixed in place: `pnpm -s` and an unquoted `=`-led word
8export function edits(segments: Segment[]): Edit[] {
9 return segments.flatMap((s) => {
10 const isTest = s.words[0]?.text === '[[';
11 const peeled = peel(s.words);
12 const end = peeled.args.findIndex((w) => w.text === '--');
13 const pnpmFlags =
14 peeled.name === 'pnpm'
15 ? peeled.args.slice(0, end < 0 ? undefined : end)
16 : [];
17 const own = s.words.flatMap((w): Edit[] => {
18 if (w.at === undefined) return [];
19 if (w.text === '-s' && pnpmFlags.includes(w))
20 return [
21 {
22 at: w.at,
23 from: w.text,
24 to: '--silent',
25 why: 'pnpm 12 reads -s as --sequential',
26 },
27 ];
28 // `--include=*.ts` matches no file, so zsh's NOMATCH aborts the command before grep sees it
29 if (/^--?[A-Za-z][\w-]*=.*[*?[]/.test(w.text))
30 return [
31 {
32 at: w.at,
33 from: w.text,
34 to: `'${w.text}'`,
35 why: 'zsh aborts on an option glob that matches no file',
36 },
37 ];
38 if (
39 w.text.startsWith('=') &&
40 w.text !== '=' &&
41 !(isTest && TEST_OPERATORS.has(w.text))
42 )
43 return [
44 {
45 at: w.at,
46 from: w.text,
47 to: `'${w.text}'`,
48 why: 'zsh reads an unquoted =word as a command path',
49 },
50 ];
51 return [];
52 });
53 // a raw `linear api` skips x's actor, its id resolution and its trace (FRM-370); the head word becomes
54 // `x linear`, so a quoted string, a heredoc body or `x as <member> -- linear api` is never one
55 const head = s.words[s.words.indexOf(peeled.args[0] as Word) - 1];
56 const viaX =
57 peeled.name === 'linear' &&
58 peeled.args[0]?.text === 'api' &&
59 head?.at !== undefined
60 ? [
61 {
62 at: head.at,
63 from: head.text,
64 to: 'x linear',
65 why: "a raw linear api skips x's actor, ids and trace",
66 },
67 ]
68 : [];
69 return [...own, ...viaX, ...edits(s.subst)];
70 });
71}
72export function rewrite(command: string) {
73 // a `$( … )`'s commands are segments of their own and of the word's subst: one edit per offset
74 const found = [
75 ...new Map(
76 edits(parse(command).segments).map((e) => [e.at, e]),
77 ).values(),
78 ].sort((a, b) => b.at - a.at);
79 let out = command;
80 for (const e of found)
81 out = out.slice(0, e.at) + e.to + out.slice(e.at + e.from.length);
82 return {
83 command: out,
84 notes: found
85 .reverse()
86 .map((e) => `\`${e.from}\` → \`${e.to}\` (${e.why})`),
87 };
88}
89hooks/rules/spec.ts 24 lines1// a coder's job of 3+ numbered items goes through a spec (cclio:shape-lane-dispatch § 6); a list in a «>» quote or a code fence
2// is someone's words, never the job — an item starts its line, so a quoted one never counts
3const TO_CODER = /🔧|\bcoder\b/i;
4const SPEC_PATH = /\.scratch\/[^\s/]+\/spec\.md\b/;
5const ITEM = /^\s*\d{1,2}[.)]\s+\S/;
6const FENCE = /^\s*(```|~~~)/;
7const ITEMS_MIN = 3;
8
9export const SPEC_WHY =
10 'a 3+-item job goes through a spec (cclio:shape-lane-dispatch § 6)';
11export const SPEC_DOOR =
12 'write the job to .scratch/<feature>/spec.md and send its path';
13
14export function isSpecMissing(to: string, message: string) {
15 if (!TO_CODER.test(to) || SPEC_PATH.test(message)) return false;
16 let isFenced = false;
17 let items = 0;
18 for (const line of message.split('\n')) {
19 if (FENCE.test(line)) isFenced = !isFenced;
20 else if (!isFenced && ITEM.test(line)) items++;
21 }
22 return items >= ITEMS_MIN;
23}
24hooks/rules.ts 320 lines1import { brief } from './rules/brief.ts';
2import {
3 type Command,
4 type Context,
5 type Refusal,
6 type Verdict,
7 adds,
8 commands,
9 gitDir,
10 gitParts,
11 hasFlag,
12 isJobTmp,
13 operands,
14 resolve,
15} from './rules/command.ts';
16import { floor } from './rules/floor.ts';
17import { hazard } from './rules/hazard.ts';
18import { background, lint, unbraced } from './rules/lint.ts';
19import { frozenInstallDirs, lockfile } from './rules/lockfile.ts';
20import { notes } from './rules/notes.ts';
21import { landings, overwrite } from './rules/overwrite.ts';
22import { parse } from './shell.ts';
23
24const SHELLS = new Set(['sh', 'bash', 'zsh']);
25// the paths every git add in the command names, for the caller to look up on disk; a path an earlier part of the
26// same command makes (a > redirect, touch, mkdir, a cp or mv dest) is there by the time the add runs
27export function addedPaths(command: string, cwd: string, ctx: Context = {}) {
28 const made = new Set<string>();
29 return commands(parse(command), cwd).flatMap((c) => {
30 const added = adds(c, ctx)
31 .map((a) => a.path)
32 .filter((p) => !made.has(p));
33 const dir = resolve(c.dir, '/', ctx);
34 for (const w of c.writes) made.add(resolve(w, dir, ctx));
35 if (c.name === 'touch' || c.name === 'mkdir')
36 for (const o of operands(c.args)) made.add(resolve(o, dir, ctx));
37 if (c.name === 'cp' || c.name === 'mv')
38 for (const l of landings(c, ctx)) made.add(l.path);
39 return added;
40 });
41}
42function missingAdd(c: Command, ctx: Context): Refusal | undefined {
43 const gone = adds(c, ctx).filter((a) => ctx.missing?.has(a.path));
44 if (!gone.length) return undefined;
45 return {
46 door: 'stage only paths that exist; a deleted file stages with git rm <path>',
47 rule: 'git-add-missing',
48 targets: gone.map((a) => a.text),
49 why: 'git add of a missing path stages nothing and the commit lands partial',
50 };
51}
52// the os temp roots: a throwaway repo from `mktemp -d` lands under /var/folders, a hand-made fixture under /tmp
53const TEMP_ROOTS = [
54 '/tmp/',
55 '/private/tmp/',
56 '/var/folders/',
57 '/private/var/folders/',
58];
59// a scratch clone under the job's own tmp or an os temp root: everything its local git does stays there; a push or a
60// skipped hook does not
61const LOCAL_GIT = new Set(['git-discard', 'git-rewrite', 'git-sweep']);
62function isScratchGit(c: Command, r: Refusal, ctx: Context) {
63 if (c.name !== 'git' || !LOCAL_GIT.has(r.rule)) return false;
64 const { sub, subArgs } = gitParts(c.args);
65 if (sub === 'push') return false;
66 const dir = gitDir(c, ctx);
67 const paths = [dir, ...operands(subArgs).map((o) => resolve(o, dir, ctx))];
68 return paths.every(
69 (p) =>
70 isJobTmp(p, ctx) || TEMP_ROOTS.some((root) => p.startsWith(root)),
71 );
72}
73// cclio removes a scratch tree (a clean one: --force still asks) and deletes a scratch/* branch without dima's word;
74// a merged branch's `git branch -d` already runs for everyone, since git itself refuses an unmerged one
75const SCRATCH_TREE = /\/\.claude\/(worktrees\/[^/]+|jobs\/[^/]+\/tmp\/.+)$/;
76// the scratch trees a cclio `git worktree remove` names, for the caller to look up; a tree elsewhere asks anyway
77export function removedTrees(command: string, cwd: string, ctx: Context = {}) {
78 if (!ctx.isCclio) return [];
79 return commands(parse(command), cwd).flatMap((c) => {
80 if (c.name !== 'git') return [];
81 const { sub, subArgs } = gitParts(c.args);
82 const ops = operands(subArgs);
83 if (sub !== 'worktree' || ops[0] !== 'remove') return [];
84 const dir = gitDir(c, ctx);
85 return ops
86 .slice(1)
87 .map((t) => resolve(t, dir, ctx))
88 .filter((t) => SCRATCH_TREE.test(t));
89 });
90}
91function isCleanup(c: Command, r: Refusal, ctx: Context) {
92 if (!ctx.isCclio || c.name !== 'git' || r.rule !== 'git-rewrite')
93 return false;
94 const { sub, subArgs } = gitParts(c.args);
95 const ops = operands(subArgs);
96 if (sub === 'branch')
97 return ops.length > 0 && ops.every((o) => o.startsWith('scratch/'));
98 if (sub !== 'worktree' || ops[0] !== 'remove') return false;
99 if (hasFlag(subArgs, ['--force'], 'f')) return false;
100 const dir = gitDir(c, ctx);
101 const trees = ops.slice(1).map((t) => resolve(t, dir, ctx));
102 // a tree never looked up, or holding a `.scratch/` plan or commits only its HEAD reaches, asks
103 return (
104 trees.length > 0 &&
105 trees.every((t) => SCRATCH_TREE.test(t) && ctx.cleanTrees?.has(t))
106 );
107}
108export function refusals(
109 command: string,
110 cwd: string,
111 ctx: Context = {},
112): Refusal[] {
113 const parsed = parse(command);
114 const list = commands(parsed, cwd);
115 const out: Refusal[] = [];
116 list.forEach((c, i) => {
117 const found =
118 floor(c, ctx) ??
119 hazard(c, ctx) ??
120 lockfile(c, ctx) ??
121 overwrite(c, ctx) ??
122 lint(c, list[i + 1]) ??
123 missingAdd(c, ctx) ??
124 brief(c, ctx) ??
125 notes(c, ctx);
126 if (found && !isScratchGit(c, found, ctx) && !isCleanup(c, found, ctx))
127 out.push(found);
128 // a nested shell's script is a command too
129 // `-c` alone or in a cluster: `bash -lc`
130 const dashC = SHELLS.has(c.name)
131 ? c.args.findIndex((w) => /^-[A-Za-z]*c[A-Za-z]*$/.test(w.text))
132 : -1;
133 const script = dashC >= 0 ? c.args[dashC + 1] : undefined;
134 if (script) out.push(...refusals(script.text, c.dir, ctx));
135 if (c.name === 'eval')
136 out.push(
137 ...refusals(c.args.map((w) => w.text).join(' '), c.dir, ctx),
138 );
139 });
140 for (const r of [background(list), unbraced(parsed)]) if (r) out.push(r);
141 // one line per rule and target: a lint seen on every command of a pipeline is one finding
142 return out.filter(
143 (r, i) =>
144 out.findIndex(
145 (o) =>
146 o.rule === r.rule && o.targets.join() === r.targets.join(),
147 ) === i,
148 );
149}
150// a target dima named as a whole word: each edge is the prompt's end, a space, a quote (his «», ios “” included),
151// punctuation or a dash; a `.` or `/` closes it only before a space or the end (`build.`, `/x/build/`).
152// a target of bare symbols (`.`, `&`) reads in any prose, so it counts only inside the marker phrase he pastes
153const EDGE = /[\s"'`,;:!?()[\]<>«»“”‘’—–]/;
154const CLOSER = /[./]/;
155export function namesWhole(said: string, target: string) {
156 if (!/[\p{L}\p{N}]/u.test(target))
157 return namesWhole(said, `dima-ok: ${target}`);
158 for (
159 let i = said.indexOf(target);
160 i >= 0;
161 i = said.indexOf(target, i + 1)
162 ) {
163 const before = said[i - 1];
164 const end = i + target.length;
165 const after = said[end];
166 const isStart = before === undefined || EDGE.test(before);
167 const isEnd =
168 after === undefined ||
169 EDGE.test(after) ||
170 (CLOSER.test(after) &&
171 (end + 1 === said.length || /\s/.test(said[end + 1] ?? '')));
172 if (isStart && isEnd) return true;
173 }
174 return false;
175}
176export function markers(command: string) {
177 return parse(command)
178 .comments.map((c) => c.match(/^\s*dima-ok:\s*(.+?)\s*$/)?.[1])
179 .filter((t): t is string => !!t);
180}
181export function check(
182 command: string,
183 cwd: string,
184 ctx: Context = {},
185): Verdict {
186 const found = refusals(command, cwd, ctx);
187 if (!found.length) return { kind: 'run' };
188 const marked = markers(command);
189 // a marker names one target, or several split by spaces or commas; every target of a refusal must be named
190 const ok = new Set(marked.flatMap((m) => [m, ...m.split(/[\s,]+/)]));
191 const open = found.find((r) => !r.targets.every((t) => ok.has(t)));
192 if (open) return { kind: 'refused', refusal: open };
193 return { kind: 'escaped', refusals: found, targets: marked };
194}
195export function message(r: Refusal) {
196 return `nothing in this command ran — x-mod-guard stopped this one command. instead: ${r.door}. why: ${r.why}. only after dima's word, end the command with # dima-ok: ${r.targets.join(' ')}`;
197}
198
199// the dirs a `CI=1 pnpm install` in this command runs in, for the caller to check for a changed manifest
200export function installDirs(command: string, cwd: string, ctx: Context = {}) {
201 return frozenInstallDirs(commands(parse(command), cwd), ctx);
202}
203
204// a foreground `claude -p` holds the session's thread until it ends: a probe of eight runs blocked cclio for 3 minutes
205// (dima's o102, FRM-395); `# fg-ok: <why>` lets a real need through, and a background run is never judged
206export function foregroundClaude(
207 command: string,
208 cwd: string,
209): Refusal | undefined {
210 const parsed = parse(command);
211 if (parsed.comments.some((c) => /^\s*fg-ok:\s*\S/.test(c)))
212 return undefined;
213 const isClaudeP = commands(parsed, cwd).some(
214 (c) =>
215 c.name === 'claude' &&
216 c.args.some((w) => w.text === '-p' || w.text === '--print'),
217 );
218 if (!isClaudeP) return undefined;
219 return {
220 door: 'run the same command with run_in_background: true, or end it with # fg-ok: <why> for a real need',
221 rule: 'foreground-claude',
222 targets: ['claude -p'],
223 why: 'a foreground claude -p holds this session until it ends',
224 };
225}
226
227// a plugin's cache moves through x plugin bump, never a raw update: 36 raw update calls in 14 days, while the bump also
228// reads the cache back (FRM-389 exit 7, dima's o33); every session, cclio's included
229export function rawPluginUpdate(
230 command: string,
231 cwd: string,
232): Refusal | undefined {
233 for (const c of commands(parse(command), cwd)) {
234 if (c.name !== 'claude') continue;
235 const [a, b, d] = c.args.map((w) => w.text);
236 if (a !== 'plugin') continue;
237 const isUpdate =
238 b === 'update' || (b === 'marketplace' && d === 'update');
239 if (!isUpdate) continue;
240 return {
241 door: 'x plugin bump --apply <plugin>',
242 rule: 'raw-plugin-update',
243 targets: [
244 b === 'update'
245 ? 'claude plugin update'
246 : 'claude plugin marketplace update',
247 ],
248 why: 'x plugin bump bumps, updates the marketplace and the plugin, and reads the cache back in one call (FRM-345)',
249 };
250 }
251 return undefined;
252}
253
254// x lane merge-auto trusts a --dima-ok <pr> that reached it, so this is the proof: dima's own last prompt names the pr
255// (FRM-423 o140, the guard's door); the caller checks the prompt
256export function mergeWord(command: string, cwd: string): Refusal | undefined {
257 for (const c of commands(parse(command), cwd)) {
258 const words = c.args.map((w) => w.text);
259 // a nested shell's script, or an eval's words, is a command too
260 const dashC = SHELLS.has(c.name)
261 ? words.findIndex((w) => /^-[A-Za-z]*c[A-Za-z]*$/.test(w))
262 : -1;
263 const nested =
264 dashC >= 0
265 ? words[dashC + 1]
266 : c.name === 'eval'
267 ? words.join(' ')
268 : undefined;
269 const inner = nested ? mergeWord(nested, c.dir) : undefined;
270 if (inner) return inner;
271 // x's root booleans (--json, --board) sit before the family or between it and the verb
272 const bare = words.filter((w) => !w.startsWith('-'));
273 const isMerge = bare.some(
274 (w, i) => w === 'lane' && bare[i + 1] === 'merge-auto',
275 );
276 if (c.name !== 'x' || !isMerge) continue;
277 const targets = words.flatMap((w, i) =>
278 w === '--dima-ok'
279 ? [words[i + 1] ?? '']
280 : w.startsWith('--dima-ok=')
281 ? [w.slice('--dima-ok='.length)]
282 : [],
283 );
284 if (!targets.length) continue;
285 return {
286 door: "ask dima; his own next prompt naming the pr (104 or #104) lets merge-auto's --dima-ok through. a bg session counts only what dima types into it himself",
287 rule: 'dima-ok-flag',
288 targets,
289 why: "merge-auto's --dima-ok stands for dima's word on a self-edit, and counts only when his last typed prompt names the pr",
290 };
291 }
292 return undefined;
293}
294
295// a member reads and comments on tickets through x linear, never the raw cli (FRM-398, rules-lazy/linear-flow.md);
296// cclio's own session is never asked, the caller checks the registry name
297export function rawLinear(command: string, cwd: string): Refusal | undefined {
298 for (const c of commands(parse(command), cwd)) {
299 if (c.name !== 'linear') continue;
300 const [a, b, d] = c.args.map((w) => w.text);
301 const isComment = a === 'issue' && b === 'comment' && d === 'add';
302 const isRead = (a === 'issue' && b === 'view') || a === 'api';
303 if (!isComment && !isRead) continue;
304 return isComment
305 ? {
306 door: 'x linear comment <id> --body-file <file>',
307 rule: 'raw-linear',
308 targets: ['linear issue comment add'],
309 why: "a member's one linear write is its done comment, through x linear (rules-lazy/linear-flow.md)",
310 }
311 : {
312 door: 'x linear read <id> --comments --relations',
313 rule: 'raw-linear',
314 targets: [a === 'api' ? 'linear api' : 'linear issue view'],
315 why: 'a member reads tickets through x linear, the whole ticket in one call (rules-lazy/linear-flow.md)',
316 };
317 }
318 return undefined;
319}
320hooks/shell.ts 303 lines1// a small reading of a shell command: enough to name each simple command, its words and what joins them.
2// quoted text, heredoc bodies and comments are never read as commands; a `$( … )` or a backtick pair is read as a command of its own.
3
4// at: the word's offset in the command, kept only for a bare word — plain characters, no quote, escape or expansion
5// hasQuote: some of the word sat in quotes or behind a backslash, so the shell neither splits nor globs that part
6export type Word = {
7 text: string;
8 isExpanding: boolean;
9 at?: number;
10 hasQuote?: boolean;
11};
12export type Sep = ';' | '&&' | '||' | '|' | '&' | '(' | ')';
13// subst: the commands inside this command's `$( … )` and backticks
14export type Segment = { words: Word[]; sep: Sep; subst: Segment[] };
15export type Parsed = {
16 segments: Segment[];
17 comments: string[];
18 unbraced: string[];
19};
20
21type Frame = {
22 kind: 'dq' | 'subst' | 'group' | 'tick';
23 words: Word[];
24 subst: Segment[];
25 text: string;
26 isWord: boolean;
27 isExpanding: boolean;
28 isBare: boolean;
29 hasQuote: boolean;
30 at: number;
31 from: number;
32};
33
34// a `$` the shell expands: a name, a digit, `{`, `(` or a special parameter
35const EXPANDS = /[A-Za-z0-9_{(@*#?!$-]/;
36const NAME = /[A-Za-z_][A-Za-z0-9_]*/y;
37
38export function parse(command: string): Parsed {
39 const segments: Segment[] = [];
40 const comments: string[] = [];
41 const unbraced: string[] = [];
42 const heredocs: string[] = [];
43 const stack: Frame[] = [];
44 let words: Word[] = [];
45 let subst: Segment[] = [];
46 let text = '';
47 let isWord = false;
48 let isExpanding = false;
49 let isQuoted = false;
50 let isBare = false;
51 let hasQuote = false;
52 let at = 0;
53 let i = 0;
54
55 const endWord = () => {
56 if (isWord)
57 words.push({
58 isExpanding,
59 text,
60 ...(isBare && { at }),
61 ...(hasQuote && { hasQuote }),
62 });
63 text = '';
64 isWord = false;
65 isExpanding = false;
66 isBare = false;
67 hasQuote = false;
68 };
69 const endSegment = (sep: Sep) => {
70 endWord();
71 if (words.length) segments.push({ sep, subst, words });
72 else {
73 // `(a) | b`: the pipe joins the group's last command to what follows
74 const last = segments.at(-1);
75 if (last?.sep === ')' && sep !== ')') last.sep = sep;
76 }
77 words = [];
78 subst = [];
79 };
80 // plain: one literal character read as itself; anything else ends the word's bareness
81 const add = (s: string, isPlain = false) => {
82 if (!isWord) at = i;
83 isBare = isPlain && (isBare || !isWord);
84 text += s;
85 isWord = true;
86 };
87 const open = (kind: Frame['kind']) => {
88 stack.push({
89 at,
90 from: segments.length,
91 hasQuote,
92 isBare,
93 isExpanding,
94 isWord,
95 kind,
96 subst,
97 text,
98 words,
99 });
100 words = [];
101 subst = [];
102 text = '';
103 isWord = false;
104 isExpanding = false;
105 isQuoted = false;
106 };
107 // the inner commands end; the outer one goes on where it stopped, the substitution standing in its word
108 const close = () => {
109 endSegment(')');
110 const frame = stack.pop();
111 if (!frame) return;
112 const inner = segments.slice(frame.from);
113 ({ words, text, isWord, isExpanding, isBare, at, hasQuote } = frame);
114 subst = [...frame.subst, ...inner];
115 if (frame.kind === 'group') return;
116 add('$(…)');
117 isExpanding = true;
118 };
119 // a substitution that sat inside double quotes resumes them
120 const resume = () => {
121 if (stack.at(-1)?.kind !== 'dq') return;
122 stack.pop();
123 isQuoted = true;
124 };
125 // a quote around a substitution is a marker frame: closing the substitution resumes the quote
126 const quoted = (kind: Frame['kind']) => {
127 if (isQuoted)
128 stack.push({
129 at: 0,
130 from: segments.length,
131 hasQuote: false,
132 isBare: false,
133 isExpanding: false,
134 isWord: false,
135 kind: 'dq',
136 subst: [],
137 text: '',
138 words: [],
139 });
140 open(kind);
141 };
142 const dollar = () => {
143 const next = command[i + 1] ?? '';
144 if (EXPANDS.test(next)) isExpanding = true;
145 if (next === '(' && command[i + 2] === '(') {
146 // arithmetic: no command and no heredoc inside
147 const end = command.indexOf('))', i + 3);
148 add(command.slice(i, end < 0 ? undefined : end + 2));
149 i = end < 0 ? command.length : end + 2;
150 return;
151 }
152 if (next === '(') {
153 i += 2;
154 quoted('subst');
155 return;
156 }
157 NAME.lastIndex = i + 1;
158 const name = NAME.exec(command)?.[0];
159 if (!name) {
160 add('$');
161 i++;
162 return;
163 }
164 // zsh reads `$name:x` as a modifier when x is a letter; bash reads a non-ascii character as part of the name
165 const after = command[i + 1 + name.length] ?? '';
166 const modifier = command[i + 2 + name.length] ?? '';
167 if (
168 (after === ':' && /[A-Za-z]/.test(modifier)) ||
169 after.charCodeAt(0) > 127
170 )
171 unbraced.push(`$${name}${after}`);
172 add(`$${name}`);
173 i += name.length + 1;
174 };
175 const skipHeredocs = () => {
176 while (heredocs.length) {
177 const delimiter = heredocs.shift();
178 while (i < command.length) {
179 const end = command.indexOf('\n', i);
180 const line = command.slice(i, end < 0 ? undefined : end);
181 i = end < 0 ? command.length : end + 1;
182 if (line.trim() === delimiter) break;
183 }
184 }
185 };
186 const heredoc = () => {
187 endWord();
188 i += 2;
189 if (command[i] === '-') i++;
190 while (command[i] === ' ' || command[i] === '\t') i++;
191 const quote = command[i];
192 let delimiter = '';
193 if (quote === "'" || quote === '"') {
194 const end = command.indexOf(quote, i + 1);
195 delimiter = command.slice(i + 1, end < 0 ? undefined : end);
196 i = end < 0 ? command.length : end + 1;
197 } else {
198 while (
199 i < command.length &&
200 !/[\s;&|<>()]/.test(command[i] ?? '')
201 ) {
202 delimiter += command[i] === '\\' ? '' : command[i];
203 i++;
204 }
205 }
206 if (delimiter) heredocs.push(delimiter);
207 };
208
209 while (i < command.length) {
210 const c = command[i] ?? '';
211 const next = command[i + 1] ?? '';
212 if (isQuoted) {
213 if (c === '"') {
214 isQuoted = false;
215 i++;
216 } else if (c === '\\') {
217 add(next);
218 i += 2;
219 } else if (c === '$') dollar();
220 else if (c === '`') {
221 i++;
222 quoted('tick');
223 } else {
224 add(c);
225 i++;
226 }
227 } else if (c === '\n') {
228 i++;
229 endSegment(';');
230 skipHeredocs();
231 } else if (c === ' ' || c === '\t') {
232 endWord();
233 i++;
234 } else if (c === '#' && !isWord) {
235 const end = command.indexOf('\n', i);
236 comments.push(command.slice(i + 1, end < 0 ? undefined : end));
237 i = end < 0 ? command.length : end;
238 } else if (c === '\\') {
239 add(next === '\n' ? '' : next);
240 hasQuote = true;
241 i += 2;
242 } else if (c === "'") {
243 const end = command.indexOf("'", i + 1);
244 add(command.slice(i + 1, end < 0 ? undefined : end));
245 hasQuote = true;
246 i = end < 0 ? command.length : end + 1;
247 } else if (c === '"') {
248 isWord = true;
249 isBare = false;
250 hasQuote = true;
251 isQuoted = true;
252 i++;
253 } else if (c === '$') {
254 dollar();
255 } else if (c === '`') {
256 i++;
257 if (stack.at(-1)?.kind === 'tick') {
258 close();
259 resume();
260 } else open('tick');
261 } else if (c === '(') {
262 i++;
263 open('group');
264 } else if (c === ')') {
265 i++;
266 close();
267 resume();
268 } else if (c === ';') {
269 i += next === ';' ? 2 : 1;
270 endSegment(';');
271 } else if (c === '&') {
272 if (next === '&') {
273 i += 2;
274 endSegment('&&');
275 } else if (next === '>' || /[<>]$/.test(text)) {
276 add('&');
277 i++;
278 } else {
279 i++;
280 endSegment('&');
281 }
282 } else if (c === '|') {
283 if (next === '|') {
284 i += 2;
285 endSegment('||');
286 } else {
287 i += next === '&' ? 2 : 1;
288 endSegment('|');
289 }
290 } else if (c === '<' && next === '<' && command[i + 2] !== '<') {
291 heredoc();
292 } else {
293 add(c, true);
294 i++;
295 }
296 }
297 while (stack.length)
298 if (stack.at(-1)?.kind === 'dq') stack.pop();
299 else close();
300 endSegment(';');
301 return { comments, segments, unbraced };
302}
303hooks/rules/floor.ts 244 lines1import {
2 ASK,
3 type Command,
4 type Context,
5 NEVER,
6 type Refusal,
7 STASH,
8 TRASH,
9 VAULT,
10 gitDir,
11 gitParts,
12 hasFlag,
13 operands,
14 or,
15 peel,
16} from './command.ts';
17import { isOwnRepo } from './hazard.ts';
18import { rewrite } from './rewrite.ts';
19
20// what reads process ids by name
21const FINDERS = new Set(['pgrep', 'ps', 'pidof', 'lsof', 'grep', 'rg', 'awk']);
22export function floor(c: Command, ctx: Context): Refusal | undefined {
23 const ops = operands(c.args);
24 if (c.name === 'rm' || c.name === 'unlink')
25 return {
26 door: TRASH,
27 rule: 'rm',
28 targets: or(ops, 'rm'),
29 why: 'rm deletes for good',
30 };
31 if (c.name === 'find') {
32 const exec = c.args.findIndex((w) =>
33 /^-(exec|execdir|ok)$/.test(w.text),
34 );
35 const execRm = exec >= 0 && peel(c.args.slice(exec + 1)).name === 'rm';
36 if (execRm || hasFlag(c.args, ['-delete'])) {
37 const roots = c.args.findIndex((w) => /^[-(!]/.test(w.text));
38 const paths = c.args
39 .slice(0, roots < 0 ? undefined : roots)
40 .map((w) => w.text);
41 return {
42 door: TRASH,
43 rule: 'rm',
44 targets: or(paths, '.'),
45 why: 'find deletes for good',
46 };
47 }
48 }
49 const pgrep = c.feeders.find((f) => f.name === 'pgrep');
50 if (
51 c.name === 'pkill' ||
52 c.name === 'killall' ||
53 (c.name === 'kill' && c.feeders.some((f) => FINDERS.has(f.name)))
54 )
55 return {
56 door: 'claude stop <id>, or kill the pid you captured at spawn',
57 rule: 'kill',
58 targets: or(
59 c.name === 'kill' ? operands(pgrep?.args ?? []) : ops,
60 c.name,
61 ),
62 why: 'a kill by pattern hits your own process too',
63 };
64 if (
65 c.name === 'mv' &&
66 (c.dir.includes(VAULT) || ops.some((o) => o.includes(VAULT)))
67 )
68 return {
69 door: 'obsidian rename / obsidian move — they rewrite the wikilinks',
70 rule: 'vault-mv',
71 targets: ops,
72 why: 'a plain mv in the vault breaks every wikilink to the note',
73 };
74 if (
75 c.assigns.some((a) => a.startsWith('HOME=')) ||
76 (c.name === 'export' && ops.some((o) => o.startsWith('HOME=')))
77 )
78 return {
79 door: 'run it without the HOME override',
80 rule: 'home',
81 targets: ['HOME'],
82 why: 'a HOME override points every tool at the wrong config',
83 };
84 if (
85 c.name === 'npm' &&
86 hasFlag(c.args, ['--global', '--location=global'], 'g')
87 )
88 return {
89 door: 'brew first, else pnpm add -g',
90 rule: 'npm-global',
91 targets: ['npm'],
92 why: 'npm -g is not used here',
93 };
94 const isPip = /^pip\d*(\.\d+)?$/.test(c.name) && ops[0] === 'install';
95 const pipAt = c.args.findIndex(
96 (w, i) => w.text === '-m' && c.args[i + 1]?.text === 'pip',
97 );
98 const isPyPip =
99 /^python\d*(\.\d+)?$/.test(c.name) &&
100 pipAt >= 0 &&
101 operands(c.args.slice(pipAt + 2))[0] === 'install';
102 if (isPip || isPyPip)
103 return {
104 door: 'uv pip install',
105 rule: 'pip',
106 targets: ['pip'],
107 why: 'pip is not used here; uv is',
108 };
109 const bypass = c.args.find(
110 (w) => w.text === '--no-verify' || w.text === '--no-gpg-sign',
111 );
112 if (bypass && (c.name === 'git' || c.name === 'x'))
113 return {
114 door: NEVER,
115 rule: 'bypass',
116 targets: [bypass.text],
117 why: `${bypass.text} skips a gate`,
118 };
119 if (c.name !== 'git') return undefined;
120
121 const { configs, sub, subArgs } = gitParts(c.args);
122 const subOps = operands(subArgs);
123 const config = configs.find(
124 (k) =>
125 /^commit\.gpgsign=false$/i.test(k) ||
126 /^user\.(name|email)=/i.test(k),
127 );
128 if (config) {
129 const key = config.split('=')[0] ?? config;
130 return {
131 door: NEVER,
132 rule: 'bypass',
133 targets: [key],
134 why: `-c ${key} overrides signing or identity`,
135 };
136 }
137 const discard = (targets: string[], what: string): Refusal => ({
138 door: STASH,
139 rule: 'git-discard',
140 targets,
141 why: `${what} throws away uncommitted work`,
142 });
143 if (sub === 'commit' && hasFlag(subArgs, [], 'n'))
144 return {
145 door: NEVER,
146 rule: 'bypass',
147 targets: ['-n'],
148 why: 'git commit -n skips the commit hooks',
149 };
150 if (
151 sub === 'config' &&
152 /^user\.(name|email)$/i.test(subOps[0] ?? '') &&
153 subOps.length > 1
154 )
155 return {
156 door: NEVER,
157 rule: 'bypass',
158 targets: [subOps[0] ?? ''],
159 why: 'git config changes the commit identity',
160 };
161 if (sub === 'reset' && hasFlag(subArgs, ['--hard']))
162 return discard(or(subOps, 'HEAD'), 'git reset --hard');
163 if (
164 sub === 'checkout' &&
165 (subArgs.some((w) => w.text === '--') ||
166 subOps.includes('.') ||
167 hasFlag(subArgs, ['--force'], 'f'))
168 )
169 return discard(or(subOps, '.'), 'git checkout over files');
170 if (
171 sub === 'restore' &&
172 !(
173 hasFlag(subArgs, ['--staged'], 'S') &&
174 !hasFlag(subArgs, ['--worktree'], 'W')
175 )
176 )
177 return discard(or(subOps, '.'), 'git restore');
178 if (sub === 'clean' && hasFlag(subArgs, ['--force'], 'f'))
179 return discard(or(subOps, '.'), 'git clean');
180 if (sub === 'stash' && (subOps[0] === 'drop' || subOps[0] === 'clear'))
181 return {
182 door: ASK,
183 rule: 'git-discard',
184 targets: or(
185 subOps.slice(1),
186 subOps[0] === 'drop' ? 'stash@{0}' : 'clear',
187 ),
188 why: `git stash ${subOps[0]} throws away set-aside work`,
189 };
190 const rewrite = (
191 targets: string[],
192 what: string,
193 door: string = ASK,
194 ): Refusal => ({
195 door,
196 rule: 'git-rewrite',
197 targets,
198 why: `${what} cannot be undone`,
199 });
200 const refspecs = subOps.slice(1);
201 if (
202 sub === 'push' &&
203 (hasFlag(subArgs, ['--delete'], 'd') ||
204 refspecs.some((o) => o.startsWith(':')))
205 )
206 return rewrite(or(subOps, 'push'), 'a remote branch delete');
207 if (
208 sub === 'push' &&
209 (hasFlag(subArgs, ['--force', '--force-with-lease'], 'f') ||
210 refspecs.some((o) => o.startsWith('+')))
211 )
212 return rewrite(
213 or(subOps, 'push'),
214 'a force-push',
215 'x lane rebase-main — it rebases a coder/* branch and pushes it with a lease; any other force-push, ask cclio',
216 );
217 if (
218 sub === 'branch' &&
219 (hasFlag(subArgs, [], 'D') ||
220 (hasFlag(subArgs, ['--delete'], 'd') &&
221 hasFlag(subArgs, ['--force'], 'f')))
222 )
223 return rewrite(subOps, 'git branch -D');
224 if (sub === 'filter-repo' || sub === 'filter-branch')
225 return rewrite([sub], `git ${sub}`);
226 if (sub === 'gc' && hasFlag(subArgs, ['--prune=now']))
227 return rewrite(['--prune=now'], 'git gc --prune=now');
228 if (sub === 'worktree' && subOps[0] === 'prune')
229 return rewrite(['prune'], 'git worktree prune');
230 if (sub === 'worktree' && subOps[0] === 'remove')
231 return rewrite(or(subOps.slice(1), 'remove'), 'git worktree remove');
232 const toMain = subOps
233 .slice(1)
234 .find((o) => /^[^+:][^:]*:(refs\/heads\/)?main$/.test(o));
235 if (sub === 'push' && toMain && isOwnRepo(gitDir(c, ctx), ctx))
236 return {
237 door: "x lane push — it pushes HEAD's sha and reads the remote back",
238 rule: 'push-lane',
239 targets: [toMain],
240 why: 'a hand-typed sha or ref pushed to main skips the read-back',
241 };
242 return undefined;
243}
244