dsh-delete-guard 2.2.3 → 2.4.2

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 CHANGED
@@ -16,8 +16,15 @@
16
16
  * operands are handed back so the caller can perform a real recycle-bin move.
17
17
  * Denial is the fallback for the cases where a safe rewrite cannot be proven
18
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`.
19
23
  */
20
24
 
25
+ import { commandWord, splitStatements, tokenize, unquote } from './shell-text.js';
26
+ import { analyzeOverwriteRisk } from './rewrite-guard.js';
27
+
21
28
  /** PowerShell delete verbs whose operand list we can trust. */
22
29
  const PS_DELETE_VERBS = ['remove-item', 'ri'];
23
30
  /** PowerShell cmdlet aliases that mean the same thing. */
@@ -57,12 +64,20 @@ const FLAGS_TAKING_VALUE = new Set([
57
64
  '-include',
58
65
  '-exclude',
59
66
  '-credential',
60
- '-confirm',
61
- '-whatif',
62
- '-verbose',
63
- '-debug',
64
67
  ]);
65
68
 
69
+ /**
70
+ * Common parameters that are **switches**: they take no value.
71
+ *
72
+ * These were listed above until 2026-11-25, which made them swallow the operand that
73
+ * followed. Measured: `Remove-Item -Verbose C:\x\a.txt` and
74
+ * `Remove-Item -Confirm C:\x\a.txt` both classified as "no explicit operands", so the
75
+ * model was told its delete had no target instead of being handed the paths to
76
+ * `file_trash`. `-WhatIf` had the same defect and, worse, turned a preview into a
77
+ * rewrite instruction (see `isDryRun` in index.js).
78
+ */
79
+ const SWITCH_PARAMETERS = new Set(['-confirm', '-whatif', '-verbose', '-debug']);
80
+
66
81
  /**
67
82
  * Programs that mean "permanently erase" rather than "delete". They are never
68
83
  * rewritten — they are denied outright.
@@ -95,12 +110,89 @@ const WIPE_FLAG_SHAPES = [
95
110
  ];
96
111
 
97
112
  /**
98
- * A wipe-program name anywhere inside the body handed to a child interpreter
113
+ * A wipe-program name anywhere inside the body handed to a child *shell*
99
114
  * (`bash -c "shred -u x"`). Such a body is shell text, not an operand, so the
100
115
  * argument that *calls* itself out of program position does not protect it.
101
116
  */
102
117
  const WIPE_NAME_IN_BODY = /\b(?:sdelete64|sdelete|shred|srm|wipe)\b/i;
103
118
 
119
+ /**
120
+ * A call that hands a string to a process, for interpreters whose body is *not*
121
+ * shell text. `node -e "…shred…"` only erases anything if the name reaches an
122
+ * `exec`/`spawn`/`system` call; without one it is a word in a string.
123
+ *
124
+ * Measured 2026-11-15, on the published 2.2.3: maintaining this very repository
125
+ * was refused, because the README text being written quoted `shred` inside a
126
+ * `node -e` body — prose, no process involved. The rule read the name anywhere in
127
+ * the body and could not tell documentation from a command.
128
+ */
129
+ const SPAWN_CALL =
130
+ /(?:\.\s*(?:exec|execFile|execSync|spawn|spawnSync|popen)\s*\(|\b(?:exec|execFile|execSync|spawn|spawnSync)\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;
131
+
132
+ /**
133
+ * A destructuring import of a process-spawning API:
134
+ * `const { execSync } = require('child_process')`. Measured 2026-11-25: this shape
135
+ * then calls a bare `execSync(...)`, which {@link SPAWN_CALL} did not catch (every
136
+ * branch required a leading dot), so `execSync('shred -u x')` was allowed.
137
+ *
138
+ * Recognised as the assignment itself rather than by loosening SPAWN_CALL: dropping
139
+ * the dot requirement would also match `db.exec(...)` and `/re/.exec(...)` in any
140
+ * context.
141
+ */
142
+ const SPAWN_DESTRUCTURED = /(?:const|let|var)\s*\{[^}]*\b(?:exec|execFile|execSync|spawn|spawnSync|popen)\b[^}]*\}\s*=\s*require\s*\(\s*['"]child_process['"]\s*\)/i;
143
+
144
+ /**
145
+ * Child interpreters whose inline body is a shell program. For these, any name in
146
+ * the body counts as a program name; for every other interpreter the name must
147
+ * also reach a process-spawning call.
148
+ *
149
+ * Matched in **program position**, never as a bare word: `node -e "…{dialect:'pwsh'}…"`
150
+ * contains the literal `pwsh` and was audited as if it were a shell script, which
151
+ * made the same word in the same body read as a program name.
152
+ */
153
+ const SHELL_INTERPRETERS = /^(?:bash|sh|zsh|pwsh|powershell)(?:\.exe)?$/i;
154
+
155
+ /**
156
+ * A shell invoked through a variable, decided from the statement's tokens rather
157
+ * than by regex over the whole line.
158
+ *
159
+ * `splitStatements` already treats `&` as a separator, so `… ; & $sh -c "…"` arrives
160
+ * as the statement `$sh -c "…"` — the `&` is gone by the time a per-statement check
161
+ * runs. Looking at the statement's own tokens is what makes the shape visible.
162
+ *
163
+ * Measured 2026-11-25: `$shellPath='…\bash.exe'; & $shellPath -c "…"` was allowed,
164
+ * while `$sh='bash'; & $sh -c "…"` was denied only because the variable name
165
+ * contains `sh` — a denial by coincidence of naming, not by rule.
166
+ *
167
+ * @param statement - one statement, already split.
168
+ * @returns whether the statement runs a variable as a shell with an inline body.
169
+ */
170
+ function invokesShellVariable(statement) {
171
+ // Cheap pre-check before tokenizing: the statement has to *start* with a variable
172
+ // and carry an inline-body flag. `tokenize` per statement was measurable on the
173
+ // tool-call path (2026-11-25), and almost no statement looks like this.
174
+ const head = statement.trimStart();
175
+ if (head.charCodeAt(0) !== 36 /* $ */) return false;
176
+ if (!/-(?:c|command)\b/i.test(statement)) return false;
177
+
178
+ const tokens = tokenize(statement).filter((t) => t.length > 0);
179
+ const program = tokens[0];
180
+ if (program === undefined) return false;
181
+ // The program position must be a variable.
182
+ if (!/^\$[A-Za-z_][\w:]*$/.test(program)) return false;
183
+ // …and it must be handed an inline-body flag.
184
+ const flagAt = tokens.findIndex((t, i) => i > 0 && /^-(?:c|command)$/i.test(t));
185
+ if (flagAt === -1) return false;
186
+ // Only when the body is worth judging: a delete verb or an erase tool. Otherwise
187
+ // this is `$bash -c "ls -la"`, and refusing it would be a false positive — the
188
+ // direct spelling `bash -c "ls -la"` is allowed on purpose.
189
+ const body = tokens.slice(flagAt + 1).join(' ');
190
+ return SHELL_DELETE_VERB.test(body) || WIPE_NAME_IN_BODY.test(body);
191
+ }
192
+
193
+ /** Any shell name, for the places that genuinely need "does this statement mention one". */
194
+ const SHELL_NAME_ANYWHERE = /\b(?:bash|sh|zsh|pwsh|powershell)\b/i;
195
+
104
196
  /** Denial text shared by every permanent-erase rule. */
105
197
  const WIPE_REASON =
106
198
  'Permanent-erase tools (shred/sdelete/srm/cipher /w/format) are disabled by the recycle-bin guard. ' +
@@ -142,7 +234,34 @@ const EMPTY_RECYCLE_RULES = [
142
234
  const EMPTY_BIN_COMMAND = /^clear-recyclebin$/i;
143
235
  const EMPTY_BIN_API = /\bSHEmptyRecycleBin\w*\b/i;
144
236
  const BIN_NAMESPACE_REF = /Namespace\(\s*(?:10|0xa)\s*\)|shell:RecycleBinFolder|\$recycle\.bin/i;
145
- const BIN_VERB_DRIVE = /\bInvokeVerb\s*\(|\.Verbs\s*\(\s*\)|\.DoIt\s*\(/i;
237
+
238
+ /**
239
+ * Driving the bin's own verbs — the part that actually destroys.
240
+ *
241
+ * `.Verbs()` was listed here until 2026-11-25, which made **enumerating** a verb
242
+ * list look like **executing** one. Measured: the sanctioned recovery path
243
+ * (`$item.Verbs() | Where-Object { $_.Name -like '*还原*' }`) was refused, and so was
244
+ * a read-only listing of what verbs a bin item offers — while the README promises
245
+ * restoring is allowed.
246
+ *
247
+ * `DoIt()` stays in the driving set and is never exempted: it runs whichever verb is
248
+ * currently selected, and which one that is cannot be read off the command. Measured
249
+ * 2026-11-25: a "restore word anywhere in the line" exemption was fooled by a bare
250
+ * comment — `… | % { $_.DoIt() } # restore is a different verb` became allowed.
251
+ */
252
+ const BIN_VERB_ENUM = /\.Verbs\s*\(\s*\)/i;
253
+ const BIN_VERB_DRIVE = /\bInvokeVerb\s*\(|\.DoIt\s*\(/i;
254
+ /** `InvokeVerb('…')` whose argument names a restore rather than a destroy. */
255
+ const BIN_VERB_RESTORE_ARG = /InvokeVerb\s*\(\s*['"][^'"]*(?:estore|还原|复原)[^'"]*['"]/i;
256
+ /** `InvokeVerb('…')` whose argument names a destroy. */
257
+ const BIN_VERB_DELETE_ARG = /InvokeVerb\s*\(\s*['"][^'"]*(?:delete|remove|删除|清除)[^'"]*['"]/i;
258
+
259
+ /**
260
+ * Cheap pre-check: could this statement reach the bin's verbs at all? Neither
261
+ * `.DoIt(`/`InvokeVerb(` nor a bin reference appears in ordinary commands, so this
262
+ * one test keeps four regexes and two `Namespace(10)` probes off the common path.
263
+ */
264
+ const BIN_TOUCH = /\bInvokeVerb\s*\(|\.DoIt\s*\(|Namespace\s*\(\s*(?:10|0xa)\s*\)|shell:RecycleBinFolder|\$recycle\.bin/i;
146
265
 
147
266
  /**
148
267
  * Constructs that can hide a delete from a text-level parser, or make the
@@ -192,9 +311,13 @@ const ERASE_CONSTRUCTS = [
192
311
  // The no-argument form was a hole until 1.0.4 — only `.Delete($true)` matched,
193
312
  // so `(Get-Item $p).Delete()` erased a file unguarded.
194
313
  { re: /\.\s*Delete\s*\(\s*(?:\)|\$?(?:true|1)\s*[,)])/i, what: 'a .NET instance Delete() call', dialects: ['pwsh'] },
195
- // Invoke-Expression / iex evaluates a string: the verb is inside the string,
196
- // so no statement-level verb is ever seen.
197
- { re: /\b(?:Invoke-Expression|iex)\b/i, what: 'Invoke-Expression / iex', dialects: ['pwsh'] },
314
+ // Invoke-Expression / iex evaluates a string: the verb is inside the string, so
315
+ // no statement-level verb is ever seen. Judged by the **body**, not the word —
316
+ // matching the bare name refused `Invoke-Expression "Write-Output 'hello'"`
317
+ // (measured 2026-11-25). When the body is a literal, its text is right there;
318
+ // when it is a variable or a file, it cannot be read and the command is refused
319
+ // by the `iex` handling in classifyCommand below.
320
+ { re: /\b(?:Invoke-Expression|iex)\b[^\n]*\b(?:Remove-Item|ri|del|erase|rd|rmdir|rm|unlink)\b/i, what: 'an Invoke-Expression body containing a delete', dialects: ['pwsh'] },
198
321
  // `cmd /c del …` hands the delete to a child interpreter.
199
322
  { re: /\bcmd(?:\.exe)?\s+\/[ck]\b[^\n]*\b(?:del|erase|rd|rmdir)\b/i, what: 'a delete delegated to cmd.exe', dialects: ['pwsh', 'bash'] },
200
323
  // `robocopy … /MIR` mirrors an empty source over the target, which empties it
@@ -252,9 +375,25 @@ const SHELL_DELETE_VERB = /\b(?:Remove-Item|ri|del|erase|rd|rmdir|rm|unlink)\b/i
252
375
  */
253
376
  const SUBSTITUTION_IN_TARGET = /\$\(|`|\$\{|\$[A-Za-z_]/;
254
377
 
378
+ /**
379
+ * PowerShell providers that hold **no files**, so a delete through them destroys
380
+ * something the Recycle Bin could never have held. Allowed: refusing these gave the
381
+ * model an instruction that cannot work (`file_trash "variable:x"`).
382
+ *
383
+ * `Remove-Variable` / `clear-variable` were already allowed, so refusing
384
+ * `Remove-Item variable:x` was inconsistent as well as useless.
385
+ */
386
+ const NON_FILE_PROVIDERS = new Set(['variable', 'env', 'function', 'alias', 'psdrive']);
387
+
388
+ /**
389
+ * Providers that hold durable state outside the file system. Denied, but with a
390
+ * reason that does **not** name `file_trash` — routing a registry key or a
391
+ * certificate to the Recycle Bin is not a thing that can happen.
392
+ */
393
+ const OTHER_PROVIDERS = new Set(['hkcu', 'hklm', 'cert', 'wsman', 'registry']);
394
+
255
395
  /** Path shapes that must never be rewritten into a recycle-bin move. */
256
- const FORBIDDEN_TARGETS = [
257
- { re: /^[a-z]:[\\/]?$/i, what: 'a drive root' },
396
+ const FORBIDDEN_TARGETS = [ { re: /^[a-z]:[\\/]?$/i, what: 'a drive root' },
258
397
  { re: /^[\\/]$/, what: 'the filesystem root' },
259
398
  { re: /^(?:\$env:SystemRoot|%SystemRoot%|[a-z]:\\Windows)(?:[\\/]|$)/i, what: 'the Windows directory' },
260
399
  { re: /^(?:\$env:ProgramFiles|%ProgramFiles%|[a-z]:\\Program Files)/i, what: 'Program Files' },
@@ -262,127 +401,6 @@ const FORBIDDEN_TARGETS = [
262
401
  { re: /^\$recycle\.bin$/i, what: 'the Recycle Bin itself' },
263
402
  ];
264
403
 
265
- /**
266
- * Strip a single layer of PowerShell quote characters.
267
- * @param token - raw operand token.
268
- * @returns the token without surrounding quotes.
269
- */
270
- function unquote(token) {
271
- const t = token.trim();
272
- if (t.length >= 2) {
273
- const first = t[0];
274
- const last = t[t.length - 1];
275
- if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
276
- return t.slice(1, -1);
277
- }
278
- }
279
- return t;
280
- }
281
-
282
- /**
283
- * Split a command string into statements on unquoted separators, so each
284
- * statement can be classified independently.
285
- *
286
- * Braces are separators. PowerShell wraps a delete in a script block all the
287
- * time — `if (Test-Path $p) { Remove-Item $p }`, `foreach ($f in $fs) { … }`,
288
- * `& { … }`, `try { … }`, `… | ForEach-Object { … }` — and a splitter that only
289
- * honours `;` and newlines leaves the verb inside the block where the
290
- * first-token matcher never reaches it. That is not a theoretical gap: it is
291
- * exactly how a real `Remove-Item` ran unguarded on 2026-10-18, while the same
292
- * delete written across three lines was caught (the newline happened to be a
293
- * separator).
294
- *
295
- * `${name}` is the one brace form that is a variable rather than a block, so it
296
- * is consumed whole. Shredding it into `$` + `NAME}` would turn a delete
297
- * target of `${TARGET_DIR}` into a literal `$`, which is worse than missing it:
298
- * the redirect message would name a path that does not exist.
299
- *
300
- * @param command - full command text.
301
- * @returns the statement strings, trimmed and non-empty.
302
- */
303
- function splitStatements(command) {
304
- const out = [];
305
- let buf = '';
306
- let quote = null;
307
- for (let i = 0; i < command.length; i += 1) {
308
- const ch = command[i];
309
- if (quote !== null) {
310
- buf += ch;
311
- if (ch === quote) quote = null;
312
- continue;
313
- }
314
- if (ch === '"' || ch === "'") {
315
- quote = ch;
316
- buf += ch;
317
- continue;
318
- }
319
- if (ch === '{' && buf.endsWith('$')) {
320
- const close = command.indexOf('}', i + 1);
321
- const end = close === -1 ? command.length : close + 1;
322
- buf += command.slice(i, end);
323
- i = end - 1;
324
- continue;
325
- }
326
- const isSep =
327
- ch === ';' ||
328
- ch === '\n' ||
329
- ch === '\r' ||
330
- ch === '|' ||
331
- ch === '&' ||
332
- ch === '{' ||
333
- ch === '}';
334
- if (isSep) {
335
- if (buf.trim().length > 0) out.push(buf.trim());
336
- buf = '';
337
- continue;
338
- }
339
- buf += ch;
340
- }
341
- if (buf.trim().length > 0) out.push(buf.trim());
342
- return out;
343
- }
344
-
345
- /**
346
- * Tokenize a single statement into argv-like words, honouring quotes.
347
- * @param statement - one statement.
348
- * @returns the token list.
349
- */
350
- function tokenize(statement) {
351
- const out = [];
352
- let buf = '';
353
- let quote = null;
354
- let started = false;
355
- for (let i = 0; i < statement.length; i += 1) {
356
- const ch = statement[i];
357
- if (quote !== null) {
358
- if (ch === quote) {
359
- quote = null;
360
- } else {
361
- buf += ch;
362
- }
363
- started = true;
364
- continue;
365
- }
366
- if (ch === '"' || ch === "'") {
367
- quote = ch;
368
- started = true;
369
- continue;
370
- }
371
- if (ch === ' ' || ch === '\t') {
372
- if (started) {
373
- out.push(buf);
374
- buf = '';
375
- started = false;
376
- }
377
- continue;
378
- }
379
- buf += ch;
380
- started = true;
381
- }
382
- if (started) out.push(buf);
383
- return out;
384
- }
385
-
386
404
  /**
387
405
  * Reduce a token to the name of the program it would execute: unquoted, with
388
406
  * the directory dropped, lower-cased, and with a launcher extension removed.
@@ -425,36 +443,6 @@ function wipeProgramIn(statement) {
425
443
  return undefined;
426
444
  }
427
445
 
428
- /**
429
- * Find the command word of one statement: the token that names the thing being
430
- * run, with the wrapper prefixes removed the same way `parseDeleteStatement`
431
- * removes them (`&`, `.`, `(`, `@(`, `$x =`) and quotes stripped.
432
- *
433
- * `& "Clear-RecycleBin"` is the case that motivated this: the statement
434
- * splitter treats `&` as a separator, so what is left is a bare quoted name, and
435
- * a `^clear-recyclebin` regex over raw text never saw it.
436
- *
437
- * @param statement - one statement.
438
- * @returns the command word, or `''`.
439
- */
440
- function commandWord(statement) {
441
- const tokens = tokenize(statement).filter((t) => t.length > 0);
442
- for (let i = 0; i < tokens.length; i += 1) {
443
- const t = tokens[i];
444
- if (/^(?:[(\[{@&.]+|\$\(|=)$/.test(t)) continue;
445
- const glued = /^[(\[{@&]+(.+)$/.exec(t);
446
- if (glued !== null) return unquote(glued[1]).trim();
447
- if (/^\$[A-Za-z_][\w:]*$/.test(t) && tokens[i + 1] === '=') {
448
- i += 1;
449
- continue;
450
- }
451
- const assign = /^\$[A-Za-z_][\w:]*\s*=\s*(.+)$/.exec(t);
452
- if (assign !== null) return assign[1].trim();
453
- return unquote(t).trim();
454
- }
455
- return '';
456
- }
457
-
458
446
  /**
459
447
  * The body text of a statement that hands a program to a child shell:
460
448
  * `pwsh -Command "…"`, `bash -c "…"`, `node -e "…"`.
@@ -577,11 +565,28 @@ function translatePosixPath(operand) {
577
565
  * interpreter (`bash -c "shred -u x"`). The body is shell text, so the name is
578
566
  * not in program position here and `wipeProgramIn` cannot see it.
579
567
  *
568
+ * Scoped by the interpreter's language. A shell body *is* shell text, so the name
569
+ * anywhere in it may run. A `node -e` / `python -c` body is not: `console.log(
570
+ * 'shred')` erases nothing, and matching the word there refused a documentation
571
+ * edit that quoted the name (measured 2026-11-15). For those interpreters the name
572
+ * counts only where it is handed to a process-spawning call.
573
+ *
580
574
  * @param statement - one statement, already split from the command.
581
575
  * @returns the matched name, or `undefined`.
582
576
  */
583
577
  function wipeProgramInInlineBody(statement) {
584
578
  if (!INLINE_BODY_FLAGS.test(statement)) return undefined;
579
+ const isShell = SHELL_INTERPRETERS.test(commandWord(statement).replace(/\.exe$/i, ''));
580
+ if (!isShell) {
581
+ // A destructured child_process import makes the call site a bare `execSync(...)`,
582
+ // which SPAWN_CALL's dot-prefixed branches do not reach.
583
+ const spawned = SPAWN_CALL.exec(statement)
584
+ ?? (SPAWN_DESTRUCTURED.test(statement) ? SPAWN_DESTRUCTURED.exec(statement) : null);
585
+ if (spawned === null) return undefined;
586
+ const tail = statement.slice(spawned.index);
587
+ const named = WIPE_NAME_IN_BODY.exec(tail);
588
+ return named === null ? undefined : named[0].toLowerCase();
589
+ }
585
590
  const found = WIPE_NAME_IN_BODY.exec(statement);
586
591
  return found === null ? undefined : found[0].toLowerCase();
587
592
  }
@@ -684,6 +689,11 @@ function parseDeleteStatement(statement) {
684
689
  // SilentlyContinue` made "SilentlyContinue" a path to recycle, and the
685
690
  // redirect message told the model to `file_trash` a value name. The two
686
691
  // path flags are the exception — their value *is* the target.
692
+ const bare = flag.replace(/:.+$/, '');
693
+ // Switches take no value, so whatever follows is a real operand.
694
+ // `-WhatIf:$false` / `-Confirm:$false` glue their boolean on; strip it and
695
+ // keep going, otherwise `$false` becomes a "path to recycle".
696
+ if (SWITCH_PARAMETERS.has(bare)) continue;
687
697
  const takesValue = FLAGS_TAKING_VALUE.has(flag);
688
698
  const isPathFlag = flag === '-path' || flag === '-literalpath';
689
699
  if ((takesValue || isPathFlag) && i + 1 < tokens.length) {
@@ -749,6 +759,8 @@ function emptyRecycleVerdict(what) {
749
759
  * @param options.forbidEmptyRecycleBin - deny commands that empty the bin.
750
760
  * @param options.forbidWipe - deny permanent-erase tools.
751
761
  * @param options.blockScriptDeletes - deny inline script text containing deletes.
762
+ * @param options.blockTruncatingWrites - deny in-place rewrites that can destroy
763
+ * the only copy of a file's content (see `rewrite-guard.js`).
752
764
  * @param options.dialect - which shell language the command is written in
753
765
  * ('pwsh' or 'bash'). Defaults to 'pwsh'. Dialect-scoped rules such as the
754
766
  * `$( … )` command-substitution check only apply to their own shell.
@@ -759,6 +771,7 @@ export function classifyCommand(command, options = {}) {
759
771
  forbidEmptyRecycleBin = true,
760
772
  forbidWipe = true,
761
773
  blockScriptDeletes = true,
774
+ blockTruncatingWrites = true,
762
775
  dialect = 'pwsh',
763
776
  } = options;
764
777
 
@@ -801,10 +814,36 @@ export function classifyCommand(command, options = {}) {
801
814
  }
802
815
  // Shell verbs driven over bin items are how Explorer empties the bin one
803
816
  // item at a time: `InvokeVerb('delete')` on a bin item is permanent, not a
804
- // recycle. Reading the bin (Move-Item out of $R, listing $I records) stays
805
- // allowed — only driving its verbs is refused.
806
- if (BIN_NAMESPACE_REF.test(command) && BIN_VERB_DRIVE.test(command)) {
807
- return emptyRecycleVerdict("the Recycle Bin's own shell verbs (InvokeVerb / Verbs / DoIt)");
817
+ // recycle. Reading the bin (Move-Item out of $R, listing $I records, listing
818
+ // which verbs an item offers) stays allowed — only *driving* is refused.
819
+ //
820
+ // Judged per statement, so a bin reference in one statement and a `DoIt()` in
821
+ // another cannot convict each other; and so that `$i.InvokeVerb('delete')` on
822
+ // its own — no `Namespace(10)` text anywhere — is still caught, which it was
823
+ // not until 2026-11-25.
824
+ for (const statement of statements) {
825
+ // Skip the loop early when the statement cannot involve the bin at all:
826
+ // `DoIt(`/`InvokeVerb(` and a bin reference are the only triggers, and neither
827
+ // appears in ordinary commands. The four regexes below run per statement, so a
828
+ // single cheap guard keeps this off the common path (measured 2026-11-25).
829
+ if (!BIN_TOUCH.test(statement)) continue;
830
+ const referencesBin = BIN_NAMESPACE_REF.test(statement);
831
+ const drivesDoIt = /\.DoIt\s*\(/i.test(statement);
832
+ const drivesVerb = /\bInvokeVerb\s*\(/i.test(statement);
833
+ const restores = BIN_VERB_RESTORE_ARG.test(statement);
834
+ const deletes = BIN_VERB_DELETE_ARG.test(statement);
835
+
836
+ // `DoIt()` runs whatever verb is selected; the selection is not in the text,
837
+ // so it is never treated as a restore — a comment saying "restore" is not a
838
+ // verb argument.
839
+ if (drivesDoIt && (referencesBin || !restores)) {
840
+ return emptyRecycleVerdict("the Recycle Bin's own shell verbs (DoIt)");
841
+ }
842
+ if (drivesVerb && !restores) {
843
+ if (referencesBin || deletes) {
844
+ return emptyRecycleVerdict("the Recycle Bin's own shell verbs (InvokeVerb)");
845
+ }
846
+ }
808
847
  }
809
848
  }
810
849
 
@@ -873,12 +912,29 @@ export function classifyCommand(command, options = {}) {
873
912
  // delete cannot hide in a base64 body.
874
913
  const statements = judged;
875
914
 
915
+ // 0. A shell invoked through a variable. Which program runs is not in the text,
916
+ // so an inline body cannot be judged — refuse rather than assume it is
917
+ // harmless. Only when the statement has an inline body: `& $cmd` alone runs
918
+ // whatever the variable holds, and that is caught elsewhere if it deletes.
919
+ for (const statement of statements) {
920
+ if (invokesShellVariable(statement)) {
921
+ return {
922
+ action: 'deny',
923
+ kind: 'opaque',
924
+ reason:
925
+ 'Refusing a shell invoked through a variable (`$name -c "…"`): which program runs is only known at ' +
926
+ 'run time, so a delete inside the command string cannot be routed to the Recycle Bin. ' +
927
+ 'Call the interpreter directly, or run the delete as a file_trash tool call.',
928
+ };
929
+ }
930
+ }
931
+
876
932
  // 1. A shell's inline body that contains a shell delete verb.
877
933
  // `pwsh -Command "Remove-Item C:\x"`, `bash -c "rm -rf /tmp/x"`.
878
934
  // Scoped to shells: in Python or Ruby, `del` and `rm` are that
879
935
  // language's own syntax, so they are judged by rule 2 instead.
880
936
  for (const statement of statements) {
881
- const shellInterp = /\b(?:bash|sh|zsh|pwsh|powershell)\b/i.test(statement);
937
+ const shellInterp = SHELL_NAME_ANYWHERE.test(statement);
882
938
  const inlineBody = INLINE_BODY_FLAGS.test(statement);
883
939
  if (shellInterp && inlineBody && SHELL_DELETE_VERB.test(statement)) {
884
940
  return {
@@ -940,6 +996,18 @@ export function classifyCommand(command, options = {}) {
940
996
  }
941
997
 
942
998
 
999
+ // Content destroyed without a delete verb: an in-place rewrite of the only
1000
+ // copy. Judged before the rewrite collection on purpose — `file_trash` is the
1001
+ // remedy for a *delete*, and moving the file away is precisely what a
1002
+ // read-modify-write is not allowed to have happened (and on a UNC share there
1003
+ // is no bin to move it into at all). Deny, and hand back the safe recipe.
1004
+ if (blockTruncatingWrites) {
1005
+ const risk = analyzeOverwriteRisk(command, { statements: judged, dialect });
1006
+ if (risk !== undefined) {
1007
+ return { action: 'deny', kind: risk.kind, reason: risk.reason };
1008
+ }
1009
+ }
1010
+
943
1011
  // Rewritable deletes: collect every operand across every statement, including
944
1012
  // the ones decoded out of an -EncodedCommand body.
945
1013
 
@@ -1000,6 +1068,27 @@ export function classifyCommand(command, options = {}) {
1000
1068
  }
1001
1069
  operand = mapped.path;
1002
1070
  }
1071
+
1072
+ // PowerShell providers are not file systems. `Remove-Item variable:x` deletes
1073
+ // a variable; `env:X` an environment entry; `function:x` a function. Telling
1074
+ // the model to `file_trash "variable:x"` is an instruction that cannot work —
1075
+ // the tool resolves it to a path that does not exist. Measured 2026-11-25.
1076
+ const provider = /^([A-Za-z]+):/.exec(operand);
1077
+ if (provider !== null && !/^[A-Za-z]$/.test(provider[1])) {
1078
+ const name = provider[1].toLowerCase();
1079
+ if (NON_FILE_PROVIDERS.has(name)) continue; // deletes nothing a bin could hold
1080
+ if (OTHER_PROVIDERS.has(name)) {
1081
+ return {
1082
+ action: 'deny',
1083
+ kind: 'forbidden-target',
1084
+ reason:
1085
+ `Refusing a delete that targets the ${provider[1]}: provider ("${operand}"). The Recycle Bin only ` +
1086
+ 'holds files, so this cannot be routed there — and erasing it is not recoverable. ' +
1087
+ 'Delete it deliberately with the provider\'s own tooling if that is really what you mean.',
1088
+ };
1089
+ }
1090
+ }
1091
+
1003
1092
  // An operand that is itself a substitution has no provable value: the
1004
1093
  // shell expands it at run time. `rm -rf $(cat list.txt)` would otherwise
1005
1094
  // be tokenized into the literal strings `$(cat` and `list.txt)`, and