dsh-delete-guard 2.4.2 → 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,69 @@ 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
+
10
73
  ## [2.4.2] — 2026-11-25
11
74
 
12
75
  **Renumbering false positives from real measurements.** The rules from 2.3.0 / 2.4.0 were
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
@@ -84,7 +80,7 @@ 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 |
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 |
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 |
88
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 |
89
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 |
90
86
 
@@ -92,9 +88,8 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
92
88
  (`Select-String -Pattern "Remove-Item"`, `Get-Content shred.exe`), **restoring**
93
89
  files out of the bin, `Add-Content` / `>>` / `-Append` (an append replaces
94
90
  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` /
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` /
98
93
  `subprocess.*` (a `bash -c` body is shell text and is judged whole).
99
94
 
100
95
  ## Two tools
@@ -122,7 +117,7 @@ block — restate every key you want to keep):
122
117
 
123
118
  ## Restoring a deleted file
124
119
 
125
- Restoring is not a plugin feature and needs none: the bin belongs to the OS.
120
+ Restoring is handled by the OS Recycle Bin.
126
121
  Explorer's right-click "Restore" works. From a script, read the
127
122
  `X:\$Recycle.Bin\<SID>\$I*` records (offset 24 = original path length in chars,
128
123
  offset 28 = UTF-16LE path), match the one you want, and `Move-Item` its paired `$R`
@@ -155,7 +150,7 @@ containing a **reparse point** (junction/symlink — a copy either duplicates th
155
150
  target's contents or needs privileges to recreate the link); **not enough free
156
151
  space** on the staging volume.
157
152
 
158
- `uncRecoverableMove: false` restores the plain refusal and deletes nothing.
153
+ `uncRecoverableMove: false` refuses a share path outright: nothing is copied and nothing is deleted.
159
154
 
160
155
  ## What it does not cover
161
156
 
@@ -168,14 +163,15 @@ space** on the staging volume.
168
163
  | A delete split across two terminal sends | Each send is judged on its own text |
169
164
  | Non-Windows platforms | The bridge is `SHFileOperationW` |
170
165
  | 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 |
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 |
172
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 |
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 |
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 |
175
172
 
176
173
  Covered shell tools: `pwsh`, `powershell`, `cmd`, `bash`, `sh`, `zsh`, `shell`,
177
- `terminal_send`, `terminal_write`. Reasoning and measurements:
178
- 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`.
179
175
 
180
176
  ## Tests
181
177
 
@@ -183,15 +179,17 @@ the decision is made on the statement's command word, the shape of the call, and
183
179
  node test/run-all.mjs
184
180
  ```
185
181
 
186
- 148 cases across eight layers: command classification (50), overwrite guard (30),
182
+ 155 cases across ten layers: command classification (50), overwrite guard (30),
187
183
  rule holes (12), share staging (8), `file_trash` operand guard (15), host schema +
188
184
  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
185
+ Recycle Bin (14, including a real `\\localhost\C$` path), failure diagnosis (7).
186
+ `test/` is not shipped in the tarball, so it
190
187
  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.
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.
195
193
 
196
194
  ## Documentation
197
195
 
@@ -199,14 +197,10 @@ is not a fix.
199
197
  | --- | --- |
200
198
  | [CHANGELOG.md](CHANGELOG.md) | Version summaries |
201
199
  | [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`) |
200
+ | [docs/incidents/](docs/incidents/) | Measured evidence behind each rule, with the verbatim command (not in the npm package) |
203
201
  | [LICENSE](LICENSE) | MIT |
204
202
 
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.
203
+
210
204
 
211
205
  ## License
212
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
@@ -81,7 +77,7 @@ 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` か検証付き一時ファイルを残す書き方は許可 |
84
- | **書き込み文に折り込まれた読み取り** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)`——1 行で読み・切り詰め・書き戻し。事故の最短表記 |
80
+ | **書き込み文に折り込まれた読み取り** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)`——1 行で読み・切り詰め・書き戻し |
85
81
  | **変数経由のシェル呼び出し** | `$shellPath='…bash.exe'; & $shellPath -c "rm -rf …"`——プログラム名がリテラルでなく、本体を判定できない |
86
82
  | **未検査のスライス端点** | 同一コマンド内でファイルを書き、かつ `$idx ± n` を端点に使う(`$l[0..($idx-2)]`、`-First ($i-1)`)。`$idx` は `$null` 検査済みでない。PowerShell はエラーにせず、`0..($null-2)` は `0..-2`(先頭行 + 末尾 2 行)になる |
87
83
 
@@ -89,7 +85,7 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
89
85
  (`Select-String -Pattern "Remove-Item"`、`Get-Content shred.exe`)、ごみ箱から
90
86
  の**復元**、`Add-Content` / `>>` / `-Append`(追記は置き換えない)、`$null` / `/dev/null`
91
87
  への書き込み、そして**`.bak` か検証付き一時ファイルを先に作る**全面書き換え
92
- (事故記録 §6 の書き方はそのまま通ります)。また `node -e` / `python -c` の本体で消去ツール名に
88
+ また `node -e` / `python -c` の本体で消去ツール名に
93
89
  **言及**しただけのテキストはプログラム名として扱いません——`exec` / `execSync` / `spawn` /
94
90
  `system` / `subprocess.*` に渡されたときだけです(`bash -c` の本体はシェルテキストなので
95
91
  全体で判定します)。
@@ -119,7 +115,7 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
119
115
 
120
116
  ## 消したファイルを戻す
121
117
 
122
- 復元はプラグインの機能ではなく、必要でもありません。ごみ箱は OS のものです。
118
+ 復元は OS のごみ箱が担います。
123
119
  エクスプローラーの右クリック「元に戻す」で戻せます。スクリプトからは
124
120
  `X:\$Recycle.Bin\<SID>\$I*` のレコードを読み(オフセット 24 が元パスの文字数、
125
121
  オフセット 28 から UTF-16LE のパス)、目的のものを探して対になる `$R` を
@@ -146,7 +142,7 @@ UNC パスにごみ箱はありません。`SHFileOperationW` はそこで**消
146
142
  複製前に拒否するもの:共有ルート(`\\host\share`)やホスト名のみの形、**リパースポイント**
147
143
  (ジャンクション/シンボリックリンク)を含むツリー、ステージング先の**空き容量不足**。
148
144
 
149
- `uncRecoverableMove: false` で 2.3.0 の拒否のみに戻り、何も削除しません。
145
+ `uncRecoverableMove: false` にすると共有パスはそのまま拒否され、複製も削除も行いません。
150
146
 
151
147
  ## 何を守らないか
152
148
 
@@ -162,7 +158,9 @@ UNC パスにごみ箱はありません。`SHFileOperationW` はそこで**消
162
158
  | **読まずに上書き**(`echo x > 既存.md`、`Invoke-WebRequest -OutFile`、`git checkout -- f`) | 意図的な書き換えであり読み書きではない。新しい内容は古い内容に依存せず、`write`/`edit` も同じことをする。すべての書き込み動詞を削除扱いにすると本プラグインが退けた過剰な規則になる |
163
159
  | 読み書きの中の**間接的な書き込み**(コンパイラ、`npm run build`、`robocopy` の成果物) | 書き込みは子プロセス内で起き、コマンドテキストに証明できる対象が無い |
164
160
  | 書き込み後のサイズ比較・ロールバック | 戻すには書き込み前のバイト列が必要で、結局は対象の列挙問題に戻る。`tools/post-execute` は結果をフィードバックに変えるだけで、切り詰めを巻き戻せない。毎回ツリーをスナップショットするのは O(ワークスペース) で、しかも UNC 上の対象は含まれない |
165
- | 共有上のものを `Move-Item` / `robocopy /MOV` で移動 | それは「移動」であり「削除」ではない。内容は移動先に残るが、共有側は完全に unlink され、ごみ箱の記録も残らない。記録を残すのは `file_trash` |
161
+ | 共有上のものを `Move-Item` / `robocopy /MOV` で移動 | 内容は移動先に残るが、共有側は完全に unlink され、ごみ箱の記録も残らない |
162
+ | **Windows が開けない名前を含むディレクトリ**(末尾が空白またはピリオド。WSL・解凍ツール・同期クライアントが残す) | Win32 はパスに書くとき末尾の文字を切り落とすため、ツリーを走査できない。どの項目がなぜ駄目かは伝えるが、**代わりに改名・削除はしない** |
163
+ | **プロセスが使用中のディレクトリ**(作業ディレクトリに設定されている、または中のファイルが開かれている) | 中のファイルは個別に消せるが、ディレクトリ本体は解放待ち。使用中であることは伝えるが、**どのプロセスかは調べない**——権限昇格かハンドル列挙が必要で、推測した PID は無いより悪いため |
166
164
 
167
165
  対象のシェルツール名:`pwsh`、`powershell`、`cmd`、`bash`、`sh`、`zsh`、`shell`、
168
166
  `terminal_send`、`terminal_write`。判定は文の命令語・呼び出しの形・プログラム位置で行い、行内に語が現れたかどうかでは見ません。
@@ -173,11 +171,13 @@ UNC パスにごみ箱はありません。`SHFileOperationW` はそこで**消
173
171
  node test/run-all.mjs
174
172
  ```
175
173
 
176
- 8 層・148 ケース:コマンド分類(50)、上書きガード(30)、規則の穴(12)、共有ステージング(8)、
174
+ 10 層・155 ケース:コマンド分類(50)、上書きガード(30)、規則の穴(12)、共有ステージング(8)、
177
175
  `file_trash` オペランドガード(15)、ホストのスキーマとフック配線(14)、ホストのスキーマ受理(5)、
178
- 実ごみ箱に対するエンドツーエンド(14、実 `\\localhost\C$` パスを含む)。`test/` は tarball に
176
+ 実ごみ箱に対するエンドツーエンド(14、実 `\\localhost\C$` パスを含む)、失敗診断(7)。`test/` は tarball に
179
177
  含まれないので、パック前に緑である必要があります。うち 2 層はホスト自身の検証器を読み込むため、
180
178
  DSH のインストールが無い環境では失敗ではなく**スキップ**として報告されます。
179
+ さらにドキュメント用の層(`scripts/verify-readme-structure.mjs`)があり、3 つの README の
180
+ 章構成と表の行数が一致していることを検査します。
181
181
 
182
182
  ## ドキュメント
183
183
 
@@ -185,12 +185,10 @@ DSH のインストールが無い環境では失敗ではなく**スキップ**
185
185
  | --- | --- |
186
186
  | [CHANGELOG.md](CHANGELOG.md) | バージョン摘要 |
187
187
  | [SECURITY.md](SECURITY.md) | 脅威モデル:サンドボックスではなくポリシー層 |
188
- | [docs/incidents/](docs/incidents/) | 事故記録:各規則の背景にある実測と逐語コマンド(npm パッケージには含まれません) |
188
+ | [docs/incidents/](docs/incidents/) | 各規則の根拠となる実測と逐語コマンド(npm パッケージには含まれません) |
189
189
  | [LICENSE](LICENSE) | MIT |
190
190
 
191
- 事故記録はリポジトリに残します。規則の根拠そのものだからです——「どのコマンドが、どんな条件で、
192
- 何を壊したか」が分からない規則は、推測でしか保守できません。設計の根拠とリリース手順は
193
- メンテナ側のノートに留め、リポジトリにもパッケージにも含めません。
191
+
194
192
 
195
193
  ## ライセンス
196
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
 
@@ -77,16 +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` = 首行 + 末两行 |
82
- | **读动词折进写语句里** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)`:一行里既读又截断再写回,是事故最紧凑的拼法 |
79
+ | **读动词折进写语句里** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)`:一行里既读、又截断、又写回 |
83
80
  | **经变量调用的 shell** | `$shellPath='…bash.exe'; & $shellPath -c "rm -rf …"`:程序名不是字面量,正文无法判定 |
