dsh-delete-guard 2.2.3 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,208 @@ 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.1] — 2026-11-24
11
+
12
+ The publish workflow's first run, and what it found. No production code changed.
13
+
14
+ Releasing 2.4.0 ran `test/run-all.mjs` on Ubuntu for the first time in this
15
+ repository's history — no tags, no releases, no prior workflow runs; 2.2.3 reached
16
+ npm through a hand-run `npm publish`. Layer ④ came back **4 pass / 11 fail**:
17
+ `move-guard.test.mjs` asserts Windows path semantics (`C:\` is a drive root,
18
+ `..\..` resolves inside a volume, `\\host\share` is a UNC share, `C:\Program Files`
19
+ is refused), and on a POSIX runner `node:path` is posix, so `C:\` is an ordinary
20
+ relative name and `resolve()` prepends the checkout path.
21
+
22
+ Fix: layers ③ ④ ⑦ are gated on `process.platform === 'win32'` in
23
+ `test/run-all.mjs` and report **skipped** elsewhere, with the measurement recorded
24
+ in the comment. The plugin is `os: ["win32"]` and the bridge is
25
+ `SHFileOperationW`: a POSIX runner cannot exercise those paths at all, so gating is
26
+ the honest answer rather than a workaround.
27
+
28
+ This also corrects a claim in 2.3.0 — "layers ① ② ④ ⑥ pass anywhere" was derived
29
+ from forcing `process.platform='linux'` on Windows, which leaves `node:path` bound
30
+ to win32 at load time, so the check proved nothing about the other platform. CI was
31
+ the only evidence, and it had never run. Same failure mode as the rules this
32
+ release series added: a check that looks green because it never exercised the thing
33
+ it names.
34
+
35
+ ## [2.4.0] — 2026-11-15
36
+
37
+ **Deleting from a network share now works instead of being refused.** A share has
38
+ no Recycle Bin: `SHFileOperationW(FOF_ALLOWUNDO)` erases there and returns 0
39
+ (reproduced 2026-10-23), so 2.3.0 refused every UNC path — safe, but the deletion
40
+ never happened and the model had to invent a workaround.
41
+
42
+ `file_trash` now does what a person does by hand, in one call, in this order:
43
+
44
+ 1. copy the item to a staging directory on a volume that does have a bin
45
+ (`%LOCALAPPDATA%\dsh-delete-guard\staging\<yyyyMMdd-HHmmss>-<name>`, override
46
+ with `stagingRoot`);
47
+ 2. verify the copy against the original — same relative paths, same kinds, same
48
+ file sizes;
49
+ 3. recycle the staging folder — the copy is now in the bin and restorable;
50
+ 4. only then remove the original.
51
+
52
+ **What this guarantees, stated exactly**: the *content* is recoverable from the
53
+ local Recycle Bin; the *original path* is not, because the share has no bin to hold
54
+ it. Step 4 is an ordinary permanent delete. That is why the order is the safety
55
+ property — every failure before step 4 leaves the original untouched, and step 4
56
+ runs only after the bridge confirms the staged copy left for the bin. A failure in
57
+ step 4 is reported with the paths that remain, never as success.
58
+
59
+ Restoring lands in the staging path, not back on the share: the bin's `$I` record
60
+ holds the staging location, so `file_trash` prints it in its result and the render
61
+ says so. That is the one place where "delete a share file" is not the same as
62
+ "delete a local file", and it is visible rather than implied.
63
+
64
+ **Refused, with the reason** (each one stops before any copy):
65
+ - a share root (`\\host\share`) or a bare host — those are not items, and staging
66
+ them would copy and then delete everything on the share;
67
+ - a tree containing a **reparse point** (junction/symlink): a copy either
68
+ duplicates the target's contents or needs privileges to recreate the link, so it
69
+ is not a faithful copy;
70
+ - **insufficient free space** on the staging volume, checked from the measured size
71
+ before copying, so a 50 GB tree fails in a second instead of halfway.
72
+
73
+ **Verified vs not**: entry sets, kinds and sizes are compared; content hashes are
74
+ not (both sides of a 50 GB tree). The result reports `verification` so nobody reads
75
+ more into "verified" than it means.
76
+
77
+ New config: `uncRecoverableMove` (default `true`; `false` restores the plain 2.3.0
78
+ refusal and deletes nothing), `stagingRoot`. New required output field `staged[]`
79
+ (`path`, `staged`, `recycled`, `sourceRemoved`, optional `verification` and
80
+ `remaining`) — a share deletion is *not* reported in `recycled`, because the
81
+ original path never goes to a bin.
82
+
83
+ Also found while reading the resolution path: `file_trash` with `\\host` (no share)
84
+ used to resolve to `<cwd drive>:\host` — a *local* file that has nothing to do with
85
+ the share the caller meant — and would happily recycle it. The shape is now refused.
86
+
87
+ Cost, stated: a share delete copies the whole item, so it is O(size) in time and
88
+ needs that much free space on the staging volume; a very large tree may exceed the
89
+ tool call's timeout. Windows' own cross-volume `Move-Item` has the same cost, but no
90
+ verification and no bin record.
91
+
92
+ Tests: 116 → 128. New layer ③ `test/staging.test.mjs` (8 cases: step order, a
93
+ truncated copy that never reaches the bin, a failed recycle that keeps the
94
+ original, a junction that stops the delete, share-root/host refusal) plus three
95
+ `file_trash`-level cases in `e2e.test.mjs`, one of which deletes a real
96
+ `\\localhost\C$\…` path end to end (reported **skipped** where the admin share is
97
+ unreachable, rather than passing vacuously).
98
+
99
+ **A documentation incident, recorded because it is the same failure mode as 2.3.0's.**
100
+ Applying these README changes with a scripted `String.replace(needle, text)` put one
101
+ replacement string containing `` $` `` (the `\\localhost\C$` code span, closed by a
102
+ backtick). JavaScript reads `` $` `` in a string replacement as "everything before
103
+ the match" and expanded it, so each README ended up containing itself twice — 6.5 KB
104
+ became 13 KB, silently, and it survived a heading-level spot check because both
105
+ copies were plausible. Caught by counting H1s (2 instead of 1) and by noticing a
106
+ `README.md` whose first copy had no 文档/许可 sections. Rebuilt from `HEAD` with a
107
+ function-based replacer (never `String.replace(_, string)` when the replacement
108
+ contains `$`), every anchor asserted to match exactly once, and the result checked
109
+ structurally: 11 sections and 44 table rows in each of the three files. The lesson is
110
+ 2.3.0's lesson one layer up: a rule that silently matches more than intended looks
111
+ exactly like a rule that worked.
112
+
113
+ ## [2.3.0] — 2026-11-15
114
+
115
+ Content destroyed **without a delete verb** is now covered. Found by measurement,
116
+ not by review: a 605-line ledger was rewritten to 24 lines by
117
+
118
+ ```powershell
119
+ $lines=Get-Content $f
120
+ $idx=($lines | Select-String -Pattern '^# 备用|同步电机' | Select-Object -First 1).LineNumber
121
+ $keep=$lines[0..($idx-2)]
122
+ Set-Content -LiteralPath $f -Value ($keep + $new) -Encoding UTF8
123
+ ```
124
+
125
+ There is no delete verb in that command, so every 2.2.3 rule was correctly silent.
126
+ `$idx` was `$null` (the anchor matched nothing) and PowerShell reads
127
+ `$lines[0..($null-2)]` as `$lines[0..-2]` — `$lines[0,-1,-2]`, the first line plus
128
+ the last two. Measured on pwsh 7 with a 10-element array: `L1,L10,L9`. No error,
129
+ no warning. Record and verbatim evidence:
130
+ `docs/incidents/2026-11-14-full-file-rewrite-truncation.md`.
131
+
132
+ New module `lib/rewrite-guard.js` (pure, no I/O), wired into `classifyCommand`
133
+ after the erase/script rules and **before** the redirect collection — `file_trash`
134
+ is the remedy for a delete, and it is the wrong remedy here (see below). New
135
+ config key `blockTruncatingWrites` (default `true`).
136
+
137
+ **Rule 1 — `in-place-rewrite`.** The same file is read *and* written by one
138
+ command (`Get-Content f … | Set-Content f`, `$c = Get-Content f; Set-Content f $c`,
139
+ `sed -i f`, `cat f > f`, `[IO.File]::ReadAllText` → `::WriteAllText`). Reused or
140
+ rewritten: the operand-key comparison resolves `$f` against a `$f='literal'`
141
+ assignment in the same command, so a literal on one side and a variable on the
142
+ other still match. Allowed when the command itself keeps a copy (`.bak`/`.orig`
143
+ destination, or a temp file it copies over the original) — which is exactly the
144
+ safe pattern the incident record's §6 recommends, so that spelling passes
145
+ untouched.
146
+
147
+ **Rule 2 — `slice-risk`.** A range/slice endpoint of the form `<var> ± n` whose
148
+ variable is never asserted, in a command that also writes a file. Endpoints proven
149
+ non-null (`.Count`, `Measure-Object`, a literal) and asserted variables
150
+ (`if (-not $idx)`, `$idx -eq $null`, …) do not fire. A read-only command with the
151
+ same bad slice stays allowed: it prints the wrong lines and destroys nothing, and
152
+ refusing it would cost a round trip and protect nothing.
153
+
154
+ **Rejected: "overwrite an existing file = delete it" (proposed as R1).** Three
155
+ reasons, in order of weight. (a) The remedy does not exist where the failure
156
+ happened: the target was on a UNC share, and `scripts/recycle-bin.ps1` refuses
157
+ those because `SHFileOperationW` erases there and reports success — "recycle the
158
+ old copy, then write" is a no-op on the case that motivated it. (b) The rule is a
159
+ verb list one vocabulary later, i.e. the same structural blind spot: `Export-Csv`,
160
+ `[IO.File]::WriteAllText`, `Invoke-WebRequest -OutFile`, `tee`, `dd of=`, `cp`,
161
+ `truncate`, `sed -i`, a compiler over its own output — any enumeration is
162
+ incomplete and reads as complete. (c) Its consequence, "every overwrite is a
163
+ delete", is the opposite of this plugin's own policy: `write` and `edit` overwrite
164
+ files, and the prompt says to prefer them.
165
+
166
+ **Rejected: post-write size fuse, refuse-and-roll-back (R2).** Roll-back requires
167
+ the old bytes, so the copy has to be taken *before* the write — which needs the
168
+ target set (the same enumeration problem) — and `tools/post-execute` cannot undo
169
+ anything: `PostToolDecision.block` only turns the result into feedback for the
170
+ next request, after the truncation already happened. Snapshotting a tree per shell
171
+ call is O(workspace) and would still have missed this incident's file, which sat
172
+ on a UNC share outside every workspace root.
173
+
174
+ **Not `ask`.** In an auto-approving deployment (this machine: approval policy
175
+ `never`) `ask` resolves to allow in the same tick — a rule that looks present and
176
+ does nothing. Deny-with-a-recipe is honest whether or not a human is watching.
177
+
178
+ **Also fixed, found while doing the above.** Maintaining this repository was
179
+ refused by the published 2.2.3: the rule that looks for a wipe-program name inside
180
+ an inline body matched the name **anywhere** in the body, so a `node -e` script
181
+ whose *prose* quoted `shred` was denied as if it were about to erase the disk
182
+ (measured 2026-11-15 — the guard blocked the `node -e` edit of this very README).
183
+ A shell body (`bash -c "…"`) is shell text, so the name anywhere in it may run; a
184
+ JavaScript or Python body is not, and the name only becomes a command when it
185
+ reaches `exec`/`execSync`/`spawn`/`system`/`subprocess.*`. Split at
186
+ `wipeProgramInInlineBody`: shell interpreters keep the whole-name rule, other
187
+ interpreters require a process-spawning call after the name. Spawned wipes are
188
+ still refused (`execSync('shred -u x')`, `os.system('sdelete …')`).
189
+
190
+ Costs, stated: the in-place rule is deliberately over-inclusive for "read a file,
191
+ then regenerate it from something else in the same command" (the fix is one
192
+ `Copy-Item` line, and the message says so); `Add-Content`, `>>`, `-Append`,
193
+ `2> $null`, `> /dev/null` and `Clear-Content`-only commands are untouched; `>` onto
194
+ an existing file *without* reading it is still allowed and is listed in the
195
+ README's 「不挡什么」.
196
+
197
+ Tests: 90 → 116. New layer ② `test/rewrite.test.mjs` (22 cases: the incident
198
+ verbatim, the assertion fix, the §6 safe pattern, every in-place spelling, the
199
+ null-device/appendix exceptions, dialect spellings, the precedence case) plus three
200
+ hook-level cases in `registration.test.mjs` proving `apply()` actually wires the
201
+ rules and that `blockTruncatingWrites: false` disables them, plus the inline-body
202
+ scoping cases in `guard.test.mjs`. The "ordinary work stays allowed" corpus (42
203
+ commands: build, git, publish, log and config plumbing) lives in the same file as
204
+ the incident regression on purpose — a rule that catches the incident and also
205
+ refuses `npm run build` is not a fix.
206
+
207
+ `lib/shell-text.js` extracted: the lexer (`splitStatements`, `tokenize`,
208
+ `unquote`, `commandWord`) is now shared by both rule modules instead of imported
209
+ across them, which would have been a cycle. `guard.js` re-exports the same four
210
+ names, so nothing downstream changes.
211
+
10
212
  ## [2.2.3] — 2026-10-23
11
213
 
12
214
  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.0.tgz
43
58
  # restart dsh web: lib/*.js is loaded at process start
44
59
  ```
45
60
 
@@ -68,16 +83,23 @@ 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
+ | **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
88
 
72
89
  **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.
90
+ (`Select-String -Pattern "Remove-Item"`, `Get-Content shred.exe`), **restoring**
91
+ files out of the bin, `Add-Content` / `>>` / `-Append` (an append replaces
92
+ nothing), writes to `$null` / `/dev/null`, a full rewrite that first copies the file
93
+ to `.bak` or writes a temp file it verifies (the incident record's §6 spelling
94
+ passes untouched), and a wipe-program **name mentioned** inside a `node -e` / `python -c`
95
+ body — it is a program only when it reaches `exec` / `execSync` / `spawn` / `system` /
96
+ `subprocess.*` (a `bash -c` body is shell text and is judged whole).
75
97
 
76
98
  ## Two tools
77
99
 
78
100
  | Tool | Purpose |
79
101
  | --- | --- |
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 |
102
+ | `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
103
  | `trash_status { drive? }` | Item count and byte size of the bin on a volume, to confirm a deletion landed |
82
104
 
83
105
  ## Configuration
@@ -92,6 +114,9 @@ block — restate every key you want to keep):
92
114
  | `forbidEmptyRecycleBin` | `true` | Refuse emptying or modifying the bin |
93
115
  | `forbidWipe` | `true` | Refuse `shred` / `sdelete` / `srm` / `cipher /w` / `format` |
94
116
  | `blockScriptDeletes` | `true` | Refuse deletes in script files and inline strings |
117
+ | `blockTruncatingWrites` | `true` | Refuse read-then-rewrite of the same file, and an unchecked slice endpoint in a command that writes |
118
+ | `uncRecoverableMove` | `true` | Share deletes: copy to a local NTFS volume, verify, recycle the copy, then remove the original. `false` keeps the plain refusal |
119
+ | `stagingRoot` | `%LOCALAPPDATA%\dsh-delete-guard\staging` | Staging directory for share deletes (must be on a local volume with a bin) |
95
120
 
96
121
  ## Restoring a deleted file
97
122
 
@@ -102,6 +127,34 @@ offset 28 = UTF-16LE path), match the one you want, and `Move-Item` its paired `
102
127
  file back. The `$R`/`$I` names are random, so those records are the only index;
103
128
  skip any whose payload is missing. Do not depend on the localized verb name.
104
129
 
130
+ ## Network shares (no Recycle Bin)
131
+
132
+ A UNC path has no Recycle Bin: `SHFileOperationW` erases there and reports success,
133
+ which is why the bridge refuses those paths. `file_trash` now does what a person does
134
+ by hand, in one call, in a fixed order:
135
+
136
+ 1. copy the item to a local NTFS volume that does have a bin
137
+ (`%LOCALAPPDATA%\dsh-delete-guard\staging\<timestamp>-<name>`, override with `stagingRoot`);
138
+ 2. verify the copy against the original: same relative paths, same kinds, same sizes;
139
+ 3. recycle the staging folder — the copy is now restorable;
140
+ 4. only then remove the original.
141
+
142
+ **What that guarantees**: the *content* is recoverable from the local bin; the
143
+ *original path* is not, because the share has no bin to hold it — step 4 is an
144
+ ordinary permanent delete. The order is therefore the safety property: any failure
145
+ before step 4 leaves the original untouched, and step 4 runs only after the bridge
146
+ confirms the staged copy is in the bin.
147
+
148
+ A restore lands in the staging path, not back on the share (the bin's `$I` record
149
+ holds the staging location), so the tool prints that path in its result.
150
+
151
+ Refused, all before any copy: a share root (`\\host\share`) or a bare host; a tree
152
+ containing a **reparse point** (junction/symlink — a copy either duplicates the
153
+ target's contents or needs privileges to recreate the link); **not enough free
154
+ space** on the staging volume.
155
+
156
+ `uncRecoverableMove: false` restores the plain refusal and deletes nothing.
157
+
105
158
  ## What it does not cover
106
159
 
107
160
  | Not covered | Why |
@@ -113,6 +166,10 @@ skip any whose payload is missing. Do not depend on the localized verb name.
113
166
  | A delete split across two terminal sends | Each send is judged on its own text |
114
167
  | Non-Windows platforms | The bridge is `SHFileOperationW` |
115
168
  | Free-space exhaustion | A same-volume NTFS recycle is a rename and consumes no space, so there is nothing to pre-check |
169
+ | **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 |
170
+ | **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 |
171
+ | 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 |
172
+ | 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
173
 
117
174
  Covered shell tools: `pwsh`, `powershell`, `cmd`, `bash`, `sh`, `zsh`, `shell`,
118
175
  `terminal_send`, `terminal_write`. Reasoning and measurements:
@@ -124,11 +181,15 @@ the decision is made on the statement's command word, the shape of the call, and
124
181
  node test/run-all.mjs
125
182
  ```
126
183
 
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.
184
+ 128 cases across seven layers: command classification (50), overwrite guard (22),
185
+ share staging (8), `file_trash` operand guard (15), host schema + hook wiring (14),
186
+ host schema acceptance (5), live end-to-end against the real Recycle Bin (14,
187
+ including a real `\\localhost\C$` path). `test/` is not shipped in the tarball, so it
188
+ must be green before packing; two layers load the host's own validators and report
189
+ **skipped** (not failed) where no DSH install exists. The overwrite-guard layer keeps
190
+ "the incident command must be refused" and "42 ordinary commands must still pass" in
191
+ one file on purpose: a rule that catches the incident and also refuses `npm run build`
192
+ is not a fix.
132
193
 
133
194
  ## Documentation
134
195
 
@@ -136,10 +197,14 @@ validators and report **skipped** (not failed) where no DSH install exists.
136
197
  | --- | --- |
137
198
  | [CHANGELOG.md](CHANGELOG.md) | Version summaries |
138
199
  | [SECURITY.md](SECURITY.md) | Threat model: a policy layer, not a sandbox |
200
+ | [docs/incidents/](docs/incidents/) | Incident records: the measurement behind each rule, with the verbatim command (not in the npm package — see `files`) |
139
201
  | [LICENSE](LICENSE) | MIT |
140
202
 
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.
203
+ Incident records stay in the repository because they *are* the evidence for the
204
+ rules: a rule whose origin ("which command, under what conditions, with what
205
+ result") is unavailable can only be maintained by guessing. Design rationale and
206
+ the release runbook remain the maintainer's notes and ship with neither the
207
+ repository nor the package.
143
208
 
144
209
  ## License
145
210
 
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.0.tgz
41
55
  # dsh web を再起動(lib/*.js はプロセス起動時に読み込まれる)
42
56
  ```
43
57
 
@@ -66,16 +80,23 @@ 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
+ | **未検査のスライス端点** | 同一コマンド内でファイルを書き、かつ `$idx ± n` を端点に使う(`$l[0..($idx-2)]`、`-First ($i-1)`)。`$idx` は `$null` 検査済みでない。PowerShell はエラーにせず、`0..($null-2)` は `0..-2`(先頭行 + 末尾 2 行)になる |
69
85
 
70
86
  **許可される**:読み取り専用の作業、削除語に言及するだけのコマンド
71
- (`Select-String -Pattern "Remove-Item"`、`Get-Content shred.exe`)、そしてごみ箱から
72
- の**復元**。
87
+ (`Select-String -Pattern "Remove-Item"`、`Get-Content shred.exe`)、ごみ箱から
88
+ の**復元**、`Add-Content` / `>>` / `-Append`(追記は置き換えない)、`$null` / `/dev/null`
89
+ への書き込み、そして**`.bak` か検証付き一時ファイルを先に作る**全面書き換え
90
+ (事故記録 §6 の書き方はそのまま通ります)。また `node -e` / `python -c` の本体で消去ツール名に
91
+ **言及**しただけのテキストはプログラム名として扱いません——`exec` / `execSync` / `spawn` /
92
+ `system` / `subprocess.*` に渡されたときだけです(`bash -c` の本体はシェルテキストなので
93
+ 全体で判定します)。
73
94
 
74
95
  ## 2 つのツール
75
96
 
76
97
  | ツール | 役割 |
77
98
  | --- | --- |
78
- | `file_trash { paths, reason? }` | 唯一許可された削除手段。ごみ箱へ移動し、パスごとに結果を報告し、完全削除へフォールバックしない |
99
+ | `file_trash { paths, reason? }` | 唯一許可された削除手段。ローカルの項目はごみ箱へ移動し、共有の項目はローカルへ複製 → 検証 → 複製をごみ箱へ → その後に元を削除(「ネットワーク共有」参照)。パスごとに結果を報告 |
79
100
  | `trash_status { drive? }` | そのボリュームのごみ箱の項目数とバイト数。削除が本当に入ったかの確認に使う |
80
101
 
81
102
  ## 設定
@@ -90,6 +111,9 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
90
111
  | `forbidEmptyRecycleBin` | `true` | ごみ箱の空化・改変を拒否 |
91
112
  | `forbidWipe` | `true` | `shred` / `sdelete` / `srm` / `cipher /w` / `format` を拒否 |
92
113
  | `blockScriptDeletes` | `true` | スクリプトファイルとインライン文字列内の削除を拒否 |
114
+ | `blockTruncatingWrites` | `true` | 同一ファイルの読み書きと、書き込みを伴う未検査スライス端点を拒否 |
115
+ | `uncRecoverableMove` | `true` | 共有の削除:ローカル NTFS へ複製 → 検証 → 複製をごみ箱へ → その後に元を削除。`false` で拒否のみ |
116
+ | `stagingRoot` | `%LOCALAPPDATA%\dsh-delete-guard\staging` | 共有削除のステージング先(ごみ箱のあるローカルボリューム) |
93
117
 
94
118
  ## 消したファイルを戻す
95
119
 
@@ -100,6 +124,28 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
100
124
  `Move-Item` で戻します。`$R`/`$I` の名前はランダムなので、そのレコードが唯一の索引です。
101
125
  payload が無いレコードは飛ばし、ローカライズされた動詞名には依存しないこと。
102
126
 
127
+ ## ネットワーク共有(ごみ箱が無い)
128
+
129
+ UNC パスにごみ箱はありません。`SHFileOperationW` はそこで**消去して成功を返す**ため、ブリッジは
130
+ 先に拒否していました。`file_trash` は人が手でやることを 1 回の呼び出しで、決まった順序で行います:
131
+
132
+ 1. ごみ箱のあるローカル NTFS ボリュームへ複製(`%LOCALAPPDATA%\dsh-delete-guard\staging\<時刻>-<名前>`、`stagingRoot` で変更可)
133
+ 2. 元と突き合わせて検証:相対パス集合・種別・各ファイルのサイズ
134
+ 3. ステージングフォルダをごみ箱へ——この時点で複製は復元可能
135
+ 4. その後にだけ元を削除
136
+
137
+ **保証の範囲**:復元できるのは**内容**(ローカルのごみ箱)であり、**元のパス**ではありません。
138
+ 共有にごみ箱が無いため、4 は通常の完全削除です。だから順序そのものが安全条件で、4 より前の失敗は
139
+ 元に触れず、4 はブリッジが複製の収容を確認した後にだけ実行されます。
140
+
141
+ 復元先は共有ではなくステージングパスになります(ごみ箱の `$I` が記録するのはその場所)。ツールは
142
+ そのパスを結果に出力します。
143
+
144
+ 複製前に拒否するもの:共有ルート(`\\host\share`)やホスト名のみの形、**リパースポイント**
145
+ (ジャンクション/シンボリックリンク)を含むツリー、ステージング先の**空き容量不足**。
146
+
147
+ `uncRecoverableMove: false` で 2.3.0 の拒否のみに戻り、何も削除しません。
148
+
103
149
  ## 何を守らないか
104
150
 
105
151
  | 対象外 | 理由 |
@@ -111,6 +157,10 @@ payload が無いレコードは飛ばし、ローカライズされた動詞名
111
157
  | ターミナル送信 2 回に分けて組み立てた削除 | 1 回の送信のテキストしか見ていない |
112
158
  | Windows 以外 | ブリッジが `SHFileOperationW` |
113
159
  | 空き容量の枯渇 | 同一 NTFS ボリューム内のごみ箱移動は rename で、新しい容量を使わない |
160
+ | **読まずに上書き**(`echo x > 既存.md`、`Invoke-WebRequest -OutFile`、`git checkout -- f`) | 意図的な書き換えであり読み書きではない。新しい内容は古い内容に依存せず、`write`/`edit` も同じことをする。すべての書き込み動詞を削除扱いにすると本プラグインが退けた過剰な規則になる |
161
+ | 読み書きの中の**間接的な書き込み**(コンパイラ、`npm run build`、`robocopy` の成果物) | 書き込みは子プロセス内で起き、コマンドテキストに証明できる対象が無い |
162
+ | 書き込み後のサイズ比較・ロールバック | 戻すには書き込み前のバイト列が必要で、結局は対象の列挙問題に戻る。`tools/post-execute` は結果をフィードバックに変えるだけで、切り詰めを巻き戻せない。毎回ツリーをスナップショットするのは O(ワークスペース) で、しかも UNC 上の対象は含まれない |
163
+ | 共有上のものを `Move-Item` / `robocopy /MOV` で移動 | それは「移動」であり「削除」ではない。内容は移動先に残るが、共有側は完全に unlink され、ごみ箱の記録も残らない。記録を残すのは `file_trash` |
114
164
 
115
165
  対象のシェルツール名:`pwsh`、`powershell`、`cmd`、`bash`、`sh`、`zsh`、`shell`、
116
166
  `terminal_send`、`terminal_write`。判定は文の命令語・呼び出しの形・プログラム位置で行い、行内に語が現れたかどうかでは見ません。
@@ -121,11 +171,11 @@ payload が無いレコードは飛ばし、ローカライズされた動詞名
121
171
  node test/run-all.mjs
122
172
  ```
123
173
 
124
- 5 層・90 ケース:コマンド分類(49)、`file_trash` オペランドガード(15)、ホストの
125
- スキーマとフック配線(11)、ホストのスキーマ受理(5)、実ごみ箱に対するエンドツーエンド
126
- (10)。`test/` は tarball に含まれないので、パック前に緑である必要があります。うち 2 層
127
- はホスト自身の検証器を読み込むため、DSH のインストールが無い環境では失敗ではなく
128
- **スキップ**として報告されます。
174
+ 7 層・128 ケース:コマンド分類(50)、上書きガード(22)、共有ステージング(8)、
175
+ `file_trash` オペランドガード(15)、ホストのスキーマとフック配線(14)、ホストのスキーマ受理(5)、
176
+ 実ごみ箱に対するエンドツーエンド(14、実 `\\localhost\C$` パスを含む)。`test/` は tarball に
177
+ 含まれないので、パック前に緑である必要があります。うち 2 層はホスト自身の検証器を読み込むため、
178
+ DSH のインストールが無い環境では失敗ではなく**スキップ**として報告されます。
129
179
 
130
180
  ## ドキュメント
131
181
 
@@ -133,10 +183,12 @@ node test/run-all.mjs
133
183
  | --- | --- |
134
184
  | [CHANGELOG.md](CHANGELOG.md) | バージョン摘要 |
135
185
  | [SECURITY.md](SECURITY.md) | 脅威モデル:サンドボックスではなくポリシー層 |
186
+ | [docs/incidents/](docs/incidents/) | 事故記録:各規則の背景にある実測と逐語コマンド(npm パッケージには含まれません) |
136
187
  | [LICENSE](LICENSE) | MIT |
137
188
 
138
- 設計の根拠、各回の実測値、リリース手順はメンテナ側のエンジニアリングノートであり、
139
- このリポジトリにもパッケージにも含まれません。
189
+ 事故記録はリポジトリに残します。規則の根拠そのものだからです——「どのコマンドが、どんな条件で、
190
+ 何を壊したか」が分からない規則は、推測でしか保守できません。設計の根拠とリリース手順は
191
+ メンテナ側のノートに留め、リポジトリにもパッケージにも含めません。
140
192
 
141
193
  ## ライセンス
142
194