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/CHANGELOG.md CHANGED
@@ -7,6 +7,319 @@ each profile actually ran.
7
7
  The long-form reasoning behind every entry — what was measured, what was
8
8
  rejected, what the trade-off costs — lives in the maintainer's engineering notes (`INCIDENTS.md`, not shipped since 2.2.0).
9
9
 
10
+ ## [2.4.2] — 2026-11-25
11
+
12
+ **Renumbering false positives from real measurements.** The rules from 2.3.0 / 2.4.0 were
13
+ built from one incident each. This release is built from **62,131 shell commands that
14
+ actually ran on this machine** (5,746 session logs), re-classified with today's matcher:
15
+ 1,580 would now be refused, and **432 of those were false positives (0.70% of all
16
+ commands)**. Three independent audits — two per-command, one code-level — plus my own
17
+ mechanical re-checks. Evidence: `docs/incidents/2026-11-24-rule-false-positive-sweep.md`,
18
+ plan: `docs/incidents/2026-11-24-fix-plan-2-4-2.md`.
19
+
20
+ ### `in-place-rewrite`: two conditions instead of a new rule
21
+
22
+ The rule stays "reads the same file it writes". What was missing was **order** and
23
+ **recoverability** — not a different predicate.
24
+
25
+ - **Order.** A read that happens only *after* the last write is a verification read-back;
26
+ its value cannot feed a write that already ran. Releases 330 historical commands.
27
+ - `.NET` writes participate: giving them no statement index made the last-write lookup
28
+ return `-1`, which emptied the read set and would have let **223** `.NET`
29
+ read→write commands through — including the shape §9.4 of the incident record
30
+ claims is covered.
31
+ - Suppressed inside any repetition construct (`for`, `foreach`, `while`, `do`, `until`,
32
+ `switch`, `%`/`ForEach-Object`, `.ForEach(`), because there textual order is not
33
+ execution order. The first gate listed only three keywords and missed `%`, the
34
+ commonest spelling.
35
+ - **Recoverability.** A copy step now has to be an actual statement writing a *different*
36
+ path derived from the target, **before** the overwrite. The previous check was a
37
+ whole-text `BACKUP_MARKER.test(command)`, so all three of these were exempted while
38
+ truly rewriting a file from its only copy: a `.bak` in a trailing comment, a `.bak` in
39
+ the target's own name, and a `.bak` in an unrelated string.
40
+ - `sed -i.bak` still counts — the editor makes the copy itself, in the same statement.
41
+ - A temp file holding the **new** content is **not** a backup: verifying the output does
42
+ not make the input recoverable. Refused (this was 4 historical commands).
43
+
44
+ ### A bounded substitution with the codec pinned is the `edit` tool
45
+
46
+ `$t = $t.Replace('a','b')` written back is a targeted change, not a rebuild. It is now
47
+ allowed when **both** sides state an encoding, which is the condition that actually
48
+ matters: `Get-Content -Raw` on a GBK document decodes it wrong, and `WriteAllText` then
49
+ writes the mojibake back — measured, with an ASCII needle the occurrence check passes and
50
+ every CJK character becomes `U+FFFD`. Encoding continuity is what prevents it; a
51
+ replacement-count check does not.
52
+
53
+ Not allowed: a document-wide regex (`-replace '(?s)^.*$'` reduces a file to one
54
+ character), a substitution applied to a slice, and a substitution with no codec stated.
55
+ Releases 183 commands (44% of the cluster).
56
+
57
+ ### Four holes the sweep found (not false positives — the opposite)
58
+
59
+ | Command | Was | Now |
60
+ | --- | --- | --- |
61
+ | `Remove-Item x.txt -WhatIf` | `rewrite/delete` → told the model to re-run it as `file_trash` | rendered as a dry run: "this previewed, nothing was deleted" |
62
+ | `$i.InvokeVerb('delete')` alone | **allowed** (the rule needed a bin reference in the same command) | refused |
63
+ | `$i.Verbs() \| % { $_.DoIt() }` | **allowed** | refused |
64
+ | `const {execSync}=require('child_process'); execSync('…')` | **allowed** (every spawn branch required a leading dot) | refused |
65
+
66
+ The first is a safety inversion, not friction: the user asked to preview and the guard
67
+ advised destroying the file. The fix renders dry runs differently rather than dropping
68
+ them from classification — dropping statements let the word `-WhatIf` in a comment or a
69
+ string exempt a real write (measured, three cases).
70
+
71
+ Also: `-WhatIf`/`-Confirm`/`-Verbose`/`-Debug` are switches, not value-taking flags.
72
+ Listing them as value-taking made `Remove-Item -Verbose C:\x\a.txt` report "no explicit
73
+ operands", so the model was told its delete had no target instead of being handed the
74
+ paths.
75
+
76
+ ### Smaller corrections
77
+
78
+ - `.Verbs()` is enumeration, not driving: the sanctioned restore path and read-only bin
79
+ listings are allowed again.
80
+ - `DoIt()` is never exempted by a restore word — a comment saying `# restore` laundered it.
81
+ - `Remove-Item variable:x` / `env:X` / `function:x` / `alias:X` are allowed: they delete
82
+ no file, and the old behaviour handed the model `file_trash "variable:x"`, an
83
+ instruction that cannot work. `HKCU:`/`Cert:`/`WSMan:` are refused **without** a
84
+ file_trash hint — the bin cannot hold a registry key.
85
+ - `Invoke-Expression` is judged by its body, not by the word.
86
+ - A shell invoked through a variable (`$shellPath='…bash.exe'; & $shellPath -c "…"`) is
87
+ refused when the body deletes. Previously the `$sh='bash'` spelling was caught only
88
+ because the variable *name* contains `sh`.
89
+ - `Select-String <pattern> <file>`: `-Path`'s value was eaten by `skip: 1`, so
90
+ `Select-String -Path a.md -Pattern x | Set-Content a.md` was allowed.
91
+ - A read folded into the write statement (`Set-Content $f (Get-Content $f | Select-Object -First 10)`)
92
+ is now a read. Four variants were allowed; this is the incident in one line.
93
+
94
+ ### Costs, stated
95
+
96
+ - **Latency: +11% best-case, +16% median** on 6,000 real commands (41 interleaved rounds,
97
+ 25 blocks, both versions in one process; the two-version comparison is in
98
+ `temp/bench-decisive.mjs`). The classifier was ~165 µs/command and is now ~192 µs.
99
+ For scale: one `stat()` is ~5 µs, one PowerShell spawn (what `file_trash` does) is
100
+ ~70 ms — the guard is 0.3% of a trash call. A cheap precondition in the hook
101
+ (two regexes, verified to skip **no** command the classifier would block, on all 6,000)
102
+ keeps the new checks off the 88% of commands that neither read nor write.
103
+ - **Not reached:** the plan's target was "误伤 < 130". The measured result is **432 → 241**.
104
+ The remainder is dominated by 156 commands whose *read* side states no encoding — refused
105
+ on purpose, since that is the mojibake hazard — plus 24 with no encoding on either side
106
+ and the `UNSURE` group whose writes come from an external script.
107
+ - **`real` count drops 1,148 → 852, which looks like over-relaxation and is not.** Verified
108
+ mechanically: across the 5,917 commands now allowed, **zero** are "same file, read before
109
+ write". The drop is the sweep's own classifier mislabeling write-then-read-back
110
+ (`python x.py | Out-File out.txt; Get-Content out.txt`) as a whole-file rewrite. The
111
+ acceptance criteria were changed to a shape gate for this reason.
112
+
113
+ ### Tests
114
+
115
+ 116 → **148**, eight layers. New layer ③ `test/holes.test.mjs` (12 cases) pins each hole
116
+ and each correction with the direction it must move; layer ② grew from 22 to 30 cases
117
+ covering order, `.NET` ordering, folded reads, repetition, real-vs-fake backup steps,
118
+ pinned encoding, and the four "no discard token" rebuilds that keep the rule from
119
+ degenerating into a token list.
120
+
121
+ ## [2.4.1] — 2026-11-24
122
+
123
+ The publish workflow's first run, and what it found. No production code changed.
124
+
125
+ Releasing 2.4.0 ran `test/run-all.mjs` on Ubuntu for the first time in this
126
+ repository's history — no tags, no releases, no prior workflow runs; 2.2.3 reached
127
+ npm through a hand-run `npm publish`. Layer ④ came back **4 pass / 11 fail**:
128
+ `move-guard.test.mjs` asserts Windows path semantics (`C:\` is a drive root,
129
+ `..\..` resolves inside a volume, `\\host\share` is a UNC share, `C:\Program Files`
130
+ is refused), and on a POSIX runner `node:path` is posix, so `C:\` is an ordinary
131
+ relative name and `resolve()` prepends the checkout path.
132
+
133
+ Fix: layers ③ ④ ⑦ are gated on `process.platform === 'win32'` in
134
+ `test/run-all.mjs` and report **skipped** elsewhere, with the measurement recorded
135
+ in the comment. The plugin is `os: ["win32"]` and the bridge is
136
+ `SHFileOperationW`: a POSIX runner cannot exercise those paths at all, so gating is
137
+ the honest answer rather than a workaround.
138
+
139
+ This also corrects a claim in 2.3.0 — "layers ① ② ④ ⑥ pass anywhere" was derived
140
+ from forcing `process.platform='linux'` on Windows, which leaves `node:path` bound
141
+ to win32 at load time, so the check proved nothing about the other platform. CI was
142
+ the only evidence, and it had never run. Same failure mode as the rules this
143
+ release series added: a check that looks green because it never exercised the thing
144
+ it names.
145
+
146
+ ## [2.4.0] — 2026-11-15
147
+
148
+ **Deleting from a network share now works instead of being refused.** A share has
149
+ no Recycle Bin: `SHFileOperationW(FOF_ALLOWUNDO)` erases there and returns 0
150
+ (reproduced 2026-10-23), so 2.3.0 refused every UNC path — safe, but the deletion
151
+ never happened and the model had to invent a workaround.
152
+
153
+ `file_trash` now does what a person does by hand, in one call, in this order:
154
+
155
+ 1. copy the item to a staging directory on a volume that does have a bin
156
+ (`%LOCALAPPDATA%\dsh-delete-guard\staging\<yyyyMMdd-HHmmss>-<name>`, override
157
+ with `stagingRoot`);
158
+ 2. verify the copy against the original — same relative paths, same kinds, same
159
+ file sizes;
160
+ 3. recycle the staging folder — the copy is now in the bin and restorable;
161
+ 4. only then remove the original.
162
+
163
+ **What this guarantees, stated exactly**: the *content* is recoverable from the
164
+ local Recycle Bin; the *original path* is not, because the share has no bin to hold
165
+ it. Step 4 is an ordinary permanent delete. That is why the order is the safety
166
+ property — every failure before step 4 leaves the original untouched, and step 4
167
+ runs only after the bridge confirms the staged copy left for the bin. A failure in
168
+ step 4 is reported with the paths that remain, never as success.
169
+
170
+ Restoring lands in the staging path, not back on the share: the bin's `$I` record
171
+ holds the staging location, so `file_trash` prints it in its result and the render
172
+ says so. That is the one place where "delete a share file" is not the same as
173
+ "delete a local file", and it is visible rather than implied.
174
+
175
+ **Refused, with the reason** (each one stops before any copy):
176
+ - a share root (`\\host\share`) or a bare host — those are not items, and staging
177
+ them would copy and then delete everything on the share;
178
+ - a tree containing a **reparse point** (junction/symlink): a copy either
179
+ duplicates the target's contents or needs privileges to recreate the link, so it
180
+ is not a faithful copy;
181
+ - **insufficient free space** on the staging volume, checked from the measured size
182
+ before copying, so a 50 GB tree fails in a second instead of halfway.
183
+
184
+ **Verified vs not**: entry sets, kinds and sizes are compared; content hashes are
185
+ not (both sides of a 50 GB tree). The result reports `verification` so nobody reads
186
+ more into "verified" than it means.
187
+
188
+ New config: `uncRecoverableMove` (default `true`; `false` restores the plain 2.3.0
189
+ refusal and deletes nothing), `stagingRoot`. New required output field `staged[]`
190
+ (`path`, `staged`, `recycled`, `sourceRemoved`, optional `verification` and
191
+ `remaining`) — a share deletion is *not* reported in `recycled`, because the
192
+ original path never goes to a bin.
193
+
194
+ Also found while reading the resolution path: `file_trash` with `\\host` (no share)
195
+ used to resolve to `<cwd drive>:\host` — a *local* file that has nothing to do with
196
+ the share the caller meant — and would happily recycle it. The shape is now refused.
197
+
198
+ Cost, stated: a share delete copies the whole item, so it is O(size) in time and
199
+ needs that much free space on the staging volume; a very large tree may exceed the
200
+ tool call's timeout. Windows' own cross-volume `Move-Item` has the same cost, but no
201
+ verification and no bin record.
202
+
203
+ Tests: 116 → 128. New layer ③ `test/staging.test.mjs` (8 cases: step order, a
204
+ truncated copy that never reaches the bin, a failed recycle that keeps the
205
+ original, a junction that stops the delete, share-root/host refusal) plus three
206
+ `file_trash`-level cases in `e2e.test.mjs`, one of which deletes a real
207
+ `\\localhost\C$\…` path end to end (reported **skipped** where the admin share is
208
+ unreachable, rather than passing vacuously).
209
+
210
+ **A documentation incident, recorded because it is the same failure mode as 2.3.0's.**
211
+ Applying these README changes with a scripted `String.replace(needle, text)` put one
212
+ replacement string containing `` $` `` (the `\\localhost\C$` code span, closed by a
213
+ backtick). JavaScript reads `` $` `` in a string replacement as "everything before
214
+ the match" and expanded it, so each README ended up containing itself twice — 6.5 KB
215
+ became 13 KB, silently, and it survived a heading-level spot check because both
216
+ copies were plausible. Caught by counting H1s (2 instead of 1) and by noticing a
217
+ `README.md` whose first copy had no 文档/许可 sections. Rebuilt from `HEAD` with a
218
+ function-based replacer (never `String.replace(_, string)` when the replacement
219
+ contains `$`), every anchor asserted to match exactly once, and the result checked
220
+ structurally: 11 sections and 44 table rows in each of the three files. The lesson is
221
+ 2.3.0's lesson one layer up: a rule that silently matches more than intended looks
222
+ exactly like a rule that worked.
223
+
224
+ ## [2.3.0] — 2026-11-15
225
+
226
+ Content destroyed **without a delete verb** is now covered. Found by measurement,
227
+ not by review: a 605-line ledger was rewritten to 24 lines by
228
+
229
+ ```powershell
230
+ $lines=Get-Content $f
231
+ $idx=($lines | Select-String -Pattern '^# 备用|同步电机' | Select-Object -First 1).LineNumber
232
+ $keep=$lines[0..($idx-2)]
233
+ Set-Content -LiteralPath $f -Value ($keep + $new) -Encoding UTF8
234
+ ```
235
+
236
+ There is no delete verb in that command, so every 2.2.3 rule was correctly silent.
237
+ `$idx` was `$null` (the anchor matched nothing) and PowerShell reads
238
+ `$lines[0..($null-2)]` as `$lines[0..-2]` — `$lines[0,-1,-2]`, the first line plus
239
+ the last two. Measured on pwsh 7 with a 10-element array: `L1,L10,L9`. No error,
240
+ no warning. Record and verbatim evidence:
241
+ `docs/incidents/2026-11-14-full-file-rewrite-truncation.md`.
242
+
243
+ New module `lib/rewrite-guard.js` (pure, no I/O), wired into `classifyCommand`
244
+ after the erase/script rules and **before** the redirect collection — `file_trash`
245
+ is the remedy for a delete, and it is the wrong remedy here (see below). New
246
+ config key `blockTruncatingWrites` (default `true`).
247
+
248
+ **Rule 1 — `in-place-rewrite`.** The same file is read *and* written by one
249
+ command (`Get-Content f … | Set-Content f`, `$c = Get-Content f; Set-Content f $c`,
250
+ `sed -i f`, `cat f > f`, `[IO.File]::ReadAllText` → `::WriteAllText`). Reused or
251
+ rewritten: the operand-key comparison resolves `$f` against a `$f='literal'`
252
+ assignment in the same command, so a literal on one side and a variable on the
253
+ other still match. Allowed when the command itself keeps a copy (`.bak`/`.orig`
254
+ destination, or a temp file it copies over the original) — which is exactly the
255
+ safe pattern the incident record's §6 recommends, so that spelling passes
256
+ untouched.
257
+
258
+ **Rule 2 — `slice-risk`.** A range/slice endpoint of the form `<var> ± n` whose
259
+ variable is never asserted, in a command that also writes a file. Endpoints proven
260
+ non-null (`.Count`, `Measure-Object`, a literal) and asserted variables
261
+ (`if (-not $idx)`, `$idx -eq $null`, …) do not fire. A read-only command with the
262
+ same bad slice stays allowed: it prints the wrong lines and destroys nothing, and
263
+ refusing it would cost a round trip and protect nothing.
264
+
265
+ **Rejected: "overwrite an existing file = delete it" (proposed as R1).** Three
266
+ reasons, in order of weight. (a) The remedy does not exist where the failure
267
+ happened: the target was on a UNC share, and `scripts/recycle-bin.ps1` refuses
268
+ those because `SHFileOperationW` erases there and reports success — "recycle the
269
+ old copy, then write" is a no-op on the case that motivated it. (b) The rule is a
270
+ verb list one vocabulary later, i.e. the same structural blind spot: `Export-Csv`,
271
+ `[IO.File]::WriteAllText`, `Invoke-WebRequest -OutFile`, `tee`, `dd of=`, `cp`,
272
+ `truncate`, `sed -i`, a compiler over its own output — any enumeration is
273
+ incomplete and reads as complete. (c) Its consequence, "every overwrite is a
274
+ delete", is the opposite of this plugin's own policy: `write` and `edit` overwrite
275
+ files, and the prompt says to prefer them.
276
+
277
+ **Rejected: post-write size fuse, refuse-and-roll-back (R2).** Roll-back requires
278
+ the old bytes, so the copy has to be taken *before* the write — which needs the
279
+ target set (the same enumeration problem) — and `tools/post-execute` cannot undo
280
+ anything: `PostToolDecision.block` only turns the result into feedback for the
281
+ next request, after the truncation already happened. Snapshotting a tree per shell
282
+ call is O(workspace) and would still have missed this incident's file, which sat
283
+ on a UNC share outside every workspace root.
284
+
285
+ **Not `ask`.** In an auto-approving deployment (this machine: approval policy
286
+ `never`) `ask` resolves to allow in the same tick — a rule that looks present and
287
+ does nothing. Deny-with-a-recipe is honest whether or not a human is watching.
288
+
289
+ **Also fixed, found while doing the above.** Maintaining this repository was
290
+ refused by the published 2.2.3: the rule that looks for a wipe-program name inside
291
+ an inline body matched the name **anywhere** in the body, so a `node -e` script
292
+ whose *prose* quoted `shred` was denied as if it were about to erase the disk
293
+ (measured 2026-11-15 — the guard blocked the `node -e` edit of this very README).
294
+ A shell body (`bash -c "…"`) is shell text, so the name anywhere in it may run; a
295
+ JavaScript or Python body is not, and the name only becomes a command when it
296
+ reaches `exec`/`execSync`/`spawn`/`system`/`subprocess.*`. Split at
297
+ `wipeProgramInInlineBody`: shell interpreters keep the whole-name rule, other
298
+ interpreters require a process-spawning call after the name. Spawned wipes are
299
+ still refused (`execSync('shred -u x')`, `os.system('sdelete …')`).
300
+
301
+ Costs, stated: the in-place rule is deliberately over-inclusive for "read a file,
302
+ then regenerate it from something else in the same command" (the fix is one
303
+ `Copy-Item` line, and the message says so); `Add-Content`, `>>`, `-Append`,
304
+ `2> $null`, `> /dev/null` and `Clear-Content`-only commands are untouched; `>` onto
305
+ an existing file *without* reading it is still allowed and is listed in the
306
+ README's 「不挡什么」.
307
+
308
+ Tests: 90 → 116. New layer ② `test/rewrite.test.mjs` (22 cases: the incident
309
+ verbatim, the assertion fix, the §6 safe pattern, every in-place spelling, the
310
+ null-device/appendix exceptions, dialect spellings, the precedence case) plus three
311
+ hook-level cases in `registration.test.mjs` proving `apply()` actually wires the
312
+ rules and that `blockTruncatingWrites: false` disables them, plus the inline-body
313
+ scoping cases in `guard.test.mjs`. The "ordinary work stays allowed" corpus (42
314
+ commands: build, git, publish, log and config plumbing) lives in the same file as
315
+ the incident regression on purpose — a rule that catches the incident and also
316
+ refuses `npm run build` is not a fix.
317
+
318
+ `lib/shell-text.js` extracted: the lexer (`splitStatements`, `tokenize`,
319
+ `unquote`, `commandWord`) is now shared by both rule modules instead of imported
320
+ across them, which would have been a cycle. `guard.js` re-exports the same four
321
+ names, so nothing downstream changes.
322
+
10
323
  ## [2.2.3] — 2026-10-23
11
324
 
12
325
  npm publish prerequisites; no behaviour change.
package/README.en.md CHANGED
@@ -6,7 +6,8 @@
6
6
 
7
7
  A deletion has exactly two outcomes here: it lands in the Windows Recycle Bin
8
8
  (restorable from Explorer), or it is refused and re-issued as a `file_trash`
9
- call. There is no third one.
9
+ call. There is no third one — and **writing the content away is the same thing as
10
+ deleting it.**
10
11
 
11
12
  ```
12
13
  agent: Remove-Item -Recurse -Force .\src
@@ -14,6 +15,12 @@ refused: The delete guard blocked this delete. Re-run this as: file_trash with p
14
15
  then: file_trash → moved to the Recycle Bin, "Restore" works
15
16
  ```
16
17
 
18
+ ```
19
+ agent: $lines=Get-Content $f; $idx=(…Select-String…).LineNumber; Set-Content $f $lines[0..($idx-2)]
20
+ refused: …`$idx` is offset by arithmetic in a slice endpoint, it is never checked for $null…
21
+ Fix, then re-run: if (-not $idx) { throw "anchor not found" }
22
+ ```
23
+
17
24
  ## The problem
18
25
 
19
26
  In DSH a model's `pwsh` delete erases files outright: `ctx.fs` has no delete,
@@ -30,6 +37,14 @@ Coverage goes past `Remove-Item`: pipelines, `xargs`, variable-built targets,
30
37
  `if { }` blocks, inline `-Command` / `-EncodedCommand`, the persistent terminal,
31
38
  Git Bash `/c/...` paths, and every spelling of emptying the bin.
32
39
 
40
+ There is a second class with **no delete verb at all**: read a file, compute a
41
+ slice, write it back over the same file. In PowerShell `$lines[0..($null-2)]` is not
42
+ an error — it is `$lines[0..-2]`, the first line plus the last two, so a 605-line
43
+ file can be saved as 24 lines silently. Such a command cannot go to the bin (a
44
+ network share has none) and cannot be caught by comparing sizes afterwards, so the
45
+ guard refuses it before the write: read-then-rewrite of one file, and an unchecked
46
+ slice endpoint that feeds a write.
47
+
33
48
  ## Install
34
49
 
35
50
  ```shell
@@ -39,7 +54,7 @@ dsh plugin --profile web add dsh-delete-guard
39
54
  dsh plugin --profile web add github:deepestevan/dsh-delete-guard
40
55
  # or from a local tarball (when you have changed the source)
41
56
  pnpm pack --pack-destination ./temp/pack # bump `version` first
42
- dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.2.2.tgz
57
+ dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.2.tgz
43
58
  # restart dsh web: lib/*.js is loaded at process start
44
59
  ```
45
60
 
@@ -68,16 +83,25 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
68
83
  | Emptying the bin | `Clear-RecycleBin` (bare, `&`, child shell, `-EncodedCommand`), `SHEmptyRecycleBin`, driving bin items' shell verbs, deleting `$Recycle.Bin` contents |
69
84
  | Locations without a bin | UNC shares and exFAT/FAT32 volumes, where "recycling" is a permanent erase |
70
85
  | Deletes inside scripts | shell / Python / Node inline bodies, and writing delete text into `.ps1`/`.sh`/`.py` |
86
+ | **Reading a file and rewriting it in one command** | `(Get-Content $f) \| Set-Content $f`, `$c = Get-Content $f; Set-Content $f $c`, `sed -i f`, `cat f > f`, `::ReadAllText` → `::WriteAllText` — the new content comes from the only copy, so a wrong slice or filter leaves nothing to restore. The `.bak` / verified-temp spelling is allowed |
87
+ | **A read folded into the write statement** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)` — reads, truncates and writes back on one line, which is the incident with fewer keystrokes |
88
+ | **A shell invoked through a variable** | `$shellPath='…bash.exe'; & $shellPath -c "rm -rf …"` — the program is not a literal, so the body cannot be judged |
89
+ | **An unchecked slice endpoint** | a command that both writes a file and slices with `$idx ± n` (`$l[0..($idx-2)]`, `-First ($i-1)`) where `$idx` was never checked for `$null`. PowerShell does not error: `0..($null-2)` *is* `0..-2` — the first line plus the last two |
71
90
 
72
91
  **Allowed**: read-only work, commands that only mention a delete word
73
- (`Select-String -Pattern "Remove-Item"`, `Get-Content shred.exe`), and
74
- **restoring** files out of the bin.
92
+ (`Select-String -Pattern "Remove-Item"`, `Get-Content shred.exe`), **restoring**
93
+ files out of the bin, `Add-Content` / `>>` / `-Append` (an append replaces
94
+ nothing), writes to `$null` / `/dev/null`, a full rewrite that first copies the file
95
+ to `.bak` or writes a temp file it verifies (the incident record's §6 spelling
96
+ passes untouched), and a wipe-program **name mentioned** inside a `node -e` / `python -c`
97
+ body — it is a program only when it reaches `exec` / `execSync` / `spawn` / `system` /
98
+ `subprocess.*` (a `bash -c` body is shell text and is judged whole).
75
99
 
76
100
  ## Two tools
77
101
 
78
102
  | Tool | Purpose |
79
103
  | --- | --- |
80
- | `file_trash { paths, reason? }` | The only permitted way to delete. Moves to the Recycle Bin, reports per-path results, never falls back to a permanent erase |
104
+ | `file_trash { paths, reason? }` | The only permitted way to delete. Local items move into the Recycle Bin; share items are copied to a local volume, verified, recycled there, and only then removed (see "Network shares"). Reports per-path results |
81
105
  | `trash_status { drive? }` | Item count and byte size of the bin on a volume, to confirm a deletion landed |
82
106
 
83
107
  ## Configuration
@@ -92,6 +116,9 @@ block — restate every key you want to keep):
92
116
  | `forbidEmptyRecycleBin` | `true` | Refuse emptying or modifying the bin |
