dsh-delete-guard 0.0.0-stage → 2.4.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.
package/lib/guard.js ADDED
@@ -0,0 +1,952 @@
1
+ /**
2
+ * Destructive-command detection and rewrite planning.
3
+ *
4
+ * This module is pure: it takes a command string and returns a verdict plus the
5
+ * list of paths a rewrite should move to the Recycle Bin. No I/O, no ctx, so it
6
+ * is directly unit-testable.
7
+ *
8
+ * Design notes
9
+ * ------------
10
+ * The matcher is *command-position aware*: a delete verb only counts when it
11
+ * appears where a command can start (after a separator or at the string head).
12
+ * That keeps `Get-Content form.txt` and `$rm = 1` from being false positives,
13
+ * which is the failure mode of naive `/\brm\b/` guards.
14
+ *
15
+ * Unlike a block-only guard, a matched command is not simply denied: the parsed
16
+ * operands are handed back so the caller can perform a real recycle-bin move.
17
+ * Denial is the fallback for the cases where a safe rewrite cannot be proven
18
+ * (pipelines, command substitution, `-Recurse` over an unresolved glob, etc.).
19
+ *
20
+ * This module judges *deletes*. Content that is destroyed without any delete
21
+ * verb — an in-place rewrite of the only copy — is `rewrite-guard.js`; the two
22
+ * are wired together at the bottom of `classifyCommand`.
23
+ */
24
+
25
+ import { commandWord, splitStatements, tokenize, unquote } from './shell-text.js';
26
+ import { analyzeOverwriteRisk } from './rewrite-guard.js';
27
+
28
+ /** PowerShell delete verbs whose operand list we can trust. */
29
+ const PS_DELETE_VERBS = ['remove-item', 'ri'];
30
+ /** PowerShell cmdlet aliases that mean the same thing. */
31
+ const PS_DELETE_ALIASES = ['del', 'erase', 'rd', 'rmdir', 'rm'];
32
+ /** POSIX delete verbs. */
33
+ const POSIX_DELETE_VERBS = ['rm', 'unlink', 'rmdir', 'shred', 'srm'];
34
+
35
+ /**
36
+ * Delete-cmdlet parameters that consume the following token as their value.
37
+ * Lower-cased, because the lookup is case-insensitive.
38
+ *
39
+ * Kept as an explicit list rather than a `-<word> <word>` heuristic: an operand
40
+ * legitimately follows no flag at all, and guessing would swallow real targets.
41
+ * `-Path` / `-LiteralPath` are handled separately because their value *is* the
42
+ * target.
43
+ */
44
+ const FLAGS_TAKING_VALUE = new Set([
45
+ '-erroraction',
46
+ '-ea',
47
+ '-errorvariable',
48
+ '-ev',
49
+ '-warningaction',
50
+ '-wa',
51
+ '-warningvariable',
52
+ '-wv',
53
+ '-informationaction',
54
+ '-infa',
55
+ '-informationvariable',
56
+ '-iv',
57
+ '-outbuffer',
58
+ '-ob',
59
+ '-outvariable',
60
+ '-ov',
61
+ '-pipelinevariable',
62
+ '-pv',
63
+ '-filter',
64
+ '-include',
65
+ '-exclude',
66
+ '-credential',
67
+ '-confirm',
68
+ '-whatif',
69
+ '-verbose',
70
+ '-debug',
71
+ ]);
72
+
73
+ /**
74
+ * Programs that mean "permanently erase" rather than "delete". They are never
75
+ * rewritten — they are denied outright.
76
+ *
77
+ * Matched in **program position** (the command word of a statement, optionally
78
+ * behind a path or a launcher), never as a substring of the whole line. Whole-
79
+ * line matching was the bug: `Get-Content C:\logs\sdelete.log`,
80
+ * `Select-String -Pattern "wipe" notes.md` and `grep -n "shred" *.md` all name an
81
+ * erase tool while erasing nothing, and all three were refused as if they were
82
+ * about to erase the disk.
83
+ */
84
+ const WIPE_PROGRAMS = new Set(['sdelete', 'sdelete64', 'shred', 'srm', 'wipe']);
85
+
86
+ /**
87
+ * Verbs whose following argument is itself the program that will run.
88
+ * `Start-Process -FilePath shred …` and `cmd /c shred …` name the wipe tool as
89
+ * an argument, so looking only at the command word would miss them.
90
+ */
91
+ const LAUNCHER_VERBS = new Set(['start-process', 'start', 'saps', 'cmd', 'invoke-item', 'ii']);
92
+
93
+ /**
94
+ * Erase by flag rather than by program name. Matched anywhere in the command:
95
+ * the flag shape *is* the evidence, and no read-only command is spelled
96
+ * `cipher /w` or `format D:`.
97
+ */
98
+ const WIPE_FLAG_SHAPES = [
99
+ /\bcipher\s+\/w\b/i,
100
+ /\bcipher\s+\/w:\S+/i,
101
+ /\bformat\s+[a-z]:/i,
102
+ ];
103
+
104
+ /**
105
+ * A wipe-program name anywhere inside the body handed to a child *shell*
106
+ * (`bash -c "shred -u x"`). Such a body is shell text, not an operand, so the
107
+ * argument that *calls* itself out of program position does not protect it.
108
+ */
109
+ const WIPE_NAME_IN_BODY = /\b(?:sdelete64|sdelete|shred|srm|wipe)\b/i;
110
+
111
+ /**
112
+ * A call that hands a string to a process, for interpreters whose body is *not*
113
+ * shell text. `node -e "…shred…"` only erases anything if the name reaches an
114
+ * `exec`/`spawn`/`system` call; without one it is a word in a string.
115
+ *
116
+ * Measured 2026-11-15, on the published 2.2.3: maintaining this very repository
117
+ * was refused, because the README text being written quoted `shred` inside a
118
+ * `node -e` body — prose, no process involved. The rule read the name anywhere in
119
+ * the body and could not tell documentation from a command.
120
+ */
121
+ const SPAWN_CALL =
122
+ /(?:\.\s*(?:exec|execFile|execSync|spawn|spawnSync|popen)\s*\(|\bsubprocess\s*\.\s*(?:run|call|Popen|check_output|check_call)\s*\(|\bos\s*\.\s*(?:system|popen|execl?\w*|spawn\w*)\s*\(|\bsystem\s*\(|%\s*x\s*[({])/i;
123
+
124
+ /**
125
+ * Child interpreters whose inline body is a shell program. For these, any name in
126
+ * the body counts as a program name; for every other interpreter the name must
127
+ * also reach a process-spawning call.
128
+ */
129
+ const SHELL_INTERPRETERS = /\b(?:bash|sh|zsh|pwsh|powershell)\b/i;
130
+
131
+ /** Denial text shared by every permanent-erase rule. */
132
+ const WIPE_REASON =
133
+ 'Permanent-erase tools (shred/sdelete/srm/cipher /w/format) are disabled by the recycle-bin guard. ' +
134
+ 'Use the file_trash tool so the data stays recoverable.';
135
+
136
+ /**
137
+ * Command fragments that empty or bypass the Recycle Bin. Denied, because the
138
+ * whole point of this plugin is that deleted data stays recoverable.
139
+ */
140
+ const EMPTY_RECYCLE_RULES = [
141
+ // `Clear-RecycleBin` is an action only in command position. Matching it
142
+ // anywhere refused `Select-String -Pattern "Clear-RecycleBin" README.md`,
143
+ // i.e. reading this plugin's own documentation about the rule. Command
144
+ // position is resolved per statement by `commandWordsOf` below, which also
145
+ // reaches the invoke-operator and child-shell spellings.
146
+ // Reaching *into* the bin store is only meaningful behind a delete verb, so
147
+ // these stay verb-anchored and are judged per statement.
148
+ { re: /\bremove-item\b[^\n;&|]*(?:\$recycle\.bin|recycler\b)/i, what: 'a delete inside the Recycle Bin' },
149
+ { re: /\brd\b[^\n;&|]*(?:\$recycle\.bin|recycler\b)/i, what: 'a delete inside the Recycle Bin' },
150
+ { re: /\brmdir\b[^\n;&|]*(?:\$recycle\.bin|recycler\b)/i, what: 'a delete inside the Recycle Bin' },
151
+ { re: /\bdel\b[^\n;&|]*(?:\$recycle\.bin|recycler\b)/i, what: 'a delete inside the Recycle Bin' },
152
+ { re: /\brm\b[^\n;&|]*(?:\$recycle\.bin|recycler\b)/i, what: 'a delete inside the Recycle Bin' },
153
+ ];
154
+
155
+ /**
156
+ * The Recycle Bin's own emptying paths, which never name a delete verb.
157
+ *
158
+ * Four shapes reach the bin's contents: the cmdlet in command position
159
+ * (`Clear-RecycleBin -Force`), the invoke operator with the name as a string
160
+ * (`& "Clear-RecycleBin"`), a child shell running it
161
+ * (`pwsh -Command "Clear-RecycleBin"`, `-EncodedCommand <base64>`), and the
162
+ * Win32 call `SHEmptyRecycleBin`. A fifth drives the bin's *own* shell verbs
163
+ * over its items (`InvokeVerb('delete')` / `Verbs()` + `DoIt()`), which is what
164
+ * Explorer's "delete" does to a bin item: permanent, no recycle.
165
+ *
166
+ * All five were allowed by 1.0.6 and are holes worth closing: `pwsh -Command
167
+ * "Clear-RecycleBin -Force"` empties the bin silently, one shell call away.
168
+ */
169
+ const EMPTY_BIN_COMMAND = /^clear-recyclebin$/i;
170
+ const EMPTY_BIN_API = /\bSHEmptyRecycleBin\w*\b/i;
171
+ const BIN_NAMESPACE_REF = /Namespace\(\s*(?:10|0xa)\s*\)|shell:RecycleBinFolder|\$recycle\.bin/i;
172
+ const BIN_VERB_DRIVE = /\bInvokeVerb\s*\(|\.Verbs\s*\(\s*\)|\.DoIt\s*\(/i;
173
+
174
+ /**
175
+ * Constructs that can hide a delete from a text-level parser, or make the
176
+ * rewrite target set unknowable. A command containing any of these is denied
177
+ * rather than rewritten: silently moving the wrong path is worse than refusing.
178
+ *
179
+ * Entries may carry `dialects` to restrict them to one shell language. The
180
+ * distinction matters for `$( … )`: PowerShell treats it as command
181
+ * substitution (opaque), while in bash it is ordinary everyday syntax
182
+ * (`$(pwd)`, `$(date)`). Applying the PowerShell rule to bash would refuse
183
+ * almost every real command, so it is dialect-scoped.
184
+ */
185
+ const OPAQUE_CONSTRUCTS = [
186
+ { re: /\$\(/, what: 'command substitution $( … )', dialects: ['pwsh'] },
187
+ { re: /`[^`]*`/, what: 'backtick command substitution', dialects: ['pwsh', 'bash'] },
188
+ { re: /(?<![<>=!])<<</, what: 'here-string / here-doc', dialects: ['pwsh', 'bash'] },
189
+ { re: /\|\s*(?:Remove-Item|del|rm|ri)\b/i, what: 'piped delete', dialects: ['pwsh', 'bash'] },
190
+ // `… | xargs rm` runs a delete whose targets arrive from stdin, so the target
191
+ // set is unknowable. `xargs` hides the verb from the statement parser.
192
+ { re: /\bxargs\b[^\n;&|]*\b(?:rm|rmdir|unlink|del|erase|rd)\b/i, what: 'xargs-driven delete', dialects: ['pwsh', 'bash'] },
193
+ { re: /(?:Remove-Item|del|rm|ri)\b[^\n;&|]*-Recurse\b[^\n;&|]*\*/, what: 'recursive wildcard delete', dialects: ['pwsh', 'bash'] },
194
+ { re: /(?:Remove-Item|rm)\b[^\n;&|]*--?no-preserve-root/, what: 'no-preserve-root', dialects: ['pwsh', 'bash'] },
195
+ ];
196
+
197
+ /**
198
+ * Deletes that never appear as a shell delete verb, so the statement parser
199
+ * cannot see them at all. Each entry names what it does in `what`; a match is
200
+ * denied outright, because there is no operand list to hand to `file_trash`.
201
+ *
202
+ * Scope is deliberately narrow. These are *specific* erasing constructs, not
203
+ * the word "delete" anywhere in a line — the previous revision matched
204
+ * `shellDeleteVerb` over the whole command, which refused read-only audits for
205
+ * containing the Python statement `del L[a:b+1]` or the flag `Get-ChildItem -File`.
206
+ *
207
+ * `-delete` is listed for `find` only: in bash, `rm --delete` is not a thing,
208
+ * while `find … -delete` is the ordinary way to erase a tree without `rm`.
209
+ */
210
+ const ERASE_CONSTRUCTS = [
211
+ // .NET calls that unlink directly, bypassing the verb table. The pattern keys
212
+ // on the *call*, not on the type reference: `[System.IO.File]::ReadAllBytes`,
213
+ // `::Exists`, `::Copy` and `::Move` name the same type and erase nothing, so
214
+ // matching the literal `[System.IO.File]` refused ordinary read-only audits —
215
+ // e.g. reading a .bat file to check its byte count and line endings.
216
+ { re: /::\s*(?:Delete|DeleteFile|DeleteDirectory)\s*\(/i, what: 'a .NET File/Directory::Delete() call', dialects: ['pwsh'] },
217
+ // The instance-method spelling: `[System.IO.FileInfo]::new($p).Delete()` and
218
+ // the recursive overload `[System.IO.DirectoryInfo]::new($d).Delete($true)`.
219
+ // The no-argument form was a hole until 1.0.4 — only `.Delete($true)` matched,
220
+ // so `(Get-Item $p).Delete()` erased a file unguarded.
221
+ { re: /\.\s*Delete\s*\(\s*(?:\)|\$?(?:true|1)\s*[,)])/i, what: 'a .NET instance Delete() call', dialects: ['pwsh'] },
222
+ // Invoke-Expression / iex evaluates a string: the verb is inside the string,
223
+ // so no statement-level verb is ever seen.
224
+ { re: /\b(?:Invoke-Expression|iex)\b/i, what: 'Invoke-Expression / iex', dialects: ['pwsh'] },
225
+ // `cmd /c del …` hands the delete to a child interpreter.
226
+ { re: /\bcmd(?:\.exe)?\s+\/[ck]\b[^\n]*\b(?:del|erase|rd|rmdir)\b/i, what: 'a delete delegated to cmd.exe', dialects: ['pwsh', 'bash'] },
227
+ // `robocopy … /MIR` mirrors an empty source over the target, which empties it
228
+ // without ever naming a delete verb. /PURGE is the same trick with pruning.
229
+ { re: /\brobocopy\b[^\n]*\/(?:MIR|PURGE)\b/i, what: 'robocopy /MIR or /PURGE (empties the target)', dialects: ['pwsh', 'bash'] },
230
+ // `find … -delete` unlinks without `rm`.
231
+ { re: /\bfind\b[^\n]*(?:^|\s)-delete\b/i, what: 'find -delete', dialects: ['bash'] },
232
+ ];
233
+
234
+ /**
235
+ * Interpreter invocations whose *body* is opaque to this parser. The check is
236
+ * two-part on purpose: the interpreter must be invoked with an inline-body flag,
237
+ * and the body must contain an erasing construct. `python -c "print(1+1)"` and
238
+ * `bash -c "ls -la"` must keep working.
239
+ *
240
+ * The erasing API is matched by member name, not by module prefix:
241
+ * `require('fs').rmSync(...)` never contains the text `fs.rmSync`, so a
242
+ * module-qualified pattern missed it. Each name below is a delete in the
243
+ * language it belongs to — `remove`, `unlink`, `rmdir`, `rmtree` — and none of
244
+ * them is a common non-deleting call.
245
+ */
246
+ const INLINE_BODY_FLAGS = /(?:^|\s)(?:-c|-e|-Command|-EncodedCommand|--eval|--execute)\s/i;
247
+ const INTERPRETER = /\b(?:bash|sh|zsh|pwsh|powershell|node|python|python3|perl|ruby)\b/i;
248
+ const PROGRAMMATIC_ERASE =
249
+ /(?:\.\s*(?:rmSync|rmdirSync|unlinkSync|removeSync|rmdir|unlink|rmtree|remove_tree|remove_entry)\s*\(|\.\s*rm\s*\(|\b(?:shutil\s*\.\s*rmtree|os\s*\.\s*(?:remove|unlink|rmdir))\b)/i;
250
+
251
+ /**
252
+ * Script-file writes that *create* a file containing delete text. Writing a
253
+ * helper script and then running it by path is the documented escape hatch in
254
+ * this plugin's own README; the guard cannot read the body back, but it can
255
+ * refuse to let the write happen.
256
+ *
257
+ * Both spellings are covered because both are ordinary: a redirection
258
+ * (`> clean.ps1`) and a write cmdlet (`| Out-File clean.ps1`). Without the
259
+ * second, the redirect rule is a formality.
260
+ */
261
+ const SCRIPT_WRITE_REDIRECT = />>?\s*\S+\.(?:ps1|sh|bash|zsh|bat|cmd|py|js|mjs|ts)\b/i;
262
+ const SCRIPT_WRITE_CMDLET =
263
+ /\b(?:Out-File|Set-Content|Add-Content|Tee-Object)\b[^\n;&|]*\.(?:ps1|sh|bash|zsh|bat|cmd|py|js|mjs|ts)\b/i;
264
+
265
+ /**
266
+ * Shell-level delete verbs, used only by the script-file rule, where the body
267
+ * is not parsed at all.
268
+ */
269
+ const SHELL_DELETE_VERB = /\b(?:Remove-Item|ri|del|erase|rd|rmdir|rm|unlink)\b/i;
270
+
271
+
272
+ /**
273
+ * Substitutions that may appear inside a delete operand. The value is only
274
+ * known when the shell expands it, so no path can be proven safe to recycle:
275
+ * the operand must be refused rather than treated as a literal path.
276
+ *
277
+ * This is dialect-independent. bash permits `$( … )` as ordinary syntax, but
278
+ * never as an unexpandable delete target.
279
+ */
280
+ const SUBSTITUTION_IN_TARGET = /\$\(|`|\$\{|\$[A-Za-z_]/;
281
+
282
+ /** Path shapes that must never be rewritten into a recycle-bin move. */
283
+ const FORBIDDEN_TARGETS = [
284
+ { re: /^[a-z]:[\\/]?$/i, what: 'a drive root' },
285
+ { re: /^[\\/]$/, what: 'the filesystem root' },
286
+ { re: /^(?:\$env:SystemRoot|%SystemRoot%|[a-z]:\\Windows)(?:[\\/]|$)/i, what: 'the Windows directory' },
287
+ { re: /^(?:\$env:ProgramFiles|%ProgramFiles%|[a-z]:\\Program Files)/i, what: 'Program Files' },
288
+ { re: /(?:^|[\\/])\.\.(?:[\\/]|$)/, what: 'a parent-directory traversal' },
289
+ { re: /^\$recycle\.bin$/i, what: 'the Recycle Bin itself' },
290
+ ];
291
+
292
+ /**
293
+ * Reduce a token to the name of the program it would execute: unquoted, with
294
+ * the directory dropped, lower-cased, and with a launcher extension removed.
295
+ *
296
+ * `"C:\tools\sdelete64.exe"` → `sdelete64`. This is what makes "is this token a
297
+ * wipe tool" answerable without also matching a *file named* `sdelete.log`.
298
+ *
299
+ * @param token - one argv token.
300
+ * @returns the program name, or `''` for an empty token.
301
+ */
302
+ function programName(token) {
303
+ const bare = unquote(token).trim();
304
+ if (bare.length === 0) return '';
305
+ const base = bare.split(/[\\/]/).pop() ?? '';
306
+ return base.toLowerCase().replace(/\.(?:exe|com|bat|cmd|ps1|sh)$/, '');
307
+ }
308
+
309
+ /**
310
+ * Find a wipe program that a single statement actually runs.
311
+ *
312
+ * Only two positions count: the command word, and the argument of a launcher
313
+ * (`Start-Process -FilePath shred`, `cmd /c shred`). Everything else in a
314
+ * statement is an operand, and an operand is allowed to be a file whose name
315
+ * contains the word.
316
+ *
317
+ * @param statement - one statement, already split from the command.
318
+ * @returns the wipe program name, or `undefined` when the statement runs none.
319
+ */
320
+ function wipeProgramIn(statement) {
321
+ const tokens = tokenize(statement).filter((t) => t.length > 0);
322
+ // Four tokens is enough for `cmd.exe /d /c shred …`; a wipe tool invoked
323
+ // further along a launcher's line is not reachable without `&`/`.`, which the
324
+ // statement splitter already treats as a boundary.
325
+ for (let i = 0; i < tokens.length && i < 4; i += 1) {
326
+ const name = programName(tokens[i]);
327
+ if (name.length === 0) continue;
328
+ if (WIPE_PROGRAMS.has(name)) return name;
329
+ if (i === 0 && !LAUNCHER_VERBS.has(name)) return undefined;
330
+ }
331
+ return undefined;
332
+ }
333
+
334
+ /**
335
+ * The body text of a statement that hands a program to a child shell:
336
+ * `pwsh -Command "…"`, `bash -c "…"`, `node -e "…"`.
337
+ *
338
+ * @param statement - one statement.
339
+ * @returns the body text, or `undefined` when the statement runs no child.
340
+ */
341
+ function inlineBodyText(statement) {
342
+ const tokens = tokenize(statement).filter((t) => t.length > 0);
343
+ for (let i = 0; i < tokens.length - 1; i += 1) {
344
+ if (!/^-(?:c|e|command|eval|execute)$/i.test(tokens[i])) continue;
345
+ return tokens.slice(i + 1).join(' ');
346
+ }
347
+ return undefined;
348
+ }
349
+
350
+ /**
351
+ * Every command word a statement can run: its own, plus the ones inside a body
352
+ * handed to a child shell.
353
+ *
354
+ * @param statement - one statement.
355
+ * @returns the command words found.
356
+ */
357
+ function commandWordsOf(statement) {
358
+ const words = [commandWord(statement), ...launcherPayloadWords(statement)];
359
+ const body = inlineBodyText(statement);
360
+ if (body !== undefined) {
361
+ for (const inner of splitStatements(body)) words.push(commandWord(inner));
362
+ }
363
+ return words.filter((w) => w.length > 0);
364
+ }
365
+
366
+ /**
367
+ * Command words hidden in a launcher's arguments: `Start-Process pwsh
368
+ * -ArgumentList "-c","Clear-RecycleBin -Force"`, `cmd /c rd …`.
369
+ *
370
+ * The program is an operand there, so `commandWord` never sees it. Each argument
371
+ * token is split on commas (PowerShell array syntax) and re-read as a statement.
372
+ *
373
+ * @param statement - one statement.
374
+ * @returns the command words found in launcher arguments.
375
+ */
376
+ function launcherPayloadWords(statement) {
377
+ if (!LAUNCHER_VERBS.has(commandWord(statement).toLowerCase())) return [];
378
+ const out = [];
379
+ for (const token of tokenize(statement).slice(1)) {
380
+ for (const piece of token.split(/[,;]/)) {
381
+ const inner = piece.trim();
382
+ if (inner.length === 0) continue;
383
+ for (const nested of splitStatements(inner)) out.push(commandWord(nested));
384
+ }
385
+ }
386
+ return out;
387
+ }
388
+
389
+ /**
390
+ * Decode `-EncodedCommand` bodies (base64 of UTF-16LE) into statements.
391
+ *
392
+ * The flag exists to hand PowerShell a program without it appearing on the
393
+ * command line, so treating it as opaque would let it carry any delete past
394
+ * every text rule. Decoding costs nothing and makes the body visible to the same
395
+ * per-statement checks as everything else.
396
+ *
397
+ * @param command - the full command text.
398
+ * @returns the statements decoded from every encoded body.
399
+ */
400
+ function decodedInlineBodies(command) {
401
+ const out = [];
402
+ for (const m of command.matchAll(/-EncodedCommand\s+([A-Za-z0-9+/=]{8,})/gi)) {
403
+ try {
404
+ const text = Buffer.from(m[1], 'base64').toString('utf16le');
405
+ if (text.trim().length > 0) out.push(...splitStatements(text));
406
+ } catch {
407
+ // Not decodable as base64/UTF-16LE: nothing to add.
408
+ }
409
+ }
410
+ return out;
411
+ }
412
+
413
+ /**
414
+ * Map a path as written in Git Bash (MSYS) onto the Windows path it denotes.
415
+ *
416
+ * Git Bash resolves `/c/Users/x` to `C:\Users\x`, and `/cygdrive/c/...` the same
417
+ * way, but handing the raw string to `file_trash` makes Node's Windows resolver
418
+ * read it as `<cwd drive>:\c\Users\x` — a different location. Only the
419
+ * drive-mapped forms are translatable without guessing: `~` is expanded by the
420
+ * shell, and `/tmp`, `/usr`, `/proc` are MSYS mount points whose real targets are
421
+ * installation-specific.
422
+ *
423
+ * @param operand - one delete operand.
424
+ * @returns `{ path }` with the Windows form, or `{ refuse }` with the reason.
425
+ */
426
+ function translatePosixPath(operand) {
427
+ if (operand === '~' || operand.startsWith('~/') || operand.startsWith('~\\')) {
428
+ return {
429
+ refuse:
430
+ 'Refusing a delete whose target is `~`: the shell expands home to a path this plugin cannot see. ' +
431
+ 'Write the real location (a Windows path, or a path relative to the working directory) and hand that to file_trash.',
432
+ };
433
+ }
434
+ if (!operand.startsWith('/')) return { path: operand };
435
+ // `/` is the same root in both shells; leave it for the forbidden-target rule
436
+ // so the refusal says "filesystem root" rather than "unmappable mount point".
437
+ if (operand === '/') return { path: operand };
438
+ const mapped = /^\/cygdrive\/([A-Za-z])(\/.*)?$/.exec(operand)
439
+ ?? /^\/([A-Za-z])(\/.*)?$/.exec(operand);
440
+ if (mapped === null) {
441
+ return {
442
+ refuse:
443
+ `Refusing a delete that targets the POSIX path "${operand}": that is a Git Bash / MSYS mount point, not a ` +
444
+ 'Windows path, so the real location cannot be proven. Resolve it first, then pass the Windows path to file_trash.',
445
+ };
446
+ }
447
+ const rest = (mapped[2] ?? '/').replace(/\//g, '\\');
448
+ return { path: `${mapped[1].toUpperCase()}:${rest}` };
449
+ }
450
+
451
+ /**
452
+ * Find a wipe program named inside a body that is handed to a child
453
+ * interpreter (`bash -c "shred -u x"`). The body is shell text, so the name is
454
+ * not in program position here and `wipeProgramIn` cannot see it.
455
+ *
456
+ * Scoped by the interpreter's language. A shell body *is* shell text, so the name
457
+ * anywhere in it may run. A `node -e` / `python -c` body is not: `console.log(
458
+ * 'shred')` erases nothing, and matching the word there refused a documentation
459
+ * edit that quoted the name (measured 2026-11-15). For those interpreters the name
460
+ * counts only where it is handed to a process-spawning call.
461
+ *
462
+ * @param statement - one statement, already split from the command.
463
+ * @returns the matched name, or `undefined`.
464
+ */
465
+ function wipeProgramInInlineBody(statement) {
466
+ if (!INLINE_BODY_FLAGS.test(statement)) return undefined;
467
+ if (!SHELL_INTERPRETERS.test(statement)) {
468
+ const spawned = SPAWN_CALL.exec(statement);
469
+ if (spawned === null) return undefined;
470
+ const tail = statement.slice(spawned.index);
471
+ const named = WIPE_NAME_IN_BODY.exec(tail);
472
+ return named === null ? undefined : named[0].toLowerCase();
473
+ }
474
+ const found = WIPE_NAME_IN_BODY.exec(statement);
475
+ return found === null ? undefined : found[0].toLowerCase();
476
+ }
477
+
478
+ /**
479
+ * Classify one statement as a delete we can rewrite.
480
+ * @param statement - one statement string.
481
+ * @returns the verb plus its operand tokens, or `undefined` when not a delete.
482
+ */
483
+ function parseDeleteStatement(statement) {
484
+ const tokens = tokenize(statement);
485
+ if (tokens.length === 0) return undefined;
486
+
487
+ const known = new Set([
488
+ ...PS_DELETE_VERBS,
489
+ ...PS_DELETE_ALIASES,
490
+ ...POSIX_DELETE_VERBS,
491
+ ]);
492
+
493
+ // A delete can be wrapped so that the verb is not the first token but is
494
+ // still the whole statement's action: `(Remove-Item $p)` groups it, and
495
+ // `$x = Remove-Item $p` binds its output. In both shapes the verb is a whole
496
+ // token and everything after it is its operand list, so step over the wrapper
497
+ // instead of dropping the statement.
498
+ //
499
+ // Only leading `(`, `$(`, `@(`, `&`, `.` and a `$name =` / `$env:name =`
500
+ // assignment are skipped. A general "find the verb anywhere" scan is not used
501
+ // here on purpose: it would re-introduce the whole-text matching that made
502
+ // `del L[a:b+1]` inside a Python body look like a shell delete.
503
+ for (let guard = 0; guard < tokens.length; guard += 1) {
504
+ const t = tokens[0];
505
+ // A wrapper that is its own token: `(`, `$(`, `@(`, `&`, `.`, `=`.
506
+ if (/^(?:[(\[{@&.]+|\$\(|=)$/.test(t)) {
507
+ tokens.shift();
508
+ continue;
509
+ }
510
+ // A wrapper glued to the verb: `(Remove-Item`, `@(Remove-Item`.
511
+ const glued = /^[(\[{@&]+(.+)$/.exec(t);
512
+ if (glued !== null) {
513
+ tokens[0] = glued[1];
514
+ continue;
515
+ }
516
+ // `$x =` as two tokens, or `$x=` glued to its value.
517
+ if (/^\$[A-Za-z_][\w:]*$/.test(t) && tokens[1] === '=') {
518
+ tokens.splice(0, 2);
519
+ continue;
520
+ }
521
+ const assign = /^\$[A-Za-z_][\w:]*\s*=\s*(.+)$/.exec(t);
522
+ if (assign !== null) {
523
+ tokens[0] = assign[1];
524
+ continue;
525
+ }
526
+ break;
527
+ }
528
+ if (tokens.length === 0) return undefined;
529
+
530
+ // `xargs <verb>` executes the verb with targets read from stdin. Step past
531
+ // the wrapper (and its own flags) so the delete is recognised at all — the
532
+ // target set stays unknowable, which is why OPAQUE_CONSTRUCTS denies it.
533
+ if (tokens[0].toLowerCase() === 'xargs') {
534
+ let i = 1;
535
+ while (i < tokens.length && tokens[i].startsWith('-')) {
536
+ // `-I{}` consumes the next token as its placeholder replacement.
537
+ if (/^-i$/i.test(tokens[i])) i += 1;
538
+ i += 1;
539
+ }
540
+ if (i < tokens.length && known.has(tokens[i].toLowerCase())) {
541
+ return {
542
+ verb: tokens[i].toLowerCase(),
543
+ operands: [],
544
+ recursive: false,
545
+ force: false,
546
+ preserveRoot: false,
547
+ statement,
548
+ viaXargs: true,
549
+ };
550
+ }
551
+ return undefined;
552
+ }
553
+
554
+ const verb = tokens[0].toLowerCase();
555
+ // Skip a leading `PowerShell -Command` style wrapper is out of scope: the
556
+ // guard denies those via OPAQUE_CONSTRUCTS or treats the wrapper as the verb.
557
+ if (!known.has(verb)) return undefined;
558
+
559
+ const operands = [];
560
+ let recursive = false;
561
+ let force = false;
562
+ let preserveRoot = false;
563
+ let splat = false;
564
+
565
+ for (let i = 1; i < tokens.length; i += 1) {
566
+ const tok = tokens[i];
567
+ if (tok.startsWith('-')) {
568
+ const flag = tok.toLowerCase();
569
+ if (flag === '-recurse' || flag === '-r') recursive = true;
570
+ if (flag === '-force' || flag === '-f') force = true;
571
+ if (flag === '--no-preserve-root') preserveRoot = true;
572
+ // A flag that takes a value is not a target: without this, `-ErrorAction
573
+ // SilentlyContinue` made "SilentlyContinue" a path to recycle, and the
574
+ // redirect message told the model to `file_trash` a value name. The two
575
+ // path flags are the exception — their value *is* the target.
576
+ const takesValue = FLAGS_TAKING_VALUE.has(flag);
577
+ const isPathFlag = flag === '-path' || flag === '-literalpath';
578
+ if ((takesValue || isPathFlag) && i + 1 < tokens.length) {
579
+ if (isPathFlag) operands.push(unquote(tokens[i + 1]));
580
+ i += 1;
581
+ }
582
+ continue;
583
+ }
584
+ // Combined short flags such as `-rf`.
585
+ if (/^-[a-z]{2,}$/i.test(tok)) {
586
+ const flags = tok.slice(1).toLowerCase();
587
+ if (flags.includes('r')) recursive = true;
588
+ if (flags.includes('f')) force = true;
589
+ continue;
590
+ }
591
+ // `Remove-Item @targets` splats an array whose contents only exist at run
592
+ // time. Treating "@targets" as a literal path would recycle a file that
593
+ // happens to be named that; the caller refuses instead (see below).
594
+ if (tok.startsWith('@')) splat = true;
595
+ operands.push(unquote(tok));
596
+ }
597
+
598
+ // PowerShell accepts a comma-separated operand list: `Remove-Item a, b`. The
599
+ // tokenizer keeps the separator glued to the preceding token, so split it off
600
+ // and treat each element as its own operand. A closing bracket glued to the
601
+ // last operand (`(Remove-Item C:\x)`) is stripped for the same reason: it is
602
+ // the wrapper's, not part of the path.
603
+ const expanded = [];
604
+ for (const operand of operands) {
605
+ for (const piece of operand.split(',')) {
606
+ const trimmed = piece.trim().replace(/^[)\]}]+/, '').replace(/[)\]}]+$/, '');
607
+ if (trimmed.length > 0) expanded.push(trimmed);
608
+ }
609
+ }
610
+
611
+ // A delete verb with no operands still has to be reported: its targets come
612
+ // from somewhere else (stdin, a splat, a pipeline). Returning `undefined` here
613
+ // would make the statement indistinguishable from a non-delete, which is how
614
+ // `xargs -I{} rm -f` slipped through after braces became separators.
615
+ return { verb, operands: expanded, recursive, force, preserveRoot, splat, statement };
616
+ }
617
+
618
+ /**
619
+ * Denial verdict for touching the Recycle Bin, naming the vector that was seen.
620
+ * @param what - the command, API or mechanism that would empty or modify the bin.
621
+ * @returns the verdict object.
622
+ */
623
+ function emptyRecycleVerdict(what) {
624
+ return {
625
+ action: 'deny',
626
+ kind: 'empty-recycle',
627
+ reason:
628
+ `Refusing ${what}, which empties or modifies the Recycle Bin: deleted items are kept recoverable on purpose. ` +
629
+ 'Purge them manually from Explorer if you really mean it.',
630
+ };
631
+ }
632
+
633
+ /**
634
+ * Decide what to do with a command that the model is about to run.
635
+ *
636
+ * @param command - the raw command text from the `pwsh`/`bash` tool arguments.
637
+ * @param options - guard policy switches.
638
+ * @param options.forbidEmptyRecycleBin - deny commands that empty the bin.
639
+ * @param options.forbidWipe - deny permanent-erase tools.
640
+ * @param options.blockScriptDeletes - deny inline script text containing deletes.
641
+ * @param options.blockTruncatingWrites - deny in-place rewrites that can destroy
642
+ * the only copy of a file's content (see `rewrite-guard.js`).
643
+ * @param options.dialect - which shell language the command is written in
644
+ * ('pwsh' or 'bash'). Defaults to 'pwsh'. Dialect-scoped rules such as the
645
+ * `$( … )` command-substitution check only apply to their own shell.
646
+ * @returns a verdict object.
647
+ */
648
+ export function classifyCommand(command, options = {}) {
649
+ const {
650
+ forbidEmptyRecycleBin = true,
651
+ forbidWipe = true,
652
+ blockScriptDeletes = true,
653
+ blockTruncatingWrites = true,
654
+ dialect = 'pwsh',
655
+ } = options;
656
+
657
+ if (typeof command !== 'string' || command.trim().length === 0) {
658
+ return { action: 'allow' };
659
+ }
660
+
661
+ // Both of the next two rule tables are judged per statement, not per command
662
+ // text: the evidence for "this command runs a wipe tool" is a word in program
663
+ // position, and "this command touches the bin" is a delete verb plus a bin
664
+ // path in the *same* statement. Whole-command matching made an unrelated
665
+ // string literal convict the rest of the line.
666
+ const statements = splitStatements(command);
667
+ // A body handed in through -EncodedCommand is judged like any other
668
+ // statement: the flag only hides it from a human reading the command line.
669
+ const bodyStatements = decodedInlineBodies(command);
670
+ const judged = [...statements, ...bodyStatements];
671
+
672
+ if (forbidEmptyRecycleBin) {
673
+ for (const statement of judged) {
674
+ for (const { re } of EMPTY_RECYCLE_RULES) {
675
+ if (re.test(statement)) {
676
+ return {
677
+ action: 'deny',
678
+ kind: 'empty-recycle',
679
+ reason:
680
+ 'Emptying or reaching into the Recycle Bin is disabled by the recycle-bin guard. ' +
681
+ 'Deleted items are kept recoverable on purpose; purge them manually from Explorer if you really mean it.',
682
+ };
683
+ }
684
+ }
685
+ // The cmdlet by command word: covers `Clear-RecycleBin`, `& "Clear-RecycleBin"`
686
+ // and `pwsh -Command "Clear-RecycleBin"` in one place.
687
+ if (commandWordsOf(statement).some((w) => EMPTY_BIN_COMMAND.test(w))) {
688
+ return emptyRecycleVerdict('Clear-RecycleBin');
689
+ }
690
+ }
691
+ if (EMPTY_BIN_API.test(command)) {
692
+ return emptyRecycleVerdict('the SHEmptyRecycleBin API');
693
+ }
694
+ // Shell verbs driven over bin items are how Explorer empties the bin one
695
+ // item at a time: `InvokeVerb('delete')` on a bin item is permanent, not a
696
+ // recycle. Reading the bin (Move-Item out of $R, listing $I records) stays
697
+ // allowed — only driving its verbs is refused.
698
+ if (BIN_NAMESPACE_REF.test(command) && BIN_VERB_DRIVE.test(command)) {
699
+ return emptyRecycleVerdict("the Recycle Bin's own shell verbs (InvokeVerb / Verbs / DoIt)");
700
+ }
701
+ }
702
+
703
+ if (forbidWipe) {
704
+ for (const statement of judged) {
705
+ const program = wipeProgramIn(statement) ?? wipeProgramInInlineBody(statement);
706
+ if (program !== undefined) {
707
+ return {
708
+ action: 'deny',
709
+ kind: 'wipe',
710
+ reason: `${WIPE_REASON} ("${program}" erases the data instead of moving it.)`,
711
+ };
712
+ }
713
+ }
714
+ for (const rule of WIPE_FLAG_SHAPES) {
715
+ if (rule.test(command)) {
716
+ return { action: 'deny', kind: 'wipe', reason: WIPE_REASON };
717
+ }
718
+ }
719
+ }
720
+
721
+ // Opaque constructs: refuse rather than risk moving the wrong path.
722
+ // Rules may be dialect-scoped; skip any that do not apply to this shell.
723
+ for (const { re, what, dialects } of OPAQUE_CONSTRUCTS) {
724
+ if (Array.isArray(dialects) && !dialects.includes(dialect)) continue;
725
+ if (re.test(command)) {
726
+ const hasDelete = judged.some((s) => parseDeleteStatement(s) !== undefined);
727
+ if (hasDelete) {
728
+ return {
729
+ action: 'deny',
730
+ kind: 'opaque',
731
+ reason:
732
+ `Refusing a delete that uses ${what}: the target set cannot be proven safe to rewrite. ` +
733
+ 'Call the file_trash tool with explicit literal paths instead.',
734
+ };
735
+ }
736
+ }
737
+ }
738
+
739
+ // Erasing constructs that carry no shell delete verb at all. Denied outright:
740
+ // there is no operand list to redirect to `file_trash`.
741
+ for (const { re, what, dialects } of ERASE_CONSTRUCTS) {
742
+ if (Array.isArray(dialects) && !dialects.includes(dialect)) continue;
743
+ if (re.test(command)) {
744
+ return {
745
+ action: 'deny',
746
+ kind: 'erase-api',
747
+ reason:
748
+ `Refusing ${what}: it unlinks files without a delete command, so nothing can be routed to the ` +
749
+ 'Recycle Bin. Use the file_trash tool with explicit literal paths instead.',
750
+ };
751
+ }
752
+ }
753
+
754
+ if (blockScriptDeletes) {
755
+ // A delete that runs inside a child process cannot be routed to the Recycle
756
+ // Bin: the shell only sees the interpreter, and the erase happens after the
757
+ // guard has finished.
758
+ //
759
+ // Every rule below is judged per *statement*, not per command text. The rule
760
+ // this replaces matched across the whole command, which meant a benign
761
+ // `python -c "…del d['a']…"` was refused as soon as any other statement in
762
+ // the same command mentioned `bash` — one statement's evidence convicted
763
+ // another statement's work. Splitting first keeps the evidence local.
764
+ // `judged` also carries statements decoded out of `-EncodedCommand`, so a
765
+ // delete cannot hide in a base64 body.
766
+ const statements = judged;
767
+
768
+ // 1. A shell's inline body that contains a shell delete verb.
769
+ // `pwsh -Command "Remove-Item C:\x"`, `bash -c "rm -rf /tmp/x"`.
770
+ // Scoped to shells: in Python or Ruby, `del` and `rm` are that
771
+ // language's own syntax, so they are judged by rule 2 instead.
772
+ for (const statement of statements) {
773
+ const shellInterp = SHELL_INTERPRETERS.test(statement);
774
+ const inlineBody = INLINE_BODY_FLAGS.test(statement);
775
+ if (shellInterp && inlineBody && SHELL_DELETE_VERB.test(statement)) {
776
+ return {
777
+ action: 'deny',
778
+ kind: 'script',
779
+ reason:
780
+ 'Deletes inside an inline shell command string are disabled by the recycle-bin guard: the erase ' +
781
+ 'happens inside the child process and would bypass the Recycle Bin. ' +
782
+ 'Run the delete as a direct file_trash tool call instead.',
783
+ };
784
+ }
785
+ }
786
+
787
+ // 2. A non-shell inline body that calls a real erasing API.
788
+ // `node -e "fs.rmSync(...)"`, `python -c "shutil.rmtree(...)"`.
789
+ //
790
+ // Judged across the whole command on purpose, unlike rules 1 and 3: an
791
+ // inline body is routinely multi-line (`python -c @' … '@`), so the
792
+ // interpreter sits on one line and the erase call several lines later.
793
+ // Per-statement matching would miss exactly those. The cross-statement
794
+ // risk that motivated splitting — a shell word in one statement
795
+ // convicting another — does not apply here: `shutil.rmtree` and
796
+ // `fs.rmSync` are not words any other statement would contain by accident.
797
+ const otherInterp = /\b(?:node|python|python3|perl|ruby)\b/i.test(command);
798
+ const inlineBody = INLINE_BODY_FLAGS.test(command);
799
+ if (otherInterp && inlineBody && PROGRAMMATIC_ERASE.test(command)) {
800
+ return {
801
+ action: 'deny',
802
+ kind: 'script',
803
+ reason:
804
+ 'Deletes inside an inline program string are disabled by the recycle-bin guard: the erase happens ' +
805
+ 'inside the child process and would bypass the Recycle Bin. ' +
806
+ 'Run the delete as a direct file_trash tool call instead.',
807
+ };
808
+ }
809
+
810
+ // 3. Writing a script file whose body contains a delete, then running it by
811
+ // path, is the escape hatch this plugin's own README documents. The guard
812
+ // cannot read the body back, but it can refuse to let the write happen.
813
+ //
814
+ // Judged across the whole command: a pipe is a statement separator here,
815
+ // so `"Remove-Item x" | Out-File clean.ps1` would otherwise be two
816
+ // statements — the delete text in one, the write target in the other, and
817
+ // neither one guilty on its own. The write target (`.ps1`, `.sh`, `.py`)
818
+ // is specific enough that no unrelated statement carries it by accident.
819
+ if (
820
+ (SCRIPT_WRITE_REDIRECT.test(command) || SCRIPT_WRITE_CMDLET.test(command)) &&
821
+ SHELL_DELETE_VERB.test(command)
822
+ ) {
823
+ return {
824
+ action: 'deny',
825
+ kind: 'script',
826
+ reason:
827
+ 'Refusing to write a script file containing a delete: a script run by path executes its deletes ' +
828
+ 'inside a child process, where they bypass the Recycle Bin. ' +
829
+ 'Run the delete as a direct file_trash tool call instead.',
830
+ };
831
+ }
832
+ }
833
+
834
+
835
+ // Content destroyed without a delete verb: an in-place rewrite of the only
836
+ // copy. Judged before the rewrite collection on purpose — `file_trash` is the
837
+ // remedy for a *delete*, and moving the file away is precisely what a
838
+ // read-modify-write is not allowed to have happened (and on a UNC share there
839
+ // is no bin to move it into at all). Deny, and hand back the safe recipe.
840
+ if (blockTruncatingWrites) {
841
+ const risk = analyzeOverwriteRisk(command, { statements: judged, dialect });
842
+ if (risk !== undefined) {
843
+ return { action: 'deny', kind: risk.kind, reason: risk.reason };
844
+ }
845
+ }
846
+
847
+ // Rewritable deletes: collect every operand across every statement, including
848
+ // the ones decoded out of an -EncodedCommand body.
849
+
850
+ // A delete verb with no operand list is a piped/receiving delete: the targets
851
+ // arrive from the upstream command or from a splat, so they cannot be
852
+ // enumerated. The pipeline case is caught earlier by OPAQUE_CONSTRUCTS, but a
853
+ // bare `Remove-Item` reaching here still means "delete whatever you were
854
+ // handed", which is never safe to wave through.
855
+ for (const statement of judged) {
856
+ const parsed = parseDeleteStatement(statement);
857
+ if (parsed === undefined) continue;
858
+ if (parsed.operands.length > 0 || parsed.splat) continue;
859
+ return {
860
+ action: 'deny',
861
+ kind: 'opaque',
862
+ reason:
863
+ `Refusing a "${parsed.verb}" with no explicit operands: its targets come from another command, ` +
864
+ 'so they cannot be proven safe to route to the Recycle Bin. ' +
865
+ 'Call the file_trash tool with explicit literal paths instead.',
866
+ };
867
+ }
868
+
869
+ const targets = [];
870
+ const seen = new Set();
871
+ for (const statement of judged) {
872
+ const parsed = parseDeleteStatement(statement);
873
+ if (parsed === undefined) continue;
874
+ if (parsed.preserveRoot) {
875
+ return {
876
+ action: 'deny',
877
+ kind: 'forbidden-target',
878
+ reason: 'Refusing a delete that targets the filesystem root.',
879
+ };
880
+ }
881
+ // `Remove-Item @targets`: the array's contents exist only at run time, so no
882
+ // literal path can be proven. Refuse rather than recycle a file whose name
883
+ // happens to be "@targets".
884
+ if (parsed.splat) {
885
+ return {
886
+ action: 'deny',
887
+ kind: 'opaque',
888
+ reason:
889
+ 'Refusing a delete that splats an argument array (@name): its contents are only known at run time, ' +
890
+ 'so they cannot be proven safe to route to the Recycle Bin. ' +
891
+ 'Pass explicit literal paths to file_trash instead.',
892
+ };
893
+ }
894
+ for (const rawOperand of parsed.operands) {
895
+ // A Git Bash user writes `/c/tmp/x`; `file_trash` needs `C:\tmp\x`. The
896
+ // translation has to happen here, where the dialect is known: `pwsh` reads
897
+ // `/c/tmp/x` as a drive-relative Windows path, so the two shells mean
898
+ // different things by the same string.
899
+ let operand = rawOperand;
900
+ if (dialect === 'bash') {
901
+ const mapped = translatePosixPath(operand);
902
+ if (mapped.refuse !== undefined) {
903
+ return { action: 'deny', kind: 'opaque', reason: mapped.refuse };
904
+ }
905
+ operand = mapped.path;
906
+ }
907
+ // An operand that is itself a substitution has no provable value: the
908
+ // shell expands it at run time. `rm -rf $(cat list.txt)` would otherwise
909
+ // be tokenized into the literal strings `$(cat` and `list.txt)`, and
910
+ // "recycling" those would move the wrong things. This check is
911
+ // dialect-independent — bash allows `$( … )` as syntax, but never as an
912
+ // unexpandable delete target.
913
+ if (SUBSTITUTION_IN_TARGET.test(operand)) {
914
+ return {
915
+ action: 'deny',
916
+ kind: 'opaque',
917
+ reason:
918
+ 'Refusing a delete whose target is a command substitution: the real path is only known at ' +
919
+ 'run time, so it cannot be proven safe to route to the Recycle Bin. ' +
920
+ 'Resolve the path first, then pass explicit literal paths to file_trash.',
921
+ };
922
+ }
923
+ for (const { re, what } of FORBIDDEN_TARGETS) {
924
+ if (re.test(operand)) {
925
+ return {
926
+ action: 'deny',
927
+ kind: 'forbidden-target',
928
+ reason: `Refusing a delete that targets ${what}.`,
929
+ };
930
+ }
931
+ }
932
+ if (operand === '*' || operand === '*.ps1' || operand === '**') {
933
+ return {
934
+ action: 'deny',
935
+ kind: 'forbidden-target',
936
+ reason: 'Refusing a bare glob delete: the expanded target set is unknown. Pass explicit paths to file_trash.',
937
+ };
938
+ }
939
+ if (!seen.has(operand)) {
940
+ seen.add(operand);
941
+ targets.push(operand);
942
+ }
943
+ }
944
+ }
945
+
946
+ if (targets.length > 0) {
947
+ return { action: 'rewrite', kind: 'delete', targets };
948
+ }
949
+ return { action: 'allow' };
950
+ }
951
+
952
+ export { splitStatements, tokenize, parseDeleteStatement, unquote };