dsh-delete-guard 2.4.1 → 2.4.3

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/SECURITY.md CHANGED
@@ -76,6 +76,93 @@ a security read:
76
76
  honest: O(size) in time and the same in free space on the staging volume, so a
77
77
  very large tree can exceed the tool call's timeout.
78
78
 
79
+ ## Why there is no permanent-delete tool
80
+
81
+ Issue #2 asks for one: a tool that really erases when the user asked for it,
82
+ gated by a `user_request` / `user_quote` field. It is refused, and the reason is
83
+ not that permanent deletion is never legitimate — a user can always do it in
84
+ Explorer, or run a script themselves. The reason is that **the gate would be
85
+ authored by the thing it is meant to guard.**
86
+
87
+ Three layers, and only the first has a machine judge:
88
+
89
+ | Layer | Question | Judge |
90
+ | --- | --- | --- |
91
+ | 1 | did these characters come from the user? | the plugin, mechanically — `source.kind === 'user'` plus an `rpcId` on the `user/message` event |
92
+ | 2 | does that sentence mean "this file may be destroyed"? | nobody, automatically |
93
+ | 3 | should it run *now*? | a human — `{ kind: 'ask' }` where approvals are real; on a box with `approval policy: never` that resolves to allow, so the only remaining human gate is a command the person runs |
94
+
95
+ A verbatim quote can be checked. Intent cannot, because **the same characters
96
+ carry both readings**: "永久删除 a.md", "不要永久删除 a.md", "别永久删除 a.md",
97
+ "能永久删除 a.md 吗", "你上次说的『永久删除 a.md』是指哪一步" all contain the
98
+ affirmative token, and the last three are not instructions at all. A lexical
99
+ filter over negations is an enumeration treadmill, and it fails in the direction
100
+ of *allowing* — the token is present — which for a destructive action is the worst
101
+ direction to fail in. Adding a semantic model to classify the sentence only moves
102
+ the trust question up one level. (Even the provenance check needs care: `user/message`
103
+ also carries `agent-instructions` from `AGENTS.md`, `runtime-context` and spliced
104
+ agent input, so a filter that does not key on `source.kind` would let the agent
105
+ author its own permission slip.)
106
+
107
+ **Measured, on why the surrounding design cannot compensate.** 126 real guard
108
+ denials across 58 sessions (300 newest session logs on this machine, 2026-11-24),
109
+ classified by what the model did before the next user turn:
110
+
111
+ | follow-up | share |
112
+ | --- | --- |
113
+ | changed approach (typically by following the recipe the deny message names: copy to `.bak`, use `edit`) | 78% |
114
+ | `file_trash` within 5 tool calls | 14% |
115
+ | re-attempted a shape the guard would block | 4% |
116
+ | diagnosed first (`read`, `grep`, `Test-Path`) | 3% |
117
+ | wrote a delete into a script and ran that path | 0.8% |
118
+ | **stopped without another tool call** | **0%** |
119
+
120
+ A block does not end a turn; it re-routes. And the re-route follows the
121
+ alternative the deny message names — which is why every refusal here names one.
122
+ There is no acceptable alternative for "make it unrecoverable", so a
123
+ `permanent_delete` tool would be the shortest path to a goal the model had already
124
+ been told to pursue, with a fabricated-or-misapplied quote as its receipt.
125
+
126
+ **What would be honest**, if this is ever revisited: the gate is a real approval or
127
+ a command the human runs (`scripts/purge-bin-entry.ps1`, keyed off the `$I` record),
128
+ and `user_quote` is an audit field — never the key. Anything else is an audited
129
+ permanent delete with a receipt the agent wrote itself.
130
+
131
+ Note the asymmetry: "no permanent delete" is a policy, not an invariant — `Add-Type`
132
+ C# still reaches `DeleteFileW`, as the README's 「不挡什么」 table says. The choice
133
+ above keeps the *easy* path safe, which is what a policy layer can actually do.
134
+
135
+ ## How the rules were calibrated (2026-11-25)
136
+
137
+ The rules from 2.3.0 / 2.4.0 each came from one incident. 2.4.2 came from a
138
+ measurement: **62,131 shell commands that actually ran on this machine** (5,746 session
139
+ logs), re-classified with the matcher as it stood. 1,580 would be refused; **432 of those
140
+ were false positives (0.70% of every command ever run here)**. Records:
141
+ `docs/incidents/2026-11-24-rule-false-positive-sweep.md` (evidence) and
142
+ `docs/incidents/2026-11-24-fix-plan-2-4-2.md` (plan, including the direction that was
143
+ rejected and why).
144
+
145
+ Two things from that exercise are worth keeping in view when changing a rule:
146
+
147
+ **1. A shape list is the same mistake as a verb list.** The first proposal was to refuse
148
+ only commands containing a discard token (`[a..b]`, `-First`, `Select-Object`). Measurements
149
+ saw four rebuilds that contain none of them and destroy a whole file anyway
150
+ (`| Where-Object { -not … }`, `for { … continue }`, `-replace '(?s)^.*$'`). The rule keeps
151
+ "reads the same file it writes" as its shape and adds **order** and **recoverability** —
152
+ it does not trade one word list for another.
153
+
154
+ **2. A count is not a shape.** After the change the sweep's `real` count fell 1,148 → 852,
155
+ which reads like 296 dangerous commands were let through. A mechanical check said otherwise:
156
+ across the 5,917 commands now allowed, **none** are "same file, read before write". The drop
157
+ was the sweep's own classifier mislabeling write-then-read-back as a whole-file rewrite. The
158
+ acceptance criteria were rewritten as a shape gate because of this.
159
+
160
+ **3. A dry run must not become an instruction.** `Remove-Item x -WhatIf` classified as
161
+ `rewrite`, and the rewrite branch tells the model to re-run the call as `file_trash` — so a
162
+ user asking to preview was advised to destroy the file. Dry runs are now rendered as
163
+ previews. The tempting fix (drop `-WhatIf` statements from classification) was measured and
164
+ rejected: the word in a comment or a string then exempts a real write.
165
+
79
166
  ## Reporting