84
81
 
85
82
  **放行**:只读命令、只提到删除词的操作(`Select-String -Pattern "Remove-Item"`、
86
83
  `Get-Content shred.exe`)、从回收站**还原**文件、`Add-Content` / `>>` / `-Append`
87
- (追加不替换)、写 `$null` / `/dev/null`、以及**带 `.bak` 备份或临时文件校验**的整档重写
88
- (事故记录 §6 的那套写法原样通过)。另外,`node -e` / `python -c` 体里**提到**擦除工具名的文本不算程序名——
89
- 只有把它交给 `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 文本,仍按整段判)。
90
87
 
91
88
  ## 两个工具
92
89
 
@@ -112,7 +109,7 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
112
109
 
113
110
  ## 恢复已删的文件
114
111
 
115
- 恢复不是插件的功能,也不需要——回收站是操作系统的。脚本里这样还原(与界面语言无关):
112
+ 恢复由操作系统的回收站完成。脚本里这样还原(与界面语言无关):
116
113
 
117
114
  1. 读 `X:\$Recycle.Bin\<SID>\$I*` 记录:偏移 24 是原路径字符数,偏移 28 起是 UTF-16LE 原路径;
118
115
  2. 按原路径匹配到目标条目,取配对的 `$R` 文件;
@@ -124,24 +121,24 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
124
121
 
125
122
  ## 网络共享(没有回收站)
126
123
 
127
- UNC 路径下不存在回收站:`SHFileOperationW` 在那里是**擦除并返回成功**,所以桥接会先拒绝。
128
- `file_trash` 于是做人在这种情况下的做法,一次调用完成,顺序固定:
124
+ UNC 路径下不存在回收站:`SHFileOperationW` 在那里是擦除并返回成功,所以桥接会先拒绝。
125
+ `file_trash` 于是按固定顺序处理,一次调用完成:
129
126
 
130
127
  1. 把条目复制到有回收站的本地 NTFS 卷(`%LOCALAPPDATA%\dsh-delete-guard\staging\<时间戳>-<名字>`,可用 `stagingRoot` 改);
131
128
  2. 对照原件校验:相对路径集合、条目类型、每个文件的大小;
132
129
  3. 把暂存目录送进回收站——副本这时可还原;
133
130
  4. 最后才删除原件。
134
131
 
135
- **保证的范围要说清**:可恢复的是**内容**(在本地回收站里),不是**原路径**——共享上没有回收站放它,
136
- 第 4 步就是一次普通永久删除。所以顺序本身就是安全属性:第 4 步之前的任何失败都不碰原件,第 4 步只在
137
- 桥接确认暂存副本已进回收站之后才跑。
132
+ 可恢复的是**内容**(在本地回收站里),不是**原路径**:共享上没有回收站放它,第 4 步就是一次
133
+ 普通永久删除。因此第 4 步之前的任何失败都不碰原件,而第 4 步只在桥接确认暂存副本已进回收站
134
+ 之后才执行。
138
135
 
139
- 还原时落点是暂存路径而不是原共享路径(回收站的 `$I` 记的是暂存位置),所以工具会把该路径打出来。
136
+ 还原时落点是暂存路径而不是原共享路径(回收站的 `$I` 记的是暂存位置),工具会把该路径打出来。
140
137
 
141
- 会被拒绝,且都在复制之前停住:共享根(`\\host\share`)与只有主机名的形态、树里含**重解析点**
142
- (junction/符号链接:复制要么把目标内容一起复制进来、要么需要权限重建链接)、暂存卷**空间不足**。
138
+ 以下情况在复制之前就被拒绝:共享根(`\\host\share`)与只有主机名的形态、树里含重解析点
139
+ (junction/符号链接:复制要么把目标内容一起复制进来、要么需要权限重建链接)、暂存卷空间不足。
143
140
 
144
- `uncRecoverableMove: false` 退回 2.3.0 的纯拒绝,且什么都不删。
141
+ `uncRecoverableMove: false` 时改为直接拒绝共享路径,不复制也不删除。
145
142
 
146
143
  ## 不挡什么
147
144
 
@@ -154,13 +151,15 @@ UNC 路径下不存在回收站:`SHFileOperationW` 在那里是**擦除并返
154
151
  | 终端里分两次发送才拼出的删除 | 每次 send 只看到这一次的文本 |
155
152
  | 非 Windows 平台 | 桥接是 `SHFileOperationW` |
156
153
  | 空余空间不足时的删除 | NTFS 同卷回收是 rename,不占新空间,没有可预检的东西 |
157
- | **没读过就覆盖**(`echo x > 既有文件.md`、`Invoke-WebRequest -OutFile $f`、`git checkout -- f`) | 这是「有意重写」,不是读改写:新内容不依赖旧内容,`write`/`edit` 工具也做同一件事。按动词列举覆盖写入会连构建日志、生成配置一起拒绝,正是本插件否掉的做法 |
154
+ | **没读过就覆盖**(`echo x > 既有文件.md`、`Invoke-WebRequest -OutFile $f`、`git checkout -- f`) | 新内容不依赖旧内容,不是读改写 |
158
155
  | 读改写里的**间接**写(编译器、`npm run build`、`robocopy` 覆盖产物) | 写入发生在子进程内部,命令文本里没有可判定的目标 |
159
- | 写完之后再比对体积(截断熔断) | 需要覆盖前的旧内容才能回滚:`tools/post-execute` 只能把结果改成反馈,撤不回已截断的内容;每轮 shell 调用快照整棵树是 O(工作区),而且本次事故的目标在 UNC 共享上,任何工作区快照都不包含它 |
160
- | 把共享上的东西 `Move-Item` / `robocopy /MOV` 到本地 | 那是"移动"不是"删除":内容到了目标位置,但共享上的原件被永久 unlink,没有回收站记录。要留记录就得走 `file_trash` |
156
+ | 写完之后按体积判断有没有被截断 | 回滚需要覆盖前的旧内容,而 `tools/post-execute` 只能把结果改成反馈 |
157
+ | 把共享上的东西 `Move-Item` / `robocopy /MOV` 到本地 | 内容到了目标位置,但共享上的原件被永久删除,没有回收站记录 |
158
+ | **内含非法名字的目录**(名字以空格或点结尾,再由 WSL、解压工具或同步客户端留下) | Win32 写到路径里会截掉尾随的空格/点,所以目录树走不完。工具会指出是哪个条目、为什么,但**不替你改名或删除** |
159
+ | **被进程占用的目录**(工作目录设在里面,或里面某个文件开着) | 里面的文件可以逐个删,目录本身要等占用释放。工具会说这是占用,但**不去查是哪个进程**——那需要提权或枚举句柄,猜一个 PID 比不给更糟 |
161
160
 
162
161
  覆盖的 shell 工具名:`pwsh`、`powershell`、`cmd`、`bash`、`sh`、`zsh`、`shell`、
163
- `terminal_send`、`terminal_write`。判定看的是语句的命令词、调用的形态和程序位置,不是「这一行里出现过这个词」。
162
+ `terminal_send`、`terminal_write`。
164
163
 
165
164
  ## 测试
166
165
 
@@ -168,26 +167,21 @@ UNC 路径下不存在回收站:`SHFileOperationW` 在那里是**擦除并返
168
167
  node test/run-all.mjs
169
168
  ```