93
117
  | `forbidWipe` | `true` | Refuse `shred` / `sdelete` / `srm` / `cipher /w` / `format` |
94
118
  | `blockScriptDeletes` | `true` | Refuse deletes in script files and inline strings |
119
+ | `blockTruncatingWrites` | `true` | Refuse read-then-rewrite of the same file, and an unchecked slice endpoint in a command that writes |
120
+ | `uncRecoverableMove` | `true` | Share deletes: copy to a local NTFS volume, verify, recycle the copy, then remove the original. `false` keeps the plain refusal |
121
+ | `stagingRoot` | `%LOCALAPPDATA%\dsh-delete-guard\staging` | Staging directory for share deletes (must be on a local volume with a bin) |
95
122
 
96
123
  ## Restoring a deleted file
97
124
 
@@ -102,6 +129,34 @@ offset 28 = UTF-16LE path), match the one you want, and `Move-Item` its paired `
102
129
  file back. The `$R`/`$I` names are random, so those records are the only index;
103
130
  skip any whose payload is missing. Do not depend on the localized verb name.
104
131
 
132
+ ## Network shares (no Recycle Bin)
133
+
134
+ A UNC path has no Recycle Bin: `SHFileOperationW` erases there and reports success,
135
+ which is why the bridge refuses those paths. `file_trash` now does what a person does
136
+ by hand, in one call, in a fixed order:
137
+
138
+ 1. copy the item to a local NTFS volume that does have a bin
139
+ (`%LOCALAPPDATA%\dsh-delete-guard\staging\<timestamp>-<name>`, override with `stagingRoot`);
140
+ 2. verify the copy against the original: same relative paths, same kinds, same sizes;
141
+ 3. recycle the staging folder — the copy is now restorable;
142
+ 4. only then remove the original.
143
+
144
+ **What that guarantees**: the *content* is recoverable from the local bin; the
145
+ *original path* is not, because the share has no bin to hold it — step 4 is an
146
+ ordinary permanent delete. The order is therefore the safety property: any failure
147
+ before step 4 leaves the original untouched, and step 4 runs only after the bridge
148
+ confirms the staged copy is in the bin.
149
+
150
+ A restore lands in the staging path, not back on the share (the bin's `$I` record
151
+ holds the staging location), so the tool prints that path in its result.
152
+
153
+ Refused, all before any copy: a share root (`\\host\share`) or a bare host; a tree
154
+ containing a **reparse point** (junction/symlink — a copy either duplicates the
155
+ target's contents or needs privileges to recreate the link); **not enough free
156
+ space** on the staging volume.
157
+
158
+ `uncRecoverableMove: false` restores the plain refusal and deletes nothing.
159
+
105
160
  ## What it does not cover
106
161
 
107
162
  | Not covered | Why |
@@ -113,6 +168,10 @@ skip any whose payload is missing. Do not depend on the localized verb name.
113
168
  | A delete split across two terminal sends | Each send is judged on its own text |
114
169
  | Non-Windows platforms | The bridge is `SHFileOperationW` |
115
170
  | Free-space exhaustion | A same-volume NTFS recycle is a rename and consumes no space, so there is nothing to pre-check |
171
+ | **Overwriting without reading** (`echo x > notes.md`, `Invoke-WebRequest -OutFile`, `git checkout -- f`) | A deliberate rewrite, not read-modify-write: the new content does not depend on the old, and `write`/`edit` do the same thing. Making every write verb a delete is the over-broad rule this plugin rejected |
172
+ | **Indirect writes inside a read-modify-write** (compilers, `npm run build`, `robocopy` over build output) | The write happens in a child process; the command text names no provable target |
173
+ | Post-write size fuse / rollback | Rolling back needs the old bytes, which must be copied *before* the write — the same target-enumeration problem. `tools/post-execute` can only turn a result into feedback, and a per-call tree snapshot is O(workspace) and would still miss a UNC target outside the workspace |
174
+ | Moving something off a share (`Move-Item`, `robocopy /MOV`) | That is a move, not a delete: the content reaches the destination, but the share copy is unlinked for good and no bin record exists. `file_trash` is the path that keeps one |
116
175
 
117
176
  Covered shell tools: `pwsh`, `powershell`, `cmd`, `bash`, `sh`, `zsh`, `shell`,
118
177
  `terminal_send`, `terminal_write`. Reasoning and measurements:
@@ -124,11 +183,15 @@ the decision is made on the statement's command word, the shape of the call, and
124
183
  node test/run-all.mjs
125
184
  ```
126
185
 
127
- 90 cases across five layers: command classification (49), `file_trash` operand
128
- guard (15), host schema + hook wiring (11), host schema acceptance (5), live
129
- end-to-end against the real Recycle Bin (10). `test/` is not shipped in the
130
- tarball, so it must be green before packing; two layers load the host's own
131
- validators and report **skipped** (not failed) where no DSH install exists.
186
+ 148 cases across eight layers: command classification (50), overwrite guard (30),
187
+ rule holes (12), share staging (8), `file_trash` operand guard (15), host schema +
188
+ hook wiring (14), host schema acceptance (5), live end-to-end against the real
189
+ Recycle Bin (14, including a real `\\localhost\C$` path). `test/` is not shipped in the tarball, so it
190
+ must be green before packing; two layers load the host's own validators and report
191
+ **skipped** (not failed) where no DSH install exists. The overwrite-guard layer keeps
192
+ "the incident command must be refused" and "42 ordinary commands must still pass" in
193
+ one file on purpose: a rule that catches the incident and also refuses `npm run build`
194
+ is not a fix.
132
195
 
133
196
  ## Documentation
134
197
 
@@ -136,10 +199,14 @@ validators and report **skipped** (not failed) where no DSH install exists.
136
199
  | --- | --- |
137
200
  | [CHANGELOG.md](CHANGELOG.md) | Version summaries |
