dsh-vigil 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +188 -0
  3. package/client.js +4652 -0
  4. package/cordis.patch.yml +7 -0
  5. package/docs/DETAIL.md +66 -0
  6. package/icon.png +0 -0
  7. package/illustrations/notice.png +0 -0
  8. package/illustrations/warning.png +0 -0
  9. package/locale/en.json +7 -0
  10. package/locale/zh.json +7 -0
  11. package/package.json +75 -0
  12. package/rules/audit.yaml +130 -0
  13. package/rules/manifest.json +7 -0
  14. package/rules/sentinel.yaml +289 -0
  15. package/src/alert-route.js +194 -0
  16. package/src/approval.js +398 -0
  17. package/src/artwork-route.js +87 -0
  18. package/src/audit/ast.js +213 -0
  19. package/src/audit/install-scan.js +127 -0
  20. package/src/audit/lexer.js +307 -0
  21. package/src/audit/narrative.js +320 -0
  22. package/src/audit/rules.js +1440 -0
  23. package/src/audit/scan.js +880 -0
  24. package/src/audit-clear-route.js +89 -0
  25. package/src/audit-feed.js +265 -0
  26. package/src/audit-log.js +887 -0
  27. package/src/config-schema.js +194 -0
  28. package/src/config.js +580 -0
  29. package/src/delete/command-kinds.js +46 -0
  30. package/src/delete/lex.js +46 -0
  31. package/src/delete/parser-posix.js +1427 -0
  32. package/src/delete/parser-pwsh.js +1729 -0
  33. package/src/delete/parser.js +2082 -0
  34. package/src/delete/policy.js +680 -0
  35. package/src/delete/quarantine.js +417 -0
  36. package/src/index.js +1134 -0
  37. package/src/install-scan-route.js +58 -0
  38. package/src/install-watch.js +389 -0
  39. package/src/integrity.js +509 -0
  40. package/src/live-config.js +88 -0
  41. package/src/quarantine-route.js +74 -0
  42. package/src/quarantine-view.js +44 -0
  43. package/src/rules/pack.js +423 -0
  44. package/src/rules/update.js +341 -0
  45. package/src/rules/yaml.js +186 -0
  46. package/src/sage-action-route.js +63 -0
  47. package/src/sage-provision.js +716 -0
  48. package/src/sentinel/guard.js +392 -0
  49. package/src/sentinel/hook.js +546 -0
  50. package/src/sentinel/rules.js +488 -0
  51. package/src/sentinel/sage-load.js +79 -0
  52. package/src/sentinel/sage.js +550 -0
  53. package/src/tools.js +727 -0
  54. package/src/update-check.js +339 -0
  55. package/src/util.js +400 -0
  56. package/threats/README.md +25 -0
