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/CHANGELOG.md CHANGED
@@ -7,6 +7,180 @@ 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.3] — 2026-11-26
11
+
12
+ **A failed delete now says what actually failed.** Reported from use: a directory whose
13
+ files could all be deleted would not delete itself, and the model worked around it by
14
+ renaming things until something took. Reproduced both causes, and both produced a
15
+ message that pointed at the wrong thing.
16
+
17
+ ### `0x2` said "the path no longer exists" while the path was there
18
+
19
+ A name ending in a space or a dot can exist on NTFS — WSL, an archive extractor, a sync
20
+ client or a port of a POSIX tool creates them — but Win32 trims those trailing
21
+ characters when a name is written into a path. `SHFileOperationW` walks the tree, the
22
+ child's own open fails with `ERROR_FILE_NOT_FOUND`, and the whole call returns `0x2`.
23
+ Measured 2026-11-25: a directory with one such child refuses; the same directory with
24
+ the child's name normalised recycles.
25
+
26
+ The old message was a lie about the path. It now names the offending entries and says
27
+ why, listing through the `\\?\` prefix — the one spelling in which Win32 takes the name
28
+ literally — capped at eight so a pathological tree cannot flood the reply.
29
+
30
+ ### `0x20` said "access is denied" with no hint of why
31
+
32
+ A directory held as some process's working directory, or holding an open file, returns
33
+ `DE_ACCESSDENIED`. Every file inside can still be deleted; the directory cannot, until
34
+ the process lets go. That is exactly the reported symptom.
35
+
36
+ The message now says a process is probably using it, that the contents can still go
37
+ individually, and that this tool **will not guess** which process — enumerating handles
38
+ needs elevation, and a screenshot of a guessed PID list would be worse than no answer.
39
+ Note what is *not* claimed: a share-mode probe of the directory does not detect a cwd
40
+ holder (measured — it opens cleanly), so there is no cheap reliable detector, which is
41
+ why this is a message rather than a verdict.
42
+
43
+ ### The `\\?\` prefix was refused as a network share
44
+
45
+ `Test-RecyclableVolume` matched `\\*`, so `\\?\C:\…` — a local path — was answered with
46
+ "a network location has no Recycle Bin". `isNetworkPath` in `staging.js` had the same
47
+ bug and sent such paths down the staging branch, where they were copied and recycled
48
+ from a staging directory instead of in place.
49
+
50
+ The bridge now strips the prefix before judging (`\\?\UNC\host\share\x` becomes the
51
+ ordinary UNC spelling, so the share rules see what they expect), and `isNetworkPath`
52
+ judges the two prefixes separately.
53
+
54
+ **Why strip rather than pass through:** `SHFileOperationW` does not accept the prefix at
55
+ all. Measured: the same file returns `0x7C` (DE_INVALIDFILES) with the prefix and
56
+ recycles without it, and a 316-character path recycles fine unprefixed — so stripping
57
+ loses no capability and removes a false "network location" verdict.
58
+
59
+ ### Not done, on purpose
60
+
61
+ The tool does not rename the offending entries, delete inside a directory it was asked
62
+ to delete, or kill the process holding it. Each would make this test pass and be the
63
+ wrong behaviour: they change the user's files or processes to satisfy a delete that the
64
+ user asked for by name. The message is the deliverable.
65
+
66
+ ### Tests
67
+
68
+ 148 → **155** across ten layers. New layer ⑨ `test/diagnosis.test.mjs` (7 cases) pins
69
+ both diagnoses, the prefix handling for local and UNC spellings, and that an absent path
70
+ gets no diagnosis. Every case asserts the operator side too: the malformed child is still
71
+ there afterwards, the held directory still has its contents, nothing was "fixed".
72
+
73
+ ## [2.4.2] — 2026-11-25
74
+
75
+ **Renumbering false positives from real measurements.** The rules from 2.3.0 / 2.4.0 were
76
+ built from one incident each. This release is built from **62,131 shell commands that
77
+ actually ran on this machine** (5,746 session logs), re-classified with today's matcher:
78
+ 1,580 would now be refused, and **432 of those were false positives (0.70% of all
79
+ commands)**. Three independent audits — two per-command, one code-level — plus my own
80
+ mechanical re-checks. Evidence: `docs/incidents/2026-11-24-rule-false-positive-sweep.md`,
81
+ plan: `docs/incidents/2026-11-24-fix-plan-2-4-2.md`.
82
+
83
+ ### `in-place-rewrite`: two conditions instead of a new rule
84
+
85
+ The rule stays "reads the same file it writes". What was missing was **order** and
86
+ **recoverability** — not a different predicate.
87
+
88
+ - **Order.** A read that happens only *after* the last write is a verification read-back;
89
+ its value cannot feed a write that already ran. Releases 330 historical commands.
90
+ - `.NET` writes participate: giving them no statement index made the last-write lookup
91
+ return `-1`, which emptied the read set and would have let **223** `.NET`
92
+ read→write commands through — including the shape §9.4 of the incident record
93
+ claims is covered.
94
+ - Suppressed inside any repetition construct (`for`, `foreach`, `while`, `do`, `until`,
95
+ `switch`, `%`/`ForEach-Object`, `.ForEach(`), because there textual order is not
96
+ execution order. The first gate listed only three keywords and missed `%`, the
97
+ commonest spelling.
98
+ - **Recoverability.** A copy step now has to be an actual statement writing a *different*
99
+ path derived from the target, **before** the overwrite. The previous check was a
100
+ whole-text `BACKUP_MARKER.test(command)`, so all three of these were exempted while
101
+ truly rewriting a file from its only copy: a `.bak` in a trailing comment, a `.bak` in
102
+ the target's own name, and a `.bak` in an unrelated string.
103
+ - `sed -i.bak` still counts — the editor makes the copy itself, in the same statement.
104
+ - A temp file holding the **new** content is **not** a backup: verifying the output does
105
+ not make the input recoverable. Refused (this was 4 historical commands).
106
+
107
+ ### A bounded substitution with the codec pinned is the `edit` tool
108
+
109
+ `$t = $t.Replace('a','b')` written back is a targeted change, not a rebuild. It is now
110
+ allowed when **both** sides state an encoding, which is the condition that actually
111
+ matters: `Get-Content -Raw` on a GBK document decodes it wrong, and `WriteAllText` then
112
+ writes the mojibake back — measured, with an ASCII needle the occurrence check passes and
113
+ every CJK character becomes `U+FFFD`. Encoding continuity is what prevents it; a
114
+ replacement-count check does not.
115
+
116
+ Not allowed: a document-wide regex (`-replace '(?s)^.*$'` reduces a file to one
117
+ character), a substitution applied to a slice, and a substitution with no codec stated.
118
+ Releases 183 commands (44% of the cluster).
119
+
120
+ ### Four holes the sweep found (not false positives — the opposite)
121
+
122
+ | Command | Was | Now |
123
+ | --- | --- | --- |
124
+ | `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" |
125
+ | `$i.InvokeVerb('delete')` alone | **allowed** (the rule needed a bin reference in the same command) | refused |
126
+ | `$i.Verbs() \| % { $_.DoIt() }` | **allowed** | refused |
127
+ | `const {execSync}=require('child_process'); execSync('…')` | **allowed** (every spawn branch required a leading dot) | refused |
128
+
129
+ The first is a safety inversion, not friction: the user asked to preview and the guard
130
+ advised destroying the file. The fix renders dry runs differently rather than dropping
131
+ them from classification — dropping statements let the word `-WhatIf` in a comment or a
132
+ string exempt a real write (measured, three cases).
133
+
134
+ Also: `-WhatIf`/`-Confirm`/`-Verbose`/`-Debug` are switches, not value-taking flags.
135
+ Listing them as value-taking made `Remove-Item -Verbose C:\x\a.txt` report "no explicit
136
+ operands", so the model was told its delete had no target instead of being handed the
137
+ paths.
138
+
139
+ ### Smaller corrections
140
+
141
+ - `.Verbs()` is enumeration, not driving: the sanctioned restore path and read-only bin
142
+ listings are allowed again.
143
+ - `DoIt()` is never exempted by a restore word — a comment saying `# restore` laundered it.
144
+ - `Remove-Item variable:x` / `env:X` / `function:x` / `alias:X` are allowed: they delete
145
+ no file, and the old behaviour handed the model `file_trash "variable:x"`, an
146
+ instruction that cannot work. `HKCU:`/`Cert:`/`WSMan:` are refused **without** a
147
+ file_trash hint — the bin cannot hold a registry key.
148
+ - `Invoke-Expression` is judged by its body, not by the word.
149
+ - A shell invoked through a variable (`$shellPath='…bash.exe'; & $shellPath -c "…"`) is
150
+ refused when the body deletes. Previously the `$sh='bash'` spelling was caught only
151
+ because the variable *name* contains `sh`.
152
+ - `Select-String <pattern> <file>`: `-Path`'s value was eaten by `skip: 1`, so
153
+ `Select-String -Path a.md -Pattern x | Set-Content a.md` was allowed.
154
+ - A read folded into the write statement (`Set-Content $f (Get-Content $f | Select-Object -First 10)`)
155
+ is now a read. Four variants were allowed; this is the incident in one line.
156
+
157
+ ### Costs, stated
158
+
159
+ - **Latency: +11% best-case, +16% median** on 6,000 real commands (41 interleaved rounds,
160
+ 25 blocks, both versions in one process; the two-version comparison is in
161
+ `temp/bench-decisive.mjs`). The classifier was ~165 µs/command and is now ~192 µs.
162
+ For scale: one `stat()` is ~5 µs, one PowerShell spawn (what `file_trash` does) is
163
+ ~70 ms — the guard is 0.3% of a trash call. A cheap precondition in the hook
164
+ (two regexes, verified to skip **no** command the classifier would block, on all 6,000)
165
+ keeps the new checks off the 88% of commands that neither read nor write.
166
+ - **Not reached:** the plan's target was "误伤 < 130". The measured result is **432 → 241**.
167
+ The remainder is dominated by 156 commands whose *read* side states no encoding — refused
168
+ on purpose, since that is the mojibake hazard — plus 24 with no encoding on either side
169
+ and the `UNSURE` group whose writes come from an external script.
170
+ - **`real` count drops 1,148 → 852, which looks like over-relaxation and is not.** Verified
171
+ mechanically: across the 5,917 commands now allowed, **zero** are "same file, read before
172
+ write". The drop is the sweep's own classifier mislabeling write-then-read-back
173
+ (`python x.py | Out-File out.txt; Get-Content out.txt`) as a whole-file rewrite. The
174
+ acceptance criteria were changed to a shape gate for this reason.
175
+
176
+ ### Tests
177
+
178
+ 116 → **148**, eight layers. New layer ③ `test/holes.test.mjs` (12 cases) pins each hole
179
+ and each correction with the direction it must move; layer ② grew from 22 to 30 cases
180
+ covering order, `.NET` ordering, folded reads, repetition, real-vs-fake backup steps,
181
+ pinned encoding, and the four "no discard token" rebuilds that keep the rule from
182
+ degenerating into a token list.
183
+
10
184
  ## [2.4.1] — 2026-11-24
11
185
 
12
186
  The publish workflow's first run, and what it found. No production code changed.
package/README.en.md CHANGED
@@ -2,12 +2,8 @@
2
2
 
3
3
  **English** | [简体中文](README.md) | [日本語](README.ja.md)
4
4
 
5
- **An agent cannot delete what it cannot recover.**
6
-
7
- A deletion has exactly two outcomes here: it lands in the Windows Recycle Bin
8
- (restorable from Explorer), or it is refused and re-issued as a `file_trash`
9
- call. There is no third one — and **writing the content away is the same thing as
10
- deleting it.**
5
+ Refuses the delete commands a model issues and moves the target into the Windows
6
+ Recycle Bin instead.
11
7
 
12
8
  ```
13
9
  agent: Remove-Item -Recurse -Force .\src
@@ -54,7 +50,7 @@ dsh plugin --profile web add dsh-delete-guard
54
50
  dsh plugin --profile web add github:deepestevan/dsh-delete-guard
55
51
  # or from a local tarball (when you have changed the source)
56
52
  pnpm pack --pack-destination ./temp/pack # bump `version` first
57
- dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.0.tgz
53
+ dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.2.tgz
58
54
  # restart dsh web: lib/*.js is loaded at process start
59
55
  ```
60
56
 
@@ -84,15 +80,16 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
84
80
  | Locations without a bin | UNC shares and exFAT/FAT32 volumes, where "recycling" is a permanent erase |
85
81
  | Deletes inside scripts | shell / Python / Node inline bodies, and writing delete text into `.ps1`/`.sh`/`.py` |
86
82
  | **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 |
83
+ | **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 |
84
+ | **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 |
87
85
  | **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 |
88
86
 
89
87
  **Allowed**: read-only work, commands that only mention a delete word
90
88
  (`Select-String -Pattern "Remove-Item"`, `Get-Content shred.exe`), **restoring**
91
89
  files out of the bin, `Add-Content` / `>>` / `-Append` (an append replaces
92
90
  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` /
91
+ to `.bak` or writes a temp file it verifies, and a wipe-program **name mentioned** inside a
92
+ `node -e` / `python -c` body — it is a program only when it reaches `exec` / `execSync` / `spawn` / `system` /
96
93
  `subprocess.*` (a `bash -c` body is shell text and is judged whole).
97
94
 
98
95
  ## Two tools
@@ -120,7 +117,7 @@ block — restate every key you want to keep):
120
117
 
121
118
  ## Restoring a deleted file
122
119
 
123
- Restoring is not a plugin feature and needs none: the bin belongs to the OS.
120
+ Restoring is handled by the OS Recycle Bin.
124
121
  Explorer's right-click "Restore" works. From a script, read the
125
122
  `X:\$Recycle.Bin\<SID>\$I*` records (offset 24 = original path length in chars,
126
123
  offset 28 = UTF-16LE path), match the one you want, and `Move-Item` its paired `$R`
@@ -153,7 +150,7 @@ containing a **reparse point** (junction/symlink — a copy either duplicates th
153
150
  target's contents or needs privileges to recreate the link); **not enough free
154
151
  space** on the staging volume.
155
152
 
156
- `uncRecoverableMove: false` restores the plain refusal and deletes nothing.
153
+ `uncRecoverableMove: false` refuses a share path outright: nothing is copied and nothing is deleted.
157
154
 
158
155
  ## What it does not cover
159
156
 
@@ -166,14 +163,15 @@ space** on the staging volume.
166
163
  | A delete split across two terminal sends | Each send is judged on its own text |
167
164
  | Non-Windows platforms | The bridge is `SHFileOperationW` |
168
165
  | 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 |
166
+ | **Overwriting without reading** (`echo x > notes.md`, `Invoke-WebRequest -OutFile`, `git checkout -- f`) | The new content does not depend on the old, so this is not read-modify-write |
170
167
  | **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 |
168
+ | Judging a truncation by size afterwards | Rolling back needs the old bytes, and `tools/post-execute` can only turn a result into feedback |
169
+ | Moving something off a share (`Move-Item`, `robocopy /MOV`) | The content reaches the destination, but the share copy is unlinked for good and no bin record exists |
170
+ | **A directory holding a name Windows cannot open** (trailing space or dot, usually left by WSL, an extractor or a sync client) | Win32 trims the trailing character when the name goes into a path, so the tree cannot be walked. The tool names the entry and the reason, and does **not** rename or delete it for you |
171
+ | **A directory a process is using** (its working directory, or an open file inside) | The files inside can go one by one; the directory waits for the holder to let go. The tool says that is what happened and does **not** hunt for the process — that needs elevation or handle scanning, and a guessed PID is worse than none |
173
172
 
174
173
  Covered shell tools: `pwsh`, `powershell`, `cmd`, `bash`, `sh`, `zsh`, `shell`,
175
- `terminal_send`, `terminal_write`. Reasoning and measurements:
176
- the decision is made on the statement's command word, the shape of the call, and program position — never on a word appearing somewhere in the line.
174
+ `terminal_send`, `terminal_write`.
177
175
 
178
176
  ## Tests
179
177
 
@@ -181,15 +179,17 @@ the decision is made on the statement's command word, the shape of the call, and
181
179
  node test/run-all.mjs
182
180
  ```
183
181
 
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
182
+ 155 cases across ten layers: command classification (50), overwrite guard (30),
183
+ rule holes (12), share staging (8), `file_trash` operand guard (15), host schema +
184
+ hook wiring (14), host schema acceptance (5), live end-to-end against the real
185
+ Recycle Bin (14, including a real `\\localhost\C$` path), failure diagnosis (7).
186
+ `test/` is not shipped in the tarball, so it
188
187
  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.
188
+ **skipped** (not failed) where no DSH install exists. The overwrite-guard layer pins both
189
+ directions in one file: the dangerous shapes are refused, and ordinary work (builds, git,
190
+ log and config rewrites) still passes. One further layer checks the documentation
191
+ (`scripts/verify-readme-structure.mjs`): the three READMEs must have the same sections and
192
+ the same number of table rows.
193
193
 
194
194
  ## Documentation
195
195
 
@@ -197,14 +197,10 @@ is not a fix.
197
197
  | --- | --- |
198
198
  | [CHANGELOG.md](CHANGELOG.md) | Version summaries |
199
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`) |
200
+ | [docs/incidents/](docs/incidents/) | Measured evidence behind each rule, with the verbatim command (not in the npm package) |
201
201
  | [LICENSE](LICENSE) | MIT |
202
202
 
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.
203
+
208
204
 
209
205
  ## License
210
206
 
package/README.ja.md CHANGED
@@ -2,11 +2,7 @@
2
2
 
3
3
  [English](README.en.md) | [简体中文](README.md) | **日本語**
4
4
 
5
- **復元できないものは、エージェントに消させない。**
6
-
7
- 削除の結果は 2 つだけです。Windows のごみ箱に入る(エクスプローラーから元に戻せる)
8
- か、拒否されて `file_trash` 呼び出しに置き換わるか。それ以外はありません。
9
- **内容を書き潰すことも、削除と同じことです。**
5
+ モデルが発行する削除コマンドを拒否し、Windows のごみ箱へ移すように促します。
10
6
 
11
7
  ```
12
8
  agent: Remove-Item -Recurse -Force .\src
@@ -51,7 +47,7 @@ dsh plugin --profile web add dsh-delete-guard
51
47
  dsh plugin --profile web add github:deepestevan/dsh-delete-guard
52
48
  # またはローカルの tarball から(ソースを変更したとき)
53
49
  pnpm pack --pack-destination ./temp/pack # 先に package.json の version を上げる
54
- dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.0.tgz
50
+ dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.2.tgz
55
51
  # dsh web を再起動(lib/*.js はプロセス起動時に読み込まれる)
56
52
  ```
57
53
 
@@ -81,13 +77,15 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
81
77
  | ごみ箱が無い場所 | UNC 共有と exFAT/FAT32 ボリューム(そこで「ごみ箱へ」は完全消去と同じ) |
82
78
  | スクリプト内の削除 | シェル / Python / Node のインライン本体、および削除語を含むテキストの `.ps1`/`.sh`/`.py` への書き込み |
83
79
  | **同一ファイルの読み書き** | `(Get-Content $f) \| Set-Content $f`、`$c = Get-Content $f; Set-Content $f $c`、`sed -i f`、`cat f > f`、`::ReadAllText` → `::WriteAllText`——新しい内容は唯一のコピーから作られるため、切り出しやフィルタを誤ると復元元が残りません。`.bak` か検証付き一時ファイルを残す書き方は許可 |
80
+ | **書き込み文に折り込まれた読み取り** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)`——1 行で読み・切り詰め・書き戻し |
81
+ | **変数経由のシェル呼び出し** | `$shellPath='…bash.exe'; & $shellPath -c "rm -rf …"`——プログラム名がリテラルでなく、本体を判定できない |
84
82
  | **未検査のスライス端点** | 同一コマンド内でファイルを書き、かつ `$idx ± n` を端点に使う(`$l[0..($idx-2)]`、`-First ($i-1)`)。`$idx` は `$null` 検査済みでない。PowerShell はエラーにせず、`0..($null-2)` は `0..-2`(先頭行 + 末尾 2 行)になる |
85
83
 
86
84
  **許可される**:読み取り専用の作業、削除語に言及するだけのコマンド
87
85
  (`Select-String -Pattern "Remove-Item"`、`Get-Content shred.exe`)、ごみ箱から
88
86
  の**復元**、`Add-Content` / `>>` / `-Append`(追記は置き換えない)、`$null` / `/dev/null`
89
87
  への書き込み、そして**`.bak` か検証付き一時ファイルを先に作る**全面書き換え
90
- (事故記録 §6 の書き方はそのまま通ります)。また `node -e` / `python -c` の本体で消去ツール名に
88
+ また `node -e` / `python -c` の本体で消去ツール名に
91
89
  **言及**しただけのテキストはプログラム名として扱いません——`exec` / `execSync` / `spawn` /
92
90
  `system` / `subprocess.*` に渡されたときだけです(`bash -c` の本体はシェルテキストなので
93
91
  全体で判定します)。
@@ -117,7 +115,7 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
117
115
 
118
116
  ## 消したファイルを戻す
119
117
 
120
- 復元はプラグインの機能ではなく、必要でもありません。ごみ箱は OS のものです。
118
+ 復元は OS のごみ箱が担います。
121
119
  エクスプローラーの右クリック「元に戻す」で戻せます。スクリプトからは
122
120
  `X:\$Recycle.Bin\<SID>\$I*` のレコードを読み(オフセット 24 が元パスの文字数、
123
121
  オフセット 28 から UTF-16LE のパス)、目的のものを探して対になる `$R` を
@@ -144,7 +142,7 @@ UNC パスにごみ箱はありません。`SHFileOperationW` はそこで**消
144
142
  複製前に拒否するもの:共有ルート(`\\host\share`)やホスト名のみの形、**リパースポイント**
145
143
  (ジャンクション/シンボリックリンク)を含むツリー、ステージング先の**空き容量不足**。
146
144
 
147
- `uncRecoverableMove: false` で 2.3.0 の拒否のみに戻り、何も削除しません。
145
+ `uncRecoverableMove: false` にすると共有パスはそのまま拒否され、複製も削除も行いません。
148
146
 
149
147
  ## 何を守らないか
150
148
 
@@ -160,7 +158,9 @@ UNC パスにごみ箱はありません。`SHFileOperationW` はそこで**消
160
158
  | **読まずに上書き**(`echo x > 既存.md`、`Invoke-WebRequest -OutFile`、`git checkout -- f`) | 意図的な書き換えであり読み書きではない。新しい内容は古い内容に依存せず、`write`/`edit` も同じことをする。すべての書き込み動詞を削除扱いにすると本プラグインが退けた過剰な規則になる |
161
159
  | 読み書きの中の**間接的な書き込み**(コンパイラ、`npm run build`、`robocopy` の成果物) | 書き込みは子プロセス内で起き、コマンドテキストに証明できる対象が無い |
162
160
  | 書き込み後のサイズ比較・ロールバック | 戻すには書き込み前のバイト列が必要で、結局は対象の列挙問題に戻る。`tools/post-execute` は結果をフィードバックに変えるだけで、切り詰めを巻き戻せない。毎回ツリーをスナップショットするのは O(ワークスペース) で、しかも UNC 上の対象は含まれない |
163
- | 共有上のものを `Move-Item` / `robocopy /MOV` で移動 | それは「移動」であり「削除」ではない。内容は移動先に残るが、共有側は完全に unlink され、ごみ箱の記録も残らない。記録を残すのは `file_trash` |
161
+ | 共有上のものを `Move-Item` / `robocopy /MOV` で移動 | 内容は移動先に残るが、共有側は完全に unlink され、ごみ箱の記録も残らない |
162
+ | **Windows が開けない名前を含むディレクトリ**(末尾が空白またはピリオド。WSL・解凍ツール・同期クライアントが残す) | Win32 はパスに書くとき末尾の文字を切り落とすため、ツリーを走査できない。どの項目がなぜ駄目かは伝えるが、**代わりに改名・削除はしない** |
163
+ | **プロセスが使用中のディレクトリ**(作業ディレクトリに設定されている、または中のファイルが開かれている) | 中のファイルは個別に消せるが、ディレクトリ本体は解放待ち。使用中であることは伝えるが、**どのプロセスかは調べない**——権限昇格かハンドル列挙が必要で、推測した PID は無いより悪いため |
164
164
 
165
165
  対象のシェルツール名:`pwsh`、`powershell`、`cmd`、`bash`、`sh`、`zsh`、`shell`、
166
166
  `terminal_send`、`terminal_write`。判定は文の命令語・呼び出しの形・プログラム位置で行い、行内に語が現れたかどうかでは見ません。
@@ -171,11 +171,13 @@ UNC パスにごみ箱はありません。`SHFileOperationW` はそこで**消
171
171
  node test/run-all.mjs
172
172
  ```
173
173
 
174
- 7 層・128 ケース:コマンド分類(50)、上書きガード(22)、共有ステージング(8)、
174
+ 10 層・155 ケース:コマンド分類(50)、上書きガード(30)、規則の穴(12)、共有ステージング(8)、
175
175
  `file_trash` オペランドガード(15)、ホストのスキーマとフック配線(14)、ホストのスキーマ受理(5)、
176
- 実ごみ箱に対するエンドツーエンド(14、実 `\\localhost\C$` パスを含む)。`test/` は tarball に
176
+ 実ごみ箱に対するエンドツーエンド(14、実 `\\localhost\C$` パスを含む)、失敗診断(7)。`test/` は tarball に
177
177
  含まれないので、パック前に緑である必要があります。うち 2 層はホスト自身の検証器を読み込むため、
178
178
  DSH のインストールが無い環境では失敗ではなく**スキップ**として報告されます。
179
+ さらにドキュメント用の層(`scripts/verify-readme-structure.mjs`)があり、3 つの README の
180
+ 章構成と表の行数が一致していることを検査します。
179
181
 
180
182
  ## ドキュメント
181
183
 
@@ -183,12 +185,10 @@ DSH のインストールが無い環境では失敗ではなく**スキップ**
183
185
  | --- | --- |
184
186
  | [CHANGELOG.md](CHANGELOG.md) | バージョン摘要 |
185
187
  | [SECURITY.md](SECURITY.md) | 脅威モデル:サンドボックスではなくポリシー層 |
186
- | [docs/incidents/](docs/incidents/) | 事故記録:各規則の背景にある実測と逐語コマンド(npm パッケージには含まれません) |
188
+ | [docs/incidents/](docs/incidents/) | 各規則の根拠となる実測と逐語コマンド(npm パッケージには含まれません) |
187
189
  | [LICENSE](LICENSE) | MIT |
188
190
 
189
- 事故記録はリポジトリに残します。規則の根拠そのものだからです——「どのコマンドが、どんな条件で、
190
- 何を壊したか」が分からない規則は、推測でしか保守できません。設計の根拠とリリース手順は
191
- メンテナ側のノートに留め、リポジトリにもパッケージにも含めません。
191
+
192
192
 
193
193
  ## ライセンス
194
194
 
package/README.md CHANGED
@@ -2,10 +2,7 @@
2
2
 
3
3
  [English](README.en.md) | **简体中文** | [日本語](README.ja.md)
4
4
 
5
- **让 agent 删不掉「恢复不了」的东西。**
6
-
7
- 删除只有两条路:进 Windows 回收站(资源管理器里能还原),或者被拦下来换成一次
8
- `file_trash` 调用。没有第三条:**把文件内容写没了,和把它删掉是同一件事。**
5
+ 拦截模型发出的删除命令,改为移入 Windows 回收站。
9
6
 
10
7
  ```
11
8
  agent: Remove-Item -Recurse -Force .\src
@@ -25,7 +22,7 @@ DSH 里模型执行 `pwsh` 的删除命令,文件是被直接抹掉的:`ctx.
25
22
  `ctx.shell` 只有 `execute()`,没有任何中间层。一句 `Remove-Item -Recurse -Force`
26
23
  就能带走一整个目录,没有回收站,没有撤销。
27
24
 
28
- 本插件挂在 `tools/pre-execute`(宿主真正路由每个工具调用的接缝),把这些调用**拒绝**,
25
+ 本插件挂在 `tools/pre-execute`(宿主路由每个工具调用的接缝),把这些调用拒绝,
29
26
  并告诉模型改用 `file_trash`;后者用 `SHFileOperationW(FOF_ALLOWUNDO)` 移动文件——和资源
30
27
  管理器删文件是同一套 Win32 API,所以 `$Recycle.Bin` 的 `$I`/`$R` 元数据正确,「还原」可用。
31
28
 
@@ -33,10 +30,10 @@ DSH 里模型执行 `pwsh` 的删除命令,文件是被直接抹掉的:`ctx.
33
30
  `-Command` / `-EncodedCommand`、持久终端里敲的命令、Git Bash 的 `/c/...` 路径、以及清空
34
31
  回收站的各种写法,各有对应规则。
35
32
 
36
- 还有一类**没有删除动词**的毁灭:把文件读进来、算一刀、再覆盖回同一个文件。
33
+ 还有一类没有删除动词的毁灭:把文件读进来、算一刀、再覆盖回同一个文件。
37
34
  `$lines[0..($null-2)]` 在 PowerShell 里不是错误,而是 `$lines[0..-2]`,即「首行 + 末两行」
38
- ——605 行可以这样被静默保存成 24 行。这类命令既不能进回收站(网络共享根本没有回收站),
39
- 也不能靠事后比对发现,所以守卫在写入前就按「读改写同一文件」和「未断言的切片端点」拒绝。
35
+ ——一个 605 行的文件可以这样被静默写成 24 行。这类命令不能进回收站(网络共享上没有),
36
+ 也不会被事后比对发现,所以在写入前就按「读改写同一文件」和「未断言的切片端点」拒绝。
40
37
 
41
38
  ## 安装
42
39
 
@@ -47,7 +44,7 @@ dsh plugin --profile web add dsh-delete-guard
47
44
  dsh plugin --profile web add github:deepestevan/dsh-delete-guard
48
45
  # 或者从本地 tarball(改过源码时用这条)
49
46
  pnpm pack --pack-destination ./temp/pack # 先升 package.json 的 version
50
- dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.0.tgz
47
+ dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.2.tgz
51
48
  # 重启 dsh web:lib/*.js 只在进程启动时加载
52
49
  ```
53
50
 
@@ -77,14 +74,16 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
77
74
  | 清空回收站 | `Clear-RecycleBin`(含 `&`、子壳、`-EncodedCommand` 形态)、`SHEmptyRecycleBin`、对回收站条目驱动 shell 动词、直接删 `$Recycle.Bin` 内容 |
78
75
  | 没有回收站的位置 | UNC 共享、exFAT/FAT32 卷(在那里"回收"等于永久擦除) |
79
76
  | 脚本内删除 | 内联 shell / Python / Node 体里的删除动词与擦除调用;把含删除的文本写进 `.ps1`/`.sh`/`.py` |
80
- | **读改写同一个文件** | `(Get-Content $f) \| Set-Content $f`、`$c = Get-Content $f; Set-Content $f $c`、`sed -i $f`、`cat $f > $f`、`::ReadAllText` → `::WriteAllText`——新内容来自唯一的副本,写坏就没得还原。带 `.bak` 备份或临时文件校验步骤的写法放行 |
77
+ | **读改写同一个文件** | `(Get-Content $f) \| Set-Content $f`、`$c = Get-Content $f; Set-Content $f $c`、`sed -i $f`、`cat $f > $f`、`::ReadAllText` → `::WriteAllText`——新内容来自唯一的副本。先备份到 `.bak`,或写临时文件校验后再换上去的写法放行 |
81
78
  | **未断言的切片端点** | 同一命令里既写文件、又用 `$idx ± n` 当区间端点(`$l[0..($idx-2)]`、`-First ($i-1)`),而 `$idx` 从没检查过 `$null`。`$null` 在 PowerShell 里不报错:`0..($null-2)` 就是 `0..-2` = 首行 + 末两行 |
79
+ | **读动词折进写语句里** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)`:一行里既读、又截断、又写回 |
80
+ | **经变量调用的 shell** | `$shellPath='…bash.exe'; & $shellPath -c "rm -rf …"`:程序名不是字面量,正文无法判定 |
82
81
 
83
82
  **放行**:只读命令、只提到删除词的操作(`Select-String -Pattern "Remove-Item"`、
84
83
  `Get-Content shred.exe`)、从回收站**还原**文件、`Add-Content` / `>>` / `-Append`
85
- (追加不替换)、写 `$null` / `/dev/null`、以及**带 `.bak` 备份或临时文件校验**的整档重写
86
- (事故记录 §6 的那套写法原样通过)。另外,`node -e` / `python -c` 体里**提到**擦除工具名的文本不算程序名——
87
- 只有把它交给 `exec` / `execSync` / `spawn` / `system` / `subprocess.*` 才算(`bash -c` 体是 shell 文本,仍按整段判)。
84
+ (追加不替换)、写 `$null` / `/dev/null`,以及带备份或校验步骤的整档重写。
85
+ `node -e` / `python -c` 体里**提到**擦除工具名的文本不算程序名——只有把它交给
86
+ `exec` / `execSync` / `spawn` / `system` / `subprocess.*` 才算(`bash -c` 体是 shell 文本,仍按整段判)。
88
87
 
89
88
  ## 两个工具
90
89
 
@@ -110,7 +109,7 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
110
109
 
111
110
  ## 恢复已删的文件
112
111
 
113
- 恢复不是插件的功能,也不需要——回收站是操作系统的。脚本里这样还原(与界面语言无关):
112
+ 恢复由操作系统的回收站完成。脚本里这样还原(与界面语言无关):
114
113
 
115
114
  1. 读 `X:\$Recycle.Bin\<SID>\$I*` 记录:偏移 24 是原路径字符数,偏移 28 起是 UTF-16LE 原路径;
116
115
  2. 按原路径匹配到目标条目,取配对的 `$R` 文件;
@@ -122,24 +121,24 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
122
121
 
123
122
  ## 网络共享(没有回收站)
124
123
 
125
- UNC 路径下不存在回收站:`SHFileOperationW` 在那里是**擦除并返回成功**,所以桥接会先拒绝。
126
- `file_trash` 于是做人在这种情况下的做法,一次调用完成,顺序固定:
124
+ UNC 路径下不存在回收站:`SHFileOperationW` 在那里是擦除并返回成功,所以桥接会先拒绝。
125
+ `file_trash` 于是按固定顺序处理,一次调用完成:
127
126
 
128
127
  1. 把条目复制到有回收站的本地 NTFS 卷(`%LOCALAPPDATA%\dsh-delete-guard\staging\<时间戳>-<名字>`,可用 `stagingRoot` 改);
129
128
  2. 对照原件校验:相对路径集合、条目类型、每个文件的大小;
130
129
  3. 把暂存目录送进回收站——副本这时可还原;
131
130
  4. 最后才删除原件。
132
131
 
133
- **保证的范围要说清**:可恢复的是**内容**(在本地回收站里),不是**原路径**——共享上没有回收站放它,
134
- 第 4 步就是一次普通永久删除。所以顺序本身就是安全属性:第 4 步之前的任何失败都不碰原件,第 4 步只在
135
- 桥接确认暂存副本已进回收站之后才跑。
132
+ 可恢复的是**内容**(在本地回收站里),不是**原路径**:共享上没有回收站放它,第 4 步就是一次
133
+ 普通永久删除。因此第 4 步之前的任何失败都不碰原件,而第 4 步只在桥接确认暂存副本已进回收站
134
+ 之后才执行。
136
135
 
137
- 还原时落点是暂存路径而不是原共享路径(回收站的 `$I` 记的是暂存位置),所以工具会把该路径打出来。
136
+ 还原时落点是暂存路径而不是原共享路径(回收站的 `$I` 记的是暂存位置),工具会把该路径打出来。
138
137
 
139
- 会被拒绝,且都在复制之前停住:共享根(`\\host\share`)与只有主机名的形态、树里含**重解析点**
140
- (junction/符号链接:复制要么把目标内容一起复制进来、要么需要权限重建链接)、暂存卷**空间不足**。
138
+ 以下情况在复制之前就被拒绝:共享根(`\\host\share`)与只有主机名的形态、树里含重解析点
139
+ (junction/符号链接:复制要么把目标内容一起复制进来、要么需要权限重建链接)、暂存卷空间不足。
141
140
 
142
- `uncRecoverableMove: false` 退回 2.3.0 的纯拒绝,且什么都不删。
141
+ `uncRecoverableMove: false` 时改为直接拒绝共享路径,不复制也不删除。
143
142
 
144
143
  ## 不挡什么
145
144
 
@@ -152,13 +151,15 @@ UNC 路径下不存在回收站:`SHFileOperationW` 在那里是**擦除并返
152
151
  | 终端里分两次发送才拼出的删除 | 每次 send 只看到这一次的文本 |
153
152
  | 非 Windows 平台 | 桥接是 `SHFileOperationW` |
154
153
  | 空余空间不足时的删除 | NTFS 同卷回收是 rename,不占新空间,没有可预检的东西 |
155
- | **没读过就覆盖**(`echo x > 既有文件.md`、`Invoke-WebRequest -OutFile $f`、`git checkout -- f`) | 这是「有意重写」,不是读改写:新内容不依赖旧内容,`write`/`edit` 工具也做同一件事。按动词列举覆盖写入会连构建日志、生成配置一起拒绝,正是本插件否掉的做法 |
154
+ | **没读过就覆盖**(`echo x > 既有文件.md`、`Invoke-WebRequest -OutFile $f`、`git checkout -- f`) | 新内容不依赖旧内容,不是读改写 |
156
155
  | 读改写里的**间接**写(编译器、`npm run build`、`robocopy` 覆盖产物) | 写入发生在子进程内部,命令文本里没有可判定的目标 |
157
- | 写完之后再比对体积(截断熔断) | 需要覆盖前的旧内容才能回滚:`tools/post-execute` 只能把结果改成反馈,撤不回已截断的内容;每轮 shell 调用快照整棵树是 O(工作区),而且本次事故的目标在 UNC 共享上,任何工作区快照都不包含它 |
158
- | 把共享上的东西 `Move-Item` / `robocopy /MOV` 到本地 | 那是"移动"不是"删除":内容到了目标位置,但共享上的原件被永久 unlink,没有回收站记录。要留记录就得走 `file_trash` |
156
+ | 写完之后按体积判断有没有被截断 | 回滚需要覆盖前的旧内容,而 `tools/post-execute` 只能把结果改成反馈 |
157
+ | 把共享上的东西 `Move-Item` / `robocopy /MOV` 到本地 | 内容到了目标位置,但共享上的原件被永久删除,没有回收站记录 |
158
+ | **内含非法名字的目录**(名字以空格或点结尾,再由 WSL、解压工具或同步客户端留下) | Win32 写到路径里会截掉尾随的空格/点,所以目录树走不完。工具会指出是哪个条目、为什么,但**不替你改名或删除** |
159
+ | **被进程占用的目录**(工作目录设在里面,或里面某个文件开着) | 里面的文件可以逐个删,目录本身要等占用释放。工具会说这是占用,但**不去查是哪个进程**——那需要提权或枚举句柄,猜一个 PID 比不给更糟 |
159
160
 
160
161
  覆盖的 shell 工具名:`pwsh`、`powershell`、`cmd`、`bash`、`sh`、`zsh`、`shell`、
161
- `terminal_send`、`terminal_write`。判定看的是语句的命令词、调用的形态和程序位置,不是「这一行里出现过这个词」。
162
+ `terminal_send`、`terminal_write`。
162
163
 
163
164
  ## 测试
164
165
 
@@ -166,26 +167,21 @@ UNC 路径下不存在回收站:`SHFileOperationW` 在那里是**擦除并返
166
167
  node test/run-all.mjs
167
168
  ```
168
169
 
169
- 128 项、七层:命令分类(50)、覆盖守卫(22)、暂存删除(8)、`file_trash` 操作数守卫(15)、宿主 schema 与钩子接线(14)、
170
- 宿主 schema 受理(5)、对真实回收站的端到端(14,含真 `\\localhost\C$` 路径)。`test/` 不进 tarball,所以打包前必须
171
- 全绿;其中两层会加载宿主自己的校验器,找不到 DSH 安装时报「跳过」而非失败。
172
- 覆盖守卫那一层里,"事故命令必须被拒" 与 "42 条日常命令必须照常放行" 用的是同一份文件:
173
- 只拦住事故、却把 `npm run build` 也拒掉的规则不算修好。
170
+ 155 项、十层:命令分类(50)、覆盖守卫(30)、规则漏洞(12)、暂存删除(8)、`file_trash` 操作数守卫(15)、
171
+ 宿主 schema 与钩子接线(14)、宿主 schema 受理(5)、对真实回收站的端到端(14,含真 `\\localhost\C$` 路径)、
172
+ 失败诊断(7)。
173
+ `test/` 不进 tarball,所以打包前必须全绿;其中两层会加载宿主自己的校验器,找不到 DSH 安装时报「跳过」而非失败。
174
+ 另有一层文档检查(`scripts/verify-readme-structure.mjs`):三份 README 的章节数与表格行数必须一致。
174
175
 
175
176
  ## 文档
176
177
 
177
178
  | 文件 | 内容 |
178
179
  | --- | --- |
179
- | [CHANGELOG.md](CHANGELOG.md) | 版本摘要 |
180
+ | [CHANGELOG.md](CHANGELOG.md) | 每个版本改了什么、为什么 |
180
181
  | [SECURITY.md](SECURITY.md) | 威胁模型:策略层,不是沙箱 |
181
- | [docs/incidents/](docs/incidents/) | 事故记录:每条规则背后的实测与逐字命令(不进 npm 包,见 `files`) |
182
+ | [docs/incidents/](docs/incidents/) | 规则的实测依据与逐字命令(不进 npm 包) |
182
183
  | [LICENSE](LICENSE) | MIT |
183
184
 
184
- 事故记录留在仓库里,因为它就是规则的证据:一条规则若说不清"当初哪条命令、在什么条件下、
185
- 造成了什么后果",接手的人就只能靠猜去维护它。设计取舍、逐轮实测与发布跑批仍属维护者侧的
186
- 工程笔记,不随仓库与包发布。(2.2.0 曾把笔记整体移出仓库,起因是里面带私有主机名与 UNC
187
- 路径;记录留在仓库时按同一条标准脱敏。)
188
-
189
185
  ## 许可
190
186
 
191
187
  MIT,见 [LICENSE](LICENSE)。