138
201
  | [SECURITY.md](SECURITY.md) | Threat model: a policy layer, not a sandbox |
202
+ | [docs/incidents/](docs/incidents/) | Incident records: the measurement behind each rule, with the verbatim command (not in the npm package — see `files`) |
139
203
  | [LICENSE](LICENSE) | MIT |
140
204
 
141
- Design rationale, the per-round measurements and the release runbook are engineering
142
- notes kept by the maintainer; they are not part of this repository or package.
205
+ Incident records stay in the repository because they *are* the evidence for the
206
+ rules: a rule whose origin ("which command, under what conditions, with what
207
+ result") is unavailable can only be maintained by guessing. Design rationale and
208
+ the release runbook remain the maintainer's notes and ship with neither the
209
+ repository nor the package.
143
210
 
144
211
  ## License
145
212
 
package/README.ja.md CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  削除の結果は 2 つだけです。Windows のごみ箱に入る(エクスプローラーから元に戻せる)
8
8
  か、拒否されて `file_trash` 呼び出しに置き換わるか。それ以外はありません。
9
+ **内容を書き潰すことも、削除と同じことです。**
9
10
 
10
11
  ```
11
12
  agent: Remove-Item -Recurse -Force .\src
@@ -13,6 +14,12 @@ agent: Remove-Item -Recurse -Force .\src
13
14
  その後: file_trash → ごみ箱へ移動。「元に戻す」が使える
14
15
  ```
15
16
 
17
+ ```
18
+ agent: $lines=Get-Content $f; $idx=(…Select-String…).LineNumber; Set-Content $f $lines[0..($idx-2)]
19
+ 拒否: …`$idx` is offset by arithmetic in a slice endpoint, it is never checked for $null…
20
+ Fix, then re-run: if (-not $idx) { throw "anchor not found" }
21
+ ```
22
+
16
23
  ## 何を解決するか
17
24
 
18
25
  DSH では、モデルが `pwsh` で削除を実行するとファイルはそのまま消えます。`ctx.fs` に
@@ -28,6 +35,13 @@ delete は無く、`ctx.shell` にあるのは `execute()` だけで、その間
28
35
  `if { }` 内の削除、インラインの `-Command` / `-EncodedCommand`、永続ターミナル、
29
36
  Git Bash の `/c/...` パス、ごみ箱を空にするあらゆる書き方に規則があります。
30
37
 
38
+ **削除動詞を伴わない破壊**にも規則があります。ファイルを読み、切り出し、同じファイルへ
39
+ 書き戻す形です。PowerShell では `$lines[0..($null-2)]` はエラーではなく `$lines[0..-2]`、
40
+ つまり「先頭行 + 末尾 2 行」になります——605 行が 24 行として静かに保存され得ます。
41
+ こうしたコマンドはごみ箱へ送れず(ネットワーク共有にごみ箱はありません)、事後の
42
+ サイズ比較でも見つからないため、ガードは書き込みの前に「同一ファイルの読み書き」と
43
+ 「未検査のスライス端点」として拒否します。
44
+
31
45
  ## インストール
32
46
 
33
47
  ```shell
@@ -37,7 +51,7 @@ dsh plugin --profile web add dsh-delete-guard
37
51
  dsh plugin --profile web add github:deepestevan/dsh-delete-guard
38
52
  # またはローカルの tarball から(ソースを変更したとき)
39
53
  pnpm pack --pack-destination ./temp/pack # 先に package.json の version を上げる
40
- dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.2.2.tgz
54
+ dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.2.tgz
41
55
  # dsh web を再起動(lib/*.js はプロセス起動時に読み込まれる)
42
56
  ```
43
57
 
@@ -66,16 +80,25 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
66
80
  | ごみ箱の空化 | `Clear-RecycleBin`(素の形・`&`・子シェル・`-EncodedCommand`)、`SHEmptyRecycleBin`、ごみ箱項目のシェル動詞、`$Recycle.Bin` 配下の直接削除 |
67
81
  | ごみ箱が無い場所 | UNC 共有と exFAT/FAT32 ボリューム(そこで「ごみ箱へ」は完全消去と同じ) |
68
82
  | スクリプト内の削除 | シェル / Python / Node のインライン本体、および削除語を含むテキストの `.ps1`/`.sh`/`.py` への書き込み |
83
+ | **同一ファイルの読み書き** | `(Get-Content $f) \| Set-Content $f`、`$c = Get-Content $f; Set-Content $f $c`、`sed -i f`、`cat f > f`、`::ReadAllText` → `::WriteAllText`——新しい内容は唯一のコピーから作られるため、切り出しやフィルタを誤ると復元元が残りません。`.bak` か検証付き一時ファイルを残す書き方は許可 |
84
+ | **書き込み文に折り込まれた読み取り** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)`——1 行で読み・切り詰め・書き戻し。事故の最短表記 |
85
+ | **変数経由のシェル呼び出し** | `$shellPath='…bash.exe'; & $shellPath -c "rm -rf …"`——プログラム名がリテラルでなく、本体を判定できない |
86
+ | **未検査のスライス端点** | 同一コマンド内でファイルを書き、かつ `$idx ± n` を端点に使う(`$l[0..($idx-2)]`、`-First ($i-1)`)。`$idx` は `$null` 検査済みでない。PowerShell はエラーにせず、`0..($null-2)` は `0..-2`(先頭行 + 末尾 2 行)になる |
69
87
 
70
88
  **許可される**:読み取り専用の作業、削除語に言及するだけのコマンド
71
- (`Select-String -Pattern "Remove-Item"`、`Get-Content shred.exe`)、そしてごみ箱から
72
- の**復元**。
89
+ (`Select-String -Pattern "Remove-Item"`、`Get-Content shred.exe`)、ごみ箱から
90
+ の**復元**、`Add-Content` / `>>` / `-Append`(追記は置き換えない)、`$null` / `/dev/null`
91
+ への書き込み、そして**`.bak` か検証付き一時ファイルを先に作る**全面書き換え
92
+ (事故記録 §6 の書き方はそのまま通ります)。また `node -e` / `python -c` の本体で消去ツール名に
93
+ **言及**しただけのテキストはプログラム名として扱いません——`exec` / `execSync` / `spawn` /
94
+ `system` / `subprocess.*` に渡されたときだけです(`bash -c` の本体はシェルテキストなので
95
+ 全体で判定します)。
73
96
 
74
97
  ## 2 つのツール
75
98
 
76
99
  | ツール | 役割 |
77
100
  | --- | --- |
78
- | `file_trash { paths, reason? }` | 唯一許可された削除手段。ごみ箱へ移動し、パスごとに結果を報告し、完全削除へフォールバックしない |
101
+ | `file_trash { paths, reason? }` | 唯一許可された削除手段。ローカルの項目はごみ箱へ移動し、共有の項目はローカルへ複製 → 検証 → 複製をごみ箱へ → その後に元を削除(「ネットワーク共有」参照)。パスごとに結果を報告 |
79
102
  | `trash_status { drive? }` | そのボリュームのごみ箱の項目数とバイト数。削除が本当に入ったかの確認に使う |
80
103
 
81
104
  ## 設定
@@ -90,6 +113,9 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
90
113
  | `forbidEmptyRecycleBin` | `true` | ごみ箱の空化・改変を拒否 |
91
114
  | `forbidWipe` | `true` | `shred` / `sdelete` / `srm` / `cipher /w` / `format` を拒否 |
92
115
  | `blockScriptDeletes` | `true` | スクリプトファイルとインライン文字列内の削除を拒否 |
116
+ | `blockTruncatingWrites` | `true` | 同一ファイルの読み書きと、書き込みを伴う未検査スライス端点を拒否 |
117
+ | `uncRecoverableMove` | `true` | 共有の削除:ローカル NTFS へ複製 → 検証 → 複製をごみ箱へ → その後に元を削除。`false` で拒否のみ |
118
+ | `stagingRoot` | `%LOCALAPPDATA%\dsh-delete-guard\staging` | 共有削除のステージング先(ごみ箱のあるローカルボリューム) |
93
119
 
94
120
  ## 消したファイルを戻す
95
121
 
@@ -100,6 +126,28 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
100
126
  `Move-Item` で戻します。`$R`/`$I` の名前はランダムなので、そのレコードが唯一の索引です。
101
127
  payload が無いレコードは飛ばし、ローカライズされた動詞名には依存しないこと。
102
128
 
129
+ ## ネットワーク共有(ごみ箱が無い)
130
+
131
+ UNC パスにごみ箱はありません。`SHFileOperationW` はそこで**消去して成功を返す**ため、ブリッジは
132
+ 先に拒否していました。`file_trash` は人が手でやることを 1 回の呼び出しで、決まった順序で行います:
133
+
134
+ 1. ごみ箱のあるローカル NTFS ボリュームへ複製(`%LOCALAPPDATA%\dsh-delete-guard\staging\<時刻>-<名前>`、`stagingRoot` で変更可)
135
+ 2. 元と突き合わせて検証:相対パス集合・種別・各ファイルのサイズ
136
+ 3. ステージングフォルダをごみ箱へ——この時点で複製は復元可能
137
+ 4. その後にだけ元を削除
138
+
139
+ **保証の範囲**:復元できるのは**内容**(ローカルのごみ箱)であり、**元のパス**ではありません。
140
+ 共有にごみ箱が無いため、4 は通常の完全削除です。だから順序そのものが安全条件で、4 より前の失敗は
141
+ 元に触れず、4 はブリッジが複製の収容を確認した後にだけ実行されます。
142
+
143
+ 復元先は共有ではなくステージングパスになります(ごみ箱の `$I` が記録するのはその場所)。ツールは
144
+ そのパスを結果に出力します。
145
+
146
+ 複製前に拒否するもの:共有ルート(`\\host\share`)やホスト名のみの形、**リパースポイント**
147
+ (ジャンクション/シンボリックリンク)を含むツリー、ステージング先の**空き容量不足**。
148
+
149
+ `uncRecoverableMove: false` で 2.3.0 の拒否のみに戻り、何も削除しません。
150
+
103
151
  ## 何を守らないか
104
152
 
105
153
  | 対象外 | 理由 |
@@ -111,6 +159,10 @@ payload が無いレコードは飛ばし、ローカライズされた動詞名
111
159
  | ターミナル送信 2 回に分けて組み立てた削除 | 1 回の送信のテキストしか見ていない |
112
160
  | Windows 以外 | ブリッジが `SHFileOperationW` |
113
161
  | 空き容量の枯渇 | 同一 NTFS ボリューム内のごみ箱移動は rename で、新しい容量を使わない |
162
+ | **読まずに上書き**(`echo x > 既存.md`、`Invoke-WebRequest -OutFile`、`git checkout -- f`) | 意図的な書き換えであり読み書きではない。新しい内容は古い内容に依存せず、`write`/`edit` も同じことをする。すべての書き込み動詞を削除扱いにすると本プラグインが退けた過剰な規則になる |
163
+ | 読み書きの中の**間接的な書き込み**(コンパイラ、`npm run build`、`robocopy` の成果物) | 書き込みは子プロセス内で起き、コマンドテキストに証明できる対象が無い |
164
+ | 書き込み後のサイズ比較・ロールバック | 戻すには書き込み前のバイト列が必要で、結局は対象の列挙問題に戻る。`tools/post-execute` は結果をフィードバックに変えるだけで、切り詰めを巻き戻せない。毎回ツリーをスナップショットするのは O(ワークスペース) で、しかも UNC 上の対象は含まれない |
165
+ | 共有上のものを `Move-Item` / `robocopy /MOV` で移動 | それは「移動」であり「削除」ではない。内容は移動先に残るが、共有側は完全に unlink され、ごみ箱の記録も残らない。記録を残すのは `file_trash` |
114
166
 
115
167
  対象のシェルツール名:`pwsh`、`powershell`、`cmd`、`bash`、`sh`、`zsh`、`shell`、
116
168
  `terminal_send`、`terminal_write`。判定は文の命令語・呼び出しの形・プログラム位置で行い、行内に語が現れたかどうかでは見ません。
@@ -121,11 +173,11 @@ payload が無いレコードは飛ばし、ローカライズされた動詞名
121
173
  node test/run-all.mjs
122
174
  ```