170
169
 
171
- 148 项、八层:命令分类(50)、覆盖守卫(30)、规则漏洞(12)、暂存删除(8)、`file_trash` 操作数守卫(15)、
172
- 宿主 schema 与钩子接线(14)、宿主 schema 受理(5)、对真实回收站的端到端(14,含真 `\\localhost\C$` 路径)。`test/` 不进 tarball,所以打包前必须
173
- 全绿;其中两层会加载宿主自己的校验器,找不到 DSH 安装时报「跳过」而非失败。
174
- 覆盖守卫那一层里,"事故命令必须被拒" 与 "42 条日常命令必须照常放行" 用的是同一份文件:
175
- 只拦住事故、却把 `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 的章节数与表格行数必须一致。
176
175
 
177
176
  ## 文档
178
177
 
179
178
  | 文件 | 内容 |
180
179
  | --- | --- |
181
- | [CHANGELOG.md](CHANGELOG.md) | 版本摘要 |
180
+ | [CHANGELOG.md](CHANGELOG.md) | 每个版本改了什么、为什么 |
182
181
  | [SECURITY.md](SECURITY.md) | 威胁模型:策略层,不是沙箱 |
183
- | [docs/incidents/](docs/incidents/) | 事故记录:每条规则背后的实测与逐字命令(不进 npm 包,见 `files`) |
182
+ | [docs/incidents/](docs/incidents/) | 规则的实测依据与逐字命令(不进 npm 包) |
184
183
  | [LICENSE](LICENSE) | MIT |
185
184
 
186
- 事故记录留在仓库里,因为它就是规则的证据:一条规则若说不清"当初哪条命令、在什么条件下、
187
- 造成了什么后果",接手的人就只能靠猜去维护它。设计取舍、逐轮实测与发布跑批仍属维护者侧的
188
- 工程笔记,不随仓库与包发布。(2.2.0 曾把笔记整体移出仓库,起因是里面带私有主机名与 UNC
189
- 路径;记录留在仓库时按同一条标准脱敏。)
190
-
191
185
  ## 许可
192
186
 
193
187
  MIT,见 [LICENSE](LICENSE)。
package/lib/staging.js CHANGED
@@ -59,7 +59,15 @@ import { basename, join } from 'node:path';
59
59
  * @returns whether it is a UNC path.
60
60
  */
61
61
  export function isNetworkPath(p) {
62
- return /^[\\/]{2}[^\\/]/.test(String(p ?? ''));
62
+ const text = String(p ?? '');
63
+ // `\\?\C:\…` starts with two backslashes but names a local volume. Treating it as a
64
+ // share sent local paths down the staging branch — they were copied, verified and
65
+ // recycled from a staging directory instead of in place (measured 2026-11-25).
66
+ if (/^[\\/]{2}\?[\\/](?!UNC[\\/])/i.test(text)) return false;
67
+ // `\\?\UNC\host\share\…` *is* a network path; it is spelled out instead of using the
68
+ // `\\host\share` form. Strip the prefix so the share rules see what they expect.
69
+ if (/^[\\/]{2}\?[\\/]UNC[\\/]/i.test(text)) return true;
70
+ return /^[\\/]{2}[^\\/]/.test(text);
63
71
  }
64
72
 
65
73
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-delete-guard",
3
- "version": "2.4.2",
3
+ "version": "2.4.3",
4
4
  "description": "Force every DSH file deletion through the OS Recycle Bin. Intercepts shell tool calls at tools/pre-execute (pwsh, bash, cmd, the persistent terminal), rewrites destructive delete commands into a recoverable recycle-bin move (Win32 SHFileOperation / SHQueryRecycleBin), and blocks permanent-erase escapes — including content destroyed without a delete verb (in-place rewrites of the only copy, unchecked null slice endpoints). Deletions on UNC shares — which have no Recycle Bin — are staged to a local NTFS volume, verified, and recycled from there before the original is removed.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -87,9 +87,33 @@ function Write-Json {
87
87
  }
88
88
 
89
89
  function Resolve-NormalizedPath {
90
- <# Resolve to an absolute path without requiring existence. #>
90
+ <#
91
+ Resolve to an absolute path without requiring existence, and drop a literal
92
+ `\\?\` prefix.
93
+
94
+ The prefix has one legitimate use — naming a path longer than MAX_PATH, or one
95
+ whose name Win32 would otherwise trim — and callers do hand it over. But
96
+ SHFileOperationW does not accept it: measured 2026-11-25, a `\\?\`-prefixed
97
+ file returns 0x7C (DE_INVALIDFILES) where the same file without the prefix
98
+ recycles. And a path over 260 characters recycles fine *without* the prefix, so
99
+ stripping loses nothing.
100
+
101
+ Left in place, the prefix was worse than useless: Test-RecyclableVolume matched
102
+ `\\*` and reported "a network location has no Recycle Bin" for a local path.
103
+
104
+ `\\?\UNC\host\share\x` becomes the ordinary UNC spelling, which is then judged
105
+ as the network location it is.
106
+ #>
91
107
  param([Parameter(Mandatory)][string] $Path)
92
- $expanded = [Environment]::ExpandEnvironmentVariables($Path)
108
+
109
+ $text = $Path
110
+ if ($text.StartsWith('\\?\UNC\', [System.StringComparison]::OrdinalIgnoreCase)) {
111
+ $text = '\\' + $text.Substring(8)
112
+ } elseif ($text.StartsWith('\\?\', [System.StringComparison]::Ordinal)) {
113
+ $text = $text.Substring(4)
114
+ }
115
+
116
+ $expanded = [Environment]::ExpandEnvironmentVariables($text)
93
117
  $full = [System.IO.Path]::GetFullPath($expanded)
94
118
  # GetFullPath keeps a trailing separator on directories; SHFileOperationW
95
119
  # requires a double-null terminated list and tolerates either form, but a
@@ -112,13 +136,22 @@ function Get-DriveRoot {
112
136
  # --- Operations --------------------------------------------------------------
113
137
 
114
138
  function Get-ShFileOperationMessage {
115
- <# Map the documented SHFileOperation error codes to something readable. #>
139
+ <#
140
+ Map the documented SHFileOperation error codes to something readable.
141
+
142
+ 0x2 is deliberately **not** "the path no longer exists": measured 2026-11-25, a
143
+ directory whose contents include a name Win32 cannot address returns 0x2 while
144
+ the path is right there. The code means "one of the files it needed was not
145
+ found", and Get-FailureDiagnosis appends which one. The wording below says only
146
+ what the code supports.
147
+ #>
116
148
  param([Parameter(Mandatory)][int] $Code)
117
149
  # A bare `switch` statement with explicit `return`s: `return switch (...) { ... }`
118
150
  # is a parse error on this pwsh build ("unexpected token '{'").
119
151
  switch ($Code) {
120
- 0x2 { return 'The path no longer exists.' }
121
- 0x3 { return 'The directory does not exist.' }
152
+ 0x2 { return 'A file in that path could not be found.' }
153
+ 0x3 { return 'A directory in that path could not be found.' }
154
+ 0x20 { return 'Access is denied.' }
122
155
  0x71 { return 'The source and destination are the same.' }
123
156
  0x72 { return 'The operation was cancelled.' }
124
157
  0x74 { return 'The path is too long.' }
@@ -127,6 +160,7 @@ function Get-ShFileOperationMessage {
127
160
  0x78 { return 'Access was denied.' }
128
161
  0x79 { return 'The operation was aborted.' }
129
162
  0x7A { return 'The source is in use by another process.' }
163
+ 0x7B { return 'The path is invalid.' }
130
164
  0x7C { return 'The path is invalid.' }
131
165
  default { return ("SHFileOperationW failed with code 0x{0:X}" -f $Code) }
132
166
  }
@@ -161,6 +195,146 @@ function Test-RecyclableVolume {
161
195
  return "Volume $root has no Recycle Bin (file system: $shown), so recycling here would erase the item permanently. Move it to an NTFS volume first, or delete it from Explorer where Windows can warn the user."
162
196
  }
163
197
 
198
+ function Get-NamesWin32CannotAddress {
199
+ <#
200
+ Find entries whose name Windows will not resolve when handed as a path.
201
+
202
+ A name ending in a space or a dot can exist on NTFS — WSL, a zip extractor, a
203
+ sync client or a port of a POSIX tool can create it — but Win32 trims those
204
+ trailing characters when the name is written into a path, so `Open` looks for a
205
+ name that is not there. That is why a directory holding such a child cannot be
206
+ recycled as a whole: SHFileOperationW walks the tree, the child's own open fails
207
+ with ERROR_FILE_NOT_FOUND, and the whole operation returns 0x2 even though the
208
+ path plainly exists.
209
+
210
+ The listing itself has to go through `\\?\` — that prefix is the only spelling in
211
+ which the name is taken literally. The prefix is used *here and only here*, to
212
+ read names; SHFileOperationW is never handed one (it returns 0x7C for those).
213
+
214
+ Returns up to `Limit` offending entries as `relative/path` strings, each with a
215
+ reason, so the message can name them.
216
+ #>
217
+ param(
218
+ [Parameter(Mandatory)][string] $Path,
219
+ [int] $Limit = 8
220
+ )
221
+
222
+ if (-not (Test-Path -LiteralPath $Path -PathType Container)) { return @() }
223
+
224
+ $found = [System.Collections.Generic.List[object]]::new()
225
+ $queue = [System.Collections.Generic.Queue[string]]::new()
226
+ $queue.Enqueue($Path)
227
+
228
+ while ($queue.Count -gt 0 -and $found.Count -lt $Limit) {
229
+ $current = $queue.Dequeue()
230
+
231
+ # Listing through the literal prefix, so a malformed name is returned as itself
232
+ # instead of being silently trimmed to a sibling that may not exist.
233
+ $literal = if ($current.StartsWith('\\')) { '\\?\UNC\' + $current.Substring(2) } else { '\\?\' + $current }
234
+ $entries = $null
235
+ try {
236
+ $entries = [System.IO.Directory]::GetFileSystemEntries($literal)
237
+ } catch {
238
+ # A tree we cannot enumerate is not this diagnostic's problem; the caller
239
+ # still reports the original failure.
240
+ return $found
241
+ }
242
+
243
+ foreach ($entry in $entries) {
244
+ if ($found.Count -ge $Limit) { break }
245
+
246
+ # The literal listing returns names with the prefix attached.
247
+ $name = [System.IO.Path]::GetFileName($entry)
248
+ $reason = $null
249
+ if ($name.EndsWith(' ')) { $reason = 'ends with a space' }
250
+ elseif ($name.EndsWith('.')) { $reason = 'ends with a dot' }
251
+ elseif ($name -match '[\x00-\x1F]') { $reason = 'contains a control character' }
252
+
253
+ if ($null -ne $reason) {
254
+ $relative = $entry
255
+ foreach ($prefix in @('\\?\UNC\', '\\?\')) {
256
+ if ($relative.StartsWith($prefix, [System.StringComparison]::Ordinal)) {
257
+ $relative = $relative.Substring($prefix.Length)
258
+ break
259
+ }
260
+ }
261
+ $found.Add([pscustomobject]@{ path = $relative; reason = $reason })
262
+ }
263
+
264
+ $isDirectory = $false
265
+ try { $isDirectory = [System.IO.Directory]::Exists($entry) } catch { $isDirectory = $false }
266
+ if ($isDirectory -and -not ($name.EndsWith(' ') -or $name.EndsWith('.'))) {
267
+ $queue.Enqueue($entry)
268
+ }
269
+ }
270
+ }
271
+
272
+ return $found.ToArray()
273
+ }
274
+
275
+ function Get-FailureDiagnosis {
276
+ <#
277
+ Turn a bare SHFileOperation failure into something a caller can act on.
278
+
279
+ Measured 2026-11-25. Two failures are worth diagnosing, because both used to
280
+ produce a message that pointed the caller at the wrong thing:
281
+
282
+ 0x2 DE_FILENOTFOUND — the message said "the path no longer exists" while the
283
+ path was right there. The real cause was a child whose name Win32 cannot
284
+ address (trims a trailing space or dot), so the tree could not be walked.
285
+ 0x20 DE_ACCESSDENIED — a directory held as some process's working directory, or
286
+ an open file inside it. Every file inside can be deleted; the directory
287
+ itself cannot, and the shell reports access denied with no hint of who holds
288
+ it. Enumerating handles needs elevation, so this reports what is observable
289
+ and says so rather than guessing a PID.
290
+
291
+ Returns extra text to append to the message, or $null.
292
+ #>
293
+ param(
294
+ [Parameter(Mandatory)][int] $Code,
295
+ [Parameter(Mandatory)][string] $Path
296
+ )
297
+
298
+ $exists = $false
299
+ try { $exists = Test-Path -LiteralPath $Path } catch { $exists = $false }
300
+
301
+ if ($Code -eq 0x2) {
302
+ if (-not $exists) {
303
+ return 'The path is not there now — something else removed it between the check and the call.'
304
+ }
305
+ $bad = Get-NamesWin32CannotAddress -Path $Path
306
+ if ($bad.Count -eq 0) {
307
+ return $null
308
+ }
309
+ $shown = ($bad | ForEach-Object { "$($_.path) ($($_.reason))" }) -join '; '
310
+ $more = if ($bad.Count -ge 8) { ' (listing stopped at 8)' } else { '' }
311
+ # One expression, not several lines joined with `+`: a `return` ends the
312
+ # statement at the line break, so a trailing `+` continuation would return
313
+ # only the first fragment and silently drop the rest.
314
+ $text = "The path exists, but it contains entries Windows cannot open by name: $shown$more. "
315
+ $text += 'Win32 trims a trailing space or dot when a name is written into a path, so the tree cannot be walked. '
316
+ $text += 'Renaming those entries to names without a trailing space or dot makes the directory recyclable; '
317
+ $text += 'they are usually left by WSL, an archive extractor or a sync client. '
318
+ $text += 'This tool does not rename or delete inside a directory it was asked to delete.'
319
+ return $text
320
+ }
321
+
322
+ if ($Code -eq 0x20 -or $Code -eq 0x78 -or $Code -eq 0x7A) {
323
+ if (-not $exists) { return $null }
324
+ # The base message already says "access is denied"; start from the meaning.
325
+ $text = 'For a directory this usually means a process is using it: its working directory is set '
326
+ $text += 'to this path, or it holds one of the files inside open. Every file inside can still be '
327
+ $text += 'deleted individually; the directory itself cannot until that process lets go. '
328
+ $text += 'This tool does not enumerate which process holds it — that needs elevation or handle-scanning, '
329
+ $text += 'and it will not guess. If you need the holder, check for a process started in this directory '
330
+ $text += '(a Python environment, a build or a shell whose cwd is here), or retry after it exits.'
331
+ return $text
332
+ }
333
+
334
+ return $null
335
+ }
336
+
337
+
164
338
  function Invoke-RecycleOne {
165
339
  <#
166
340
  Recycle a single path.
@@ -190,7 +364,12 @@ function Invoke-RecycleOne {
190
364
  )
191
365
 
192
366
  $rc = [RecycleBinNative]::SHFileOperationW([ref]$op)
193
- if ($rc -ne 0) { return (Get-ShFileOperationMessage -Code $rc) }
367
+ if ($rc -ne 0) {
368
+ $message = Get-ShFileOperationMessage -Code $rc
369
+ $diagnosis = Get-FailureDiagnosis -Code $rc -Path $Path
370
+ if ($null -ne $diagnosis) { return "$message $diagnosis" }
371
+ return $message
372
+ }
194
373
  if ($op.fAnyOperationsAborted) { return 'The shell aborted the move to the Recycle Bin.' }
195
374
  # The call reports success for the whole request; confirm this path actually left.
196
375
  if (Test-Path -LiteralPath $Path) { return 'The path still exists after the recycle operation.' }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Structural check for the three READMEs.
3
+ *
4
+ * `README.md` / `README.en.md` / `README.ja.md` are the same document in three
5
+ * languages. Editing one and forgetting another does not show up in a diff — the
6
+ * wording differs anyway — so the check is on structure: the same sections, the same
7
+ * number of table rows, one H1.
8
+ *
9
+ * This exists because a previous README rewrite silently duplicated each file inside
10
+ * itself (a `String.replace` replacement string contained `$`, which JavaScript
11
+ * expanded). Counting H1s was what found it; the numbers below are what the fix has
12
+ * to keep matching.
13
+ *
14
+ * Run: node scripts/verify-readme-structure.mjs
15
+ * Exit code 1 when the three files disagree or a file has more than one H1.
16
+ */
17
+
18
+ import { readFileSync } from 'node:fs';
19
+ import { dirname, join } from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+
22
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
23
+ const FILES = ['README.md', 'README.en.md', 'README.ja.md'];
24
+
25
+ /**
26
+ * Measure the structural facts that must agree across the three files.
27
+ *
28
+ * Headings are counted **outside code fences only**: a Markdown block that shows a
29
+ * shell command can contain `# comment` lines, and an early version of this script
30
+ * reported five H1s because of them. Counting inside fences would flag every README
31
+ * that documents a PowerShell snippet.
32
+ *
33
+ * @param text - the file's contents.
34
+ * @returns the counts and the section headings, in order.
35
+ */
36
+ function measure(text) {
37
+ const lines = text.split(/\r?\n/);
38
+ let inFence = false;
39
+ let h1 = 0;
40
+ const h2 = [];
41
+ let tableRows = 0;
42
+ let codeFences = 0;
43
+
44
+ for (const line of lines) {
45
+ if (/^```/.test(line)) {
46
+ inFence = !inFence;
47
+ codeFences += 1;
48
+ continue;
49
+ }
50
+ if (inFence) continue;
51
+ if (/^# /.test(line)) h1 += 1;
52
+ const section = /^## (.+)$/.exec(line);
53
+ if (section !== null) h2.push(section[1].trim());
54
+ if (/^\| /.test(line)) tableRows += 1;
55
+ }
56
+ return { h1, h2Count: h2.length, h2, tableRows, codeFences };
57
+ }
58
+
59
+ const measured = FILES.map((name) => ({ name, ...measure(readFileSync(join(ROOT, name), 'utf8')) }));
60
+
61
+ let failed = false;
62
+ const base = measured[0];
63
+
64
+ for (const m of measured) {
65
+ const problems = [];
66
+ if (m.h1 !== 1) problems.push(`H1 count is ${m.h1}, expected 1`);
67
+ if (m.h2Count !== base.h2Count) problems.push(`H2 count ${m.h2Count}, ${base.name} has ${base.h2Count}`);
68
+ if (m.tableRows !== base.tableRows) problems.push(`table rows ${m.tableRows}, ${base.name} has ${base.tableRows}`);
69
+ if (m.codeFences % 2 !== 0) problems.push(`odd number of code fences (${m.codeFences}) — an unclosed block`);
70
+
71
+ const status = problems.length === 0 ? 'ok ' : 'FAIL';
72
+ if (problems.length > 0) failed = true;
73
+ console.log(`${status} ${m.name.padEnd(14)} H1=${m.h1} H2=${m.h2Count} rows=${m.tableRows} fences=${m.codeFences}`);
74
+ for (const p of problems) console.log(` ${p}`);
75
+ }
76
+
77
+ // Section titles differ by language, so only the position and count are comparable.
78
+ // Print them side by side anyway: a missing section is easier to spot by name.
79
+ const width = Math.max(...measured.map((m) => m.h2.length));
80
+ console.log('\nsections by position:');
81
+ for (let i = 0; i < width; i += 1) {
82
+ const row = measured.map((m) => (m.h2[i] ?? '(none)').slice(0, 34).padEnd(36)).join('');
83
+ console.log(' ' + row);
84
+ }
85
+
86
+ if (failed) {
87
+ console.error('\nREADME structure differs between languages, or a file has a stray H1.');
88
+ process.exit(1);
89
+ }
90
+ console.log('\nthree READMEs are structurally identical');