@hasna/hooks 0.13.2 → 0.14.0

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 (41) hide show
  1. package/README.md +30 -15
  2. package/bin/hooks/stop-review.js +53 -17
  3. package/bin/hooks-mcp.js +4787 -1415
  4. package/bin/index.js +5250 -2337
  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 +4970 -1579
  9. package/dist/lib/claude-skills-coordination.d.ts +1 -1
  10. package/dist/lib/codex-safety-trust.d.ts +2 -2
  11. package/dist/lib/native-safety-registration.d.ts +2 -2
  12. package/dist/lib/native-safety.d.ts +1 -1
  13. package/dist/lib/registry.d.ts +3 -1
  14. package/dist/native-safety.d.ts +4 -2
  15. package/dist/native-safety.js +21 -2
  16. package/dist/sdk/index.js +9 -53
  17. package/hooks/hook-job-folder-guard/README.md +61 -0
  18. package/hooks/hook-job-folder-guard/package.json +12 -0
  19. package/hooks/hook-job-folder-guard/src/classify.ts +398 -0
  20. package/hooks/hook-job-folder-guard/src/hook.ts +96 -0
  21. package/hooks/hook-protected-delete-guard/README.md +114 -0
  22. package/hooks/hook-protected-delete-guard/package.json +12 -0
  23. package/hooks/hook-protected-delete-guard/src/hook.ts +539 -0
  24. package/hooks/hook-signed-link-guard/src/classify.ts +41 -2
  25. package/hooks/hook-stop-review/README.md +16 -0
  26. package/hooks/hook-stop-review/manifest.json +1 -1
  27. package/hooks/hook-stop-review/package.json +1 -1
  28. package/hooks/hook-stop-review/src/hook.ts +1 -1
  29. package/hooks/hook-stop-review/src/native.ts +44 -8
  30. package/hooks/hook-stop-review/src/policy.ts +20 -8
  31. package/hooks/hook-stop-review/src/runtime.ts +16 -13
  32. package/hooks/hook-stop-review/src/types.ts +12 -2
  33. package/hooks/hook-trash-guard/README.md +130 -13
  34. package/hooks/hook-trash-guard/src/hook.ts +518 -71
  35. package/hooks/local-executors.ts +33 -0
  36. package/hooks/native-safety-composite.ts +19 -8
  37. package/package.json +3 -3
  38. package/scripts/build-native-entry.ts +123 -0
  39. package/scripts/build-native-worker.ts +11 -4
  40. package/scripts/validate-package.ts +8 -2
  41. package/hooks/native-safety-entry.ts +0 -11
