@hasna/hooks 0.13.2 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +31 -16
  2. package/bin/hooks/stop-review.js +53 -17
  3. package/bin/hooks-mcp.js +4787 -1415
  4. package/bin/index.js +5254 -2339
  5. package/bin/native-safety-entry.js +15 -37
  6. package/bin/native-safety-worker.cjs +38 -36
  7. package/bin/serve.js +34 -11
  8. package/dist/index.js +4974 -1581
  9. package/dist/lib/claude-skills-coordination.d.ts +1 -1
  10. package/dist/lib/codex-safety-check.d.ts +1 -1
  11. package/dist/lib/codex-safety-trust.d.ts +2 -2
  12. package/dist/lib/native-safety-registration.d.ts +2 -2
  13. package/dist/lib/native-safety.d.ts +1 -1
  14. package/dist/lib/registry.d.ts +3 -1
  15. package/dist/native-safety.d.ts +4 -2
  16. package/dist/native-safety.js +21 -2
  17. package/dist/sdk/index.js +9 -53
  18. package/hooks/hook-job-folder-guard/README.md +61 -0
  19. package/hooks/hook-job-folder-guard/package.json +12 -0
  20. package/hooks/hook-job-folder-guard/src/classify.ts +398 -0
  21. package/hooks/hook-job-folder-guard/src/hook.ts +96 -0
  22. package/hooks/hook-protected-delete-guard/README.md +114 -0
  23. package/hooks/hook-protected-delete-guard/package.json +12 -0
  24. package/hooks/hook-protected-delete-guard/src/hook.ts +539 -0
  25. package/hooks/hook-signed-link-guard/src/classify.ts +41 -2
  26. package/hooks/hook-stop-review/README.md +16 -0
  27. package/hooks/hook-stop-review/manifest.json +1 -1
  28. package/hooks/hook-stop-review/package.json +1 -1
  29. package/hooks/hook-stop-review/src/hook.ts +1 -1
  30. package/hooks/hook-stop-review/src/native.ts +44 -8
  31. package/hooks/hook-stop-review/src/policy.ts +20 -8
  32. package/hooks/hook-stop-review/src/runtime.ts +16 -13
  33. package/hooks/hook-stop-review/src/types.ts +12 -2
  34. package/hooks/hook-trash-guard/README.md +130 -13
  35. package/hooks/hook-trash-guard/src/hook.ts +518 -71
  36. package/hooks/local-executors.ts +33 -0
  37. package/hooks/native-safety-composite.ts +19 -8
  38. package/package.json +3 -3
  39. package/scripts/build-native-entry.ts +123 -0
  40. package/scripts/build-native-worker.ts +11 -4
  41. package/scripts/validate-package.ts +8 -2
  42. package/hooks/native-safety-entry.ts +0 -11
@@ -0,0 +1,539 @@
1
+ #!/usr/bin/env bun
2
+
3
+ /**
4
+ * PreToolUse hook: protected-delete-guard
5
+ *
6
+ * Refuses a delete of the protected class and of coding-agent session and
7
+ * history stores. It only refuses: it never rewrites a command, never looks
8
+ * for a trash binary and never consults a store, a network or a credential.
9
+ * An ordinary removal passes untouched.
10
+ *
11
+ * These refusals were part of trash-guard, which cannot be registered without
12
+ * Trash. They are lifted here so that they hold where trash-guard is switched
13
+ * off (HAA-00045).
14
+ *
15
+ * What is refused:
16
+ * - `rm`, `rmdir`, `unlink` and `shred` whose operand is in the protected
17
+ * class trash-guard already names (protectedTargetReason): `/` and the
18
+ * system roots, the home directory, and `~/.hasna`, `~/.ssh` and `~/.aws`
19
+ * (the path, anything that contains it, anything inside it). Inside
20
+ * `~/.hasna` two places hold files an agent removes itself and are left
21
+ * alone: a session's scratch content (trash-guard's own carve-out) and the
22
+ * content of a managed worktree, never the worktree root itself.
23
+ * - the same verbs on a path that is, contains or lies inside a coding-agent
24
+ * session or history store (the list @hasna/trash refuses as
25
+ * protected_session_history).
26
+ * - a pattern operand that can name one of those (`rm -rf ~/*`, `/*`,
27
+ * `~/.s*`). trash-guard left patterns to `trash guard`, which classified
28
+ * what the shell expanded; nothing does that here.
29
+ * - `find` with a delete action (`-delete`, or `-exec`/`-execdir`/`-ok`
30
+ * running a delete verb), wherever it runs: what it removes is decided by
31
+ * its walk, not by words this guard can read. This is trash-guard's
32
+ * refusal, kept as it was, and it is the one that covers a repository
33
+ * checkout, where workspace-repos-guard does not read `find`.
34
+ * - a patch whose `*** Delete File:` path is in the class or a store.
35
+ * - a delete this guard cannot read exactly (an operand the shell expands,
36
+ * a shell string, a launcher, an expansion in command position, an
37
+ * unclosed quote), but only when a word of the command names a protected
38
+ * path.
39
+ *
40
+ * Commands are read by trash-guard's scan (scanCommand): wrappers, quoting,
41
+ * continued lines, `cd`, brace patterns, command substitutions and both
42
+ * command-position readings. This hook sees each delete that scan reads
43
+ * (ScanOptions.observe) and judges it by the class above.
44
+ *
45
+ * What it cannot judge: an operand the shell expands before the command runs
46
+ * (a variable other than HOME, a substitution). Such a delete is refused only
47
+ * when the command itself names a protected path, as in
48
+ * `for d in ~/.claude ~/.codex; do rm -rf "$d"; done`; `rm -rf "$DIR"` on its
49
+ * own passes. No hook that reads words can do better; with trash-guard that
50
+ * part was `trash guard`'s, at run time.
51
+ */
52
+
53
+ import { lstatSync, readdirSync, realpathSync } from "node:fs";
54
+ import { homedir } from "node:os";
55
+ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
56
+ import {
57
+ SYSTEM_PROTECTED_ROOTS,
58
+ getCommand,
59
+ globComponentMatches,
60
+ readInput,
61
+ respond,
62
+ warn,
63
+ type CodewithHookInput,
64
+ type CodewithHookOutput,
65
+ } from "../../codewith-native-common";
66
+ import {
67
+ OBSERVED_REFUSALS,
68
+ decodeWord,
69
+ expandBraces,
70
+ expandHomeSpelling,
71
+ mentionsDeleteVerb,
72
+ mentionsRefusedDeleteForm,
73
+ protectedTargetReason,
74
+ resolveLiteralTarget,
75
+ scanCommand,
76
+ type ObservedDelete,
77
+ type ScanResult,
78
+ } from "../../hook-trash-guard/src/hook";
79
+ import { readWithLegacyQuotes } from "../../local-executors";
80
+
81
+ const RULE = "protected-delete-guard";
82
+
83
+ /* ------------------------------------------------------------------ */
84
+ /* Coding-agent session and history stores */
85
+ /* ------------------------------------------------------------------ */
86
+
87
+ /** One protected store: the agent tool that owns it and its root. */
88
+ export interface SessionStoreRoot {
89
+ tool: string;
90
+ path: string;
91
+ }
92
+
93
+ const listDirectory = (directory: string): string[] => readdirSync(directory);
94
+ const realPath = (path: string): string => realpathSync(path);
95
+ const pathExists = (path: string): boolean => lstatSync(path, { throwIfNoEntry: false }) !== undefined;
96
+
97
+ /** Codex keeps resume metadata beside its transcripts: the prompt history, the session index and the thread/state databases. */
98
+ const CODEX_HISTORY_FILE = /^(?:history\.jsonl|session_index\.jsonl|(?:state|thread_history)_\d+\.sqlite(?:-shm|-wal)?)$/;
99
+
100
+ /**
101
+ * Every coding-agent session and history store, as @hasna/trash lists them
102
+ * (apps/trash/src/lib/session-stores.ts, sessionStoreRoots; a test compares
103
+ * the two lists): Claude Code, Codex, OpenCode, Sumi, Devin, Cursor, DSH,
104
+ * antigravity, Cline, Gemini CLI, Qwen Code, GitHub Copilot CLI, Codewith, and
105
+ * each path in HASNA_TRASH_SESSION_ROOTS.
106
+ *
107
+ * One difference: a Codex home that exists but cannot be listed makes Trash
108
+ * refuse every capture. Here the whole Codex home becomes the root instead, so
109
+ * the history files that could not be listed are still covered and an
110
+ * unrelated removal still passes.
111
+ *
112
+ * The native safety supervisor runs this hook with HOME and PATH only, so the
113
+ * roots that come from other variables (CLAUDE_CONFIG_DIR, CODEX_HOME, XDG_*,
114
+ * DSH_HOME, DSH_TUI_SESSION_ROOT, HASNA_TRASH_SESSION_ROOTS) are read where the
115
+ * hook is given an environment and are absent there.
116
+ */
117
+ export function sessionStoreRoots(home: string, env: NodeJS.ProcessEnv, list: (directory: string) => string[] = listDirectory): SessionStoreRoot[] {
118
+ const configured = (name: string) => (env[name] ? [resolve(env[name]!)] : []);
119
+ const xdg = (name: string, fallback: string) => (env[name] ? resolve(env[name]!) : join(home, fallback));
120
+ const data = xdg("XDG_DATA_HOME", ".local/share");
121
+ const state = xdg("XDG_STATE_HOME", ".local/state");
122
+ const config = xdg("XDG_CONFIG_HOME", ".config");
123
+ const roots: SessionStoreRoot[] = [];
124
+ for (const root of [join(home, ".claude"), join(home, ".claude.json"), ...configured("CLAUDE_CONFIG_DIR")]) roots.push({ tool: "Claude Code", path: root });
125
+ for (const codex of [join(home, ".codex"), ...configured("CODEX_HOME")]) {
126
+ for (const name of ["sessions", "archived_sessions"]) roots.push({ tool: "Codex", path: join(codex, name) });
127
+ let names: string[] = [];
128
+ try {
129
+ names = list(codex);
130
+ } catch (error) {
131
+ const code = (error as NodeJS.ErrnoException | null)?.code;
132
+ if (code !== "ENOENT" && code !== "ENOTDIR") roots.push({ tool: "Codex", path: codex });
133
+ }
134
+ for (const name of names) if (CODEX_HISTORY_FILE.test(name)) roots.push({ tool: "Codex", path: join(codex, name) });
135
+ }
136
+ for (const [folder, tool] of [["opencode", "OpenCode"], ["sumi", "Sumi"], ["devin", "Devin"]] as const) for (const base of [data, state]) roots.push({ tool, path: join(base, folder) });
137
+ for (const root of [join(home, ".cursor"), join(home, "Library", "Application Support", "Cursor"), join(config, "Cursor")]) roots.push({ tool: "Cursor", path: root });
138
+ for (const root of [resolve(env.DSH_HOME ?? join(home, ".dsh")), join(home, ".dsh-tui"), ...configured("DSH_TUI_SESSION_ROOT")]) roots.push({ tool: "DSH", path: root });
139
+ roots.push({ tool: "antigravity", path: join(home, ".gemini", "antigravity-cli") });
140
+ roots.push({ tool: "Cline", path: join(home, ".cline") });
141
+ for (const root of [join(home, ".gemini", "tmp"), join(home, ".gemini", "history")]) roots.push({ tool: "Gemini CLI", path: root });
142
+ roots.push({ tool: "Qwen Code", path: join(home, ".qwen") });
143
+ roots.push({ tool: "GitHub Copilot CLI", path: join(home, ".copilot") });
144
+ roots.push({ tool: "Codewith", path: join(home, ".codewith") });
145
+ for (const root of (env.HASNA_TRASH_SESSION_ROOTS ?? "").split(delimiter).filter(Boolean)) roots.push({ tool: "configured coding-agent", path: resolve(root) });
146
+ return roots;
147
+ }
148
+
149
+ /**
150
+ * `path` with every symlink on the way to it followed, as far as the path
151
+ * exists: the nearest existing ancestor is resolved and the rest is kept as
152
+ * written. A path that cannot be resolved keeps its spelling.
153
+ */
154
+ export function resolvedSpelling(path: string, realpath: (path: string) => string = realPath): string {
155
+ const rest: string[] = [];
156
+ for (let current = path; ; current = dirname(current)) {
157
+ try {
158
+ return join(realpath(current), ...rest);
159
+ } catch {
160
+ if (dirname(current) === current) return path;
161
+ rest.unshift(basename(current));
162
+ }
163
+ }
164
+ }
165
+
166
+ /** Case-equivalent spellings are one path on the volumes macOS and Windows commonly use. */
167
+ function spelled(value: string, platform: NodeJS.Platform): string {
168
+ return platform === "darwin" || platform === "win32" ? value.normalize("NFC").toLowerCase() : value;
169
+ }
170
+
171
+ /** Whether `child` is `parent` or lies inside it. */
172
+ function within(child: string, parent: string, platform: NodeJS.Platform): boolean {
173
+ const a = spelled(child, platform);
174
+ const b = spelled(parent, platform);
175
+ return a === b || a.startsWith(b.endsWith(sep) ? b : `${b}${sep}`);
176
+ }
177
+
178
+ /** The first store any spelling of the candidate is, lies inside or contains. */
179
+ export function sessionStoreMatch(roots: readonly SessionStoreRoot[], candidates: readonly string[], platform: NodeJS.Platform = process.platform): SessionStoreRoot | null {
180
+ for (const candidate of candidates) {
181
+ for (const root of roots) {
182
+ if (within(candidate, root.path, platform) || within(root.path, candidate, platform)) return root;
183
+ }
184
+ }
185
+ return null;
186
+ }
187
+
188
+ /* ------------------------------------------------------------------ */
189
+ /* The class */
190
+ /* ------------------------------------------------------------------ */
191
+
192
+ export interface GuardDependencies {
193
+ home: string;
194
+ cwd: string;
195
+ /** Where the store roots that variables configure are read from. */
196
+ env?: NodeJS.ProcessEnv;
197
+ platform?: NodeJS.Platform;
198
+ realpath?: (path: string) => string;
199
+ list?: (directory: string) => string[];
200
+ /** Whether a path exists, itself and not what a link at it names. */
201
+ exists?: (path: string) => boolean;
202
+ }
203
+
204
+ /**
205
+ * Content of a managed worktree: a path strictly inside a worktree root under
206
+ * `~/.hasna/repos/worktrees`. Build output and dependency folders live there,
207
+ * and trash-guard's tree rule for `~/.hasna` would refuse every one.
208
+ *
209
+ * A worktree root is the folder that holds git's `.git` entry, two levels
210
+ * below the worktrees root in the flat layout (`<repo>/<worktree>`) and three
211
+ * in the org layout (`<org>/<repo>/<worktree>`). The root itself, a repository
212
+ * or org folder and the worktrees root stay refused, and so does a path under
213
+ * the worktrees root that is in no worktree: a worktree is removed by the
214
+ * tool that leased it, not by `rm`.
215
+ */
216
+ export function isWorktreeContent(target: string, home: string, exists: (path: string) => boolean = pathExists): boolean {
217
+ const root = join(home, ".hasna", "repos", "worktrees");
218
+ if (!target.startsWith(`${root}${sep}`)) return false;
219
+ const parts = target.slice(root.length + 1).split(sep);
220
+ if (parts.some((part) => part === "" || part === "." || part === "..")) return false;
221
+ return [2, 3].some((depth) => parts.length > depth && exists(join(root, ...parts.slice(0, depth), ".git")));
222
+ }
223
+
224
+ /**
225
+ * The HOME expansions that yield HOME itself whenever HOME is set, written as
226
+ * `${HOME}`: `${HOME:?…}`, `${HOME?…}`, `${HOME:-…}`, `${HOME-…}`, `${HOME:=…}`,
227
+ * `${HOME=…}` and `${HOME%/}` / `${HOME%%/}`. `${HOME:?}/.ssh` is the spelling
228
+ * ShellCheck recommends for exactly this delete, so it is read as the home.
229
+ */
230
+ export function homeForms(value: string): string {
231
+ return value.replace(/\$\{HOME(?::?[-?=][^}]*|%%?\/)\}/g, "${HOME}");
232
+ }
233
+
234
+ /**
235
+ * The absolute path a literal operand names, or null when it cannot be read
236
+ * before the shell expands it. It is trash-guard's reading
237
+ * (resolveLiteralTarget), with one addition: `$HOME/x` and `${HOME}/x` (and the
238
+ * forms homeForms reads as `${HOME}`) name a path under the home directory.
239
+ * trash-guard reads those as a name under the current directory and leaves
240
+ * them to `trash guard`; here nothing runs after the hook, so
241
+ * `rm -rf $HOME/.ssh` has to be read for what it is.
242
+ */
243
+ function literalTarget(raw: string, cwd: string, home: string): string | null {
244
+ const decoded = homeForms(decodeWord(raw));
245
+ if (!/^\$(?:HOME|\{HOME\})\//.test(decoded)) return resolveLiteralTarget(raw, cwd, home);
246
+ const expanded = expandHomeSpelling(decoded, home);
247
+ if (expanded === decoded || /[$`*?[\]]/.test(expanded)) return null;
248
+ const trimmed = resolve(expanded).replace(/\/+$/, "");
249
+ return trimmed === "" ? sep : trimmed;
250
+ }
251
+
252
+ /** A path rendered for a refusal so that pasting the line into a shell runs nothing. */
253
+ function renderPath(raw: string): string {
254
+ return `'${raw.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?").slice(0, 512).replace(/'/g, `'\\''`)}'`;
255
+ }
256
+
257
+ interface Classifier {
258
+ /** Why a literal absolute path is protected, or null for an ordinary one. */
259
+ path: (target: string) => string | null;
260
+ /** Why a pattern word could name a protected path, null for an ordinary one, undefined when it cannot be read. */
261
+ pattern: (raw: string, cwd: string) => string | null | undefined;
262
+ /** Why an operand word (literal, brace pattern or glob) is protected, or null. */
263
+ operand: (raw: string, cwd: string) => string | null;
264
+ /** Whether an operand cannot be read before the shell expands it (a variable other than HOME, a substitution). */
265
+ expands: (raw: string, cwd: string) => boolean;
266
+ }
267
+
268
+ function classifier(deps: GuardDependencies): Classifier {
269
+ const platform = deps.platform ?? process.platform;
270
+ const realpath = deps.realpath ?? realPath;
271
+ const { home } = deps;
272
+ // The stores are listed once per call, and only when a delete is judged.
273
+ let stores: SessionStoreRoot[] | null = null;
274
+ const storeRoots = (): SessionStoreRoot[] => {
275
+ if (stores === null) {
276
+ const listed = sessionStoreRoots(home, deps.env ?? {}, deps.list ?? listDirectory);
277
+ stores = listed.flatMap((root) => {
278
+ const resolved = resolvedSpelling(root.path, realpath);
279
+ return resolved === root.path ? [root] : [root, { ...root, path: resolved }];
280
+ });
281
+ }
282
+ return stores;
283
+ };
284
+
285
+ /**
286
+ * On a case-insensitive platform, the spellings under which the class names
287
+ * `name` when its case differs from the class's own: under the home
288
+ * directory the rest is folded (`~/.SSH/x` is judged as `~/.ssh/x`), under a
289
+ * system root the root is spelled as the class spells it. Elsewhere none.
290
+ */
291
+ const foldedSpellings = (name: string): string[] => {
292
+ if (platform !== "darwin" && platform !== "win32") return [];
293
+ const out: string[] = [];
294
+ for (const anchor of [home, ...SYSTEM_PROTECTED_ROOTS.filter((root) => root !== sep)]) {
295
+ const head = name.slice(0, anchor.length);
296
+ const rest = name.slice(anchor.length);
297
+ if (spelled(head, platform) !== spelled(anchor, platform) || (rest !== "" && !rest.startsWith(sep))) continue;
298
+ const candidate = anchor === home ? `${home}${spelled(rest, platform)}` : `${anchor}${rest}`;
299
+ if (candidate !== name) out.push(candidate);
300
+ }
301
+ return out;
302
+ };
303
+
304
+ const path = (target: string): string | null => {
305
+ // rm, rmdir and unlink remove the name they are given, so the name is read
306
+ // as written and with its parent resolved. A store is also matched on the
307
+ // fully resolved spelling, as Trash matches it: a link that names a store
308
+ // is refused with it.
309
+ const parentResolved = join(resolvedSpelling(dirname(target), realpath), basename(target));
310
+ const names = parentResolved === target ? [target] : [target, parentResolved];
311
+ // The class first, so that `/` and the home directory are named as what
312
+ // they are and not as a folder that contains a store. On macOS and Windows
313
+ // `~/.SSH` is `~/.ssh`: each name is also judged in its folded spelling.
314
+ for (const name of [...names, ...names.flatMap(foldedSpellings)]) {
315
+ if (isWorktreeContent(name, home, deps.exists ?? pathExists)) continue;
316
+ const reason = protectedTargetReason(name, home);
317
+ if (reason) return reason;
318
+ }
319
+ const resolved = resolvedSpelling(target, realpath);
320
+ const store = sessionStoreMatch(storeRoots(), names.includes(resolved) ? names : [...names, resolved], platform);
321
+ if (store) {
322
+ return `${renderPath(target)} is, contains or lies inside ${store.tool} session history (${renderPath(store.path)}). Coding-agent sessions and their history are never deleted, including inactive and archived ones, because agents need them to resume.`;
323
+ }
324
+ return null;
325
+ };
326
+
327
+ /**
328
+ * Whether a pattern can name a protected root or something that contains it
329
+ * (as many components as the root or fewer, each matching), or, for a tree,
330
+ * something inside it (its leading components match the root). Components
331
+ * are matched by the linear matcher pre-bash uses, which errs towards a
332
+ * match. A pattern written inside `~/.hasna` is judged by a sample of what it
333
+ * names, so a pattern over worktree or scratch content passes.
334
+ */
335
+ const pattern = (raw: string, cwd: string): string | null | undefined => {
336
+ const decoded = homeForms(decodeWord(raw));
337
+ if (!decoded || decoded.includes("`") || !/[*?[]/.test(decoded)) return undefined;
338
+ if (decoded.replace(/\$\{HOME\}/g, "").replace(/\$HOME/g, "").includes("$")) return undefined;
339
+ const expanded = decoded.startsWith("~") || decoded.startsWith("$") ? expandHomeSpelling(decoded, home) : decoded;
340
+ if (expanded.startsWith("~") || expanded.startsWith("$")) return undefined;
341
+ const parts = (isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded)).split(sep).filter(Boolean);
342
+ const firstPattern = parts.findIndex((part) => /[*?[]/.test(part));
343
+ if (firstPattern < 0) return undefined;
344
+ const asWritten = (value: string): string => value;
345
+ const names = (root: string, read = asWritten): boolean => {
346
+ const rootParts = root.split(sep).filter(Boolean);
347
+ return parts.length <= rootParts.length && parts.every((part, index) => globComponentMatches(read(part), read(rootParts[index]!)));
348
+ };
349
+ const namesInside = (root: string, read = asWritten): boolean => {
350
+ const rootParts = root.split(sep).filter(Boolean);
351
+ return parts.length > rootParts.length && rootParts.every((part, index) => globComponentMatches(read(parts[index]!), read(part)));
352
+ };
353
+ const refused = (what: string) => `The pattern ${renderPath(decoded)} can name ${what}, which is never deleted. Write the delete out as plain paths.`;
354
+ // One path whatever its case on macOS and Windows, for the class as for a store.
355
+ const folded = (value: string): string => spelled(value, platform);
356
+ for (const root of SYSTEM_PROTECTED_ROOTS) {
357
+ if (root !== sep && names(root, folded)) return refused(`the system root \`${root}\``);
358
+ }
359
+ if (names(home, folded)) return refused("the home directory");
360
+ for (const suffix of [".ssh", ".aws"]) {
361
+ const root = join(home, suffix);
362
+ if (names(root, folded) || namesInside(root, folded)) return refused(`\`~/${suffix}\` or a path inside it`);
363
+ }
364
+ const state = join(home, ".hasna");
365
+ if (names(state, folded)) return refused("`~/.hasna`");
366
+ if (namesInside(state, folded)) {
367
+ const stateParts = state.split(sep).filter(Boolean).length;
368
+ const sample = `${sep}${parts.map((part) => (/[*?[]/.test(part) ? "x" : part)).join(sep)}`;
369
+ const sampled = firstPattern >= stateParts ? path(sample) : "a pattern";
370
+ if (sampled !== null) return refused("a path inside `~/.hasna` outside worktree and scratch content");
371
+ }
372
+ for (const store of storeRoots()) {
373
+ if (names(store.path, folded) || namesInside(store.path, folded)) return refused(`${store.tool} session history (${renderPath(store.path)})`);
374
+ }
375
+ return null;
376
+ };
377
+
378
+ const operand = (raw: string, cwd: string): string | null => {
379
+ // A brace pattern is expanded first, as bash does before the command runs.
380
+ // One that names more paths than the expansion will produce cannot be
381
+ // checked path by path, and is refused as trash-guard refuses it.
382
+ const braces = raw.includes("{") ? expandBraces(raw) : [];
383
+ if (braces === null) return "This delete's brace pattern names more paths than this guard will check. Write the delete out as plain paths.";
384
+ for (const word of [raw, ...braces]) {
385
+ const literal = literalTarget(word, cwd, home);
386
+ const reason = literal !== null ? path(literal) : pattern(word, cwd);
387
+ if (reason) return reason;
388
+ }
389
+ return null;
390
+ };
391
+
392
+ const expands = (raw: string, cwd: string): boolean =>
393
+ [raw, ...((raw.includes("{") ? expandBraces(raw) : []) ?? [])].some((word) => literalTarget(word, cwd, home) === null && pattern(word, cwd) === undefined);
394
+
395
+ return { path, pattern, operand, expands };
396
+ }
397
+
398
+ /* ------------------------------------------------------------------ */
399
+ /* Verdict */
400
+ /* ------------------------------------------------------------------ */
401
+
402
+ const FIND_REASON =
403
+ "`find` with a delete action (`-delete`, or `-exec` running a delete) removes whatever its walk matches, which this guard cannot read before it runs. List the paths first (`find … -print`), then remove them with `rm -- <path>`.";
404
+
405
+ function deny(reason: string): CodewithHookOutput {
406
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: `[${RULE}] ${reason}` } };
407
+ }
408
+
409
+ /**
410
+ * The first word of the command that names a protected path. Used only for a
411
+ * delete the scan could not attribute to its operands: the text is split at
412
+ * blanks, quotes and operators, and each piece written as a path (it starts
413
+ * with `/`, `~`, `.` or a HOME expansion, or holds a `/`) is read as one. A bare
414
+ * word is not: read against the directory, `rm` or `bash` would name a path
415
+ * inside it. It can only refuse.
416
+ */
417
+ function namedProtectedPath(command: string, cwd: string, classify: Classifier): string | null {
418
+ for (const word of new Set(command.split(/[\s;|&()<>"'`=]+/))) {
419
+ if (!word || word.startsWith("-") || !/^(?:[/~.]|\$HOME|\$\{HOME\})|\//.test(word)) continue;
420
+ const reason = classify.operand(word, cwd);
421
+ if (reason) return reason;
422
+ }
423
+ return null;
424
+ }
425
+
426
+ /** The verdict for one reading of a Bash command. */
427
+ function commandVerdict(command: string, deps: GuardDependencies, classify: Classifier): string | null {
428
+ const seen: ObservedDelete[] = [];
429
+ const scanned: ScanResult = scanCommand(command, { cwd: deps.cwd, home: deps.home, observe: (delete_) => seen.push(delete_) });
430
+ // A delete whose operand the shell expands (a variable, a substitution).
431
+ let expanded = false;
432
+ for (const delete_ of seen) {
433
+ if (delete_.verb === "find") continue;
434
+ for (const raw of delete_.operands) {
435
+ const reason = classify.operand(raw, delete_.cwd);
436
+ if (reason) return reason;
437
+ expanded ||= classify.expands(raw, delete_.cwd);
438
+ }
439
+ }
440
+ if (seen.some((delete_) => delete_.verb === "find")) return FIND_REASON;
441
+ // A delete this guard cannot read exactly: one with an expanded operand, one
442
+ // the scan found but could not attribute to its operands, or a command it
443
+ // could not follow to its end that names a delete.
444
+ const unread = expanded || scanned.refusals.some((refusal) => !OBSERVED_REFUSALS.has(refusal.reason))
445
+ || (!scanned.trustworthy && (scanned.rmHits.length > 0 || scanned.handoffHits.length > 0 || mentionsDeleteVerb(command) || mentionsRefusedDeleteForm(command)));
446
+ if (!unread) return null;
447
+ const named = namedProtectedPath(command, deps.cwd, classify);
448
+ return named === null
449
+ ? null
450
+ : `This command runs a delete this guard cannot read exactly (an operand the shell expands, a shell string, a launcher, an expansion in command position or an unclosed quote), and it names a protected path: ${named} Run the delete as a plain \`rm -- <path>\` command on its own.`;
451
+ }
452
+
453
+ const PATCH_TOOLS = ["apply_patch", "ApplyPatch", "functions.apply_patch"];
454
+
455
+ /** The verdict for a patch: each `*** Delete File:` path is judged like an operand. */
456
+ function patchVerdict(patch: string, deps: GuardDependencies, classify: Classifier): string | null {
457
+ for (const match of patch.matchAll(/^\s*\*\*\* Delete File:[ \t]*(.*)$/gm)) {
458
+ const raw = match[1]!.trim();
459
+ if (!raw) continue;
460
+ const target = isAbsolute(raw) ? resolve(raw) : resolve(deps.cwd, raw.startsWith("~/") ? join(deps.home, raw.slice(2)) : raw);
461
+ const reason = classify.path(target);
462
+ if (reason) return `Delete File is refused: ${reason}`;
463
+ }
464
+ return null;
465
+ }
466
+
467
+ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): CodewithHookOutput {
468
+ if (input.hook_event_name !== "PreToolUse") return { continue: true };
469
+ const classify = classifier(deps);
470
+ if (PATCH_TOOLS.includes(input.tool_name ?? "")) {
471
+ const patch = input.tool_input?.command ?? input.tool_input?.patch;
472
+ if (typeof patch !== "string") return { continue: true };
473
+ const reason = patchVerdict(patch, deps, classify);
474
+ return reason === null ? { continue: true } : deny(reason);
475
+ }
476
+ if (input.tool_name !== "Bash") return { continue: true };
477
+ const command = getCommand(input);
478
+ if (!command.trim()) return { continue: true };
479
+ // The command is read as written and with `$HOME` and `${HOME}` spelled out:
480
+ // the scan follows `cd ~/x` but reads `cd $HOME/x` as a name under the current
481
+ // directory, and a delete after it would be judged in the wrong place. The
482
+ // second reading can only add a refusal. The HOME forms that yield HOME
483
+ // (`${HOME:?}`, `${HOME%/}`, …) are spelled out with them.
484
+ const spelled = /^[A-Za-z0-9._/-]+$/.test(deps.home) ? homeForms(command).replace(/\$\{HOME\}|\$HOME(?![A-Za-z0-9_])/g, deps.home) : command;
485
+ for (const reading of spelled === command ? [command] : [command, spelled]) {
486
+ const reason = commandVerdict(reading, deps, classify)
487
+ // The earlier double-quote backslash reading too: what it refuses stays refused.
488
+ ?? readWithLegacyQuotes(reading, () => commandVerdict(reading, deps, classify))
489
+ ?? null;
490
+ if (reason !== null) return deny(reason);
491
+ }
492
+ return { continue: true };
493
+ }
494
+
495
+ /**
496
+ * The verdict when evaluation itself fails: a command that names a delete and
497
+ * a protected path is refused, and so is one that names a delete when even
498
+ * that reading fails. Anything else passes, so a defect here cannot stop
499
+ * commands that delete nothing.
500
+ */
501
+ export function fallbackVerdict(input: CodewithHookInput, deps: GuardDependencies): CodewithHookOutput {
502
+ const command = getCommand(input);
503
+ if (!(mentionsDeleteVerb(command) || mentionsRefusedDeleteForm(command) || /^\s*\*\*\* Delete File:/m.test(command))) return { continue: true };
504
+ const failed = "The guard failed while reading this command, so it cannot show that the delete in it spares the protected paths.";
505
+ try {
506
+ return namedProtectedPath(command, deps.cwd, classifier(deps)) === null ? { continue: true } : deny(`${failed} Run the delete as a plain \`rm -- <path>\` command on its own.`);
507
+ } catch {
508
+ return deny(`${failed} Report it, and run the delete as a plain \`rm -- <path>\` command on its own.`);
509
+ }
510
+ }
511
+
512
+ /** `evaluate`, with the fallback verdict for any failure inside it. */
513
+ export function guard(input: CodewithHookInput, deps: GuardDependencies): CodewithHookOutput {
514
+ try {
515
+ return evaluate(input, deps);
516
+ } catch {
517
+ return fallbackVerdict(input, deps);
518
+ }
519
+ }
520
+
521
+ export async function run(): Promise<void> {
522
+ const input = readInput();
523
+ const cwd = typeof input.cwd === "string" && input.cwd ? input.cwd : process.cwd();
524
+ let verdict: CodewithHookOutput;
525
+ try {
526
+ verdict = guard(input, { home: homedir(), cwd, env: process.env });
527
+ } catch (error) {
528
+ warn(`${RULE} failed: ${error instanceof Error ? error.message : String(error)}`);
529
+ verdict = { continue: true };
530
+ }
531
+ // Silence is the no-op for Codex and Claude; only a decision is written.
532
+ if (!("continue" in verdict && verdict.continue === true)) respond(verdict);
533
+ }
534
+
535
+ // Standalone run only. No top-level await: the CommonJS native safety worker
536
+ // bundles this module, and its parser refuses top-level await.
537
+ if (import.meta.main) {
538
+ void run().then(() => process.exit(0));
539
+ }
@@ -38,8 +38,9 @@
38
38
  * command that may be an alias, an unterminated command) fails closed.
39
39
  */
40
40
 
41
- import { commandWordIndex, envSplitCommandText, heredocMarkerAt, lexCommand, scanParenAt, skipHeredocBodies, type Word } from "../../hook-trash-guard/src/hook";
41
+ import { blankComments, commandWordIndex, decodeCommandWord, envSplitCommandText, heredocMarkerAt, lexCommand, scanParenAt, skipHeredocBodies, type Word } from "../../hook-trash-guard/src/hook";
42
42
  import { jqProjectionIsScalar } from "./jq";
43
+ import { ansiPlain, ansiPlainEvery } from "../../local-executors";
43
44
 
44
45
  /** The exact refusal reason, fixed by the engineering decision for this class. */
45
46
  export const SIGNED_LINK_REFUSAL =
@@ -990,8 +991,28 @@ function scriptsFromSubstitutions(raw: string, depth: number, ctx: Context): Sig
990
991
  return ALLOW;
991
992
  }
992
993
 
993
- /** Classify a complete shell command string. */
994
+ /**
995
+ * Classify a complete shell command string. A command with `#` comments is read twice, as before and with its comments
996
+ * blanked as bash reads them (HO-00210): a quote in a comment hid the gh read on the next line. A command with a `\'`
997
+ * inside an ANSI-C `$'…'` word is also read with it spelled `\x27` (ansiPlain, HO-00213), because the lexer ended the
998
+ * word at the escaped quote and could hide the next lines. Those words are found in one pass from the left and, beside
999
+ * that, from every `$'` (ansiPlainEvery, HO-00222), because a `$'` bash does not read as ANSI-C can start a word that
1000
+ * hides the real one. Refused when any reading refuses.
1001
+ */
994
1002
  export function classifyCommand(command: string, depth = 0, inheritedDebug = false): SignedLinkVerdict {
1003
+ const verdict = classifyReading(command, depth, inheritedDebug);
1004
+ if (verdict.refused || typeof command !== "string") return verdict;
1005
+ const blanked = blankComments(command);
1006
+ const other = blanked === command ? verdict : classifyReading(blanked, depth, inheritedDebug);
1007
+ if (other.refused) return other;
1008
+ const plain = ansiPlain(command);
1009
+ const spelled = plain === command ? other : classifyCommand(plain, depth, inheritedDebug);
1010
+ if (spelled.refused) return spelled;
1011
+ const every = ansiPlainEvery(command);
1012
+ return every === command || every === plain ? spelled : classifyCommand(every, depth, inheritedDebug);
1013
+ }
1014
+
1015
+ function classifyReading(command: string, depth: number, inheritedDebug: boolean): SignedLinkVerdict {
995
1016
  if (typeof command !== "string" || !command.trim()) return ALLOW;
996
1017
  if (depth > MAX_DEPTH) return GH_MENTION.test(command) ? refused("unclassifiable") : ALLOW;
997
1018
  const { segments, trustworthy } = segmentsOf(command);
@@ -1112,6 +1133,10 @@ function classifyInvocation(verb: string, verbWord: ShellWord, args: ShellWord[]
1112
1133
  if (script) {
1113
1134
  const verdict = next(script.value);
1114
1135
  if (verdict.refused || !script.opaque) return verdict;
1136
+ // An ANSI-C `$'…'` program is read as bash decodes it (HO-00221): its
1137
+ // `\n` is a newline, so a gh read on the next line is a command.
1138
+ const decoded = ansiProgram(script.raw, next);
1139
+ if (decoded.refused) return decoded;
1115
1140
  // `bash -c "$(cat <<EOF …)"`: the substitution's literal output is the script.
1116
1141
  return scriptsFromSubstitutions(script.raw, depth, ctx);
1117
1142
  }
@@ -1145,6 +1170,8 @@ function classifyInvocation(verb: string, verbWord: ShellWord, args: ShellWord[]
1145
1170
  }
1146
1171
  const verdict = next(words.map((word) => word.value).join(" "));
1147
1172
  if (verdict.refused) return verdict;
1173
+ const decoded = ansiProgram(words.map((word) => word.raw).join(" "), next);
1174
+ if (decoded.refused) return decoded;
1148
1175
  for (const word of words) {
1149
1176
  const fromSubstitution = scriptsFromSubstitutions(word.raw, depth, ctx);
1150
1177
  if (fromSubstitution.refused) return fromSubstitution;
@@ -1213,6 +1240,18 @@ function bareGh(args: ShellWord[], ctx: Context): SignedLinkVerdict {
1213
1240
  return at >= 0 ? classifyGh(args.slice(at + 1), ctx) : ALLOW;
1214
1241
  }
1215
1242
 
1243
+ /**
1244
+ * A shell program written with ANSI-C `$'…'` quoting, classified with its words
1245
+ * decoded as bash decodes them, so its `\n` is a newline. ALLOW when the program
1246
+ * holds no `$'`. A `$'…'` inside double quotes, which only the inner shell
1247
+ * decodes, needs nothing more: the program text still holds that `$'…'`, and
1248
+ * classifying it reads the word as the inner shell does (a bare
1249
+ * `$'\x67h' pr view 123` is refused). HO-00221.
1250
+ */
1251
+ function ansiProgram(raw: string, next: (text: string) => SignedLinkVerdict): SignedLinkVerdict {
1252
+ return raw.includes("$'") ? next(decodeCommandWord(raw)) : ALLOW;
1253
+ }
1254
+
1216
1255
  /** The command string given to `-c` (also inside a short-option cluster such as `-lc`). */
1217
1256
  function dashCValue(args: ShellWord[]): ShellWord | undefined {
1218
1257
  for (let i = 0; i < args.length; i++) {
@@ -114,3 +114,19 @@ bun test hooks/hook-stop-review/src/policy.test.ts hooks/hook-stop-review/src/je
114
114
 
115
115
  API contract: <https://docs.typesafe.ai/api>. Judgments and confidence semantics:
116
116
  <https://docs.typesafe.ai/primitives/choice> and <https://docs.typesafe.ai/confidence>.
117
+
118
+ ## Codex agent-blocked goals
119
+
120
+ Stop Review 0.1.1 consumes Codex's optional top-level
121
+ `native_goal_stop_review` command-stdin snapshot. It checks the exact snapshot
122
+ shape and turn, then matches its status, objective, budget, tokens and elapsed
123
+ accounting to the native goal getter before review and again before delivery.
124
+ `request_metadata`, transcript text and blocked status alone grant no admission.
125
+
126
+ An admitted agent-blocked goal stays blocked in the classification input. The
127
+ result uses the normal Stop `decision: block` response. Codex alone compares its
128
+ retained goal identity and admission epoch under its final input and accounting
129
+ locks before continuing. Hooks never resumes the goal or changes accounting.
130
+ Owner pauses, exhausted budgets, unavailable native state and provider failures
131
+ continue to stop. Older Codex builds that omit this native capability retain
132
+ the existing active-goal behavior.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stop-review",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Review turn completion against the latest user request and active goal",
5
5
  "events": ["Stop"],
6
6
  "nativeTargetDispatch": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hook-stop-review",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Review premature coding-agent stops with typed Jev classification and native runtime guards",
5
5
  "type": "module",
6
6
  "main": "./src/hook.ts",
@@ -47,7 +47,7 @@ export async function main(argv = process.argv.slice(2), env = process.env): Pro
47
47
  codexHome: config.codexHome ?? env.CODEX_HOME ?? join(env.HOME || homedir(), ".codex"),
48
48
  socketPath: config.codexSocketPath,
49
49
  }),
50
- }, (envelope, isCurrent) => reviewNativeEnvelope(envelope, isCurrent, env, undefined, harness));
50
+ }, (envelope, isCurrent, nativeAdmission) => reviewNativeEnvelope(envelope, isCurrent, env, undefined, harness, nativeAdmission));
51
51
  output = result.output; reason = result.reason;
52
52
  }
53
53
  } catch { reason = "native_review_unavailable"; }