80
167
 
81
168
  Once this repository is public, use a GitHub Security Advisory (or a private
package/lib/guard.js CHANGED
@@ -64,12 +64,20 @@ const FLAGS_TAKING_VALUE = new Set([
64
64
  '-include',
65
65
  '-exclude',
66
66
  '-credential',
67
- '-confirm',
68
- '-whatif',
69
- '-verbose',
70
- '-debug',
71
67
  ]);
72
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
+
73
81
  /**
74
82
  * Programs that mean "permanently erase" rather than "delete". They are never
75
83
  * rewritten — they are denied outright.
@@ -119,14 +127,71 @@ const WIPE_NAME_IN_BODY = /\b(?:sdelete64|sdelete|shred|srm|wipe)\b/i;
119
127
  * the body and could not tell documentation from a command.
120
128
  */
121
129
  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;
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;
123
143
 
124
144
  /**
125
145
  * Child interpreters whose inline body is a shell program. For these, any name in
126
146
  * the body counts as a program name; for every other interpreter the name must
127
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.
128
169
  */
129
- const SHELL_INTERPRETERS = /\b(?:bash|sh|zsh|pwsh|powershell)\b/i;
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;
130
195
 
131
196
  /** Denial text shared by every permanent-erase rule. */
132
197
  const WIPE_REASON =
@@ -169,7 +234,34 @@ const EMPTY_RECYCLE_RULES = [
169
234
  const EMPTY_BIN_COMMAND = /^clear-recyclebin$/i;
170
235
  const EMPTY_BIN_API = /\bSHEmptyRecycleBin\w*\b/i;
171
236
  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;
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;
173
265
 
174
266
  /**
175
267
  * Constructs that can hide a delete from a text-level parser, or make the
@@ -219,9 +311,13 @@ const ERASE_CONSTRUCTS = [
219
311
  // The no-argument form was a hole until 1.0.4 — only `.Delete($true)` matched,
220
312
  // so `(Get-Item $p).Delete()` erased a file unguarded.
221
313
  { 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'] },
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'] },
225
321
  // `cmd /c del …` hands the delete to a child interpreter.
226
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'] },
227
323
  // `robocopy … /MIR` mirrors an empty source over the target, which empties it
@@ -279,9 +375,25 @@ const SHELL_DELETE_VERB = /\b(?:Remove-Item|ri|del|erase|rd|rmdir|rm|unlink)\b/i
279
375
  */
280
376
  const SUBSTITUTION_IN_TARGET = /\$\(|`|\$\{|\$[A-Za-z_]/;
281
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
+
282
395
  /** 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' },
396
+ const FORBIDDEN_TARGETS = [ { re: /^[a-z]:[\\/]?$/i, what: 'a drive root' },
285
397
  { re: /^[\\/]$/, what: 'the filesystem root' },
286
398
  { re: /^(?:\$env:SystemRoot|%SystemRoot%|[a-z]:\\Windows)(?:[\\/]|$)/i, what: 'the Windows directory' },
287
399
  { re: /^(?:\$env:ProgramFiles|%ProgramFiles%|[a-z]:\\Program Files)/i, what: 'Program Files' },
@@ -464,8 +576,12 @@ function translatePosixPath(operand) {
464
576
  */
465
577
  function wipeProgramInInlineBody(statement) {
466
578
  if (!INLINE_BODY_FLAGS.test(statement)) return undefined;
467
- if (!SHELL_INTERPRETERS.test(statement)) {
468
- const spawned = SPAWN_CALL.exec(statement);
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);
469
585
  if (spawned === null) return undefined;
470
586
  const tail = statement.slice(spawned.index);
471
587
  const named = WIPE_NAME_IN_BODY.exec(tail);
@@ -573,6 +689,11 @@ function parseDeleteStatement(statement) {
573
689
  // SilentlyContinue` made "SilentlyContinue" a path to recycle, and the
574
690
  // redirect message told the model to `file_trash` a value name. The two
575
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;
576
697
  const takesValue = FLAGS_TAKING_VALUE.has(flag);
577
698
  const isPathFlag = flag === '-path' || flag === '-literalpath';
578
699
  if ((takesValue || isPathFlag) && i + 1 < tokens.length) {
@@ -693,10 +814,36 @@ export function classifyCommand(command, options = {}) {
693
814
  }
694
815
  // Shell verbs driven over bin items are how Explorer empties the bin one
695
816
  // 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)");
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
+ }
700
847
  }
701
848
  }
702
849
 
@@ -765,12 +912,29 @@ export function classifyCommand(command, options = {}) {
765
912
  // delete cannot hide in a base64 body.
766
913
  const statements = judged;
767
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
+
768
932
  // 1. A shell's inline body that contains a shell delete verb.
769
933
  // `pwsh -Command "Remove-Item C:\x"`, `bash -c "rm -rf /tmp/x"`.
770
934
  // Scoped to shells: in Python or Ruby, `del` and `rm` are that
771
935
  // language's own syntax, so they are judged by rule 2 instead.
772
936
  for (const statement of statements) {
773
- const shellInterp = SHELL_INTERPRETERS.test(statement);
937
+ const shellInterp = SHELL_NAME_ANYWHERE.test(statement);
774
938
  const inlineBody = INLINE_BODY_FLAGS.test(statement);
775
939
  if (shellInterp && inlineBody && SHELL_DELETE_VERB.test(statement)) {
776
940
  return {
@@ -904,6 +1068,27 @@ export function classifyCommand(command, options = {}) {
904
1068
  }
905
1069
  operand = mapped.path;
906
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
+
907
1092
  // An operand that is itself a substitution has no provable value: the
908
1093
  // shell expands it at run time. `rm -rf $(cat list.txt)` would otherwise
909
1094
  // be tokenized into the literal strings `$(cat` and `list.txt)`, and
package/lib/index.js CHANGED
@@ -74,6 +74,31 @@ const SHELL_TOOLS = new Map([
74
74
  ['terminal_write', { field: 'text', dialect: 'pwsh' }],
75
75
  ]);
76
76
 
77
+ /**
78
+ * A cheap "could this command possibly touch files, the bin, or an interpreter?"
79
+ * test, used to skip the full classifier.
80
+ *
81
+ * Must be **over-inclusive**: every rule in `guard.js` needs at least one of these
82
+ * signals to fire, so anything this misses is a command that no rule could have
83
+ * matched anyway. The cost of a false positive is a few hundred microseconds; the
84
+ * cost of a false negative would be an unguarded command.
85
+ */
86
+ const MAY_TOUCH_FILES = new RegExp([
87
+ // delete verbs
88
+ '\\b(?:Remove-Item|ri|del|erase|rd|rmdir|rm|unlink|clear-content)\\b',
89
+ // write verbs and redirects
90
+ '\\b(?:Set-Content|Out-File|Add-Content|Export-Csv|Tee-Object|Copy-Item|Move-Item|New-Item|::Write\\w+|::Create\\w*)\\b',
91
+ '>{1}(?!>)',
92
+ // readers (they matter to the in-place rule)
93
+ '\\b(?:Get-Content|ReadAllText|ReadAllLines|Import-Csv|Select-String|OpenText)\\b',
94
+ // interpreters, inline bodies, opaque constructs
95
+ '\\b(?:bash|sh|zsh|pwsh|powershell|node|python|python3|perl|ruby|cmd(?:\\.exe)?)\\b',
96
+ '\\$-{0,1}\\(|`|<<|\\bxargs\\b|\\bfind\\b',
97
+ // trash / wipe / bin surfaces
98
+ '\\b(?:sdelete|sdelete64|shred|srm|wipe|cipher|format|robocopy|Invoke-Expression|iex|Add-Type)\\b',
99
+ 'recycle|namespace\\(\\s*(?:10|0xa)\\s*\\)|invokeverb|\\bdoit\\b|\\.verbs\\s*\\(|shemptyrecyclebin',
100
+ ].join('|'), 'i');
101
+
77
102
  /**
78
103
  * Reject an empty path list before any I/O.
79
104
  * @param paths - candidate paths.
@@ -87,6 +112,32 @@ function cleanPaths(paths) {
87
112
  .filter((p) => p.length > 0);
88
113
  }
89
114
 
115
+ /**
116
+ * Whether a shell command is a dry run (`-WhatIf`).
117
+ *
118
+ * Token-level on purpose. A textual test is fooled by the word appearing in a
119
+ * comment or inside a string value — measured 2026-11-25: with a textual test,
120
+ * `Set-Content $f $t # always -WhatIf first` and
121
+ * `Set-Content -Value "run -WhatIf then finish"` were both treated as dry runs even
122
+ * though they really write.
123
+ *
124
+ * `-WhatIf:$false` / `-WhatIf:$true` are **not** dry runs: the first really executes,
125
+ * and neither is the bare preview the switch is for.
126
+ *
127
+ * @param command - the raw command text.
128
+ * @returns whether the command would only preview.
129
+ */
130
+ function isDryRun(command) {
131
+ if (typeof command !== 'string' || !/-whatif/i.test(command)) return false;
132
+ for (const line of command.split(/\r?\n/)) {
133
+ // Strip a trailing PowerShell comment so `… -WhatIf` in prose does not count.
134
+ const code = line.replace(/(?:^|\s)#.*$/, '');
135
+ // A `-WhatIf` token that is not followed by a `:` (i.e. not `:$false`).
136
+ if (/(?:^|\s)-whatif(?![:\w-])/i.test(code)) return true;
137
+ }
138
+ return false;
139
+ }
140
+
90
141
  /**
91
142
  * Resolve the workspace root the sandbox policy reports, falling back to the
92
143
  * process working directory. The fallback matters: without a sandbox service
@@ -143,6 +194,20 @@ export function apply(ctx, config = {}) {
143
194
  const command = args[spec.field];
144
195
  if (typeof command !== 'string') return next();
145
196
 
197
+ // Cheap precondition: a command that cannot possibly delete or destroy content
198
+ // is not worth the full classifier.
199
+ //
200
+ // The classifier is ~250 µs on a long command (dozens of regexes over the whole
201
+ // text), which is real money on the tool-call path — the host pays it before
202
+ // every shell call. Two regexes cost ~1.8 µs and skip 88% of commands: measured
203
+ // on 6,000 real commands, only 11.6% mention both a reader and a writer.
204
+ //
205
+ // Deliberately over-inclusive: any mention of a delete verb, a write verb, a
206
+ // redirect, an interpreter, or a bin API lets the command through to the full
207
+ // check. A false positive here only costs time; a false negative would skip the
208
+ // guard, so the net is wide.
209
+ if (!MAY_TOUCH_FILES.test(command)) return next();
210
+
146
211
  const verdict = classifyCommand(command, {
147
212
  ...guardOptions,
148
213
  // The tool name identifies the shell language, which decides
@@ -162,6 +227,31 @@ export function apply(ctx, config = {}) {
162
227
 
163
228
  // action === 'rewrite': steer the model to the recoverable path.
164
229
  const list = verdict.targets.map((t) => `"${t}"`).join(', ');
230
+
231
+ // A dry run must not be turned into an instruction to really delete.
232
+ //
233
+ // Measured 2026-11-25: `Remove-Item -LiteralPath x.txt -WhatIf` classified as
234
+ // `rewrite/delete`, and this branch told the model to re-run it as `file_trash`
235
+ // — i.e. the user asked to preview and the guard advised destroying the file.
236
+ // That is a safety inversion, not a false positive. The reverse also happened:
237
+ // `Remove-Item -WhatIf x.txt` was refused as "no explicit operands" because
238
+ // `-WhatIf` was listed as a flag that consumes its value.
239
+ //
240
+ // The fix renders dry runs differently rather than omitting the statement from
241
+ // classification: dropping statements would let a real write be exempted by the
242
+ // word `-WhatIf` appearing in a comment or a string value.
243
+ if (isDryRun(command)) {
244
+ return {
245
+ kind: 'deny',
246
+ reason:
247
+ `This command is a dry run (\`-WhatIf\`), so nothing was executed and nothing needs to be deleted. ` +
248
+ `The guard does not rewrite dry runs into real deletions.\n\n` +
249
+ `If you actually meant to delete ${list}, call ${TRASH_TOOL} with those paths. If you only wanted to ` +
250
+ `preview, the command you just ran was correct — but remove \`-WhatIf\` would really delete, so don't.`,
251
+ info: { name: 'DeleteGuardError', code: 'DELETE_GUARD_DRY_RUN' },
252
+ };
253
+ }
254
+
165
255
  return {
166
256
  kind: 'deny',
167
257
  reason: