dsh-delete-guard 2.2.3 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,925 @@
1
+ /**
2
+ * The overwrite guard: content destroyed without a delete verb.
3
+ *
4
+ * `guard.js` polices commands that *name* a delete. The 2026-11-14 incident named
5
+ * none: `Get-Content $f` … `Set-Content -LiteralPath $f` replaced a 605-line
6
+ * ledger with 24 lines, and every rule in `guard.js` was correctly silent —
7
+ * there was no delete verb, no erase API, no script file. What was destroyed was
8
+ * not a file but the file's *content*, in place, with no other copy anywhere.
9
+ *
10
+ * Two things follow from that, and they decide the shape of this module.
11
+ *
12
+ * 1. "Route it to the Recycle Bin" — the remedy every other rule ends with — is
13
+ * not available here. The target lived on a UNC share, and
14
+ * `scripts/recycle-bin.ps1` refuses those on purpose: `SHFileOperationW`
15
+ * erases there and reports success. So a rule of the form "recycle the old
16
+ * copy before the write" (proposed as R1 in the incident record) would have
17
+ * been a no-op exactly on the case that motivated it, and would still fail
18
+ * wherever the bin has no store. Prevention has to happen before the write,
19
+ * and recovery has to come from a copy the *command itself* makes.
20
+ *
21
+ * 2. The signal cannot be a verb list. Enumerating write verbs
22
+ * (`Set-Content`/`Out-File`/`Copy-Item -Force`/`>`/…) re-creates, one
23
+ * vocabulary later, the blind spot that made this incident invisible:
24
+ * `Export-Csv`, `[IO.File]::WriteAllText`, `sed -i`, `tee`, `dd of=`, `cp`,
25
+ * `truncate`, a compiler writing over its own output … any list is incomplete,
26
+ * and a guard that reads as complete but is not is worse than one that states
27
+ * its scope. So this module does not ask "is this a write verb?" and neither
28
+ * does it ask "did the file get smaller?" (see below). It asks two narrower
29
+ * questions whose answers are provable from the text.
30
+ *
31
+ * Rule 1 — in-place rewrite. The same file is read *and* written by one command:
32
+ * `Get-Content f | Set-Content f`, `sed -i f`, `cat f > f`. The new content is
33
+ * derived from the only copy, so a wrong slice, a wrong filter or a failing
34
+ * redirect leaves nothing to restore from. Refused unless the command itself
35
+ * makes a copy (`.bak`, a temp file it then verifies) — which is also the exact
36
+ * workflow the incident's own §6 recommends, so the safe spelling is allowed
37
+ * untouched.
38
+ *
39
+ * Rule 2 — unchecked slice endpoint. A range/slice whose endpoint is `<var> ± n`
40
+ * and whose variable is never checked for `$null`, in a command that also writes
41
+ * a file. In PowerShell `$lines[0..($null-2)]` is `$lines[0..-2]`, which is
42
+ * `$lines[0,-1,-2]`: first line plus the last two (measured on pwsh 7: a
43
+ * 10-element array yields `L1,L10,L9`). No error, no warning — a 605-line ledger
44
+ * becomes 3 kept lines, and the write then saves that.
45
+ *
46
+ * Both rules require the *write* half on purpose. A read-only command that slices
47
+ * wrongly prints wrong text — that is how the incident was noticed, and it loses
48
+ * nothing. Refusing it would cost the model a round trip and protect nothing, so
49
+ * a buggy slice with no write in the same command stays allowed.
50
+ *
51
+ * What this module deliberately does not do
52
+ * ----------------------------------------
53
+ * - No post-hoc size comparison. "Refuse the write if the file shrank" needs the
54
+ * old content to restore, and a `tools/post-execute` hook cannot roll anything
55
+ * back: `PostToolDecision.block` only turns the result into feedback, after the
56
+ * truncation already happened. Taking the copy up front needs the target set,
57
+ * which is the enumeration problem again; snapshotting a whole tree per shell
58
+ * call is O(workspace) — and would still miss the incident's file, which was on
59
+ * a UNC share outside every workspace root.
60
+ * - No I/O. Pure function of the command text, like `guard.js`, so it is unit
61
+ * testable and cannot fail halfway through a decision.
62
+ * - No `ask` decision. In an auto-approving deployment (this machine: approval
63
+ * policy `never`) `ask` resolves to allow in the same tick, which would make
64
+ * the rule look present and do nothing. Deny-with-a-recipe is the shape that
65
+ * stays honest whether or not a human is watching.
66
+ */
67
+
68
+ import { commandWord, statementTokens, unquote } from './shell-text.js';
69
+
70
+ /**
71
+ * Verbs that replace a file's content. Targets are read the same way
72
+ * `parseDeleteStatement` reads delete operands: `-Path` / `-LiteralPath` /
73
+ * `-FilePath` name the target, otherwise it is the first positional argument.
74
+ *
75
+ * `copy`/`move` are here because they destroy an existing destination; `tee`,
76
+ * `dd`, `truncate` cover the bash side. `dd` names its target as `of=`.
77
+ */
78
+ const WRITE_COMMANDS = new Set([
79
+ 'set-content',
80
+ 'clear-content',
81
+ 'out-file',
82
+ 'tee-object',
83
+ 'export-csv',
84
+ 'export-clixml',
85
+ 'set-item',
86
+ 'new-item',
87
+ 'copy-item',
88
+ 'move-item',
89
+ 'rename-item',
90
+ 'tee',
91
+ 'truncate',
92
+ 'cp',
93
+ 'copy',
94
+ 'mv',
95
+ 'move',
96
+ 'dd',
97
+ ]);
98
+
99
+ /**
100
+ * Flags whose *value* is the file being written.
101
+ * `-Destination`/`-NewName` are how `Copy-Item`/`Move-Item`/`Rename-Item` name
102
+ * the path that gets destroyed.
103
+ */
104
+ const WRITE_PATH_FLAGS = new Set([
105
+ '-path',
106
+ '-literalpath',
107
+ '-filepath',
108
+ '-pspath',
109
+ '-destination',
110
+ '-newname',
111
+ ]);
112
+
113
+ /**
114
+ * Flags that consume the next token as a value without it being a target.
115
+ * Without this, `Set-Content -Encoding UTF8 $f` would read `UTF8` as the file.
116
+ */
117
+ const WRITE_VALUE_FLAGS = new Set([
118
+ '-value',
119
+ '-encoding',
120
+ '-delimiter',
121
+ '-width',
122
+ '-inputobject',
123
+ '-stream',
124
+ '-filter',
125
+ '-include',
126
+ '-exclude',
127
+ '-credential',
128
+ '-erroraction',
129
+ '-ea',
130
+ '-errorvariable',
131
+ '-ev',
132
+ '-warningaction',
133
+ '-wa',
134
+ '-informationaction',
135
+ '-infa',
136
+ '-outbuffer',
137
+ '-ob',
138
+ '-outvariable',
139
+ '-ov',
140
+ '-pipelinevariable',
141
+ '-pv',
142
+ ]);
143
+
144
+ /**
145
+ * Verbs that read a file's content. `skip` counts leading positionals that are
146
+ * not paths (`grep <pattern> <file>`, `Select-String <pattern> <file>`,
147
+ * `awk <program> <file>`); `last` marks the tools whose *last* positional is the
148
+ * file (`sed 's/a/b/' <file>`).
149
+ */
150
+ const READ_COMMANDS = new Map([
151
+ ['get-content', { skip: 0 }],
152
+ ['gc', { skip: 0 }],
153
+ ['type', { skip: 0 }],
154
+ ['import-csv', { skip: 0 }],
155
+ ['import-clixml', { skip: 0 }],
156
+ // `Select-String <pattern> <file>`: the pattern is the first positional. But the
157
+ // commonest spelling names the file with `-Path`, and `argumentsOf` already lifted
158
+ // that value into the positional list — so `skip: 1` ate the path and
159
+ // `Select-String -Path a.md -Pattern x | Set-Content a.md` was allowed
160
+ // (measured 2026-11-25). Matching the path flag explicitly avoids that.
161
+ ['select-string', { skip: 0, pathFlag: true }],
162
+ ['cat', { skip: 0 }],
163
+ ['head', { skip: 0 }],
164
+ ['tail', { skip: 0 }],
165
+ ['more', { skip: 0 }],
166
+ ['less', { skip: 0 }],
167
+ ['grep', { skip: 1 }],
168
+ ['awk', { skip: 1 }],
169
+ ['sort', { skip: 0 }],
170
+ ['uniq', { skip: 0 }],
171
+ ['sed', { last: true }],
172
+ ['perl', { last: true }],
173
+ ]);
174
+
175
+ /**
176
+ * .NET content calls, read and write, matched by member name.
177
+ * `[IO.File]::WriteAllText(path, text)` destroys the old content;
178
+ * `::ReadAllText(path)` reads it. Argument 0 is the path in both.
179
+ */
180
+ const DOTNET_READ = /::\s*(?:ReadAllText|ReadAllLines|ReadAllBytes|OpenRead|OpenText)\s*\(\s*([^,)]+)/gi;
181
+ const DOTNET_WRITE = /::\s*(?:WriteAllText|WriteAllLines|WriteAllBytes|CreateText|Create|AppendAllText|AppendAllLines)\s*\(\s*([^,)]+)/gi;
182
+
183
+ /**
184
+ * A copy of the target made by the command itself, or a temp-then-replace step:
185
+ * either way the old content survives somewhere before the write. This is the
186
+ * escape hatch, and it is deliberately textual — the guard cannot run the
187
+ * command to find out.
188
+ *
189
+ * Note: these are only consulted **per statement and before the overwrite** (see
190
+ * `hasCopyStepFor`). A bare textual hit anywhere in the command is not evidence —
191
+ * a trailing comment or a bystander string used to be enough to exempt a real
192
+ * in-place rewrite.
193
+ */
194
+ const BACKUP_MARKER = /\.(?:bak|backup|orig|old)\b|(?:^|[\\/\s'"`-])bak[-_.\d]/i;
195
+ const TEMP_MARKER = /\$env:(?:TEMP|TMP)\b|%TEMP%|%TMP%|New-TemporaryFile|\/tmp\/|[\\/]Temp[\\/]/i;
196
+
197
+ /**
198
+ * A statement that writes somewhere: a write verb, a copy verb, or a redirect.
199
+ * Used together with {@link BACKUP_MARKER} / {@link TEMP_MARKER} to decide whether
200
+ * a statement is the copy step itself rather than merely mentioning a backup name.
201
+ */
202
+ const COPY_DESTINATION =
203
+ /\b(?:Set-Content|Out-File|Add-Content|Tee-Object|Copy-Item|Move-Item|cp|mv|move|New-Item)\b|>{1}(?!>)/i;
204
+
205
+ /**
206
+ * Read verbs, matched **anywhere inside a statement**, not just as its first word.
207
+ *
208
+ * `Set-Content $f (Get-Content $f | Select-Object -First 10)` reads and truncates
209
+ * `$f` in one line — the most compact spelling of the 2026-11-14 incident. Until
210
+ * 2026-11-25 `readTargets` only looked at the statement's head, so every such form
211
+ * was allowed (four measured variants, all `allow`).
212
+ */
213
+ const NESTED_READ = /\b(?:Get-Content|ReadAllText|ReadAllLines|ReadAllBytes|Import-Csv|Import-Clixml|Select-String|Get-Item|OpenText|OpenRead)\s*\(?\s*([^\s)|,;]+)/gi;
214
+
215
+ /**
216
+ * Slice endpoints whose value can be `$null` and which are then offset by
217
+ * arithmetic: `$idx - 2`. The `±` is what makes the failure silent rather than
218
+ * loud — `$null` itself indexes the last element, it does not throw.
219
+ */
220
+ const OFFSET_ENDPOINT = /\$\{?([A-Za-z_][\w:]*)\}?\s*[-+]\s*\d/;
221
+
222
+ /** The same hazard in the parameter forms that take a count. */
223
+ const COUNT_ARG =
224
+ /(?:-first|-skip|-last|\.substring\s*\(|\.remove\s*\()\s*\(?\s*\$\{?([A-Za-z_][\w:]*)\}?\s*[-+]/gi;
225
+
226
+ /** `.Count` / `Measure-Object` are 0 for an empty result, never `$null`. */
227
+ const SAFE_PROVENANCE = /\.count\b|\bmeasure-object\b|^\s*-?\d+\s*$/i;
228
+
229
+ /**
230
+ * Normalize a path for comparison: separators, case, trailing separator.
231
+ * Windows paths are case-insensitive, so `C:\Tmp\A.md` and `c:/tmp/a.md` are the
232
+ * same file and must compare equal, or the rule misses the plainest spelling.
233
+ * @param p - the path text.
234
+ * @returns the comparison key.
235
+ */
236
+ function pathKey(p) {
237
+ return p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
238
+ }
239
+
240
+ /**
241
+ * Remove the grouping punctuation a statement's own wrapper leaves on an operand:
242
+ * `(Get-Content $f)` tokenizes to `['(Get-Content', '$f)']`, and `$f)` is the same
243
+ * file as `$f`. Without this the read side is unkeyed and a piped in-place rewrite
244
+ * — the commonest spelling of the hazard — goes unseen.
245
+ *
246
+ * @param expr - the operand as written.
247
+ * @returns the operand without leading/trailing brackets.
248
+ */
249
+ function cleanOperand(expr) {
250
+ let t = String(expr ?? '').trim();
251
+ for (let i = 0; i < 2; i += 1) {
252
+ t = t.replace(/^[({\[]+/, '').replace(/[)}\]]+$/, '');
253
+ }
254
+ return t;
255
+ }
256
+
257
+ /**
258
+ * The comparison keys for one operand expression.
259
+ *
260
+ * A variable contributes two keys — its own name, and (when the command itself
261
+ * assigns it a literal) the path it holds — so `Get-Content $f` matches both
262
+ * `Set-Content $f` and `Set-Content 'C:\x\a.md'`. An interpolated string
263
+ * (`"$f.bak"`) contributes none: its value is not knowable here, and a wrong
264
+ * match would name a file the command never touches.
265
+ *
266
+ * @param expr - the operand as written.
267
+ * @param literals - variable name → literal path, from this command's assignments.
268
+ * @returns the keys, possibly empty.
269
+ */
270
+ function exprKeys(expr, literals) {
271
+ const t = cleanOperand(unquote(String(expr ?? '').trim()));
272
+ if (t.length === 0) return [];
273
+ const variable = /^\$\{?([A-Za-z_][\w:]*)\}?$/.exec(t);
274
+ if (variable !== null) {
275
+ const name = variable[1].toLowerCase();
276
+ const keys = [`var:${name}`];
277
+ const literal = literals.get(name);
278
+ if (literal !== undefined) keys.push(`lit:${pathKey(literal)}`);
279
+ return keys;
280
+ }
281
+ if (t.includes('$') || t.includes('%')) return [];
282
+ return [`lit:${pathKey(t)}`];
283
+ }
284
+
285
+ /**
286
+ * Record `$v = <literal>` assignments, which is how a command usually names the
287
+ * file it is about to destroy (`$f = '…\台账.md'`; `Set-Content -LiteralPath $f`).
288
+ *
289
+ * Only single-literal right-hand sides are recorded. Anything else stays
290
+ * unresolved — the operand key then remains `var:<name>`, which still matches the
291
+ * read side when both sides use the same variable, and that is the common case.
292
+ *
293
+ * @param statements - the statements of one command.
294
+ * @returns variable name → literal text.
295
+ */
296
+ function collectLiterals(statements) {
297
+ const literals = new Map();
298
+ for (const statement of statements) {
299
+ const assign = /^\s*\$\{?([A-Za-z_][\w:]*)\}?\s*=\s*(.+?)\s*$/.exec(statement);
300
+ if (assign === null) continue;
301
+ const name = assign[1].toLowerCase();
302
+ const value = unquote(assign[2]);
303
+ if (value.length === 0 || value.includes('$')) continue;
304
+ if (/[;(){}|]/.test(value)) continue;
305
+ literals.set(name, value);
306
+ }
307
+ return literals;
308
+ }
309
+
310
+ /**
311
+ * Record how a variable's value was produced, for the `$null` question.
312
+ *
313
+ * `$idx = (… | Select-Object -First 1).LineNumber` is `$null` when the pattern
314
+ * matches nothing; `$n = $lines.Count` is `0`. Only the second is safe to offset.
315
+ * Anything not visible in the command counts as unproven — the guard refuses what
316
+ * it cannot check, and this rule additionally requires a file write in the same
317
+ * command, so "unproven" is affordable here.
318
+ *
319
+ * @param statements - the statements of one command.
320
+ * @returns variable name → whether its provenance proves a non-null value.
321
+ */
322
+ function collectProvenance(statements) {
323
+ const safe = new Map();
324
+ for (const statement of statements) {
325
+ const assign = /^\s*\$\{?([A-Za-z_][\w:]*)\}?\s*=\s*(.+?)\s*$/.exec(statement);
326
+ if (assign === null) continue;
327
+ const name = assign[1].toLowerCase();
328
+ const provenSafe = SAFE_PROVENANCE.test(assign[2]);
329
+ // Any unsafe assignment outweighs a safe one: the loop may take either path.
330
+ safe.set(name, provenSafe && (safe.get(name) ?? true));
331
+ }
332
+ return safe;
333
+ }
334
+
335
+ /**
336
+ * Split a token that carries a `>` redirect into the part before it and the target
337
+ * after it: `f.txt>f.txt` → `{ before: 'f.txt', after: 'f.txt' }`, `2>$null` →
338
+ * `{ before: '', after: '$null' }`, `>out.md` → `{ before: '', after: 'out.md' }`.
339
+ *
340
+ * `>>` (append) never matches — the character class cannot span two `>`s — which
341
+ * is the desired outcome: an append destroys nothing.
342
+ *
343
+ * @param tok - one token.
344
+ * @returns the split, or `undefined` when the token carries no redirect.
345
+ */
346
+ function splitRedirect(tok) {
347
+ const match = /^([^\s>]*)>([^\s>]*)$/.exec(tok);
348
+ if (match === null) return undefined;
349
+ const before = /^(?:\d+|\*)$/.test(match[1]) ? '' : match[1];
350
+ return { before, after: match[2] };
351
+ }
352
+
353
+ /**
354
+ * The file expressions one statement writes.
355
+ *
356
+ * `Add-Content` never appears here: it is the one write that does not replace
357
+ * anything. `Set-Content -Append` and `>>` are treated the same way. Writing to
358
+ * the null device (`$null`, `NUL`, `/dev/null`) is still collected here and
359
+ * discarded by the caller, because that decision belongs with the comparison, not
360
+ * with the parsing.
361
+ *
362
+ * @param statement - one statement.
363
+ * @returns the operands being written.
364
+ */
365
+ function writtenTargets(statement) {
366
+ const tokens = statementTokens(statement);
367
+ if (tokens.length === 0) return [];
368
+ const targets = [];
369
+
370
+ // Redirection: `> f`, `>f`, `f>f`, `2> f`. `>>` appends, so it is not a rewrite;
371
+ // `splitRedirect` cannot span two `>`s, which is what makes that automatic.
372
+ for (let i = 0; i < tokens.length; i += 1) {
373
+ const tok = tokens[i];
374
+ if (tok === '>') {
375
+ if (tokens[i + 1] !== undefined) targets.push(tokens[i + 1]);
376
+ continue;
377
+ }
378
+ const redirect = splitRedirect(tok);
379
+ if (redirect !== undefined && redirect.after.length > 0) targets.push(redirect.after);
380
+ }
381
+
382
+ const verb = commandWord(statement).toLowerCase().replace(/\.(?:exe|cmd|bat)$/, '');
383
+ if (verb === 'dd') {
384
+ for (const tok of tokens) {
385
+ const of = /^of=(.+)$/i.exec(tok);
386
+ if (of !== null) targets.push(of[1]);
387
+ }
388
+ return targets;
389
+ }
390
+
391
+ // In-place editors: `sed -i`, `sed -i.bak`, `perl -pi`, `perl -i`. The file is
392
+ // read and rewritten in one step by definition, which is rule 1's exact shape.
393
+ if (verb === 'sed' || verb === 'perl') {
394
+ if (tokens.some((t) => /^-[a-z]*i/.test(t))) {
395
+ const positionals = argumentsOf(tokens);
396
+ if (positionals.length > 0) targets.push(positionals[positionals.length - 1]);
397
+ }
398
+ return targets;
399
+ }
400
+
401
+ if (!WRITE_COMMANDS.has(verb)) return targets;
402
+
403
+ // `Set-Content -Append` / `Export-Csv -Append` add to the file instead of
404
+ // truncating it, so the statement is not a rewrite.
405
+ if (tokens.some((t) => /^-append$/i.test(t))) return targets;
406
+
407
+ // For copy/move/rename the *source* is read, not written: only the destination
408
+ // is replaced. Treating `-LiteralPath` as a write target here made
409
+ // `Get-Content $f …; Copy-Item -LiteralPath $f -Destination $g` look like an
410
+ // in-place rewrite of `$f`.
411
+ const isCopy = verb === 'copy-item' || verb === 'move-item' || verb === 'rename-item'
412
+ || verb === 'copy' || verb === 'cp' || verb === 'mv' || verb === 'move';
413
+ if (isCopy) {
414
+ for (let i = 1; i < tokens.length; i += 1) {
415
+ const flag = tokens[i].toLowerCase();
416
+ if ((flag === '-destination' || flag === '-newname') && tokens[i + 1] !== undefined) {
417
+ targets.push(tokens[i + 1]);
418
+ i += 1;
419
+ }
420
+ }
421
+ const positionals = argumentsOf(tokens);
422
+ if (positionals.length > 0) targets.push(positionals[positionals.length - 1]);
423
+ return targets;
424
+ }
425
+
426
+ const positionals = argumentsOf(tokens);
427
+ if (positionals.length > 0) targets.push(positionals[0]);
428
+ return targets;
429
+ }
430
+
431
+ /**
432
+ * The positional arguments of one statement's command, with flag values consumed
433
+ * and redirection tokens dropped.
434
+ *
435
+ * Both halves matter for a false positive: `sed 's/a/b/' a.txt > b.txt` has `b.txt`
436
+ * as a *destination*, not an argument, and counting it as a positional made the
437
+ * `sed` reader claim it was writing the file it reads (`{ last: true }`).
438
+ *
439
+ * @param tokens - the statement's tokens, command word first.
440
+ * @returns the positional arguments.
441
+ */
442
+ function argumentsOf(tokens) {
443
+ const positionals = [];
444
+ for (let i = 1; i < tokens.length; i += 1) {
445
+ const tok = tokens[i];
446
+ if (tok === '>') {
447
+ i += 1;
448
+ continue;
449
+ }
450
+ const redirect = splitRedirect(tok);
451
+ if (redirect !== undefined) {
452
+ // `cat f.txt>f.txt` reads and truncates the same file in one token, which is
453
+ // the plainest form of the hazard: the operand before the `>` is an argument.
454
+ if (redirect.before.length > 0) positionals.push(redirect.before);
455
+ continue;
456
+ }
457
+ if (tok.startsWith('-')) {
458
+ const flag = tok.toLowerCase();
459
+ if (WRITE_PATH_FLAGS.has(flag) && tokens[i + 1] !== undefined) {
460
+ positionals.push(tokens[i + 1]);
461
+ i += 1;
462
+ continue;
463
+ }
464
+ if (WRITE_VALUE_FLAGS.has(flag) && tokens[i + 1] !== undefined) {
465
+ i += 1;
466
+ continue;
467
+ }
468
+ continue;
469
+ }
470
+ positionals.push(tok);
471
+ }
472
+ return positionals;
473
+ }
474
+
475
+ /**
476
+ * The file expressions one statement reads.
477
+ *
478
+ * Two sources, and the second is the one that closes a hole:
479
+ *
480
+ * - the statement's **head** verb, when it is a reader (`Get-Content $f`);
481
+ * - a reader **nested inside** a write statement
482
+ * (`Set-Content $f (Get-Content $f | Select-Object -First 10)`).
483
+ *
484
+ * Until 2026-11-25 only the first was checked, so a read folded into the write
485
+ * was invisible and the whole in-place rewrite was allowed. That spelling is the
486
+ * most compact form of the incident this rule exists for, so it is not a corner
487
+ * case — it is the hazard with fewer keystrokes.
488
+ *
489
+ * @param statement - one statement.
490
+ * @returns the operands being read.
491
+ */
492
+ function readTargets(statement) {
493
+ const out = [];
494
+ const tokens = statementTokens(statement);
495
+ const verb = tokens.length > 0
496
+ ? commandWord(statement).toLowerCase().replace(/\.(?:exe|cmd|bat)$/, '')
497
+ : '';
498
+ const spec = READ_COMMANDS.get(verb);
499
+
500
+ if (spec !== undefined) {
501
+ const positionals = argumentsOf(tokens);
502
+ // `Select-String` names its file with `-Path`, which `argumentsOf` already lifted
503
+ // into the positionals — so a plain `skip: N` would drop it. The pattern then
504
+ // reads as a file name and the real target is never compared.
505
+ if (spec.pathFlag === true) {
506
+ out.push(...positionals);
507
+ } else if (spec.last === true) {
508
+ if (positionals.length > 0) out.push(positionals[positionals.length - 1]);
509
+ } else {
510
+ out.push(...positionals.slice(spec.skip ?? 0));
511
+ }
512
+ }
513
+
514
+ // Nested readers. Only when the statement is not already a reader itself —
515
+ // otherwise the head scan above already covered the file, and re-running this
516
+ // would duplicate operands (harmless, but it makes the maps noisier than needed).
517
+ if (spec === undefined) {
518
+ for (const match of statement.matchAll(NESTED_READ)) {
519
+ const operand = cleanOperand(match[1]);
520
+ if (operand.length > 0 && !/^[-)]/.test(operand)) out.push(operand);
521
+ }
522
+ }
523
+
524
+ return out;
525
+ }
526
+
527
+ /**
528
+ * Whether the command makes its own copy of what it is about to overwrite.
529
+ *
530
+ * **Statement-level, not textual.** The previous version short-circuited on
531
+ * `BACKUP_MARKER.test(command)`, so any of these was exempted while truly
532
+ * rewriting a file from its only copy (measured 2026-11-25, all three allowed):
533
+ *
534
+ * Set-Content $f $t # no .bak needed here ← marker in a comment
535
+ * $f='a.md.bak'; Set-Content $f $t ← marker in the TARGET name
536
+ * $note='.bak is for wimps'; Set-Content a.md $f ← marker in a bystander string
537
+ *
538
+ * A copy step has to be an actual write to a *different* path that derives from
539
+ * the item itself, and it has to happen before the overwrite. Three conditions,
540
+ * all decidable from the statement list:
541
+ *
542
+ * 1. a statement writes `<target>.bak*` / `<target>.tmp*` / `.new` / `.orig` …
543
+ * 2. that statement comes **before** the target's last write
544
+ * 3. the copy path is not the target path itself
545
+ *
546
+ * @param statements - the statements of the command.
547
+ * @param literals - variable name → literal path, from this command's assignments.
548
+ * @param targetKeys - the comparison keys of the file being overwritten.
549
+ * @param targetIndex - the statement index of the last write to that file.
550
+ * @returns whether a real copy step precedes the overwrite.
551
+ */
552
+ function hasCopyStepFor(statements, literals, targetKeys, targetIndex) {
553
+ // Build the target matchers once per call rather than once per statement: this
554
+ // runs on every command that reads and rewrites a file, and constructing regexes
555
+ // in a loop was measurable (2026-11-25: ~17 µs of added cost on 6,000 commands).
556
+ const targetMatchers = [];
557
+ for (const key of targetKeys) {
558
+ if (!key.startsWith('lit:')) continue;
559
+ const t = key.slice(4);
560
+ const esc = t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
561
+ targetMatchers.push({
562
+ bare: new RegExp(`(?:^|[\\\\/\\s"'\`])${esc}(?![.\\w-])`, 'i'),
563
+ suffixed: new RegExp(`${esc}[._-](?:bak|backup|orig|old|tmp|new)`, 'i'),
564
+ });
565
+ }
566
+
567
+ for (let i = 0; i <= targetIndex && i < statements.length; i += 1) {
568
+ const statement = statements[i];
569
+
570
+ // `sed -i.bak` / `perl -pi.bak`: the editor makes the backup itself, in the
571
+ // same statement as the write. The suffix is the copy, so it counts — and this
572
+ // is the one case where the copy is not a separate, earlier statement.
573
+ if (/\b(?:sed|perl)\b[^\n;&|]*\s-[a-z]*i[._-](?:bak|backup|orig|old)\b/i.test(statement)) return true;
574
+
575
+ // Every other copy step has to come strictly BEFORE the overwrite: a backup
576
+ // taken afterwards preserves the already-destroyed content.
577
+ if (i >= targetIndex) continue;
578
+
579
+ const tokenText = statementTokens(statement).join(' ');
580
+
581
+ // A copy/temp destination in this statement, on the text level, is necessary
582
+ // but not sufficient: it also has to be a distinct path derived from the target.
583
+ if (!COPY_DESTINATION.test(tokenText)) continue;
584
+
585
+ // Condition 3: the copy must not be the target itself.
586
+ const samePath = targetMatchers.some((m) => m.bare.test(tokenText) && !m.suffixed.test(tokenText));
587
+ if (samePath) continue;
588
+
589
+ // Any distinct backup/temp destination that this statement writes counts.
590
+ if (BACKUP_MARKER.test(tokenText) || TEMP_MARKER.test(tokenText)) return true;
591
+ }
592
+ return false;
593
+ }
594
+
595
+ /**
596
+ * Whether the command repeats statements in a way that makes textual order
597
+ * unreliable: a read after a write may feed the *next* iteration's write.
598
+ *
599
+ * The previous gate only listed `for`/`foreach`/`while`, which misses the
600
+ * commonest PowerShell spellings — `%` (ForEach-Object), `do`/`until`, `switch`,
601
+ * and `.ForEach(`. Measured: `$fs | % { Set-Content $_ $c; $c = Get-Content $_ }`
602
+ * was not gated.
603
+ *
604
+ * The keyword must be in **command or pipeline position**, not merely present:
605
+ * `python -c "for i,l in enumerate(...)"` is a Python loop in a string, and
606
+ * treating it as a shell loop kept a legitimate command refused.
607
+ *
608
+ * @param command - the full command text.
609
+ * @param statements - the statements of the command.
610
+ * @returns whether any repetition construct is present in executable position.
611
+ */
612
+ function hasRepetition(command, statements) {
613
+ for (const statement of statements) {
614
+ const word = commandWord(statement).toLowerCase();
615
+ if (/^(?:for|foreach|while|do|until|switch|%|foreach-object)$/.test(word)) return true;
616
+ // `1..3 | % { … }` and `$x | ForEach-Object { … }`: the loop verb sits after a pipe.
617
+ if (/(?:^|\|)\s*(?:%|foreach-object)\b/i.test(statement)) return true;
618
+ if (/\.\s*foreach\s*\(/i.test(statement)) return true;
619
+ }
620
+ // `for(`/`foreach(` glued to a paren never tokenizes as a bare word.
621
+ if (/(?:^|[;|&\n])\s*(?:for|foreach|while|switch)\s*\(/i.test(command)) return true;
622
+ return false;
623
+ }
624
+
625
+ /**
626
+ * Whether this command pins the text encoding on **both** sides of the rewrite.
627
+ *
628
+ * A byte-level hazard that the shape rules cannot see: `Get-Content -Raw` on a GBK
629
+ * or UTF-16 document decodes it with the wrong code page, and `WriteAllText` then
630
+ * writes the mojibake back as UTF-8. Nothing in the command is "wrong" — a plain
631
+ * `.Replace` of an ASCII needle passes every count check — and the CJK content is
632
+ * destroyed. Measured 2026-11-25: with an ASCII needle the occurrence check passes
633
+ * and every CJK character becomes U+FFFD.
634
+ *
635
+ * A single, bounded substitution with both encodings stated is equivalent to the
636
+ * `edit` tool: it changes the matched substring, leaves the rest byte-identical,
637
+ * and cannot re-encode the file because the codec is pinned. Anything less than
638
+ * that (no `-Encoding`, or only one side) stays refused.
639
+ *
640
+ * @param command - the full command text.
641
+ * @returns whether both sides name an encoding.
642
+ */
643
+ function hasPinnedEncoding(command) {
644
+ // A read that states its codec: `Get-Content -Encoding utf8`, or a .NET read that
645
+ // passes an encoding object as its second argument
646
+ // (`::ReadAllText($path, $enc)` / `::ReadAllText('x', [Text.Encoding]::UTF8)`).
647
+ const readPins = /Get-Content\b[^\n;&|]*\s-Encoding\s+\w+/i.test(command)
648
+ || /::\s*(?:ReadAllText|ReadAllLines)\s*\(\s*[^,()]+,\s*[^)]+\)/i.test(command);
649
+ // A write that states its codec: `Set-Content -Encoding utf8`, `Out-File -Encoding`,
650
+ // or `WriteAllText(path, text, <encoding>)` — the third argument is the codec.
651
+ const writePins = /(?:Set-Content|Out-File|Add-Content)\b[^\n;&|]*\s-Encoding\s+\w+/i.test(command)
652
+ || /::\s*WriteAllText\s*\(\s*[^,()]+,\s*[^,()]+,\s*[^)]+\)/i.test(command);
653
+ return readPins && writePins;
654
+ }
655
+ /**
656
+ * Whether the command's only content change is a bounded, literal substitution.
657
+ *
658
+ * `$t = $t.Replace('old','new')` and `$t = $t -replace 'a','b'` change one
659
+ * substring; they do not rebuild the document. The distinction matters because
660
+ * the shape rules otherwise treat "read then write the same file" as one hazard,
661
+ * and a targeted replacement is nowhere near as destructive as a slice.
662
+ *
663
+ * Deliberately **not** enough on its own: a `-replace` whose pattern is a
664
+ * document-wide regex (`(?s)^.*$`, `\s+`) rewrites everything. That is why this
665
+ * predicate is only consulted together with {@link hasPinnedEncoding}.
666
+ *
667
+ * @param command - the full command text.
668
+ * @returns whether a bounded substitution is present.
669
+ */
670
+ function hasBoundedSubstitution(command) {
671
+ // A literal-to-literal Replace / -replace, both sides quoted.
672
+ const literalSub = /\.\s*Replace\s*\(\s*'(?:[^'\\]|\\.){0,300}'\s*,\s*'(?:[^'\\]|\\.){0,300}'\s*\)/i.test(command)
673
+ || /\.\s*Replace\s*\(\s*"(?:[^"\\]|\\.){0,300}"\s*,\s*"(?:[^"\\]|\\.){0,300}"\s*\)/i.test(command)
674
+ || /\$\w+\s*-replace\s*'(?:[^'\\]|\\.){0,300}'\s*,\s*'(?:[^'\\]|\\.){0,300}'/i.test(command);
675
+
676
+ // A bare `-replace 'a','b'` in a pipeline: `(Get-Content $f -Raw) -replace 'a','b' | Set-Content $f`.
677
+ // `splitStatements` breaks on `|`, so the operator lands in its own statement and
678
+ // the leading `$\w+ =` / `(` anchor above never matches it.
679
+ const pipedSub = /(?:^|[;|]\s*|\)\s*)\(?-replace\s*'(?:[^'\\]|\\.){0,300}'\s*,\s*'(?:[^'\\]|\\.){0,300}'/i.test(command)
680
+ || /(?:^|[;|]\s*)\(?-replace\s*"(?:[^"\\]|\\.){0,300}"\s*,\s*"(?:[^"\\]|\\.){0,300}"/i.test(command);
681
+
682
+ // The same substitution with the needle/replacement held in variables or a mix of
683
+ // variable and literal: `$t = $t.Replace($old, $new)`, `$c.Replace($old, "text")`.
684
+ // Common in real work (the pair is built earlier), and equivalent to the literal
685
+ // form as long as it stays a substitution — the wholesale-rewrite checks below
686
+ // still apply.
687
+ const varSub = /\.\s*Replace\s*\(\s*(?:\$[A-Za-z_][\w:]*|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\s*,\s*(?:\$[A-Za-z_][\w:]*|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\s*\)/i.test(command);
688
+
689
+ // A table of literal pairs applied in a loop:
690
+ // $pairs = @( @('old1','new1'), @('old2','new2'), … ); foreach ($p in $pairs) { $t = $t.Replace($p[0], $p[1]) }
691
+ // Same bounded substitution, just driven by data. Common for bulk renames in docs.
692
+ const tableSub = /\$\w+\s*=\s*@\s*\(\s*@\s*\(\s*'[^']*'\s*,\s*'[^']*'\s*\)/i.test(command)
693
+ || /\.\s*Replace\s*\(\s*\$[A-Za-z_][\w:]*\s*\[\s*0\s*\]\s*,\s*\$[A-Za-z_][\w:]*\s*\[\s*1\s*\]\s*\)/i.test(command);
694
+
695
+ if (!literalSub && !pipedSub && !varSub && !tableSub) return false;
696
+
697
+ // The pattern must not match the whole document. These are the shapes that turn a
698
+ // substitution into a wholesale rewrite; with a pinned codec the bytes survive, but
699
+ // the content does not.
700
+ //
701
+ // Measured 2026-11-25: `$t -replace '(?s)^.*$','x'` with `-Encoding utf8` on both
702
+ // sides passed the old check and reduced a whole file to one character.
703
+ const wholeDocument = /\(\?s\)\s*\^?\.[*+]\$?|\^\.[*+]\$|\\s\*\\S\*|\^\.\*\$/i.test(command);
704
+ if (wholeDocument) return false;
705
+
706
+ // …and no wholesale discarding/rebuilding alongside it.
707
+ const destructive = /\[[^\]\n]*\.\.[^\]\n]*\]/.test(command)
708
+ || /\|\s*Select-Object\s+-?(?:First|Skip|Last)\b/i.test(command)
709
+ || /-TotalCount\b/i.test(command);
710
+ return !destructive;
711
+ }
712
+
713
+ /**
714
+ * Whether a statement writes `<something>.tmp/.bak` — i.e. makes a *copy* that can
715
+ * still hold the original bytes.
716
+ *
717
+ * Deliberately narrow. A temp file holding the **new** content is not a backup: if
718
+ * the transformation was semantically wrong, the original is gone just the same.
719
+ * `read → transform → write temp → verify temp → copy temp over original` verifies
720
+ * the output, not that the input is recoverable, so it does not qualify. This
721
+ * guard's own deny message asks for a backup of the original first, and that is
722
+ * the only step that makes a rewrite undoable.
723
+ *
724
+ * @param statement - one statement.
725
+ * @returns whether the statement writes a temp/backup destination.
726
+ */
727
+ function writesTempOrBackup(statement) {
728
+ const text = statementTokens(statement).join(' ');
729
+ if (!/\.(?:tmp|bak|backup|orig|old)\b|[-_.]tmp\b/i.test(text)) return false;
730
+ return COPY_DESTINATION.test(text);
731
+ }
732
+
733
+ /**
734
+ * Rule 1: is this command reading and rewriting the same file?
735
+ *
736
+ * @param command - the full command text.
737
+ * @param statements - the statements of the command.
738
+ * @param dialect - `pwsh` or `bash`, for the recipe in the message.
739
+ * @returns the refusal, or `undefined`.
740
+ */
741
+ function inPlaceRewrite(command, statements, dialect) {
742
+ const literals = collectLiterals(statements);
743
+
744
+ // Per-file bookkeeping. A single global "last write" index was wrong: in
745
+ // `Set-Content a …; Get-Content b`, it would treat b's read as a read-back of a.
746
+ /** @type {Map<string, { expr: string, lastWrite: number }>} */
747
+ const written = new Map();
748
+ /** @type {Map<string, { expr: string, firstRead: number }>} */
749
+ const read = new Map();
750
+
751
+ for (let index = 0; index < statements.length; index += 1) {
752
+ const statement = statements[index];
753
+
754
+ for (const expr of writtenTargets(statement)) {
755
+ for (const key of exprKeys(expr, literals)) {
756
+ const prior = written.get(key);
757
+ written.set(key, { expr, lastWrite: index, });
758
+ if (prior !== undefined && prior.expr !== expr) written.set(key, { expr: prior.expr, lastWrite: index });
759
+ }
760
+ }
761
+ for (const expr of readTargets(statement)) {
762
+ for (const key of exprKeys(expr, literals)) {
763
+ if (!read.has(key)) read.set(key, { expr, firstRead: index });
764
+ }
765
+ }
766
+ }
767
+
768
+ // .NET content calls are not shell verbs, so `statementTokens` never sees them;
769
+ // they name the file as their first argument and are the other way to rewrite a
770
+ // file from its own bytes ([IO.File]::ReadAllText → ::WriteAllText).
771
+ //
772
+ // These must participate in the ORDER bookkeeping. Measured 2026-11-25: giving
773
+ // them no statement index made the last-write lookup return -1, which emptied
774
+ // the read set and let 223 historical `.NET` read→write commands through.
775
+ for (let index = 0; index < statements.length; index += 1) {
776
+ const statement = statements[index];
777
+ for (const match of statement.matchAll(DOTNET_WRITE)) {
778
+ for (const key of exprKeys(match[1], literals)) {
779
+ const prior = written.get(key);
780
+ written.set(key, { expr: prior?.expr ?? match[1], lastWrite: index });
781
+ }
782
+ }
783
+ for (const match of statement.matchAll(DOTNET_READ)) {
784
+ for (const key of exprKeys(match[1], literals)) {
785
+ if (!read.has(key)) read.set(key, { expr: match[1], firstRead: index });
786
+ }
787
+ }
788
+ }
789
+
790
+ const repeating = hasRepetition(command, statements);
791
+
792
+ for (const [key, { expr: writtenExpr, lastWrite }] of written) {
793
+ // The null device is plumbing, not a file.
794
+ if (/^(?:lit:)?(?:\$null|nul|\/dev\/null)$/i.test(key)) continue;
795
+ const readSide = read.get(key);
796
+ if (readSide === undefined) continue;
797
+
798
+ // Order: a read that happens only *after* the last write is a verification
799
+ // read-back, not the source of the new content. It cannot feed a write that
800
+ // already ran. Skipped entirely when the command repeats statements, because
801
+ // there textual order is not execution order.
802
+ if (!repeating && readSide.firstRead > lastWrite) continue;
803
+
804
+ // A real copy of the target, made before the overwrite, makes the write undoable.
805
+ if (hasCopyStepFor(statements, literals, new Set([key]), lastWrite)) continue;
806
+
807
+ // A bounded substitution with the codec pinned on both sides is what the `edit`
808
+ // tool does: it cannot re-encode the file and cannot drop content outside the
809
+ // matched substring. Anything weaker stays refused — see hasPinnedEncoding.
810
+ if (hasBoundedSubstitution(command) && hasPinnedEncoding(command)) continue;
811
+
812
+ const shown = unquote(String(writtenExpr));
813
+ const backup = dialect === 'bash'
814
+ ? `cp "${shown}" "${shown}.bak-$(date +%Y%m%d-%H%M%S)"`
815
+ : `Copy-Item -LiteralPath "${shown}" -Destination "${shown}.bak-$(Get-Date -f yyyyMMdd-HHmmss)"`;
816
+ return {
817
+ kind: 'in-place-rewrite',
818
+ reason:
819
+ `The recycle-bin guard blocked this command: it reads "${shown}" and then overwrites that same file, ` +
820
+ 'so the new content is derived from the only copy. If the read, the slice or the pipeline is wrong, ' +
821
+ 'the original is gone — there is nothing to restore from, and a network share has no Recycle Bin.\n\n' +
822
+ `Do this instead (the copy step is what makes the write undoable):\n` +
823
+ ` 1. ${backup}\n` +
824
+ ' 2. write the new text to a temp file\n' +
825
+ ' 3. check it (line count or first/last line), then copy it over the original\n\n' +
826
+ 'For a find-and-replace on a document, the `edit` tool is safer than rewriting the whole file from a shell. ' +
827
+ 'For a rewrite that already copies the file to `<name>.bak-<timestamp>` first, re-run unchanged — that step is accepted.',
828
+ };
829
+ }
830
+ return undefined;
831
+ }
832
+
833
+ /**
834
+ * Rule 2: does an unchecked, offset slice endpoint feed a file write in the same
835
+ * command?
836
+ *
837
+ * @param command - the full command text.
838
+ * @param statements - the statements of the command.
839
+ * @returns the refusal, or `undefined`.
840
+ */
841
+ function uncheckedSlice(command, statements) {
842
+ // The write half is what turns a wrong slice into lost data. Without it the
843
+ // command prints the wrong lines and the file survives, so it stays allowed.
844
+ const writes = statements.some((s) => writtenTargets(s).length > 0);
845
+ if (!writes) return undefined;
846
+
847
+ const variables = new Set();
848
+ for (const match of command.matchAll(/\[([^[\]\n]{0,160}?\.\.[^[\]\n]{0,160}?)\]/g)) {
849
+ const endpoint = OFFSET_ENDPOINT.exec(match[1]);
850
+ if (endpoint === null) continue;
851
+ // `$lines[0..($lines.Count-1)]` cannot be null: Count is 0 for an empty array.
852
+ if (/\.count\b/i.test(match[1])) continue;
853
+ variables.add(endpoint[1].toLowerCase());
854
+ }
855
+ for (const match of command.matchAll(COUNT_ARG)) {
856
+ variables.add(match[1].toLowerCase());
857
+ }
858
+ if (variables.size === 0) return undefined;
859
+
860
+ // An assertion anywhere in the command clears the variable: the incident's own
861
+ // fix is one line, so the rule accepts it wherever it appears.
862
+ const provenance = collectProvenance(statements);
863
+ let offender;
864
+ for (const name of variables) {
865
+ if (provenance.get(name) === true) continue;
866
+ if (isAsserted(command, name)) continue;
867
+ offender = name;
868
+ break;
869
+ }
870
+ if (offender === undefined) return undefined;
871
+
872
+ return {
873
+ kind: 'slice-risk',
874
+ reason:
875
+ `The recycle-bin guard blocked this command: \`$${offender}\` is offset by arithmetic in a slice endpoint, ` +
876
+ 'it is never checked for $null, and the same command writes a file. In PowerShell a null offset is not an ' +
877
+ 'error — `$lines[0..($null-2)]` is `$lines[0..-2]`, i.e. `$lines[0,-1,-2]`, the first line and the last two — ' +
878
+ 'so a 605-line file can be saved over as 24 lines with no warning anywhere.\n\n' +
879
+ `Fix, then re-run: if (-not $${offender}) { throw "anchor not found" }\n` +
880
+ `Or compute the endpoint from a proven value (e.g. \`$lines.Count\`) instead of an unchecked match index. ` +
881
+ 'For the write itself, copy the original to `<name>.bak-<timestamp>` first, write a temp file, verify it, then replace.',
882
+ };
883
+ }
884
+
885
+ /**
886
+ * Whether the command proves a variable is not `$null` before using it.
887
+ * @param command - the full command text.
888
+ * @param name - the lower-cased variable name.
889
+ * @returns whether an assertion on that variable is present.
890
+ */
891
+ function isAsserted(command, name) {
892
+ const v = `\\$${name}\\b`;
893
+ const patterns = [
894
+ `${v}\\s*-\\s*(?:eq|ne|lt|le|gt|ge)\\s*\\$null`,
895
+ `\\$null\\s*-\\s*(?:eq|ne|lt|le)\\s*${v}`,
896
+ `${v}\\s*-(?:eq|le)\\s*(?:0|''|"")`,
897
+ `${v}\\s*\\?\\?`,
898
+ `if\\s*\\(\\s*!\\s*${v}`,
899
+ `if\\s*\\(\\s*-\\s*not\\s*\\(?\\s*${v}`,
900
+ `if\\s*\\(\\s*${v}\\s*\\)`,
901
+ ];
902
+ return patterns.some((p) => new RegExp(p, 'i').test(command));
903
+ }
904
+
905
+ /**
906
+ * Classify a command for content-destroying writes.
907
+ *
908
+ * @param command - the full command text.
909
+ * @param options - `statements` (already split, including decoded bodies) and
910
+ * `dialect` (`pwsh` or `bash`).
911
+ * @returns `{ kind, reason }` when the command must be refused, else `undefined`.
912
+ */
913
+ export function analyzeOverwriteRisk(command, options = {}) {
914
+ const { statements = [], dialect = 'pwsh' } = options;
915
+ if (typeof command !== 'string' || command.trim().length === 0) return undefined;
916
+ if (statements.length === 0) return undefined;
917
+
918
+ // The slice rule is judged first: its message names the actual mistake and the
919
+ // one-line fix, which is far more useful than the general "you are rewriting in
920
+ // place" note when both apply (the incident had both).
921
+ const slice = uncheckedSlice(command, statements);
922
+ if (slice !== undefined) return slice;
923
+
924
+ return inPlaceRewrite(command, statements, dialect);
925
+ }