123
175
 
124
- 5 層・90 ケース:コマンド分類(49)、`file_trash` オペランドガード(15)、ホストの
125
- スキーマとフック配線(11)、ホストのスキーマ受理(5)、実ごみ箱に対するエンドツーエンド
126
- (10)。`test/` は tarball に含まれないので、パック前に緑である必要があります。うち 2 層
127
- はホスト自身の検証器を読み込むため、DSH のインストールが無い環境では失敗ではなく
128
- **スキップ**として報告されます。
176
+ 8 層・148 ケース:コマンド分類(50)、上書きガード(30)、規則の穴(12)、共有ステージング(8)、
177
+ `file_trash` オペランドガード(15)、ホストのスキーマとフック配線(14)、ホストのスキーマ受理(5)、
178
+ 実ごみ箱に対するエンドツーエンド(14、実 `\\localhost\C$` パスを含む)。`test/` は tarball に
179
+ 含まれないので、パック前に緑である必要があります。うち 2 層はホスト自身の検証器を読み込むため、
180
+ DSH のインストールが無い環境では失敗ではなく**スキップ**として報告されます。
129
181
 
130
182
  ## ドキュメント
131
183
 
@@ -133,10 +185,12 @@ node test/run-all.mjs
133
185
  | --- | --- |
134
186
  | [CHANGELOG.md](CHANGELOG.md) | バージョン摘要 |
135
187
  | [SECURITY.md](SECURITY.md) | 脅威モデル:サンドボックスではなくポリシー層 |
188
+ | [docs/incidents/](docs/incidents/) | 事故記録:各規則の背景にある実測と逐語コマンド(npm パッケージには含まれません) |
136
189
  | [LICENSE](LICENSE) | MIT |
137
190
 
138
- 設計の根拠、各回の実測値、リリース手順はメンテナ側のエンジニアリングノートであり、
139
- このリポジトリにもパッケージにも含まれません。
191
+ 事故記録はリポジトリに残します。規則の根拠そのものだからです——「どのコマンドが、どんな条件で、
192
+ 何を壊したか」が分からない規則は、推測でしか保守できません。設計の根拠とリリース手順は
193
+ メンテナ側のノートに留め、リポジトリにもパッケージにも含めません。
140
194
 
141
195
  ## ライセンス
142
196