@@ -0,0 +1,398 @@
1
+ /**
2
+ * Job folder classification for the job-folder-guard hook.
3
+ *
4
+ * A harness job folder holds one background session's files and is removed with that session, outside Trash:
5
+ * - Claude Code: <config dir>/jobs/<id>/ (~/.claude/jobs/<id>/, or $CLAUDE_CONFIG_DIR/jobs/<id>/), the value of
6
+ * $CLAUDE_JOB_DIR inside the session;
7
+ * - Switcher-launched Claude: ~/.hasna/switcher/state/<...>/jobs/<id>/;
8
+ * - <any path>/jobs/<id>/tmp/, wherever it is.
9
+ * The harness writes its own state.json and timeline.jsonl directly in jobs/<id>/; those two are excluded. Paths
10
+ * are classified as written, without touching the file system: ~, $HOME and ${HOME} are expanded, $CLAUDE_JOB_DIR
11
+ * and ${CLAUDE_JOB_DIR} are expanded when the hook's environment has the value and otherwise count as a job folder
12
+ * themselves, and a relative path is resolved against the tool call's cwd. Other variables, globs and symlinks are
13
+ * not followed.
14
+ *
15
+ * For Bash, a small lexer reads the command (quotes, backslashes, comments, heredoc bodies skipped, command
16
+ * substitutions and subshells read as their own commands) and reports:
17
+ * - writes: redirect targets (>, >>, >|, &>, &>>, <>, >& FILE), tee's files, the destination of cp, mv, install
18
+ * and ln (or their -t/--target-directory), install -d's directories, and mkdir's and touch's operands;
19
+ * - uses: any other word of a command that names a job folder (a program's argument, the program itself, an
20
+ * input redirect, an assignment's value or an --option=value).
21
+ * It is a reading for a notice, not a shell: what it cannot see (cd within the command, other variables, writes made
22
+ * by the programs it runs) it does not report.
23
+ */
24
+ import { posix } from "node:path";
25
+
26
+ export interface PathContext {
27
+ home: string | null;
28
+ cwd: string | null;
29
+ jobDir: string | null;
30
+ claudeConfigDir: string | null;
31
+ }
32
+
33
+ export interface Hit {
34
+ kind: "write" | "use";
35
+ /** The path as written in the tool call (unquoted). */
36
+ target: string;
37
+ via: string;
38
+ }
39
+
40
+ export interface Classification {
41
+ writes: Hit[];
42
+ uses: Hit[];
43
+ }
44
+
45
+ const HARNESS_FILES: ReadonlySet<string> = new Set(["state.json", "timeline.jsonl"]);
46
+ const JOB_VAR = /^(?:\$CLAUDE_JOB_DIR|\$\{CLAUDE_JOB_DIR\})(?=\/|$)/;
47
+ const HOME_VAR = /^(?:~|\$HOME|\$\{HOME\})(?=\/|$)/;
48
+
49
+ function norm(path: string): string {
50
+ const out = posix.normalize(path);
51
+ return out.length > 1 ? out.replace(/\/+$/, "") : out;
52
+ }
53
+
54
+ function segments(path: string): string[] {
55
+ return path.split("/").filter(Boolean);
56
+ }
57
+
58
+ /** The segments after `root/`, or null when `abs` is not below `root`. */
59
+ function below(abs: string, root: string): string[] | null {
60
+ const r = norm(root);
61
+ return abs.startsWith(`${r}/`) ? segments(abs.slice(r.length)) : null;
62
+ }
63
+
64
+ /** A job folder's content: an id and at least one more segment, not the harness's own file directly in it. */
65
+ function jobContent(rest: string[] | null): boolean {
66
+ if (!rest || rest.length < 2) return false;
67
+ return !(rest.length === 2 && HARNESS_FILES.has(rest[1]));
68
+ }
69
+
70
+ function isJobFolder(abs: string, ctx: PathContext): boolean {
71
+ const segs = segments(abs);
72
+ for (let i = 0; i + 2 < segs.length; i++) if (segs[i] === "jobs" && segs[i + 2] === "tmp") return true;
73
+ if (ctx.home && jobContent(below(abs, `${ctx.home}/.claude/jobs`))) return true;
74
+ if (ctx.claudeConfigDir && jobContent(below(abs, `${ctx.claudeConfigDir}/jobs`))) return true;
75
+ if (ctx.home) {
76
+ const rest = below(abs, `${ctx.home}/.hasna/switcher/state`);
77
+ if (rest) {
78
+ for (let i = 0; i < rest.length; i++) if (rest[i] === "jobs" && jobContent(rest.slice(i + 1))) return true;
79
+ }
80
+ }
81
+ if (ctx.jobDir) {
82
+ const rest = below(abs, ctx.jobDir);
83
+ if (rest && rest.length > 0 && !(rest.length === 1 && HARNESS_FILES.has(rest[0]))) return true;
84
+ }
85
+ return false;
86
+ }
87
+
88
+ /**
89
+ * The path's normalized absolute form when it is in a harness job folder, else null. With $CLAUDE_JOB_DIR unset in
90
+ * the hook's environment, a path starting with it is returned as written.
91
+ */
92
+ export function jobFolderPath(raw: string, ctx: PathContext): string | null {
93
+ if (typeof raw !== "string" || raw === "") return null;
94
+ let path = raw;
95
+ const jobVar = JOB_VAR.exec(path);
96
+ if (jobVar) {
97
+ if (!ctx.jobDir) {
98
+ const rest = segments(norm(`/${path.slice(jobVar[0].length)}`));
99
+ return rest.length === 1 && HARNESS_FILES.has(rest[0]) ? null : raw;
100
+ }
101
+ path = ctx.jobDir + path.slice(jobVar[0].length);
102
+ }
103
+ const homeVar = HOME_VAR.exec(path);
104
+ if (homeVar) {
105
+ if (!ctx.home) return null;
106
+ path = ctx.home + path.slice(homeVar[0].length);
107
+ }
108
+ if (!path.startsWith("/")) {
109
+ if (!ctx.cwd || !ctx.cwd.startsWith("/")) return null;
110
+ path = `${ctx.cwd}/${path}`;
111
+ }
112
+ const abs = norm(path);
113
+ return isJobFolder(abs, ctx) ? abs : null;
114
+ }
115
+
116
+ // ---------------------------------------------------------------------------------------------------------------
117
+ // Lexer
118
+
119
+ type Token = { t: "word"; v: string } | { t: "op"; v: string };
120
+
121
+ const OPERATORS = ["&>>", "<<<", "<<-", "&&", "||", ";;", "|&", ">>", "&>", ">|", ">&", "<<", "<>", "<&", ";", "&", "|", "(", ")", "<", ">", "\n"];
122
+ const SEPARATORS: ReadonlySet<string> = new Set([";", ";;", "&", "&&", "||", "|", "|&", "(", ")", "\n", "`"]);
123
+ const WRITE_REDIRECTS: ReadonlySet<string> = new Set([">", ">>", ">|", "&>", "&>>", "<>"]);
124
+
125
+ export function lex(command: string): Token[] {
126
+ const s = command;
127
+ const tokens: Token[] = [];
128
+ const heredocs: { delim: string; strip: boolean }[] = [];
129
+ let expectDelim: boolean | null = null; // the next word is a heredoc delimiter (value: strip tabs)
130
+ let word = "";
131
+ let inWord = false;
132
+ let quoted = false;
133
+ let i = 0;
134
+
135
+ const endWord = () => {
136
+ if (!inWord) return;
137
+ if (expectDelim !== null) {
138
+ heredocs.push({ delim: word, strip: expectDelim });
139
+ expectDelim = null;
140
+ } else {
141
+ tokens.push({ t: "word", v: word });
142
+ }
143
+ word = "";
144
+ inWord = false;
145
+ quoted = false;
146
+ };
147
+ const skipHeredocBodies = () => {
148
+ while (heredocs.length > 0) {
149
+ const { delim, strip } = heredocs.shift()!;
150
+ while (i < s.length) {
151
+ const nl = s.indexOf("\n", i);
152
+ const line = nl === -1 ? s.slice(i) : s.slice(i, nl);
153
+ i = nl === -1 ? s.length : nl + 1;
154
+ if ((strip ? line.replace(/^\t+/, "") : line) === delim) break;
155
+ }
156
+ }
157
+ };
158
+
159
+ while (i < s.length) {
160
+ const c = s[i];
161
+ if (c === "\\") {
162
+ if (s[i + 1] === "\n") { i += 2; continue; }
163
+ if (i + 1 < s.length) { word += s[i + 1]; inWord = true; quoted = true; }
164
+ i += 2;
165
+ continue;
166
+ }
167
+ if (c === "'") {
168
+ const end = s.indexOf("'", i + 1);
169
+ word += end === -1 ? s.slice(i + 1) : s.slice(i + 1, end);
170
+ inWord = true; quoted = true;
171
+ i = end === -1 ? s.length : end + 1;
172
+ continue;
173
+ }
174
+ if (c === "$" && s[i + 1] === "'") {
175
+ let j = i + 2;
176
+ while (j < s.length && s[j] !== "'") {
177
+ if (s[j] === "\\" && j + 1 < s.length) { word += s[j + 1]; j += 2; } else { word += s[j]; j += 1; }
178
+ }
179
+ inWord = true; quoted = true;
180
+ i = j + 1;
181
+ continue;
182
+ }
183
+ if (c === '"') {
184
+ let j = i + 1;
185
+ while (j < s.length && s[j] !== '"') {
186
+ if (s[j] === "\\" && j + 1 < s.length && '"\\$`\n'.includes(s[j + 1])) {
187
+ if (s[j + 1] !== "\n") word += s[j + 1];
188
+ j += 2;
189
+ } else { word += s[j]; j += 1; }
190
+ }
191
+ inWord = true; quoted = true;
192
+ i = j + 1;
193
+ continue;
194
+ }
195
+ if (c === "$" && s[i + 1] === "(") {
196
+ endWord();
197
+ tokens.push({ t: "op", v: "(" });
198
+ i += s[i + 2] === "(" ? 3 : 2;
199
+ continue;
200
+ }
201
+ if (c === "`") {
202
+ endWord();
203
+ tokens.push({ t: "op", v: "`" });
204
+ i += 1;
205
+ continue;
206
+ }
207
+ if (c === "#" && !inWord) {
208
+ const nl = s.indexOf("\n", i);
209
+ i = nl === -1 ? s.length : nl;
210
+ continue;
211
+ }
212
+ if (c === " " || c === "\t") {
213
+ endWord();
214
+ i += 1;
215
+ continue;
216
+ }
217
+ const op = OPERATORS.find((o) => s.startsWith(o, i));
218
+ if (op) {
219
+ // A digit-only unquoted word right before a redirect is its file descriptor, not a word.
220
+ if ((op[0] === "<" || op[0] === ">") && inWord && !quoted && /^\d+$/.test(word)) {
221
+ word = ""; inWord = false;
222
+ } else {
223
+ endWord();
224
+ }
225
+ tokens.push({ t: "op", v: op });
226
+ i += op.length;
227
+ if (op === "<<" || op === "<<-") expectDelim = op === "<<-";
228
+ if (op === "\n") skipHeredocBodies();
229
+ continue;
230
+ }
231
+ word += c;
232
+ inWord = true;
233
+ i += 1;
234
+ }
235
+ endWord();
236
+ return tokens;
237
+ }
238
+
239
+ // ---------------------------------------------------------------------------------------------------------------
240
+ // Commands
241
+
242
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
243
+
244
+ function basename(word: string): string {
245
+ const parts = word.split("/");
246
+ return parts[parts.length - 1];
247
+ }
248
+
249
+ /** Skip leading assignments and wrapper commands; the index of the command word, or -1. */
250
+ function commandIndex(words: string[]): number {
251
+ let k = 0;
252
+ const skipOptions = (withArg: ReadonlySet<string>): void => {
253
+ while (k < words.length && words[k].startsWith("-") && words[k] !== "-") {
254
+ const w = words[k];
255
+ k += 1;
256
+ if (w === "--") return;
257
+ if (withArg.has(w)) k += 1;
258
+ }
259
+ };
260
+ for (let guard = 0; guard < 32 && k < words.length; guard++) {
261
+ if (ASSIGNMENT.test(words[k])) { k += 1; continue; }
262
+ const name = basename(words[k]);
263
+ if (name === "env") {
264
+ k += 1;
265
+ skipOptions(new Set(["-u", "--unset", "-C", "--chdir", "-S", "--split-string"]));
266
+ while (k < words.length && (ASSIGNMENT.test(words[k]) || words[k] === "-")) k += 1;
267
+ continue;
268
+ }
269
+ if (name === "sudo") { k += 1; skipOptions(new Set(["-u", "-g", "-p", "-C", "-D", "-r", "-t", "-U", "-h"])); continue; }
270
+ if (name === "timeout") { k += 1; skipOptions(new Set(["-k", "-s", "--kill-after", "--signal"])); k += 1; continue; }
271
+ if (name === "nice") { k += 1; skipOptions(new Set(["-n", "--adjustment"])); continue; }
272
+ if (name === "stdbuf") { k += 1; skipOptions(new Set(["-i", "-o", "-e", "--input", "--output", "--error"])); continue; }
273
+ if (name === "exec") { k += 1; skipOptions(new Set(["-a"])); continue; }
274
+ if (name === "nohup" || name === "command" || name === "builtin" || name === "time") { k += 1; skipOptions(new Set()); continue; }
275
+ return k;
276
+ }
277
+ return k < words.length ? k : -1;
278
+ }
279
+
280
+ interface Operands {
281
+ positional: string[];
282
+ targetDir: string | null;
283
+ flags: Set<string>;
284
+ }
285
+
286
+ function operands(args: string[], withArg: ReadonlySet<string>, targetOptions: ReadonlySet<string>): Operands {
287
+ const out: Operands = { positional: [], targetDir: null, flags: new Set() };
288
+ for (let j = 0; j < args.length; j++) {
289
+ const a = args[j];
290
+ if (a === "--") { out.positional.push(...args.slice(j + 1)); break; }
291
+ if (a.startsWith("--")) {
292
+ const eq = a.indexOf("=");
293
+ const name = eq === -1 ? a : a.slice(0, eq);
294
+ if (targetOptions.has(name)) out.targetDir = eq === -1 ? (args[++j] ?? null) : a.slice(eq + 1);
295
+ else if (eq === -1 && withArg.has(name)) j += 1;
296
+ out.flags.add(name);
297
+ continue;
298
+ }
299
+ if (a.startsWith("-") && a.length > 1) {
300
+ // A cluster of short options; one that takes an argument takes the rest of the word or the next word.
301
+ for (let n = 1; n < a.length; n++) {
302
+ const opt = `-${a[n]}`;
303
+ out.flags.add(opt);
304
+ if (targetOptions.has(opt) || withArg.has(opt)) {
305
+ const value = n + 1 < a.length ? a.slice(n + 1) : (args[++j] ?? null);
306
+ if (targetOptions.has(opt)) out.targetDir = value;
307
+ break;
308
+ }
309
+ }
310
+ continue;
311
+ }
312
+ out.positional.push(a);
313
+ }
314
+ return out;
315
+ }
316
+
317
+ const COPY_LIKE: ReadonlySet<string> = new Set(["cp", "mv", "install", "ln"]);
318
+ const COPY_WITH_ARG: ReadonlySet<string> = new Set(["-m", "--mode", "-o", "--owner", "-g", "--group", "-S", "--suffix"]);
319
+ const TARGET_DIR: ReadonlySet<string> = new Set(["-t", "--target-directory"]);
320
+ const CREATE_WITH_ARG: Record<string, ReadonlySet<string>> = {
321
+ mkdir: new Set(["-m", "--mode", "--context"]),
322
+ touch: new Set(["-d", "--date", "-t", "-r", "--reference"]),
323
+ };
324
+
325
+ /** Writes and other words of one simple command. */
326
+ function commandTargets(words: string[]): { writes: { target: string; via: string }[]; others: string[] } {
327
+ const writes: { target: string; via: string }[] = [];
328
+ const others: string[] = [];
329
+ const k = commandIndex(words);
330
+ for (const w of words.slice(0, k === -1 ? words.length : k)) {
331
+ const eq = w.indexOf("=");
332
+ others.push(ASSIGNMENT.test(w) ? w.slice(eq + 1) : w);
333
+ }
334
+ if (k === -1) return { writes, others };
335
+ const name = basename(words[k]);
336
+ const args = words.slice(k + 1);
337
+ others.push(words[k]);
338
+ let written: Set<string> = new Set();
339
+ if (name === "tee") {
340
+ const ops = operands(args, new Set(["--output-error"]), new Set());
341
+ for (const p of ops.positional) writes.push({ target: p, via: "tee" });
342
+ written = new Set(ops.positional);
343
+ } else if (COPY_LIKE.has(name)) {
344
+ const ops = operands(args, COPY_WITH_ARG, TARGET_DIR);
345
+ if (ops.targetDir !== null) {
346
+ writes.push({ target: ops.targetDir, via: name });
347
+ } else if (name === "install" && (ops.flags.has("-d") || ops.flags.has("--directory"))) {
348
+ for (const p of ops.positional) writes.push({ target: p, via: "install -d" });
349
+ written = new Set(ops.positional);
350
+ } else if (ops.positional.length >= 2) {
351
+ const dest = ops.positional[ops.positional.length - 1];
352
+ writes.push({ target: dest, via: name });
353
+ written = new Set([dest]);
354
+ }
355
+ } else if (name in CREATE_WITH_ARG) {
356
+ const ops = operands(args, CREATE_WITH_ARG[name], new Set());
357
+ for (const p of ops.positional) writes.push({ target: p, via: name });
358
+ written = new Set(ops.positional);
359
+ }
360
+ for (const a of args) {
361
+ if (written.has(a)) continue;
362
+ const eq = a.startsWith("-") ? a.indexOf("=") : -1;
363
+ others.push(eq === -1 ? a : a.slice(eq + 1));
364
+ }
365
+ return { writes, others };
366
+ }
367
+
368
+ export function classifyCommand(command: string, ctx: PathContext): Classification {
369
+ const result: Classification = { writes: [], uses: [] };
370
+ if (typeof command !== "string" || command.trim() === "") return result;
371
+ const tokens = lex(command);
372
+ const add = (kind: "write" | "use", target: string, via: string) => {
373
+ if (jobFolderPath(target, ctx) === null) return;
374
+ (kind === "write" ? result.writes : result.uses).push({ kind, target, via });
375
+ };
376
+ let words: string[] = [];
377
+ const flush = () => {
378
+ if (words.length === 0) return;
379
+ const { writes, others } = commandTargets(words);
380
+ for (const w of writes) add("write", w.target, w.via);
381
+ for (const o of others) add("use", o, "argument");
382
+ words = [];
383
+ };
384
+ for (let n = 0; n < tokens.length; n++) {
385
+ const tok = tokens[n];
386
+ if (tok.t === "word") { words.push(tok.v); continue; }
387
+ if (SEPARATORS.has(tok.v)) { flush(); continue; }
388
+ const next = tokens[n + 1];
389
+ if (!next || next.t !== "word") continue;
390
+ n += 1;
391
+ if (WRITE_REDIRECTS.has(tok.v)) add("write", next.v, "redirect");
392
+ else if (tok.v === ">&") { if (!/^(\d+|-)$/.test(next.v)) add("write", next.v, "redirect"); }
393
+ else if (tok.v === "<") add("use", next.v, "redirect");
394
+ // <&, <<< and heredoc delimiters name descriptors or text, not files.
395
+ }
396
+ flush();
397
+ return result;
398
+ }
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env bun
2
+
3
+ /**
4
+ * PreToolUse hook: job-folder-guard (HO-00190, stage 1)
5
+ *
6
+ * Agents put scratch files in harness job folders (…/jobs/<id>/tmp/, as the background-session prompt suggests with
7
+ * $CLAUDE_JOB_DIR/tmp, and Switcher-launched sessions' ~/.hasna/switcher/state/…/jobs/<id>/). Those folders are
8
+ * removed with their session, outside Trash. When a Write, Edit, MultiEdit or NotebookEdit targets one, or a Bash
9
+ * command writes to or uses one, this hook adds a notice to the model's context naming the session's Scratchpad
10
+ * folder, ~/.hasna/scratchpad/scratch/<session-id>/.
11
+ *
12
+ * Stage 1 never decides: the output carries only `additionalContext`, never `permissionDecision`, so the user's
13
+ * permission flow and every other hook's verdict are unchanged. It runs as its own hook because the native safety
14
+ * entry accepts only a deny. A later stage may refuse such writes; that is a separate, reviewed change.
15
+ *
16
+ * Output contract:
17
+ * - nothing to say -> nothing on stdout
18
+ * - a job folder -> { hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext } }
19
+ * Any error in classification is silence: a notice must never stand in the way of a tool call.
20
+ */
21
+
22
+ import { readInput, respond, type CodewithHookInput, type CodewithHookOutput } from "../../codewith-native-common";
23
+ import { classifyCommand, jobFolderPath, type Hit, type PathContext } from "./classify";
24
+
25
+ export { classifyCommand, jobFolderPath } from "./classify";
26
+
27
+ const FILE_TOOLS: Record<string, string> = { Write: "file_path", Edit: "file_path", MultiEdit: "file_path", NotebookEdit: "notebook_path" };
28
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
29
+ const UNSAFE_CHARS = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u200e\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069]", "g");
30
+ const MAX_SHOWN = 200;
31
+
32
+ function shown(path: string): string {
33
+ const clean = path.replace(UNSAFE_CHARS, "");
34
+ return clean.length > MAX_SHOWN ? `${clean.slice(0, MAX_SHOWN)}…` : clean;
35
+ }
36
+
37
+ /** The notice for one hit. The session id is used only when it is a plain id. */
38
+ export function contextFor(hit: Hit, sessionId: unknown): string {
39
+ const id = typeof sessionId === "string" && SESSION_ID.test(sessionId) ? sessionId : "<session-id>";
40
+ const folder = `~/.hasna/scratchpad/scratch/${id}/`;
41
+ const what = hit.kind === "write" ? `This writes to ${shown(hit.target)}` : `This command uses ${shown(hit.target)}`;
42
+ return [
43
+ `[job-folder-guard] ${what}, inside a harness job folder (…/jobs/<id>/).`,
44
+ "Job folders are removed with their session, outside Trash, so what is kept there is lost without a record.",
45
+ `Keep scratch in ${folder} instead (rules global-hosted-app-authority and global-scratch-is-transient);`,
46
+ "the harness prompt's $CLAUDE_JOB_DIR/tmp hint does not apply.",
47
+ "This is a notice only: the tool call goes ahead.",
48
+ ].join(" ");
49
+ }
50
+
51
+ function pathContext(input: CodewithHookInput, env: NodeJS.ProcessEnv): PathContext {
52
+ return {
53
+ home: env.HOME && env.HOME.startsWith("/") ? env.HOME : null,
54
+ cwd: typeof input.cwd === "string" ? input.cwd : null,
55
+ jobDir: env.CLAUDE_JOB_DIR && env.CLAUDE_JOB_DIR.startsWith("/") ? env.CLAUDE_JOB_DIR : null,
56
+ claudeConfigDir: env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.startsWith("/") ? env.CLAUDE_CONFIG_DIR : null,
57
+ };
58
+ }
59
+
60
+ function firstHit(input: CodewithHookInput, ctx: PathContext): Hit | null {
61
+ const tool = input.tool_name ?? "";
62
+ const field = FILE_TOOLS[tool];
63
+ if (field) {
64
+ const path = input.tool_input?.[field];
65
+ return typeof path === "string" && jobFolderPath(path, ctx) !== null ? { kind: "write", target: path, via: tool } : null;
66
+ }
67
+ if (tool === "Bash") {
68
+ const command = input.tool_input?.command;
69
+ if (typeof command !== "string") return null;
70
+ const result = classifyCommand(command, ctx);
71
+ return result.writes[0] ?? result.uses[0] ?? null;
72
+ }
73
+ return null;
74
+ }
75
+
76
+ /** The hook's output for one input. `{ continue: true }` means "nothing to say". */
77
+ export function evaluate(input: CodewithHookInput, env: NodeJS.ProcessEnv = process.env): CodewithHookOutput {
78
+ if (input?.hook_event_name !== "PreToolUse") return { continue: true };
79
+ let hit: Hit | null = null;
80
+ try {
81
+ hit = firstHit(input, pathContext(input, env));
82
+ } catch {
83
+ return { continue: true };
84
+ }
85
+ if (!hit) return { continue: true };
86
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: contextFor(hit, input.session_id) } };
87
+ }
88
+
89
+ export async function run(): Promise<void> {
90
+ const verdict = evaluate(readInput());
91
+ if ("hookSpecificOutput" in verdict) respond(verdict);
92
+ }
93
+
94
+ if (import.meta.main) {
95
+ void run().then(() => process.exit(0));
96
+ }
@@ -0,0 +1,114 @@
1
+ # protected-delete-guard
2
+
3
+ A `PreToolUse` guard that refuses a delete of the protected class and of
4
+ coding-agent session and history stores. It only refuses. It never rewrites a
5
+ command, never looks for a trash binary, and reads no store, network or
6
+ credential. An ordinary removal passes untouched.
7
+
8
+ These refusals used to be part of `trash-guard`, which cannot be registered
9
+ without Trash. This guard carries them on their own, so they hold where
10
+ `trash-guard` is not registered.
11
+
12
+ ## What it refuses
13
+
14
+ `rm`, `rmdir`, `unlink` and `shred`, when an operand is:
15
+
16
+ - `/` or a system root (`/etc`, `/usr`, `/Users`, …);
17
+ - the home directory;
18
+ - `~/.ssh` or `~/.aws`: the path, anything that contains it, anything inside it;
19
+ - `~/.hasna`: the path, anything that contains it, and anything inside it
20
+ except
21
+ - the content of a session's scratch folder,
22
+ `~/.hasna/scratchpad/scratch/<session-id>/<child…>` (not the session
23
+ folder itself, nor its `meta.json` and `.lock`), and
24
+ - the content of a managed worktree under `~/.hasna/repos/worktrees` (not
25
+ the worktree root, a repository or org folder, or the worktrees root);
26
+ - a coding-agent session or history store, or a path that contains one or lies
27
+ inside one: Claude Code (`~/.claude`, `~/.claude.json`), Codex (`sessions`,
28
+ `archived_sessions` and the history, index and state files of `~/.codex`),
29
+ OpenCode, Sumi and Devin (their data and state folders), Cursor, DSH
30
+ (`~/.dsh`, `~/.dsh-tui`), antigravity (`~/.gemini/antigravity-cli`), Cline
31
+ (`~/.cline`), Gemini CLI (`~/.gemini/tmp`, `~/.gemini/history`), Qwen Code
32
+ (`~/.qwen`), GitHub Copilot CLI (`~/.copilot`) and Codewith (`~/.codewith`).
33
+ It is the list `@hasna/trash` refuses as `protected_session_history`, and a
34
+ test compares the two lists;
35
+ - a pattern that can name one of the above: `rm -rf ~/*`, `rm -rf /*`,
36
+ `rm -rf ~/.s*`.
37
+
38
+ `find` with a delete action (`-delete`, or `-exec`, `-execdir`, `-ok` running a
39
+ delete verb) is refused wherever it runs, a repository checkout included: what
40
+ it removes is decided by its walk. List the paths with `-print`, then remove
41
+ them with `rm -- <path>`.
42
+
43
+ A patch (`apply_patch`) is refused when a `*** Delete File:` path is in the
44
+ class or in a store.
45
+
46
+ A delete the guard cannot read exactly (an operand the shell expands, a shell
47
+ string such as `sh -c '…'`, `xargs rm`, `git clean`, an expansion in command
48
+ position, an unclosed quote) is refused only when a word of the command names
49
+ a protected path, as in `for d in ~/.claude ~/.codex; do rm -rf "$d"; done`.
50
+ Otherwise it passes.
51
+
52
+ Commands are read with `trash-guard`'s scan: wrappers (`sudo`, `env`,
53
+ `timeout`, …), quoting, continued lines, `cd`, brace patterns and command
54
+ substitutions.
55
+
56
+ ## Limits
57
+
58
+ - **An operand the shell expands is judged only by the rest of the command.**
59
+ `rm -rf "$DIR"` and `rm -rf "$(cat list)"` pass unless the command itself
60
+ names a protected path: the guard reads words before the command runs, and
61
+ does not know what a variable set elsewhere holds. `~`, `$HOME`, `${HOME}`
62
+ and the forms that yield the home whenever it is set (`${HOME:?}`,
63
+ `${HOME?}`, `${HOME:-…}`, `${HOME-…}`, `${HOME:=…}`, `${HOME%/}`) are read.
64
+ - **Session roots that come from environment variables are not seen under the
65
+ native registration.** The registered command runs with `HOME` and `PATH`
66
+ only, so roots configured through `CLAUDE_CONFIG_DIR`, `CODEX_HOME`,
67
+ `XDG_DATA_HOME`, `XDG_STATE_HOME`, `XDG_CONFIG_HOME`, `DSH_HOME`,
68
+ `DSH_TUI_SESSION_ROOT` or `HASNA_TRASH_SESSION_ROOTS` are protected only at
69
+ their default places under the home directory.
70
+ - **The stores are not walked for symlinks that lead out of them.**
71
+ `@hasna/trash` protects the target of every link found inside a store; that
72
+ walk takes seconds on a large store and this guard runs on every command.
73
+ The guard follows the links on the way to a store root and on the way to the
74
+ path being removed, not the links inside a store.
75
+ - **Launchers the scan does not model pass.** The scan reads the common
76
+ wrappers (`sudo`, `env`, `timeout`, `nice`, `command`, …), shell strings and
77
+ substitutions. A command that runs a delete through a launcher it does not
78
+ know (`trap '…' EXIT`, `caffeinate`, `arch`, `watch`, `parallel`) is read as
79
+ a command that deletes nothing, as `trash-guard` reads it.
80
+ - **A worktree's own `.git` is worktree content.** `rm -rf <worktree>/.git`
81
+ passes, as other content of a managed worktree does; it detaches the
82
+ worktree, and `repos` can still recover it from its branch.
83
+ - On macOS and Windows the protected paths and the stores are compared without
84
+ regard to case (`~/.SSH` is `~/.ssh`); elsewhere they are compared as
85
+ written. Both are also compared with the parent folder resolved.
86
+
87
+ ## Registration
88
+
89
+ It is a bundled native safety guard, registered on its own and pinned by
90
+ digest, like `workspace-repos-guard`:
91
+
92
+ ```sh
93
+ hooks safety registration-plan --target claude --guard protected-delete-guard
94
+ hooks safety registration-apply --target claude --guard protected-delete-guard --expected-plan-digest <digest>
95
+
96
+ hooks safety registration-plan --target codex --guard protected-delete-guard
97
+ hooks safety registration-apply --target codex --guard protected-delete-guard --expected-plan-digest <digest>
98
+ hooks safety trust-plan --target codex --guard protected-delete-guard
99
+ hooks safety trust-apply --target codex --guard protected-delete-guard --expected-plan-digest <digest>
100
+ ```
101
+
102
+ Only this guard's entry is written. In Codex it is appended after the existing
103
+ handlers, so no other handler's position or trusted hash changes.
104
+
105
+ A `@hasna/hooks` older than the release that adds this guard does not know its
106
+ name: it reads a settings file that holds this registration as an unknown
107
+ managed definition and refuses to write a native guard there. Run the
108
+ registration commands with the release that carries the guard.
109
+
110
+ ## Switching it off
111
+
112
+ Remove or disable this guard's own registration: its `PreToolUse` entry in
113
+ Claude Code's settings, or `enabled = false` on its own key in Codex's
114
+ `hooks.state`. No other guard depends on it, and it depends on none.
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "protected-delete-guard",
3
+ "version": "0.1.0",
4
+ "description": "Native Protected Delete Guard hook for @hasna/hooks",
5
+ "type": "module",
6
+ "main": "./src/hook.ts",
7
+ "scripts": {
8
+ "typecheck": "tsc --noEmit"
9
+ },
10
+ "author": "Hasna",
11
+ "license": "Apache-2.0"
12
+ }