@@ -0,0 +1,2082 @@
1
+ /**
2
+ * dsh-vigil — FR-3.1 deletion-intent parser (public API).
3
+ *
4
+ * Parses raw tool command text (PowerShell 5.1/7, cmd.exe, POSIX sh/bash/zsh)
5
+ * into a structured {@link DeleteIntent} so the policy layer can decide
6
+ * allow / ask / deny.
7
+ *
8
+ * Hard guarantees:
9
+ * - Pure: no filesystem access, no process spawning, no network, no deps.
10
+ * - Deterministic: identical input + options always yield identical output.
11
+ * - Never throws for any input; unparseable input degrades to `unparsed: true`
12
+ * (fail-closed for callers).
13
+ *
14
+ * Variable expansion and path resolution only use the supplied
15
+ * `options.homeDir / options.env / options.cwd`, never `process.env`, so the
16
+ * result is reproducible across hosts and operating systems.
17
+ *
18
+ * @module delete/parser
19
+ */
20
+
21
+ import path from 'node:path';
22
+
23
+ import { parsePosixStatements } from './parser-posix.js';
24
+ import { parsePwshStatements, parseCmdStatements } from './parser-pwsh.js';
25
+
26
+ /** Commands longer than this are only analysed up to this many characters. */
27
+ const MAX_COMMAND_LENGTH = 200000;
28
+
29
+ /** Maximum number of simple statements kept from one command. */
30
+ const MAX_STATEMENTS = 400;
31
+
32
+ /** Maximum number of command substitutions (`$(...)`, backticks) analysed. */
33
+ const MAX_SUBCOMMANDS = 100;
34
+
35
+ /** Maximum nesting depth for shell wrappers (`bash -c`, `pwsh -Command`, ...). */
36
+ const MAX_WRAP_DEPTH = 6;
37
+
38
+ /** Maximum nesting depth for command substitutions. */
39
+ const MAX_ANALYZE_DEPTH = 8;
40
+
41
+ /** Sentinel matching the one used by parser-posix / parser-pwsh. */
42
+ const ESC = '\u0001';
43
+
44
+ /** Canonical ordering for `riskSignals` (keeps output deterministic). */
45
+ const RISK_ORDER = [
46
+ 'recursive',
47
+ 'wildcard',
48
+ 'protected-path',
49
+ 'absolute-root',
50
+ 'variable-target',
51
+ 'pipeline-generic',
52
+ 'encoded-command',
53
+ 'mirror-delete',
54
+ 'find-delete',
55
+ 'unlink',
56
+ 'rm-long-options',
57
+ 'dry-run',
58
+ 'unknown-construct',
59
+ ];
60
+
61
+ /** Presentation labels for describeIntent(). */
62
+ const SHELL_LABELS = {
63
+ pwsh: 'PowerShell',
64
+ posix: 'POSIX shell',
65
+ cmd: 'cmd',
66
+ mixed: '混合 shell',
67
+ unknown: '未知 shell',
68
+ };
69
+
70
+ /** PowerShell cmdlets / advanced-function names recognised during classification. */
71
+ const PWSH_CMDLETS = new Set([
72
+ 'remove-item',
73
+ 'get-childitem',
74
+ 'get-item',
75
+ 'set-item',
76
+ 'new-item',
77
+ 'copy-item',
78
+ 'move-item',
79
+ 'rename-item',
80
+ 'clear-item',
81
+ 'get-content',
82
+ 'set-content',
83
+ 'add-content',
84
+ 'clear-content',
85
+ 'test-path',
86
+ 'resolve-path',
87
+ 'split-path',
88
+ 'join-path',
89
+ 'get-location',
90
+ 'set-location',
91
+ 'push-location',
92
+ 'pop-location',
93
+ 'select-object',
94
+ 'where-object',
95
+ 'foreach-object',
96
+ 'sort-object',
97
+ 'measure-object',
98
+ 'group-object',
99
+ 'out-null',
100
+ 'out-file',
101
+ 'out-string',
102
+ 'write-output',
103
+ 'write-host',
104
+ 'write-error',
105
+ 'invoke-expression',
106
+ 'invoke-command',
107
+ 'invoke-webrequest',
108
+ 'invoke-restmethod',
109
+ 'start-process',
110
+ 'stop-process',
111
+ 'get-process',
112
+ 'get-service',
113
+ 'get-command',
114
+ 'new-object',
115
+ 'remove-variable',
116
+ 'remove-module',
117
+ 'uninstall-module',
118
+ 'uninstall-package',
119
+ 'import-module',
120
+ 'get-module',
121
+ 'start-job',
122
+ 'stop-job',
123
+ 'get-itemproperty',
124
+ 'set-itemproperty',
125
+ 'remove-itemproperty',
126
+ 'get-acl',
127
+ 'set-acl',
128
+ 'export-csv',
129
+ 'import-csv',
130
+ 'convertto-json',
131
+ 'convertfrom-json',
132
+ 'format-table',
133
+ 'format-list',
134
+ ]);
135
+
136
+ /** Shell/bash commands always parsed with POSIX rules. */
137
+ const POSIX_COMMANDS = new Set([
138
+ 'rm',
139
+ 'find',
140
+ 'xargs',
141
+ 'shred',
142
+ 'unlink',
143
+ 'git',
144
+ 'rsync',
145
+ 'ls',
146
+ 'cat',
147
+ 'echo',
148
+ 'printf',
149
+ 'grep',
150
+ 'egrep',
151
+ 'fgrep',
152
+ 'sed',
153
+ 'awk',
154
+ 'head',
155
+ 'tail',
156
+ 'cut',
157
+ 'sort',
158
+ 'uniq',
159
+ 'wc',
160
+ 'chmod',
161
+ 'chown',
162
+ 'cp',
163
+ 'mv',
164
+ 'mkdir',
165
+ 'touch',
166
+ 'tar',
167
+ 'zip',
168
+ 'unzip',
169
+ 'gzip',
170
+ 'gunzip',
171
+ 'curl',
172
+ 'wget',
173
+ 'bash',
174
+ 'sh',
175
+ 'zsh',
176
+ 'dash',
177
+ 'ksh',
178
+ 'eval',
179
+ 'env',
180
+ 'sudo',
181
+ 'nohup',
182
+ 'node',
183
+ 'npm',
184
+ 'pnpm',
185
+ 'yarn',
186
+ 'python',
187
+ 'python3',
188
+ 'busybox',
189
+ 'make',
190
+ 'dd',
191
+ 'ln',
192
+ 'stat',
193
+ 'du',
194
+ 'df',
195
+ ]);
196
+
197
+ /** cmd.exe built-ins / commands that are parsed with cmd rules. */
198
+ const CMD_COMMANDS = new Set([
199
+ 'del',
200
+ 'erase',
201
+ 'rd',
202
+ 'robocopy',
203
+ 'for',
204
+ 'copy',
205
+ 'move',
206
+ 'ren',
207
+ 'rename',
208
+ 'type',
209
+ 'dir',
210
+ 'set',
211
+ 'call',
212
+ 'start',
213
+ 'xcopy',
214
+ 'attrib',
215
+ 'icacls',
216
+ 'takeown',
217
+ 'format',
218
+ 'diskpart',
219
+ 'mkd',
220
+ 'md',
221
+ 'chdir',
222
+ 'chkdsk',
223
+ 'fc',
224
+ 'findstr',
225
+ 'choice',
226
+ 'shutdown',
227
+ 'more',
228
+ 'cls',
229
+ 'ver',
230
+ 'vol',
231
+ ]);
232
+
233
+ /** Prefix wrappers that do not change the deletion semantics of the rest. */
234
+ const COMMAND_PREFIXES = new Set([
235
+ 'sudo',
236
+ 'doas',
237
+ 'nohup',
238
+ 'time',
239
+ 'command',
240
+ 'builtin',
241
+ 'exec',
242
+ 'env',
243
+ 'nice',
244
+ 'ionice',
245
+ 'stdbuf',
246
+ 'timeout',
247
+ 'noglob',
248
+ ]);
249
+
250
+ /** Prefix options that consume a value (`sudo -u root ...`). */
251
+ const PREFIX_VALUE_OPTIONS = {
252
+ sudo: new Set(['u', 'g', 'h', 'p', 'c', 't', 'r', 'd', 'u', 'U', 'C', 'T', 'R', 'D']),
253
+ doas: new Set(['u', 'C']),
254
+ env: new Set(['u', 'C', 'S']),
255
+ nice: new Set(['n']),
256
+ ionice: new Set(['c', 'n', 'p']),
257
+ stdbuf: new Set(['i', 'o', 'e']),
258
+ timeout: new Set(['s', 'k']),
259
+ };
260
+
261
+ /** Path segments that indicate credential / self-protection sensitive data. */
262
+ const SENSITIVE_SEGMENTS = new Set(['.ssh', '.aws', '.gnupg', '.dsh', '.pi', '.git', '.kube', '.docker']);
263
+
264
+ /** File names that indicate credentials / secrets. */
265
+ const SENSITIVE_NAMES = new Set([
266
+ 'id_rsa',
267
+ 'id_dsa',
268
+ 'id_ecdsa',
269
+ 'id_ed25519',
270
+ 'authorized_keys',
271
+ 'known_hosts',
272
+ '.npmrc',
273
+ '.netrc',
274
+ '.pgpass',
275
+ '.env',
276
+ 'credentials',
277
+ ]);
278
+
279
+ /** Windows system directories (lowercase segments). */
280
+ const WINDOWS_SYSTEM_SEGMENTS = new Set([
281
+ 'windows',
282
+ 'system32',
283
+ 'syswow64',
284
+ 'program files',
285
+ 'program files (x86)',
286
+ 'programdata',
287
+ 'winsxs',
288
+ ]);
289
+
290
+ /** POSIX system directories (lowercase absolute prefixes). */
291
+ const POSIX_SYSTEM_PREFIXES = ['/etc', '/usr', '/bin', '/sbin', '/boot', '/dev', '/proc', '/sys', '/lib', '/lib64', '/System', '/Library'];
292
+
293
+ /**
294
+ * @typedef {object} DeleteTarget
295
+ * @property {string} raw as written, without quotes
296
+ * @property {string|null} resolvedPath best-effort absolute path; null when variable-dependent or not a path
297
+ * @property {'literal'|'variable'|'unknown'} scope
298
+ * @property {boolean} hasGlob
299
+ * @property {'none'|'asterisk'|'question'|'bracket'|'brace'|'mixed'} globKind
300
+ * @property {boolean} absolute
301
+ * @property {boolean} rootLike
302
+ * @property {boolean} viaPipeline
303
+ */
304
+
305
+ /**
306
+ * @typedef {object} StatementIntent
307
+ * @property {'pwsh'|'posix'|'cmd'|'mixed'|'unknown'} shell
308
+ * @property {string} text
309
+ * @property {string} command
310
+ * @property {boolean} isDelete
311
+ * @property {boolean} dryRun
312
+ * @property {boolean} recursive
313
+ * @property {boolean} force
314
+ * @property {boolean} wildcard
315
+ * @property {DeleteTarget[]} targets
316
+ * @property {'rm'|'remove-item'|'find-delete'|'rmdir'|'del'|'rd'|'robocopy-mirror'|'unlink'|'git-clean'|'io-delete'|'other'|'move'|'none'} deleteKind
317
+ * @property {boolean} unparsed
318
+ * @property {string[]} notes
319
+ */
320
+
321
+ /**
322
+ * @typedef {object} DeleteIntent
323
+ * @property {'pwsh'|'posix'|'cmd'|'mixed'|'unknown'} shell
324
+ * @property {boolean} isDelete
325
+ * @property {boolean} dryRun
326
+ * @property {boolean} recursive
327
+ * @property {boolean} force
328
+ * @property {boolean} wildcard
329
+ * @property {boolean} destructive
330
+ * @property {DeleteTarget[]} targets
331
+ * @property {StatementIntent[]} statements
332
+ * @property {string[]} reasons
333
+ * @property {boolean} unparsed
334
+ * @property {string[]} riskSignals
335
+ */
336
+
337
+ /* ------------------------------------------------------------------------- *
338
+ * Generic helpers
339
+ * ------------------------------------------------------------------------- */
340
+
341
+ /**
342
+ * Lowercase basename of a command word.
343
+ * @param {string} value
344
+ * @returns {string}
345
+ */
346
+ function baseName(value) {
347
+ const text = String(value || '')
348
+ .replace(ESC, '')
349
+ .trim()
350
+ .replace(/^&/, '')
351
+ .trim();
352
+ const index = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'));
353
+ return (index >= 0 ? text.slice(index + 1) : text).replace(/\.exe$/i, '').toLowerCase();
354
+ }
355
+
356
+ /**
357
+ * Split `text` into up to `limit` whitespace-delimited head tokens, preserving
358
+ * raw text and character offsets. Quote-aware (single, double, backslash).
359
+ *
360
+ * @param {string} text
361
+ * @param {number} limit
362
+ * @returns {Array<{value:string, raw:string, start:number, end:number}>}
363
+ */
364
+ function headTokens(text, limit) {
365
+ const tokens = [];
366
+ const src = String(text || '');
367
+ const n = src.length;
368
+ let i = 0;
369
+ while (i < n && tokens.length < limit) {
370
+ while (i < n && /\s/.test(src[i])) i += 1;
371
+ if (i >= n) break;
372
+ const start = i;
373
+ let value = '';
374
+ let quote = null;
375
+ while (i < n) {
376
+ const c = src[i];
377
+ if (quote) {
378
+ if (c === '\\' && quote === '"') {
379
+ value += src[i + 1] === undefined ? '' : src[i + 1];
380
+ i += 2;
381
+ continue;
382
+ }
383
+ if (c === quote) {
384
+ quote = null;
385
+ i += 1;
386
+ continue;
387
+ }
388
+ value += c;
389
+ i += 1;
390
+ continue;
391
+ }
392
+ if (c === "'" || c === '"') {
393
+ quote = c;
394
+ i += 1;
395
+ continue;
396
+ }
397
+ if (c === '\\') {
398
+ value += src[i + 1] === undefined ? '' : src[i + 1];
399
+ i += 2;
400
+ continue;
401
+ }
402
+ if (/\s/.test(c)) break;
403
+ value += c;
404
+ i += 1;
405
+ }
406
+ tokens.push({ value, raw: src.slice(start, i), start, end: i });
407
+ }
408
+ return tokens;
409
+ }
410
+
411
+ /**
412
+ * Remove one layer of matching quotes from a word.
413
+ * @param {string} text
414
+ * @returns {string}
415
+ */
416
+ function unquoteWord(text) {
417
+ let value = String(text || '').trim();
418
+ if (value.length >= 2) {
419
+ const quote = value[0];
420
+ if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
421
+ value = value.slice(1, -1);
422
+ value = quote === "'" ? value.replace(/''/g, "'") : value.replace(/\\"/g, '"');
423
+ }
424
+ }
425
+ return value;
426
+ }
427
+
428
+ /**
429
+ * Find the closing `)` for the `(` at `open`, quote-aware.
430
+ * @param {string} src
431
+ * @param {number} open
432
+ * @returns {number}
433
+ */
434
+ function findMatchingParen(src, open) {
435
+ let depth = 0;
436
+ let quote = null;
437
+ for (let i = open; i < src.length; i += 1) {
438
+ const c = src[i];
439
+ if (quote === "'") {
440
+ if (c === "'") quote = null;
441
+ continue;
442
+ }
443
+ if (quote === '"') {
444
+ if (c === '\\' || c === '`') {
445
+ i += 1;
446
+ continue;
447
+ }
448
+ if (c === '"') quote = null;
449
+ continue;
450
+ }
451
+ if (c === "'" || c === '"') {
452
+ quote = c;
453
+ continue;
454
+ }
455
+ if (c === '\\') {
456
+ i += 1;
457
+ continue;
458
+ }
459
+ if (c === '(') depth += 1;
460
+ else if (c === ')') {
461
+ depth -= 1;
462
+ if (depth === 0) return i;
463
+ }
464
+ }
465
+ return src.length;
466
+ }
467
+
468
+ /**
469
+ * Find the closing backtick for the substitution starting at `start`.
470
+ * @param {string} src
471
+ * @param {number} start
472
+ * @returns {number}
473
+ */
474
+ function findBacktickEnd(src, start) {
475
+ for (let i = start + 1; i < src.length; i += 1) {
476
+ if (src[i] === '\\') {
477
+ i += 1;
478
+ continue;
479
+ }
480
+ if (src[i] === '`') return i;
481
+ }
482
+ return src.length;
483
+ }
484
+
485
+ /**
486
+ * Split a raw command into top-level statements.
487
+ *
488
+ * Separators: newline, `;`, `&&`, `||`, single `&`. Single `|` is *kept* inside
489
+ * the chunk (shell parsers split pipelines themselves). Quotes, `$(...)`,
490
+ * backtick substitutions and PowerShell here-strings are treated as opaque so
491
+ * separators inside them are not honoured here (command substitutions are
492
+ * analysed separately).
493
+ *
494
+ * @param {string} text
495
+ * @returns {string[]}
496
+ */
497
+ function splitTopLevel(text) {
498
+ const chunks = [];
499
+ const src = String(text || '');
500
+ const n = src.length;
501
+ let current = '';
502
+ let quote = null;
503
+ let i = 0;
504
+ const flush = () => {
505
+ const chunk = current.trim();
506
+ if (chunk) chunks.push(chunk);
507
+ current = '';
508
+ };
509
+ while (i < n) {
510
+ const c = src[i];
511
+ if (quote === "'") {
512
+ current += c;
513
+ if (c === "'") quote = null;
514
+ i += 1;
515
+ continue;
516
+ }
517
+ if (quote === '"') {
518
+ current += c;
519
+ if (c === '\\' || c === '`') {
520
+ if (i + 1 < n) {
521
+ current += src[i + 1];
522
+ i += 2;
523
+ continue;
524
+ }
525
+ }
526
+ if (c === '"') quote = null;
527
+ i += 1;
528
+ continue;
529
+ }
530
+ if (c === "'" || c === '"') {
531
+ quote = c;
532
+ current += c;
533
+ i += 1;
534
+ continue;
535
+ }
536
+ if (c === '\\') {
537
+ if (src[i + 1] === '\n') {
538
+ current += ' ';
539
+ i += 2;
540
+ continue;
541
+ }
542
+ current += c + (src[i + 1] === undefined ? '' : src[i + 1]);
543
+ i += 2;
544
+ continue;
545
+ }
546
+ if (c === '`' && /^(?:[A-Za-z_])/.exec(src[i + 1] || '')) {
547
+ // Ambiguous between POSIX substitution and PowerShell escape: keep the
548
+ // whole backtick region verbatim so separators inside are not split, and
549
+ // let collectSubcommands() decide whether it is a substitution.
550
+ const end = findBacktickEnd(src, i);
551
+ current += src.slice(i, Math.min(end + 1, n));
552
+ i = Math.min(end + 1, n);
553
+ continue;
554
+ }
555
+ if (c === '$' && src[i + 1] === '(') {
556
+ const end = findMatchingParen(src, i + 1);
557
+ current += src.slice(i, Math.min(end + 1, n));
558
+ i = Math.min(end + 1, n);
559
+ continue;
560
+ }
561
+ if (c === '@' && (src[i + 1] === '"' || src[i + 1] === "'") && /^\r?\n/.test(src.slice(i + 2))) {
562
+ const quoteChar = src[i + 1];
563
+ const terminator = '\n' + quoteChar + '@';
564
+ let end = src.indexOf(terminator, i + 2);
565
+ end = end < 0 ? n : end + terminator.length;
566
+ current += src.slice(i, end);
567
+ i = end;
568
+ continue;
569
+ }
570
+ if (c === '#') {
571
+ const prev = i > 0 ? src[i - 1] : '\n';
572
+ if (/\s/.test(prev) || prev === ';' || prev === '&') {
573
+ while (i < n && src[i] !== '\n') i += 1;
574
+ continue;
575
+ }
576
+ current += c;
577
+ i += 1;
578
+ continue;
579
+ }
580
+ if (c === ';' && src[i + 1] === ';') {
581
+ i += 2;
582
+ continue;
583
+ }
584
+ if (c === '|') {
585
+ if (src[i + 1] === '|') {
586
+ flush();
587
+ i += 2;
588
+ continue;
589
+ }
590
+ current += c;
591
+ i += 1;
592
+ continue;
593
+ }
594
+ if (c === '&' && src[i + 1] === '&') {
595
+ flush();
596
+ i += 2;
597
+ continue;
598
+ }
599
+ if (c === '&') {
600
+ flush();
601
+ i += 1;
602
+ continue;
603
+ }
604
+ if (c === ';' || c === '\n' || c === '\r') {
605
+ flush();
606
+ i += 1;
607
+ continue;
608
+ }
609
+ current += c;
610
+ i += 1;
611
+ }
612
+ flush();
613
+ return chunks;
614
+ }
615
+
616
+ /**
617
+ * Rough shell-style detection used to decide whether backticks are command
618
+ * substitutions (POSIX) or escape characters (PowerShell).
619
+ * @param {string} text
620
+ * @returns {{pwshish:boolean}}
621
+ */
622
+ function detectStyle(text) {
623
+ const src = String(text || '');
624
+ const pwshish =
625
+ /(?:^|[\s|;&])(?:remove-item|get-childitem|get-item|where-object|foreach-object|invoke-expression|out-null|select-object)\b/i.test(src) ||
626
+ /\$env:/i.test(src) ||
627
+ /\[[A-Za-z0-9_.]+\]\s*::/i.test(src) ||
628
+ /(?:^|\s)-[A-Za-z]+:(?:\$|\{|['"])/.test(src) ||
629
+ /(?:^|\s)-(?:recurse|literalpath|whatif|erroraction|passthru|confirm)\b/i.test(src) ||
630
+ /@["']\r?\n/.test(src);
631
+ return { pwshish };
632
+ }
633
+
634
+ /**
635
+ * Collect command-substitution bodies (`$(...)` plus POSIX backticks).
636
+ * @param {string} text
637
+ * @param {{pwshish:boolean}} style
638
+ * @returns {string[]}
639
+ */
640
+ function collectSubcommands(text, style) {
641
+ const out = [];
642
+ const src = String(text || '');
643
+ const n = src.length;
644
+ let i = 0;
645
+ let quote = null;
646
+ while (i < n && out.length < MAX_SUBCOMMANDS) {
647
+ const c = src[i];
648
+ if (quote === "'") {
649
+ if (c === "'") quote = null;
650
+ i += 1;
651
+ continue;
652
+ }
653
+ if (quote === '"') {
654
+ if (c === '\\') {
655
+ i += 2;
656
+ continue;
657
+ }
658
+ if (c === '"') quote = null;
659
+ i += 1;
660
+ continue;
661
+ }
662
+ if (c === "'" || c === '"') {
663
+ quote = c;
664
+ i += 1;
665
+ continue;
666
+ }
667
+ if (c === '#') {
668
+ const prev = i > 0 ? src[i - 1] : '\n';
669
+ if (/\s/.test(prev)) {
670
+ while (i < n && src[i] !== '\n') i += 1;
671
+ continue;
672
+ }
673
+ i += 1;
674
+ continue;
675
+ }
676
+ if (c === '\\') {
677
+ i += 2;
678
+ continue;
679
+ }
680
+ if (c === '$' && src[i + 1] === '(') {
681
+ const end = findMatchingParen(src, i + 1);
682
+ out.push(src.slice(i + 2, Math.min(end, n)));
683
+ i = Math.min(end + 1, n);
684
+ continue;
685
+ }
686
+ if (c === '`' && !style.pwshish) {
687
+ const end = findBacktickEnd(src, i);
688
+ out.push(src.slice(i + 1, Math.min(end, n)));
689
+ i = Math.min(end + 1, n);
690
+ continue;
691
+ }
692
+ i += 1;
693
+ }
694
+ return out;
695
+ }
696
+
697
+ /**
698
+ * Split on top-level `|` (used only for encoded-pipeline detection).
699
+ * @param {string} text
700
+ * @returns {string[]}
701
+ */
702
+ function splitPipelineLoose(text) {
703
+ const stages = [];
704
+ const src = String(text || '');
705
+ let start = 0;
706
+ let quote = null;
707
+ for (let i = 0; i < src.length; i += 1) {
708
+ const c = src[i];
709
+ if (quote) {
710
+ if (c === '\\') {
711
+ i += 1;
712
+ continue;
713
+ }
714
+ if (c === quote) quote = null;
715
+ continue;
716
+ }
717
+ if (c === "'" || c === '"') {
718
+ quote = c;
719
+ continue;
720
+ }
721
+ if (c === '|') {
722
+ stages.push(src.slice(start, i).trim());
723
+ start = i + 1;
724
+ }
725
+ }
726
+ stages.push(src.slice(start).trim());
727
+ return stages.filter((stage) => stage.length > 0);
728
+ }
729
+
730
+ /* ------------------------------------------------------------------------- *
731
+ * Options / context
732
+ * ------------------------------------------------------------------------- */
733
+
734
+ /**
735
+ * Detect the path flavour of a path-looking string.
736
+ * @param {string} value
737
+ * @returns {'win32'|'posix'|null}
738
+ */
739
+ function detectFlavor(value) {
740
+ const text = String(value || '');
741
+ if (/^[A-Za-z]:[\\/]/.test(text) || /^\\\\/.test(text)) return 'win32';
742
+ if (text.startsWith('/')) return 'posix';
743
+ if (text.includes('\\') && !text.includes('/')) return 'win32';
744
+ return null;
745
+ }
746
+
747
+ /**
748
+ * Case-insensitive environment lookup (exact match wins).
749
+ * @param {Record<string,string>} env
750
+ * @param {Map<string,string>} envLower
751
+ * @param {string} name
752
+ * @returns {string|null}
753
+ */
754
+ function lookupEnv(env, envLower, name) {
755
+ if (Object.prototype.hasOwnProperty.call(env, name)) return env[name];
756
+ const lowered = envLower.get(String(name).toLowerCase());
757
+ return lowered === undefined ? null : lowered;
758
+ }
759
+
760
+ /**
761
+ * Build the immutable analysis context from user options.
762
+ * @param {object} options
763
+ * @returns {object}
764
+ */
765
+ function buildContext(options) {
766
+ const opts = options && typeof options === 'object' ? options : {};
767
+ const env = {};
768
+ if (opts.env && typeof opts.env === 'object') {
769
+ for (const [key, value] of Object.entries(opts.env)) {
770
+ if (typeof value === 'string') env[key] = value;
771
+ }
772
+ }
773
+ const envLower = new Map();
774
+ for (const [key, value] of Object.entries(env)) envLower.set(key.toLowerCase(), value);
775
+ const cwd = typeof opts.cwd === 'string' && opts.cwd ? opts.cwd : null;
776
+ let homeDir = typeof opts.homeDir === 'string' && opts.homeDir ? opts.homeDir : null;
777
+ if (!homeDir) {
778
+ homeDir = lookupEnv(env, envLower, 'HOME') || lookupEnv(env, envLower, 'USERPROFILE');
779
+ if (!homeDir) {
780
+ const drive = lookupEnv(env, envLower, 'HOMEDRIVE');
781
+ const homePath = lookupEnv(env, envLower, 'HOMEPATH');
782
+ if (drive && homePath) homeDir = drive + homePath;
783
+ }
784
+ }
785
+ const platform = typeof opts.platform === 'string' ? opts.platform.toLowerCase() : null;
786
+ let platformFlavor = null;
787
+ if (platform === 'win32' || platform === 'windows' || platform === 'win') platformFlavor = 'win32';
788
+ else if (['linux', 'darwin', 'posix', 'freebsd', 'openbsd', 'sunos'].includes(platform)) platformFlavor = 'posix';
789
+ const cwdFlavor = cwd ? detectFlavor(cwd) : null;
790
+ const homeFlavor = homeDir ? detectFlavor(homeDir) : null;
791
+ const defaultFlavor = platformFlavor || cwdFlavor || homeFlavor || null;
792
+ return {
793
+ cwd,
794
+ homeDir,
795
+ env,
796
+ envLower,
797
+ platform,
798
+ cwdFlavor,
799
+ homeFlavor,
800
+ defaultFlavor,
801
+ cwdResolved: cwd ? normalizeAbsolute(cwd, cwdFlavor || defaultFlavor || 'posix') : null,
802
+ homeResolved: homeDir ? normalizeAbsolute(homeDir, homeFlavor || defaultFlavor || 'posix') : null,
803
+ };
804
+ }
805
+
806
+ /**
807
+ * Normalise an absolute path (no trailing separator except for a root).
808
+ * @param {string} value
809
+ * @param {'win32'|'posix'} flavor
810
+ * @returns {string}
811
+ */
812
+ function normalizeAbsolute(value, flavor) {
813
+ const mod = flavor === 'win32' ? path.win32 : path.posix;
814
+ let text = String(value || '');
815
+ try {
816
+ text = mod.normalize(text);
817
+ } catch {
818
+ return text;
819
+ }
820
+ const root = mod.parse(text).root;
821
+ if (text.length > root.length && /[\\/]$/.test(text)) text = text.slice(0, -1);
822
+ return text;
823
+ }
824
+
825
+ /**
826
+ * Compare two paths under a given flavour (case-insensitive on Windows).
827
+ * @param {string} a
828
+ * @param {string} b
829
+ * @param {'win32'|'posix'} flavor
830
+ * @returns {boolean}
831
+ */
832
+ function samePath(a, b, flavor) {
833
+ if (flavor === 'win32') return String(a).toLowerCase() === String(b).toLowerCase();
834
+ return a === b;
835
+ }
836
+
837
+ /* ------------------------------------------------------------------------- *
838
+ * Variable expansion / target resolution
839
+ * ------------------------------------------------------------------------- */
840
+
841
+ /**
842
+ * Expand `~`, `$VAR`, `${VAR}`, `$env:VAR`, `${env:VAR}`, `%VAR%` using only
843
+ * the supplied context.
844
+ *
845
+ * @param {string} masked ESC-masked text
846
+ * @param {'pwsh'|'posix'|'cmd'|'unknown'} shell
847
+ * @param {object} ctx
848
+ * @returns {{text:string, unresolved:string[], dynamic:boolean}}
849
+ */
850
+ function expandVariables(masked, shell, ctx) {
851
+ const src = String(masked || '');
852
+ const allowPercent = shell !== 'posix';
853
+ const unresolved = [];
854
+ let dynamic = false;
855
+ let out = '';
856
+ let i = 0;
857
+
858
+ const resolveName = (name) => {
859
+ const lower = name.toLowerCase();
860
+ if (lower === 'home') return ctx.homeDir || lookupEnv(ctx.env, ctx.envLower, 'HOME');
861
+ if (lower === 'userprofile') return lookupEnv(ctx.env, ctx.envLower, 'USERPROFILE') || ctx.homeDir;
862
+ if (lower === 'pwd' || lower === 'cd') return ctx.cwd || lookupEnv(ctx.env, ctx.envLower, 'PWD');
863
+ return lookupEnv(ctx.env, ctx.envLower, name);
864
+ };
865
+
866
+ while (i < src.length) {
867
+ const c = src[i];
868
+ if (c === ESC) {
869
+ if (i + 1 < src.length) out += src[i + 1];
870
+ i += 2;
871
+ continue;
872
+ }
873
+ if (c === '~' && i === 0) {
874
+ if (ctx.homeDir) out += ctx.homeDir;
875
+ else {
876
+ unresolved.push('~');
877
+ out += '~';
878
+ }
879
+ i += 1;
880
+ continue;
881
+ }
882
+ if (c === '$') {
883
+ const rest = src.slice(i);
884
+ const envMatch = /^\$env:([A-Za-z_][A-Za-z0-9_]*)/i.exec(rest);
885
+ if (envMatch) {
886
+ const value = lookupEnv(ctx.env, ctx.envLower, envMatch[1]);
887
+ if (value === null) {
888
+ unresolved.push('$env:' + envMatch[1]);
889
+ out += envMatch[0];
890
+ } else out += value;
891
+ i += envMatch[0].length;
892
+ continue;
893
+ }
894
+ const braced = /^\$\{([^}]*)\}/.exec(rest);
895
+ if (braced) {
896
+ const content = braced[1].trim();
897
+ const envInner = /^env:([A-Za-z_][A-Za-z0-9_]*)$/i.exec(content);
898
+ if (envInner) {
899
+ const value = lookupEnv(ctx.env, ctx.envLower, envInner[1]);
900
+ if (value === null) unresolved.push('${env:' + envInner[1] + '}');
901
+ else out += value;
902
+ } else if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(content)) {
903
+ const value = resolveName(content);
904
+ if (value === null) unresolved.push('${' + content + '}');
905
+ else out += value;
906
+ } else {
907
+ unresolved.push('${' + content + '}');
908
+ dynamic = true;
909
+ out += braced[0];
910
+ }
911
+ i += braced[0].length;
912
+ continue;
913
+ }
914
+ const named = /^\$([A-Za-z_][A-Za-z0-9_]*)/.exec(rest);
915
+ if (named) {
916
+ const value = resolveName(named[1]);
917
+ if (value === null) unresolved.push('$' + named[1]);
918
+ else out += value;
919
+ i += named[0].length;
920
+ continue;
921
+ }
922
+ if (rest[1] === '(') {
923
+ dynamic = true;
924
+ unresolved.push('$(');
925
+ out += '$(';
926
+ i += 2;
927
+ continue;
928
+ }
929
+ if (/[0-9@*#?$!_-]/.test(rest[1] || '')) {
930
+ dynamic = true;
931
+ unresolved.push('$' + rest[1]);
932
+ out += '$' + rest[1];
933
+ i += 2;
934
+ continue;
935
+ }
936
+ out += '$';
937
+ i += 1;
938
+ continue;
939
+ }
940
+ if (c === '`') {
941
+ dynamic = true;
942
+ unresolved.push('`');
943
+ out += '`';
944
+ i += 1;
945
+ continue;
946
+ }
947
+ if (c === '%' && allowPercent) {
948
+ const percentMatch = /^%([A-Za-z_][A-Za-z0-9_]*)%/.exec(src.slice(i));
949
+ if (percentMatch) {
950
+ const value = lookupEnv(ctx.env, ctx.envLower, percentMatch[1]);
951
+ if (value === null) unresolved.push(percentMatch[0]);
952
+ else out += value;
953
+ i += percentMatch[0].length;
954
+ continue;
955
+ }
956
+ }
957
+ out += c;
958
+ i += 1;
959
+ }
960
+
961
+ return { text: out, unresolved, dynamic };
962
+ }
963
+
964
+ /**
965
+ * Detect a PowerShell provider path (registry, cert, env, ...) which is not a
966
+ * filesystem path.
967
+ * @param {string} raw
968
+ * @returns {string|null}
969
+ */
970
+ function detectProvider(raw) {
971
+ const match = /^(HKLM|HKCU|HKCR|HKU|HKCC|Cert|WSMan|Registry|Env|Function|Alias|Variable):/i.exec(String(raw || ''));
972
+ return match ? match[1].toLowerCase() : null;
973
+ }
974
+
975
+ /**
976
+ * Glob classification fallback from raw text.
977
+ * @param {string} text
978
+ * @param {boolean} allowBrace
979
+ * @returns {{hasGlob:boolean, globKind:string}}
980
+ */
981
+ function computeGlobFromText(text, allowBrace) {
982
+ const value = String(text || '');
983
+ const kinds = new Set();
984
+ if (value.includes('*')) kinds.add('asterisk');
985
+ if (value.includes('?')) kinds.add('question');
986
+ if (/\[[^\]]*\]/.test(value)) kinds.add('bracket');
987
+ if (allowBrace && /\{[^}]*[,][^}]*\}/.test(value)) kinds.add('brace');
988
+ if (kinds.size === 0) return { hasGlob: false, globKind: 'none' };
989
+ if (kinds.size > 1) return { hasGlob: true, globKind: 'mixed' };
990
+ return { hasGlob: true, globKind: kinds.values().next().value };
991
+ }
992
+
993
+ /**
994
+ * Pick the path flavour (Windows vs POSIX) for a target.
995
+ * @param {string} raw
996
+ * @param {string} shell
997
+ * @param {object} ctx
998
+ * @returns {'win32'|'posix'}
999
+ */
1000
+ function pickFlavor(raw, shell, ctx) {
1001
+ const value = String(raw || '').trim();
1002
+ if (/^[A-Za-z]:[\\/]/.test(value) || /^[A-Za-z]:$/.test(value) || /^\\\\/.test(value)) return 'win32';
1003
+ if (/^%[A-Za-z_][A-Za-z0-9_]*%/.test(value) || /\$env:/i.test(value)) return 'win32';
1004
+ if (value.startsWith('/')) {
1005
+ // A leading `/` is POSIX absolute in a POSIX shell even when the supplied
1006
+ // cwd looks like a Windows path (cross-platform parsing requirement).
1007
+ if (shell === 'posix') return 'posix';
1008
+ return ctx.defaultFlavor || 'posix';
1009
+ }
1010
+ if (value === '~' || value.startsWith('~/') || value.startsWith('~\\')) return ctx.homeFlavor || ctx.defaultFlavor || (shell === 'posix' ? 'posix' : 'win32');
1011
+ if (value.startsWith('./') || value.startsWith('../')) return ctx.defaultFlavor || (shell === 'posix' ? 'posix' : 'win32');
1012
+ if (value.includes('\\') && !value.includes('/')) return 'win32';
1013
+ // `cmd` path syntax is Windows-native, but a bare relative name is still
1014
+ // resolved against the working directory. On a POSIX host — PowerShell's
1015
+ // `ren` / `move` aliases, or an explicit cross-platform analysis — joining it
1016
+ // to the POSIX cwd beats leaving it unresolved: the self-guard can only judge
1017
+ // an unresolved move by its text, and `ren package.json package.bak` never
1018
+ // mentions the (relative) directory it runs in.
1019
+ if (shell === 'cmd') return ctx.cwdFlavor || ctx.defaultFlavor || 'win32';
1020
+ if (shell === 'posix') return ctx.defaultFlavor || 'posix';
1021
+ if (shell === 'pwsh') return ctx.defaultFlavor || 'win32';
1022
+ return ctx.defaultFlavor || 'posix';
1023
+ }
1024
+
1025
+ /**
1026
+ * Resolve an (already variable-expanded) path to an absolute normalised path.
1027
+ * @param {string} text
1028
+ * @param {'win32'|'posix'} flavor
1029
+ * @param {object} ctx
1030
+ * @returns {string|null}
1031
+ */
1032
+ function resolvePathValue(text, flavor, ctx) {
1033
+ if (typeof text !== 'string' || text.length === 0) return null;
1034
+ const mod = flavor === 'win32' ? path.win32 : path.posix;
1035
+ if (mod.isAbsolute(text)) return normalizeAbsolute(text, flavor);
1036
+ const cwdFlavor = ctx.cwdFlavor || ctx.defaultFlavor;
1037
+ if (!ctx.cwd || cwdFlavor !== flavor || !mod.isAbsolute(ctx.cwd)) return null;
1038
+ try {
1039
+ return normalizeAbsolute(mod.resolve(ctx.cwd, text), flavor);
1040
+ } catch {
1041
+ return null;
1042
+ }
1043
+ }
1044
+
1045
+ /**
1046
+ * Strip a `\\?\` / `\\.\` device prefix before wildcard probing.
1047
+ * @param {string} value
1048
+ * @returns {string}
1049
+ */
1050
+ function globProbeText(value) {
1051
+ const text = String(value || '');
1052
+ return /^\\\\[?.]\\/.test(text) ? text.slice(4) : text;
1053
+ }
1054
+
1055
+ /**
1056
+ * Home-dir / root / ancestor classification.
1057
+ * @param {string} raw
1058
+ * @param {string|null} resolvedPath
1059
+ * @param {'win32'|'posix'} flavor
1060
+ * @param {object} ctx
1061
+ * @returns {boolean}
1062
+ */
1063
+ function isRootLike(raw, resolvedPath, flavor, ctx) {
1064
+ const value = String(raw || '');
1065
+ if (value === '~' || value === '~/' || value === '~\\') return true;
1066
+ if (/(^|[\\/])\.\.([\\/]|$)/.test(value)) return true;
1067
+ if (value === '/' || /^[A-Za-z]:[\\/]*$/.test(value)) return true;
1068
+ if (!resolvedPath) return false;
1069
+ const mod = flavor === 'win32' ? path.win32 : path.posix;
1070
+ const root = mod.parse(resolvedPath).root;
1071
+ if (flavor === 'win32') {
1072
+ if (resolvedPath.toLowerCase() === root.toLowerCase()) return true;
1073
+ } else if (resolvedPath === root) {
1074
+ return true;
1075
+ }
1076
+ if (ctx.homeResolved && samePath(resolvedPath, ctx.homeResolved, flavor)) return true;
1077
+ if (mod.dirname(resolvedPath) === root && /[*?[\]{}]/.test(globProbeText(resolvedPath))) return true;
1078
+ if (ctx.cwd) {
1079
+ const cwdFlavor = ctx.cwdFlavor || ctx.defaultFlavor;
1080
+ if (cwdFlavor === flavor && mod.isAbsolute(ctx.cwd)) {
1081
+ const relative = mod.relative(resolvedPath, ctx.cwd);
1082
+ if (relative && relative !== '' && !relative.startsWith('..') && !mod.isAbsolute(relative)) return true;
1083
+ }
1084
+ }
1085
+ return false;
1086
+ }
1087
+
1088
+ /**
1089
+ * Whether a target is (or deletes everything under) a filesystem root.
1090
+ * @param {string} raw
1091
+ * @param {string|null} resolvedPath
1092
+ * @param {'win32'|'posix'} flavor
1093
+ * @returns {boolean}
1094
+ */
1095
+ function isAbsoluteRoot(raw, resolvedPath, flavor) {
1096
+ const value = String(raw || '');
1097
+ if (value === '/' || /^[A-Za-z]:[\\/]*$/.test(value)) return true;
1098
+ if (!resolvedPath) return false;
1099
+ const mod = flavor === 'win32' ? path.win32 : path.posix;
1100
+ const root = mod.parse(resolvedPath).root;
1101
+ if (flavor === 'win32' && resolvedPath.toLowerCase() === root.toLowerCase()) return true;
1102
+ if (flavor !== 'win32' && resolvedPath === root) return true;
1103
+ if (mod.dirname(resolvedPath) === root && /[*?[\]{}]/.test(globProbeText(resolvedPath))) return true;
1104
+ return false;
1105
+ }
1106
+
1107
+ /**
1108
+ * Whether a target path points into credential / system sensitive locations.
1109
+ * @param {string} raw
1110
+ * @param {string|null} resolvedPath
1111
+ * @returns {boolean}
1112
+ */
1113
+ function isProtectedPath(raw, resolvedPath) {
1114
+ const candidates = [raw, resolvedPath].filter((value) => typeof value === 'string' && value.length > 0);
1115
+ for (const candidate of candidates) {
1116
+ const text = String(candidate);
1117
+ const segments = text.toLowerCase().split(/[\\/]+/).filter(Boolean);
1118
+ for (const segment of segments) {
1119
+ if (SENSITIVE_SEGMENTS.has(segment) || SENSITIVE_NAMES.has(segment)) return true;
1120
+ if (WINDOWS_SYSTEM_SEGMENTS.has(segment)) return true;
1121
+ }
1122
+ const lowered = text.toLowerCase();
1123
+ for (const prefix of POSIX_SYSTEM_PREFIXES) {
1124
+ const lowerPrefix = prefix.toLowerCase();
1125
+ if (lowered === lowerPrefix || lowered.startsWith(lowerPrefix + '/')) return true;
1126
+ }
1127
+ }
1128
+ return false;
1129
+ }
1130
+
1131
+ /**
1132
+ * Resolve one raw target into a full {@link DeleteTarget} plus derived risks.
1133
+ * @param {object} rawTarget
1134
+ * @param {string} shell
1135
+ * @param {object} ctx
1136
+ * @returns {{target: DeleteTarget, risks: string[], unparsed: boolean, note: string|null}}
1137
+ */
1138
+ function resolveTarget(rawTarget, shell, ctx) {
1139
+ const risks = new Set();
1140
+ const raw = typeof rawTarget.raw === 'string' ? rawTarget.raw : '';
1141
+ const masked = typeof rawTarget.text === 'string' && rawTarget.text.length > 0 ? rawTarget.text : raw;
1142
+ const literal = rawTarget.literalGlob === true || rawTarget.literal === true;
1143
+ const provider = rawTarget.provider || detectProvider(raw);
1144
+ const expansion = expandVariables(masked, shell, ctx);
1145
+ let scope = rawTarget.scopeOverride || 'literal';
1146
+ if (!rawTarget.scopeOverride && (expansion.unresolved.length > 0 || expansion.dynamic)) scope = 'variable';
1147
+
1148
+ let hasGlob = false;
1149
+ let globKind = 'none';
1150
+ const extendedPathPrefix = /^\\\\[?.]\\/.test(raw);
1151
+ if (!literal) {
1152
+ if (extendedPathPrefix) {
1153
+ // `\\?\C:\...` / `\\.\C:\...` device prefixes use `?` as syntax, not as a
1154
+ // wildcard; classify glob characters in the remainder only.
1155
+ const derived = computeGlobFromText(raw.slice(4), shell === 'posix');
1156
+ hasGlob = derived.hasGlob;
1157
+ globKind = derived.globKind;
1158
+ } else {
1159
+ hasGlob = Boolean(rawTarget.hasGlob);
1160
+ if (hasGlob) globKind = rawTarget.globKind && rawTarget.globKind !== 'none' ? rawTarget.globKind : 'asterisk';
1161
+ }
1162
+ if (!hasGlob && scope === 'literal' && !/[*?[\]{}]/.test(raw)) {
1163
+ const derived = computeGlobFromText(expansion.text, shell === 'posix');
1164
+ // Only variable-derived globs are interesting here (raw text has none).
1165
+ if (derived.hasGlob && expansion.text !== raw) {
1166
+ hasGlob = true;
1167
+ globKind = derived.globKind;
1168
+ }
1169
+ }
1170
+ }
1171
+
1172
+ let resolvedPath = null;
1173
+ const flavor = pickFlavor(raw, shell, ctx);
1174
+ const note = typeof rawTarget.note === 'string' ? rawTarget.note : null;
1175
+ if (!provider && scope === 'literal') {
1176
+ resolvedPath = resolvePathValue(expansion.text, flavor, ctx);
1177
+ }
1178
+ if (provider) {
1179
+ resolvedPath = null;
1180
+ }
1181
+
1182
+ let absolute = false;
1183
+ if (resolvedPath) {
1184
+ const mod = flavor === 'win32' ? path.win32 : path.posix;
1185
+ absolute = mod.isAbsolute(resolvedPath);
1186
+ } else {
1187
+ absolute = /^[\\/]/.test(raw) || /^[A-Za-z]:[\\/]?/.test(raw) || /^~([\\/]|$)/.test(raw);
1188
+ }
1189
+ const rootLike = isRootLike(raw, resolvedPath, flavor, ctx);
1190
+
1191
+ if (scope === 'variable') risks.add('variable-target');
1192
+ if (rawTarget.synthetic) risks.add('unknown-construct');
1193
+ if (!provider && isAbsoluteRoot(raw, resolvedPath, flavor) && absolute) risks.add('absolute-root');
1194
+ if (provider || isProtectedPath(raw, resolvedPath)) risks.add('protected-path');
1195
+
1196
+ // A relative literal target with no usable working directory stays unresolved:
1197
+ // the caller interprets that as "unknown", never as "safe to delete".
1198
+ const relativeWithoutBase = scope === 'literal'
1199
+ && !provider
1200
+ && resolvedPath === null
1201
+ && !/^[\\/]/.test(raw)
1202
+ && !/^[A-Za-z]:[\\/]?/.test(raw)
1203
+ && !/^~([\\/]|$)/.test(raw);
1204
+ const unparsed = Boolean(rawTarget.synthetic) || scope === 'variable' || relativeWithoutBase;
1205
+ const target = {
1206
+ raw,
1207
+ resolvedPath,
1208
+ scope,
1209
+ hasGlob,
1210
+ globKind,
1211
+ absolute,
1212
+ rootLike,
1213
+ viaPipeline: Boolean(rawTarget.viaPipeline),
1214
+ ...(rawTarget.synthetic ? { synthetic: true } : {}),
1215
+ };
1216
+ return { target, risks: Array.from(risks), unparsed, note };
1217
+ }
1218
+
1219
+ /* ------------------------------------------------------------------------- *
1220
+ * Partial statement finalisation / intent assembly
1221
+ * ------------------------------------------------------------------------- */
1222
+
1223
+ /**
1224
+ * Build a partial statement with all defaults (parser.js side).
1225
+ * @param {object} fields
1226
+ * @returns {object}
1227
+ */
1228
+ function makePartial(fields) {
1229
+ return Object.assign(
1230
+ {
1231
+ shell: 'unknown',
1232
+ text: '',
1233
+ command: '',
1234
+ isDelete: false,
1235
+ dryRun: false,
1236
+ recursive: false,
1237
+ force: false,
1238
+ wildcard: false,
1239
+ deleteKind: 'none',
1240
+ unparsed: false,
1241
+ notes: [],
1242
+ risks: [],
1243
+ rawTargets: [],
1244
+ },
1245
+ fields,
1246
+ );
1247
+ }
1248
+
1249
+ /**
1250
+ * Turn a partial statement into a public {@link StatementIntent}.
1251
+ * @param {object} partial
1252
+ * @param {object} ctx
1253
+ * @returns {{statement: StatementIntent, risks: string[]}}
1254
+ */
1255
+ function finalizeStatement(partial, ctx) {
1256
+ const shell = ['pwsh', 'posix', 'cmd'].includes(partial.shell) ? partial.shell : 'unknown';
1257
+ const notes = [];
1258
+ for (const note of partial.notes || []) {
1259
+ if (typeof note === 'string' && note && !notes.includes(note)) notes.push(note);
1260
+ }
1261
+ const risks = new Set();
1262
+ for (const risk of partial.risks || []) if (typeof risk === 'string' && risk) risks.add(risk);
1263
+ const targets = [];
1264
+ let unparsed = Boolean(partial.unparsed);
1265
+
1266
+ if (partial.isDelete || partial.resolveTargets === true) {
1267
+ for (const rawTarget of partial.rawTargets || []) {
1268
+ try {
1269
+ const resolved = resolveTarget(rawTarget, shell === 'unknown' ? 'unknown' : shell, ctx);
1270
+ targets.push(resolved.target);
1271
+ for (const risk of resolved.risks) risks.add(risk);
1272
+ if (resolved.note && !notes.includes(resolved.note)) notes.push(resolved.note);
1273
+ if (resolved.unparsed) unparsed = true;
1274
+ } catch {
1275
+ unparsed = true;
1276
+ risks.add('unknown-construct');
1277
+ }
1278
+ }
1279
+ }
1280
+
1281
+ const wildcard = Boolean(partial.wildcard) || targets.some((target) => target.hasGlob);
1282
+ const statement = {
1283
+ shell,
1284
+ text: typeof partial.text === 'string' ? partial.text : '',
1285
+ command: typeof partial.command === 'string' ? partial.command : '',
1286
+ isDelete: Boolean(partial.isDelete),
1287
+ dryRun: Boolean(partial.dryRun),
1288
+ recursive: Boolean(partial.recursive),
1289
+ force: Boolean(partial.force),
1290
+ wildcard,
1291
+ targets,
1292
+ deleteKind: partial.deleteKind || (partial.isDelete ? 'other' : 'none'),
1293
+ unparsed,
1294
+ notes,
1295
+ };
1296
+
1297
+ if (statement.isDelete) {
1298
+ if (statement.recursive) risks.add('recursive');
1299
+ if (statement.wildcard) risks.add('wildcard');
1300
+ if (statement.dryRun) risks.add('dry-run');
1301
+ if (statement.unparsed) risks.add('unknown-construct');
1302
+ }
1303
+ if (targets.some((target) => target.viaPipeline)) risks.add('pipeline-generic');
1304
+ return { statement, risks: Array.from(risks) };
1305
+ }
1306
+
1307
+ /**
1308
+ * Push one partial statement into the accumulated state.
1309
+ * @param {object} state
1310
+ * @param {object} partial
1311
+ * @param {object} ctx
1312
+ */
1313
+ function pushPartial(state, partial, ctx) {
1314
+ const finalized = finalizeStatement(partial, ctx);
1315
+ state.statements.push(finalized.statement);
1316
+ for (const risk of finalized.risks) state.risks.add(risk);
1317
+ }
1318
+
1319
+ /**
1320
+ * Push an unparseable placeholder statement (internal error / depth cap).
1321
+ * @param {object} state
1322
+ * @param {object} ctx
1323
+ * @param {string} note
1324
+ */
1325
+ function pushStub(state, ctx, note) {
1326
+ pushPartial(
1327
+ state,
1328
+ makePartial({
1329
+ shell: 'unknown',
1330
+ unparsed: true,
1331
+ risks: ['unknown-construct'],
1332
+ notes: [note],
1333
+ }),
1334
+ ctx,
1335
+ );
1336
+ }
1337
+
1338
+ /**
1339
+ * Deduplicate targets while preserving first-seen order.
1340
+ * @param {DeleteTarget[]} targets
1341
+ * @returns {DeleteTarget[]}
1342
+ */
1343
+ function dedupeTargets(targets) {
1344
+ const seen = new Set();
1345
+ const out = [];
1346
+ for (const target of targets) {
1347
+ const key = (target.viaPipeline ? 'pipe|' : 'arg|') + (target.resolvedPath || '') + '|' + target.raw;
1348
+ if (seen.has(key)) continue;
1349
+ seen.add(key);
1350
+ out.push(target);
1351
+ }
1352
+ return out;
1353
+ }
1354
+
1355
+ /**
1356
+ * Stable sort of risk ids.
1357
+ * @param {Iterable<string>} risks
1358
+ * @returns {string[]}
1359
+ */
1360
+ function sortRisks(risks) {
1361
+ const unique = Array.from(new Set(Array.from(risks || []).filter((risk) => typeof risk === 'string' && risk)));
1362
+ return unique.sort((a, b) => {
1363
+ const ia = RISK_ORDER.indexOf(a);
1364
+ const ib = RISK_ORDER.indexOf(b);
1365
+ if (ia === -1 && ib === -1) return a.localeCompare(b);
1366
+ if (ia === -1) return 1;
1367
+ if (ib === -1) return -1;
1368
+ return ia - ib;
1369
+ });
1370
+ }
1371
+
1372
+ /**
1373
+ * Best-effort overall shell classification.
1374
+ * @param {StatementIntent[]} statements
1375
+ * @returns {'pwsh'|'posix'|'cmd'|'mixed'|'unknown'}
1376
+ */
1377
+ function overallShell(statements) {
1378
+ const shells = new Set();
1379
+ for (const statement of statements) if (statement.shell && statement.shell !== 'unknown') shells.add(statement.shell);
1380
+ if (shells.size === 0) return 'unknown';
1381
+ if (shells.size === 1) return shells.values().next().value;
1382
+ return 'mixed';
1383
+ }
1384
+
1385
+ /**
1386
+ * Build human-readable Chinese audit reasons.
1387
+ * @param {object} data partial intent data
1388
+ * @param {object} state analysis state
1389
+ * @returns {string[]}
1390
+ */
1391
+ function buildReasons(data, state) {
1392
+ const reasons = [];
1393
+ const risks = new Set(data.riskSignals || []);
1394
+ if (data.isDelete) reasons.push('检测到破坏性删除命令');
1395
+ else if (data.dryRun) reasons.push('检测到删除命令,但为干跑/预览模式(不会实际删除)');
1396
+ else if (state.truncated || state.overLimit) reasons.push('检测到可能删除的命令片段,但无法完整解析');
1397
+ else reasons.push('未检测到删除行为');
1398
+ if (data.recursive) reasons.push('检测到递归删除');
1399
+ if (data.wildcard) reasons.push('检测到通配符目标');
1400
+ if (risks.has('absolute-root')) reasons.push('删除目标为文件系统根路径');
1401
+ if (risks.has('protected-path')) reasons.push('删除目标位于受保护的系统/凭证路径');
1402
+ if (risks.has('variable-target') || risks.has('pipeline-generic')) reasons.push('删除目标不可解析或来自管道上游');
1403
+ if (risks.has('encoded-command')) reasons.push('检测到编码或间接执行命令,无法静态确认删除目标');
1404
+ if (risks.has('find-delete')) reasons.push('find -delete 会递归删除所有匹配项');
1405
+ if (risks.has('mirror-delete')) reasons.push('镜像删除会清除目标目录中多余的文件');
1406
+ if (risks.has('unlink')) reasons.push('unlink 直接移除文件,可能绕过回收站');
1407
+ if (risks.has('rm-long-options')) reasons.push('使用了 rm 长选项,删除语义需人工复核');
1408
+ if (risks.has('dry-run') && data.dryRun) reasons.push('命令包含干跑/预览标志 -WhatIf/--dry-run');
1409
+ if (state.truncated) reasons.push('命令超长,仅解析前 ' + MAX_COMMAND_LENGTH + ' 个字符');
1410
+ if (state.overLimit) reasons.push('语句或嵌套数量超限,仅解析了前一部分');
1411
+ return Array.from(new Set(reasons));
1412
+ }
1413
+
1414
+ /**
1415
+ * Assemble the final intent object.
1416
+ * @param {object} state
1417
+ * @param {object} ctx
1418
+ * @returns {DeleteIntent}
1419
+ */
1420
+ function buildIntent(state, ctx) {
1421
+ const statements = state.statements;
1422
+ const deleteStatements = statements.filter((statement) => statement.isDelete);
1423
+ const effective = deleteStatements.filter((statement) => !statement.dryRun);
1424
+ const isDelete = effective.length > 0;
1425
+ const dryRun = !isDelete && deleteStatements.some((statement) => statement.dryRun);
1426
+ const recursive = deleteStatements.some((statement) => statement.recursive);
1427
+ const force = deleteStatements.some((statement) => statement.force);
1428
+ const wildcard = deleteStatements.some((statement) => statement.wildcard);
1429
+ const targetSource = isDelete ? effective : deleteStatements;
1430
+ const targets = dedupeTargets(targetSource.flatMap((statement) => statement.targets));
1431
+ const riskSignals = sortRisks(state.risks);
1432
+ const unparsed = Boolean(state.unparsed || state.truncated || statements.some((statement) => statement.unparsed));
1433
+ const reasons = buildReasons(
1434
+ { isDelete, dryRun, recursive, wildcard, riskSignals: new Set(riskSignals) },
1435
+ state,
1436
+ );
1437
+ return {
1438
+ shell: overallShell(statements),
1439
+ isDelete,
1440
+ dryRun,
1441
+ recursive,
1442
+ force,
1443
+ wildcard,
1444
+ destructive: isDelete && !dryRun,
1445
+ deleteKind: (effective[0] ?? deleteStatements[0])?.deleteKind ?? 'none',
1446
+ targets,
1447
+ statements,
1448
+ reasons,
1449
+ unparsed,
1450
+ riskSignals,
1451
+ };
1452
+ }
1453
+
1454
+ /* ------------------------------------------------------------------------- *
1455
+ * Shell classification / wrappers / encoded commands
1456
+ * ------------------------------------------------------------------------- */
1457
+
1458
+ /** Aliases that unambiguously belong to PowerShell (not shared with POSIX/cmd). */
1459
+ const PWSH_ONLY_ALIASES = new Set(['ri', 'gci', 'gi', 'iex', 'iwr', 'irm', 'clc', 'cli', 'si', 'ni']);
1460
+
1461
+ /** POSIX / cmd control-structure keywords that can lead a statement chunk. */
1462
+ const CONTROL_KEYWORDS = new Set(['for', 'while', 'until', 'if', 'then', 'elif', 'else', 'do', 'done', 'fi', 'case', 'esac', 'select', 'function']);
1463
+
1464
+ /**
1465
+ * Classify a chunk as pwsh / cmd / posix / unknown.
1466
+ * @param {string} text
1467
+ * @param {object} ctx
1468
+ * @returns {'pwsh'|'cmd'|'posix'|'unknown'}
1469
+ */
1470
+ function classifyChunk(text, ctx) {
1471
+ const tokens = headTokens(text, 10);
1472
+ if (!tokens.length) return 'unknown';
1473
+ // Skip control keywords that can prefix a simple command (`do rm -rf ...`).
1474
+ let tokenIndex = 0;
1475
+ while (tokenIndex < tokens.length && ['do', 'then', 'else', 'elif', '!'].includes(baseName(tokens[tokenIndex].value))) {
1476
+ tokenIndex += 1;
1477
+ }
1478
+ const keywordOnly = tokenIndex >= tokens.length;
1479
+ const commandRaw = keywordOnly ? tokens[0].value : tokens[tokenIndex].value;
1480
+ const command = baseName(commandRaw);
1481
+ const lower = text.toLowerCase();
1482
+
1483
+ if (!keywordOnly && PWSH_CMDLETS.has(command)) return 'pwsh';
1484
+ if (!keywordOnly && PWSH_ONLY_ALIASES.has(command)) return 'pwsh';
1485
+ if (/\$env:/i.test(text) || /\$\{env:/i.test(text)) return 'pwsh';
1486
+ if (/::\s*Delete\s*\(/i.test(text) || /\.\s*Delete\s*\(/i.test(text)) return 'pwsh';
1487
+ if (/(?:^|\s)-[A-Za-z]+:(?:\$|\{|['"])/.test(text)) return 'pwsh';
1488
+ if (/(?:^|\s)-(?:whatif|literalpath|path|recurse|include|exclude|filter|confirm|erroraction|passthru|force|verbose|debug)\b/i.test(text)) {
1489
+ return 'pwsh';
1490
+ }
1491
+ if (/@["']\r?\n/.test(text)) return 'pwsh';
1492
+ if (/^[A-Z][a-z]+-[A-Z][A-Za-z]+$/.test(commandRaw)) return 'pwsh';
1493
+ if (/^[A-Za-z]+-[A-Za-z]+$/.test(commandRaw) && /^[A-Z]/.test(commandRaw)) return 'pwsh';
1494
+
1495
+ for (const stage of splitPipelineLoose(text).slice(1)) {
1496
+ const stageTokens = headTokens(stage, 2);
1497
+ if (stageTokens.length && PWSH_CMDLETS.has(baseName(stageTokens[0].value))) return 'pwsh';
1498
+ if (stageTokens.length && /\$env:/i.test(stage)) return 'pwsh';
1499
+ }
1500
+
1501
+ const hasSlashFlags = /(?:^|\s)\/[A-Za-z]/.test(text);
1502
+ // On Windows the shell tool is PowerShell: `rm -rf D:\x` is the Remove-Item
1503
+ // alias, not POSIX rm. Letting the POSIX parser treat backslashes as escapes
1504
+ // mangles the target (`D:\x` → `D:x`), which can hide a protected root.
1505
+ const windowsPath = /(?:^|[\s'"=])(?:[A-Za-z]:[\\/]|\\\\|\.{1,2}\\)/.test(text);
1506
+ const platform = ctx?.platform ?? process.platform;
1507
+ const nativeCmd = command === 'del' || command === 'erase' || command === 'rd' || command === 'robocopy' || command === 'rmdir' || command === 'for' || command === 'if';
1508
+ if (windowsPath && platform === 'win32' && !nativeCmd) return 'pwsh';
1509
+ // cmd control structures that embed a delete command in the same chunk.
1510
+ if (command === 'for' || command === 'if') {
1511
+ if (/\b(?:del|erase|rd|rmdir|robocopy)\b/i.test(text) && (hasSlashFlags || /%[A-Za-z_][A-Za-z0-9_]*%/.test(text) || text.includes('\\'))) {
1512
+ return 'cmd';
1513
+ }
1514
+ if (command === 'for' && /\bdo\b/i.test(text)) return 'cmd';
1515
+ return 'posix';
1516
+ }
1517
+ if (command === 'del' || command === 'erase' || command === 'robocopy' || command === 'rd') return 'cmd';
1518
+ if (command === 'rmdir') return hasSlashFlags ? 'cmd' : windowsPath ? 'pwsh' : 'posix';
1519
+ if (CMD_COMMANDS.has(command)) return 'cmd';
1520
+ if (POSIX_COMMANDS.has(command)) return 'posix';
1521
+ if (CONTROL_KEYWORDS.has(command) || keywordOnly) return 'posix';
1522
+ if (commandRaw.includes('/') || commandRaw.includes('\\')) {
1523
+ if (/\.ps1$/i.test(commandRaw)) return 'pwsh';
1524
+ if (/\.(cmd|bat)$/i.test(commandRaw)) return 'cmd';
1525
+ return 'unknown';
1526
+ }
1527
+ if (lower.length === 0) return 'unknown';
1528
+ return 'unknown';
1529
+ }
1530
+
1531
+ /** Delete/truncate verbs that make a wrapped child process destructive. */
1532
+ const DELETE_PAYLOAD_RE = /(^|[\s;|&{'"`])(?:remove-item|ri|rm|del|erase|rd|rmdir|clear-content|move-item)\b/i;
1533
+
1534
+ /**
1535
+ * Detect a shell wrapper (`bash -c`, `pwsh -Command`, `cmd /c`, `eval`, ...).
1536
+ * @param {string} text
1537
+ * @returns {object|null}
1538
+ */
1539
+ function detectWrapper(text) {
1540
+ const tokens = headTokens(text, 16);
1541
+ if (!tokens.length) return null;
1542
+ const first = baseName(tokens[0].value);
1543
+
1544
+ if (['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish'].includes(first)) {
1545
+ for (let i = 1; i < tokens.length; i += 1) {
1546
+ const value = tokens[i].value;
1547
+ const name = value.replace(/^-+/, '').toLowerCase();
1548
+ const combinedCommandFlag = value.startsWith('-') && !value.startsWith('--') && /^[a-z]*c[a-z]*$/.test(name);
1549
+ if (value.startsWith('-') && (name === 'c' || name === 'command' || combinedCommandFlag)) {
1550
+ const next = tokens[i + 1];
1551
+ if (!next) return null;
1552
+ const rest = text.slice(next.start, next.end);
1553
+ const restTokens = headTokens(rest, 2);
1554
+ const innerText = restTokens.length === 1 ? unquoteWord(rest) : rest;
1555
+ return { kind: 'inner', innerShell: 'posix', innerText, notes: ['经由 ' + first + ' -c 内联脚本执行'] };
1556
+ }
1557
+ if (value === '--' ) break;
1558
+ }
1559
+ return null;
1560
+ }
1561
+
1562
+ if (['pwsh', 'powershell'].includes(first)) {
1563
+ for (let i = 1; i < tokens.length; i += 1) {
1564
+ const value = tokens[i].value;
1565
+ if (!value.startsWith('-')) continue;
1566
+ const name = value.replace(/^-+/, '').toLowerCase();
1567
+ if (['encodedcommand', 'enc', 'ec', 'e'].includes(name)) {
1568
+ const next = tokens[i + 1];
1569
+ if (next && /^[A-Za-z0-9+/=]{8,}$/.test(unquoteWord(next.value))) {
1570
+ return { kind: 'encoded', shell: 'pwsh', note: 'PowerShell -EncodedCommand 使用 Base64 编码命令,无法静态解析(fail-closed)' };
1571
+ }
1572
+ }
1573
+ if (['command', 'c', 'com', 'commandwithargs'].includes(name)) {
1574
+ let innerText = text.slice(tokens[i].end).trim();
1575
+ const restTokens = headTokens(innerText, 2);
1576
+ if (restTokens.length === 1) innerText = unquoteWord(innerText);
1577
+ return { kind: 'inner', innerShell: 'pwsh', innerText, notes: ['经由 PowerShell -Command 内联脚本执行'] };
1578
+ }
1579
+ if (name === 'file' || name === 'f') return null;
1580
+ }
1581
+ return null;
1582
+ }
1583
+
1584
+ if (first === 'cmd') {
1585
+ for (let i = 1; i < tokens.length; i += 1) {
1586
+ const value = tokens[i].value.toLowerCase();
1587
+ if (value === '/c' || value === '/k') {
1588
+ let innerText = text.slice(tokens[i].end).trim();
1589
+ // `cmd /c "del /q /s *.*"`: cmd strips the surrounding quotes.
1590
+ const restTokens = headTokens(innerText, 2);
1591
+ if (restTokens.length === 1) innerText = unquoteWord(innerText);
1592
+ return { kind: 'inner', innerShell: 'cmd', innerText, notes: ['经由 cmd ' + value + ' 内联命令执行'] };
1593
+ }
1594
+ }
1595
+ return null;
1596
+ }
1597
+
1598
+ if (first === 'eval') {
1599
+ let innerText = text.slice(tokens[0].end).trim();
1600
+ const restTokens = headTokens(innerText, 2);
1601
+ if (restTokens.length === 1) innerText = unquoteWord(innerText);
1602
+ return { kind: 'inner', innerShell: 'posix', innerText, notes: ['经由 eval 动态执行'] };
1603
+ }
1604
+
1605
+ if (first === 'iex' || first === 'invoke-expression') {
1606
+ let rest = text.slice(tokens[0].end).trim();
1607
+ const restTokens = headTokens(rest, 2);
1608
+ if (restTokens.length === 0) return { kind: 'dynamic', shell: 'pwsh', note: 'Invoke-Expression 缺少可解析参数' };
1609
+ // `iex -Command "Remove-Item …"` is the same call as
1610
+ // `iex "Remove-Item …"`; the parameter name must not hide the payload.
1611
+ if (/^-(?:c|co|com|comm|comma|comman|command)$/i.test(restTokens[0].value)) {
1612
+ rest = rest.slice(restTokens[0].end).trim();
1613
+ return { kind: 'inner', innerShell: 'pwsh', innerText: unquoteWord(rest), notes: ['经由 Invoke-Expression -Command 执行'] };
1614
+ }
1615
+ const candidateRaw = restTokens[0].raw.trim();
1616
+ const literal = /^['"]/.test(candidateRaw);
1617
+ const candidate = restTokens[0].value;
1618
+ if (!literal && (/^\$/.test(candidate) || candidate.includes('$('))) {
1619
+ return { kind: 'dynamic', shell: 'pwsh', note: 'Invoke-Expression 接收变量/动态表达式,无法静态解析' };
1620
+ }
1621
+ const innerText = unquoteWord(rest);
1622
+ return { kind: 'inner', innerShell: 'pwsh', innerText, notes: ['经由 Invoke-Expression 执行'] };
1623
+ }
1624
+
1625
+ // `Start-Process` / `wsl` are process launchers: the deletion happens in the
1626
+ // child process. Extract the payload when it is a literal, otherwise treat the
1627
+ // call as an unparsed destructive command instead of letting it through.
1628
+ if (first === 'start-process' || first === 'saps' || first === 'start') {
1629
+ const quoted = [...text.matchAll(/(['"])([\s\S]*?)\1/g)].map(match => match[2]);
1630
+ const payload = quoted.find(value => DELETE_PAYLOAD_RE.test(value));
1631
+ if (payload) {
1632
+ // `Start-Process cmd -ArgumentList '/c del …'` runs the payload under
1633
+ // cmd.exe, not PowerShell. Dropping the `/c` context made the inner
1634
+ // parser see a harmless "del" statement and let the call through.
1635
+ const cmdPrefix = /^\/(?:c|k)\s+/i.exec(payload.trim());
1636
+ if (cmdPrefix) {
1637
+ return {
1638
+ kind: 'inner',
1639
+ innerShell: 'cmd',
1640
+ innerText: payload.trim().slice(cmdPrefix[0].length),
1641
+ notes: ['经由 Start-Process cmd /c 间接执行'],
1642
+ };
1643
+ }
1644
+ return { kind: 'inner', innerShell: 'pwsh', innerText: payload, notes: ['经由 Start-Process 间接执行'] };
1645
+ }
1646
+ if (DELETE_PAYLOAD_RE.test(text)) {
1647
+ return { kind: 'dynamic', shell: 'pwsh', note: 'Start-Process 启动的子进程可能执行删除,目标无法静态解析' };
1648
+ }
1649
+ return null;
1650
+ }
1651
+
1652
+ if (first === 'wsl') {
1653
+ // `wsl [-d distro] [-u user] [--cd dir] [--exec] <command …>`
1654
+ let index = 1;
1655
+ while (index < tokens.length) {
1656
+ const value = tokens[index].value;
1657
+ if (!value.startsWith('-')) break;
1658
+ const name = value.replace(/^-+/, '').toLowerCase();
1659
+ if (['d', 'distribution', 'u', 'user', 'cd', 'shell-type', 'set-default-user'].includes(name)) index += 2;
1660
+ else index += 1;
1661
+ }
1662
+ if (index >= tokens.length) return null;
1663
+ return {
1664
+ kind: 'inner',
1665
+ innerShell: 'posix',
1666
+ innerText: text.slice(tokens[index].start),
1667
+ notes: ['经由 wsl 在 Linux 子系统中执行'],
1668
+ };
1669
+ }
1670
+
1671
+ return null;
1672
+ }
1673
+
1674
+ /**
1675
+ * Strip leading wrappers that do not change deletion semantics (`sudo`, `env`, ...).
1676
+ * @param {string} text
1677
+ * @returns {{text:string, notes:string[]}}
1678
+ */
1679
+ function stripLeadingPrefixes(text) {
1680
+ let rest = String(text || '').trim();
1681
+ const notes = [];
1682
+ for (let guard = 0; guard < 6; guard += 1) {
1683
+ const tokens = headTokens(rest, 12);
1684
+ if (!tokens.length) break;
1685
+ const first = baseName(tokens[0].value);
1686
+ if (COMMAND_PREFIXES.has(first)) {
1687
+ const valueOptions = PREFIX_VALUE_OPTIONS[first] || new Set();
1688
+ let index = 1;
1689
+ while (index < tokens.length) {
1690
+ const value = tokens[index].value;
1691
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(value)) {
1692
+ index += 1;
1693
+ continue;
1694
+ }
1695
+ if (value.startsWith('-')) {
1696
+ const option = value.replace(/^-+/, '').toLowerCase();
1697
+ if (valueOptions.has(option) && tokens[index + 1] && !tokens[index + 1].value.startsWith('-')) index += 2;
1698
+ else index += 1;
1699
+ continue;
1700
+ }
1701
+ if (first === 'timeout' && /^\d+(?:\.\d+)?[smhd]?$/.test(value)) {
1702
+ index += 1;
1703
+ continue;
1704
+ }
1705
+ break;
1706
+ }
1707
+ if (index >= tokens.length) break;
1708
+ notes.push('经 ' + first + ' 前缀包装');
1709
+ rest = rest.slice(tokens[index].start).trim();
1710
+ continue;
1711
+ }
1712
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0].value)) {
1713
+ notes.push('剥离前置环境变量赋值');
1714
+ rest = rest.slice(tokens[0].end).trim();
1715
+ continue;
1716
+ }
1717
+ break;
1718
+ }
1719
+ return { text: rest, notes };
1720
+ }
1721
+
1722
+ /**
1723
+ * Detect `base64 -d ... | sh` style encoded execution.
1724
+ * @param {string} text
1725
+ * @returns {object|null} partial statement
1726
+ */
1727
+ function detectEncodedPipeline(text) {
1728
+ const stages = splitPipelineLoose(text);
1729
+ if (stages.length < 2) return null;
1730
+ let sawDecode = false;
1731
+ let decoder = '';
1732
+ for (const stage of stages) {
1733
+ const tokens = headTokens(stage, 4);
1734
+ if (!tokens.length) continue;
1735
+ const command = baseName(tokens[0].value);
1736
+ if ((command === 'base64' || command === 'b64decode' || command === 'openssl') && /(?:^|\s)(?:-d|--decode|-D)(?:\s|$)/.test(stage)) {
1737
+ sawDecode = true;
1738
+ decoder = command;
1739
+ continue;
1740
+ }
1741
+ if (command === 'certutil' && /-decode/i.test(stage)) {
1742
+ sawDecode = true;
1743
+ decoder = command;
1744
+ continue;
1745
+ }
1746
+ const interpreters = ['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish', 'pwsh', 'powershell', 'iex', 'invoke-expression', 'node', 'python', 'python3'];
1747
+ if (sawDecode && interpreters.includes(command)) {
1748
+ let shell = 'posix';
1749
+ if (['pwsh', 'powershell', 'iex', 'invoke-expression'].includes(command)) shell = 'pwsh';
1750
+ else if (command === 'node' || command.startsWith('python')) shell = 'unknown';
1751
+ return makePartial({
1752
+ shell,
1753
+ text: text.trim(),
1754
+ command,
1755
+ isDelete: true,
1756
+ deleteKind: 'other',
1757
+ unparsed: true,
1758
+ notes: [decoder + ' 解码后的内容经管道交给 ' + command + ' 执行,无法静态解析(fail-closed)'],
1759
+ risks: ['encoded-command'],
1760
+ });
1761
+ }
1762
+ }
1763
+ return null;
1764
+ }
1765
+
1766
+ /**
1767
+ * Build a generic (non-delete) partial statement.
1768
+ * @param {string} text
1769
+ * @param {string} shell
1770
+ * @returns {object}
1771
+ */
1772
+ function makeGenericPartial(text, shell) {
1773
+ const tokens = headTokens(text, 4);
1774
+ return makePartial({
1775
+ shell,
1776
+ text: String(text || '').trim(),
1777
+ command: tokens.length ? baseName(tokens[0].value) : '',
1778
+ });
1779
+ }
1780
+
1781
+ /* ------------------------------------------------------------------------- *
1782
+ * Chunk analysis
1783
+ * ------------------------------------------------------------------------- */
1784
+
1785
+ /**
1786
+ * Analyse one chunk (simple statement or pipeline).
1787
+ * @param {string} chunk
1788
+ * @param {object} state
1789
+ * @param {object} ctx
1790
+ * @param {{depth:number, forcedShell:string|null}} opts
1791
+ */
1792
+ function parseChunk(chunk, state, ctx, opts) {
1793
+ const depth = opts.depth || 0;
1794
+ if (state.statements.length >= MAX_STATEMENTS) {
1795
+ state.unparsed = true;
1796
+ state.overLimit = true;
1797
+ return;
1798
+ }
1799
+ const stripped = stripLeadingPrefixes(chunk);
1800
+ const text = stripped.text;
1801
+ if (!text) return;
1802
+ const prefixNotes = stripped.notes;
1803
+
1804
+ try {
1805
+ const wrapper = detectWrapper(text);
1806
+ if (wrapper) {
1807
+ if (wrapper.kind === 'encoded') {
1808
+ pushPartial(
1809
+ state,
1810
+ makePartial({
1811
+ shell: wrapper.shell || 'unknown',
1812
+ text: text.trim(),
1813
+ command: baseName(text),
1814
+ isDelete: true,
1815
+ deleteKind: 'other',
1816
+ unparsed: true,
1817
+ notes: [wrapper.note],
1818
+ risks: ['encoded-command'],
1819
+ }),
1820
+ ctx,
1821
+ );
1822
+ return;
1823
+ }
1824
+ if (wrapper.kind === 'dynamic') {
1825
+ pushPartial(
1826
+ state,
1827
+ makePartial({
1828
+ shell: wrapper.shell || 'unknown',
1829
+ text: text.trim(),
1830
+ command: baseName(text),
1831
+ isDelete: true,
1832
+ deleteKind: 'other',
1833
+ unparsed: true,
1834
+ notes: [wrapper.note],
1835
+ risks: ['unknown-construct'],
1836
+ }),
1837
+ ctx,
1838
+ );
1839
+ return;
1840
+ }
1841
+ if (wrapper.kind === 'inner') {
1842
+ if (depth + 1 > MAX_WRAP_DEPTH) {
1843
+ pushStub(state, ctx, 'shell 包装嵌套层级过深,无法继续解析');
1844
+ return;
1845
+ }
1846
+ const before = state.statements.length;
1847
+ analyze(wrapper.innerText, state, ctx, { depth: depth + 1, forcedShell: wrapper.innerShell });
1848
+ const added = state.statements.slice(before);
1849
+ const destructive = added.some(statement =>
1850
+ statement.isDelete === true
1851
+ || statement.deleteKind === 'move'
1852
+ || statement.deleteKind === 'truncate');
1853
+ if (added.length === 0) {
1854
+ pushPartial(state, makeGenericPartial(text, wrapper.innerShell || 'unknown'), ctx);
1855
+ } else if (DELETE_PAYLOAD_RE.test(wrapper.innerText) && !destructive) {
1856
+ // The wrapper clearly names a delete/move verb but the inner parser
1857
+ // produced only generic statements (shell syntax mismatch, e.g. a
1858
+ // cmd-style payload parsed as PowerShell). Fail closed instead of
1859
+ // reporting the call as harmless.
1860
+ pushPartial(
1861
+ state,
1862
+ makePartial({
1863
+ shell: wrapper.innerShell || 'unknown',
1864
+ text: text.trim(),
1865
+ command: baseName(text),
1866
+ isDelete: true,
1867
+ deleteKind: 'other',
1868
+ unparsed: true,
1869
+ notes: prefixNotes.concat(wrapper.notes || [], '包装命令内出现删除/移动动词,但内层无法解析,按不可确认风险处理'),
1870
+ risks: ['unknown-construct'],
1871
+ }),
1872
+ ctx,
1873
+ );
1874
+ } else {
1875
+ for (const statement of added) {
1876
+ for (const note of prefixNotes.concat(wrapper.notes || [])) {
1877
+ if (note && !statement.notes.includes(note)) statement.notes.push(note);
1878
+ }
1879
+ }
1880
+ }
1881
+ return;
1882
+ }
1883
+ }
1884
+
1885
+ const encoded = detectEncodedPipeline(text);
1886
+ if (encoded) {
1887
+ pushPartial(state, encoded, ctx);
1888
+ return;
1889
+ }
1890
+
1891
+ const shell = opts.forcedShell || classifyChunk(text, ctx);
1892
+ let partials;
1893
+ if (shell === 'pwsh') partials = parsePwshStatements(text, depth);
1894
+ else if (shell === 'cmd') partials = parseCmdStatements(text, depth);
1895
+ else if (shell === 'posix') partials = parsePosixStatements(text, depth);
1896
+ else partials = [makeGenericPartial(text, 'unknown')];
1897
+ if (!partials || partials.length === 0) partials = [makeGenericPartial(text, shell === 'unknown' ? 'unknown' : shell)];
1898
+ for (const partial of partials) {
1899
+ if (prefixNotes.length) partial.notes = (partial.notes || []).concat(prefixNotes);
1900
+ pushPartial(state, partial, ctx);
1901
+ }
1902
+ } catch {
1903
+ pushStub(state, ctx, '命令片段解析异常,已按不可解析处理');
1904
+ }
1905
+ }
1906
+
1907
+ /**
1908
+ * Recursively analyse command text (top-level statements + substitutions).
1909
+ * @param {string} text
1910
+ * @param {object} state
1911
+ * @param {object} ctx
1912
+ * @param {{depth:number, forcedShell:string|null}} opts
1913
+ */
1914
+ function analyze(text, state, ctx, opts) {
1915
+ const depth = opts.depth || 0;
1916
+ if (depth > MAX_ANALYZE_DEPTH) {
1917
+ pushStub(state, ctx, '命令替换嵌套层级过深,无法继续解析');
1918
+ return;
1919
+ }
1920
+ const source = String(text || '');
1921
+ if (!source.trim()) return;
1922
+ try {
1923
+ const style = detectStyle(source);
1924
+ const subcommands = collectSubcommands(source, style);
1925
+ const chunks = splitTopLevel(source);
1926
+ for (const chunk of chunks) {
1927
+ if (state.statements.length >= MAX_STATEMENTS) {
1928
+ state.unparsed = true;
1929
+ state.overLimit = true;
1930
+ break;
1931
+ }
1932
+ parseChunk(chunk, state, ctx, { depth, forcedShell: opts.forcedShell || null });
1933
+ }
1934
+ for (const subcommand of subcommands) {
1935
+ if (state.subcommandCount >= MAX_SUBCOMMANDS) {
1936
+ state.unparsed = true;
1937
+ state.overLimit = true;
1938
+ break;
1939
+ }
1940
+ state.subcommandCount += 1;
1941
+ if (state.statements.length >= MAX_STATEMENTS) {
1942
+ state.unparsed = true;
1943
+ state.overLimit = true;
1944
+ break;
1945
+ }
1946
+ analyze(subcommand, state, ctx, { depth: depth + 1, forcedShell: opts.forcedShell || null });
1947
+ }
1948
+ } catch {
1949
+ pushStub(state, ctx, '命令解析异常,已按不可解析处理');
1950
+ }
1951
+ }
1952
+
1953
+ /**
1954
+ * Build a minimal empty intent.
1955
+ * @param {'pwsh'|'posix'|'cmd'|'mixed'|'unknown'} shell
1956
+ * @param {boolean} unparsed
1957
+ * @param {string[]} reasons
1958
+ * @returns {DeleteIntent}
1959
+ */
1960
+ function emptyIntent(shell, unparsed, reasons) {
1961
+ return {
1962
+ shell,
1963
+ isDelete: false,
1964
+ dryRun: false,
1965
+ recursive: false,
1966
+ force: false,
1967
+ wildcard: false,
1968
+ destructive: false,
1969
+ targets: [],
1970
+ statements: [],
1971
+ reasons,
1972
+ unparsed,
1973
+ riskSignals: [],
1974
+ };
1975
+ }
1976
+
1977
+ /* ------------------------------------------------------------------------- *
1978
+ * Public API
1979
+ * ------------------------------------------------------------------------- */
1980
+
1981
+ /**
1982
+ * Parse raw tool command text into a deletion intent.
1983
+ *
1984
+ * @param {string} command raw tool command text (pwsh / bash / cmd)
1985
+ * @param {{ cwd?: string, homeDir?: string, env?: Record<string,string>, platform?: string }} [options]
1986
+ * @returns {DeleteIntent}
1987
+ */
1988
+ export function parseDeleteIntent(command, options = {}) {
1989
+ try {
1990
+ const ctx = buildContext(options);
1991
+ if (typeof command !== 'string') {
1992
+ return emptyIntent('unknown', true, ['输入不是字符串,无法解析命令']);
1993
+ }
1994
+ let text = command;
1995
+ let truncated = false;
1996
+ if (text.length > MAX_COMMAND_LENGTH) {
1997
+ text = text.slice(0, MAX_COMMAND_LENGTH);
1998
+ truncated = true;
1999
+ }
2000
+ if (!text.trim()) {
2001
+ return emptyIntent('unknown', false, ['命令为空,未检测到删除行为']);
2002
+ }
2003
+ const state = {
2004
+ statements: [],
2005
+ risks: new Set(),
2006
+ unparsed: truncated,
2007
+ truncated,
2008
+ overLimit: false,
2009
+ subcommandCount: 0,
2010
+ };
2011
+ analyze(text, state, ctx, { depth: 0, forcedShell: null });
2012
+ const intent = buildIntent(state, ctx);
2013
+ if (truncated) intent.unparsed = true;
2014
+ return intent;
2015
+ } catch {
2016
+ return emptyIntent('unknown', true, ['解析器内部异常,已按不可解析处理']);
2017
+ }
2018
+ }
2019
+
2020
+ /**
2021
+ * True when the intent contains a real destructive deletion (not dry-run).
2022
+ *
2023
+ * A dry-run-only intent (`Remove-Item -WhatIf ...`) is not destructive.
2024
+ *
2025
+ * @param {DeleteIntent} intent
2026
+ * @returns {boolean}
2027
+ */
2028
+ export function isDestructive(intent) {
2029
+ try {
2030
+ if (!intent || typeof intent !== 'object') return false;
2031
+ return intent.isDelete === true && intent.dryRun !== true;
2032
+ } catch {
2033
+ return false;
2034
+ }
2035
+ }
2036
+
2037
+ /**
2038
+ * Human-readable Chinese one-liner summary of the intent (audit log / reason).
2039
+ *
2040
+ * @param {DeleteIntent} intent
2041
+ * @param {{ maxTargets?: number, maxLength?: number }} [options]
2042
+ * @returns {string}
2043
+ */
2044
+ export function describeIntent(intent, options = {}) {
2045
+ try {
2046
+ if (!intent || typeof intent !== 'object') return '删除意图无效';
2047
+ const opts = options && typeof options === 'object' ? options : {};
2048
+ const maxTargets = Number.isInteger(opts.maxTargets) && opts.maxTargets > 0 ? opts.maxTargets : 3;
2049
+ const maxLength = Number.isInteger(opts.maxLength) && opts.maxLength >= 20 ? opts.maxLength : 240;
2050
+ const shellLabel = SHELL_LABELS[intent.shell] || SHELL_LABELS.unknown;
2051
+ const targets = Array.isArray(intent.targets) ? intent.targets : [];
2052
+ const targetTexts = targets
2053
+ .slice(0, maxTargets)
2054
+ .map((target) => {
2055
+ const value = target && (target.resolvedPath || target.raw);
2056
+ const text = typeof value === 'string' && value ? value : '<未知目标>';
2057
+ return text.length > 60 ? text.slice(0, 57) + '...' : text;
2058
+ });
2059
+ let summary;
2060
+ if (intent.isDelete) {
2061
+ const traits = [];
2062
+ if (intent.recursive) traits.push('递归');
2063
+ if (intent.wildcard) traits.push('通配符');
2064
+ if (intent.force) traits.push('强制');
2065
+ summary = '检测到破坏性删除(' + shellLabel + (traits.length ? ',' + traits.join(' / ') : '') + ')';
2066
+ if (targets.length > 0) {
2067
+ summary += ',目标' + (targets.length > 1 ? '(' + targets.length + ' 个)' : '') + ':' + targetTexts.join('、');
2068
+ if (targets.length > maxTargets) summary += ' 等';
2069
+ }
2070
+ if (intent.unparsed) summary += ';存在无法静态解析的部分,需要人工确认';
2071
+ } else if (intent.dryRun) {
2072
+ summary = '检测到删除命令但为干跑/预览模式(' + shellLabel + '),不会实际删除';
2073
+ } else if (intent.unparsed) {
2074
+ summary = '未确认到具体删除行为,但存在无法解析的命令片段(' + shellLabel + '),需要人工确认';
2075
+ } else {
2076
+ summary = '未检测到删除行为(' + shellLabel + ')';
2077
+ }
2078
+ return summary.length > maxLength ? summary.slice(0, maxLength - 1) + '…' : summary;
2079
+ } catch {
2080
+ return '删除意图描述不可用';
2081
+ }
2082
+ }