pi-odd-worktree 2.1.0 → 3.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 (160) hide show
  1. package/README.md +54 -319
  2. package/extensions/odd-worktree-tools.ts +4182 -2539
  3. package/lib/bash-activity.js +1166 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1421 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +323 -15
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -712
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1420 -0
  75. package/tools/bash-design.test.js +1093 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +613 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1889 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +417 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1517 -67
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4235 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2565 -309
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +419 -199
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,559 @@
1
+ 'use strict';
2
+ // S2 / S3 / S4 (T3): the DESTRUCTIVE evidence behind the eighth bash card identity —
3
+ // what a call deletes, so the card can head with `⚠ destructive` before the output
4
+ // arrives.
5
+ //
6
+ // Ported from the user's own gentle-shell branch (`cards-bash-v2`,
7
+ // `lib/destructive-card-activity.ts` and the pure `recognizeDestructiveCommands` of
8
+ // `lib/destructive-command-guard.ts`, read read-only) and TRIMMED to the family it
9
+ // serves.
10
+ //
11
+ // This is PRESENTATION evidence only. It decides the mark and the word a bash card
12
+ // heads with, and NO permission, guard or execution decision in this package may ever
13
+ // read it: "would a reader want to see what this deletes?" is a different question
14
+ // from "may this run?", and that question is answered elsewhere, by other code, on
15
+ // another path. Nothing here returns a verdict, refuses a command or gates a spawn.
16
+ //
17
+ // The rule it implements is the one a database client forces on any reader: a client
18
+ // is fed its statements through a pipe or a heredoc, so the WHOLE command — not one
19
+ // segment — has to be read to prove what it deletes. Everything this reader cannot
20
+ // prove answers "not proven", never "probably safe": an unknown wrapper, a client
21
+ // reading a script it never shows, a payload that expands at run time, a program this
22
+ // vocabulary does not name. A "false" here is an absence of evidence, which is what
23
+ // lets the call keep whatever other identity it has, or the generic `$ bash` card.
24
+ //
25
+ // The vocabulary is deliberately small and positional: only a command-position word
26
+ // can name a program, so prose a program merely receives — `echo 'rm -rf /'`,
27
+ // `git commit -m "rm -rf /tmp"`, a quoted payload — is never read as a deletion.
28
+ //
29
+ // Plain CommonJS and Node builtins only: this package ships no dependency.
30
+
31
+ // The three kinds the recognizer below can prove. Only the database kind is evidence
32
+ // a segment cannot state on its own, so it is the kind the whole-command reader keeps;
33
+ // the other two are proven by the segment the shell already spells out, and naming
34
+ // them here is what keeps the recognizer's own reading readable.
35
+ const DESTRUCTION_KIND = { DATABASE: 'database', FILESYSTEM: 'filesystem', GIT: 'git' };
36
+
37
+ // ---- the whole-command evidence ----
38
+
39
+ /**
40
+ * Whether a whole command carries data-loss evidence its segments cannot show on
41
+ * their own: the SQL a pipe or a heredoc feeds a client (`echo 'DROP TABLE t' |
42
+ * psql`). Only the database verdict is read here — a filesystem or git deletion is
43
+ * already visible in the segment that performs it, so this reader answers the one
44
+ * question a segment cannot.
45
+ */
46
+ function isDestructiveCommand(command) {
47
+ if (typeof command !== 'string' || command.length === 0) return false;
48
+ return recognizeDestructiveCommands(command).some((match) => match.kind === DESTRUCTION_KIND.DATABASE);
49
+ }
50
+
51
+ /**
52
+ * Whether one segment runs a database client, whose statements arrive through a pipe
53
+ * or a heredoc rather than in the segment's own text. The classifier reads it to know
54
+ * which segments a proven deletion already names, so the client and the payload it
55
+ * reads do not leave the call unnamed beside evidence that was proven elsewhere.
56
+ */
57
+ function isSqlClientSegment(segment) {
58
+ const command = commandArguments(segment);
59
+ if (command === undefined) return false;
60
+ return SQL_CLIENT_PROGRAMS.has(executable(command[0]));
61
+ }
62
+
63
+ // ---- the segment evidence ----
64
+
65
+ /**
66
+ * Whether one simple shell segment deletes something irreversible, as far as a reader
67
+ * of the command can tell. A help request, a dry run and a recovery are exempt: they
68
+ * change nothing, so the card keeps the identity the call really has (a query, a
69
+ * remote verb, an unnameable action) instead of warning about a deletion that will
70
+ * not happen.
71
+ */
72
+ function isDestructiveSegment(segment) {
73
+ const command = commandArguments(segment);
74
+ if (command === undefined) return false;
75
+ const head = command[0];
76
+ const args = command.slice(1);
77
+ const program = executable(head);
78
+ // A usage page prints and stops. The shell removed any quoting, so a word that
79
+ // reaches the program as `--help` is one, whichever way it was written.
80
+ if (args.includes('--help')) return false;
81
+ // `--dry-run` reports what a command would do; it never does it.
82
+ if (args.some((arg) => arg === '--dry-run' || arg.startsWith('--dry-run='))) return false;
83
+ // The short spelling is not universal: git's own `-n` is the dry run its deleting
84
+ // verbs accept, but another program spells an ordinary option that way —
85
+ // `kubectl delete pod web -n prod` names the namespace and deletes the pod — so the
86
+ // one-letter flag is read only where git itself assigns it that meaning.
87
+ if (program === 'git' && args.some((arg) => /^-[^-]*n/.test(arg))) return false;
88
+ if (program === 'git') return gitDeletes(args);
89
+ if (program === 'docker' || program === 'kubectl') return containerDeletes(program, args);
90
+ if (PAYLOAD_PROGRAMS.has(program)) return recognizeDestructiveCommands(segment).length > 0;
91
+ return DELETING_PROGRAMS.has(program) && programDeletes(program, args);
92
+ }
93
+
94
+ /** Options that take the word after them, so a wrapper's value is not read as its command. */
95
+ const WRAPPER_VALUE_OPTIONS = {
96
+ env: ['-u', '--unset', '-C', '--chdir'],
97
+ sudo: ['-u', '-g', '-h', '-p', '-C', '--user', '--group', '--host', '--prompt', '--chdir'],
98
+ timeout: ['-s', '--signal', '-k', '--kill-after'],
99
+ // `nice -n 5 rm …` only changes the priority of the command it runs.
100
+ nice: ['-n', '--adjustment'],
101
+ };
102
+
103
+ /** Programs that run the command after them, unchanged in what it deletes. */
104
+ const WRAPPERS = new Set(['env', 'sudo', 'doas', 'command', 'exec', 'nohup', 'timeout', 'nice']);
105
+
106
+ /** Programs whose own arguments name what they delete. */
107
+ const DELETING_PROGRAMS = new Set(['rm', 'shred', 'truncate', 'dd']);
108
+
109
+ /** Programs that run the SQL a pipe or a heredoc hands them. */
110
+ const SQL_CLIENT_PROGRAMS = new Set(['psql', 'mysql', 'mariadb', 'sqlite3']);
111
+
112
+ /**
113
+ * Programs whose payload the recognizer below already reads: a shell body, an `eval`,
114
+ * a SQL client's statements, and `find`'s exec. Their reading is reused rather than
115
+ * re-implemented, so there is one definition of what those payloads delete and no
116
+ * second shell or SQL vocabulary to drift.
117
+ */
118
+ const PAYLOAD_PROGRAMS = new Set(['sh', 'bash', 'zsh', 'dash', 'eval', ...SQL_CLIENT_PROGRAMS, 'find']);
119
+
120
+ /** Git global options that consume the word after them. */
121
+ const GIT_GLOBAL_VALUE_OPTIONS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace']);
122
+
123
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z_0-9]*=/;
124
+
125
+ /** What one non-git, non-payload tool's own arguments say it deletes. */
126
+ function programDeletes(program, args) {
127
+ // `dd` only destroys when it writes to a file or a device; a sink is not a target.
128
+ if (program === 'dd') return args.some((arg) => arg.startsWith('of=') && !/^of=\/dev\/(null|stdout|stderr|zero)$/.test(arg));
129
+ // `rm`, `shred` and `truncate` need something to act on: without an operand the
130
+ // program prints its usage and exits.
131
+ return hasOperand(args);
132
+ }
133
+
134
+ /**
135
+ * Containers and clusters: a verb that removes, deletes or prunes what it names.
136
+ * `docker rm` without a target prints usage, while `prune` deletes by definition.
137
+ */
138
+ function containerDeletes(program, args) {
139
+ if (program === 'kubectl') return args[0] === 'delete' && hasOperand(args.slice(1));
140
+ const subcommand = args[0];
141
+ if (subcommand === 'rm' || subcommand === 'rmi') return hasOperand(args.slice(1));
142
+ // `docker system|builder|image|volume|container|network <rm|prune>`.
143
+ if (subcommand === undefined || !DOCKER_OBJECTS.has(subcommand)) return false;
144
+ const action = args[1];
145
+ if (action === 'prune') return true;
146
+ return (action === 'rm' || action === 'rmi') && hasOperand(args.slice(2));
147
+ }
148
+
149
+ /** The docker object groups whose `rm`/`prune` sub-subcommand deletes. */
150
+ const DOCKER_OBJECTS = new Set(['system', 'builder', 'image', 'volume', 'container', 'network']);
151
+
152
+ /** Whether the arguments name at least one operand, honouring the `--` terminator. */
153
+ function hasOperand(args) {
154
+ let options = true;
155
+ for (const arg of args) {
156
+ if (options && arg === '--') {
157
+ options = false;
158
+ continue;
159
+ }
160
+ if (options && arg.length > 1 && arg.startsWith('-')) continue;
161
+ return true;
162
+ }
163
+ return false;
164
+ }
165
+
166
+ /** The git verbs that discard work, and the flags that make a gentler verb do it. */
167
+ function gitDeletes(args) {
168
+ let index = 0;
169
+ while (index < args.length && args[index].startsWith('-')) {
170
+ const flag = args[index];
171
+ index += 1;
172
+ if (GIT_GLOBAL_VALUE_OPTIONS.has(flag)) index += 1;
173
+ }
174
+ const action = args[index];
175
+ const flags = args.slice(index + 1);
176
+ const force = flags.some((flag) => /^-[^-]*f/.test(flag) || /^--force(=|$)/.test(flag));
177
+ const dryRun = flags.some((flag) => /^-[^-]*n/.test(flag));
178
+ switch (action) {
179
+ // `--soft` and `--mixed` move the index only; `--hard` throws the worktree away.
180
+ case 'reset':
181
+ return flags.includes('--hard');
182
+ // A clean without a force flag refuses to delete anything, and `-n` only lists.
183
+ case 'clean':
184
+ return force && !dryRun;
185
+ // A path checkout discards uncommitted work: the working tree after `--`, a forced
186
+ // checkout, or the unambiguous path `.`/`..` (git has no branch with that name). A
187
+ // branch checkout — `git checkout main`, `git checkout -b x` — switches branch and
188
+ // leaves the working tree alone.
189
+ case 'checkout':
190
+ return force || namesWorkingTree(flags);
191
+ // Unstaging alone changes no file, so only a worktree restore deletes work.
192
+ case 'restore':
193
+ return !onlyStaged(flags);
194
+ // `--cached` drops the entry from the index and keeps the file.
195
+ case 'rm':
196
+ return !flags.includes('--cached') && hasOperand(flags);
197
+ case 'branch':
198
+ return flags.some((flag) => /^-[^-]*D/.test(flag)) || (force && flags.some((flag) => flag === '--delete' || /^-[^-]*d/.test(flag)));
199
+ case 'push':
200
+ // A forced or ref-deleting push removes history on the remote.
201
+ return force
202
+ || flags.some((flag) => /^--force(-with-lease|-if-includes)?(=|$)/.test(flag))
203
+ || flags.some((flag) => flag === '--delete' || /^-[^-]*d/.test(flag))
204
+ // `git push origin :feat/x` names the deletion with its refspec.
205
+ || flags.some((flag) => /^:[^:]/.test(flag));
206
+ case 'stash':
207
+ return flags[0] === 'drop' || flags[0] === 'clear';
208
+ case 'worktree':
209
+ // A checkout the call removes takes whatever was uncommitted inside it, and
210
+ // `prune` drops the records of checkouts that are already gone. `add`, `move`,
211
+ // `lock`, `unlock`, `repair` and `list` delete neither.
212
+ return flags[0] === 'remove' || flags[0] === 'prune';
213
+ default:
214
+ return false;
215
+ }
216
+ }
217
+
218
+ /** Whether the arguments name working-tree paths, either after `--` or as `.`/`..`. */
219
+ function namesWorkingTree(flags) {
220
+ const separator = flags.indexOf('--');
221
+ if (separator >= 0) return flags.length > separator + 1;
222
+ return flags.some((flag) => WORKING_TREE_PATHS.has(flag));
223
+ }
224
+
225
+ /** Paths git can read as nothing but a working-tree path, never as a branch. */
226
+ const WORKING_TREE_PATHS = new Set(['.', './', '..', '../']);
227
+
228
+ /** `git restore --staged` leaves every file as it is; anything touching the worktree does not. */
229
+ function onlyStaged(flags) {
230
+ const staged = flags.some((flag) => flag === '--staged' || /^-[^-]*S/.test(flag));
231
+ const worktree = flags.some((flag) => flag === '--worktree' || /^-[^-]*W/.test(flag));
232
+ return staged && !worktree;
233
+ }
234
+
235
+ /**
236
+ * The words the program after the wrappers receives. Assignments — before the command
237
+ * or in the environment a wrapper sets — a familiar wrapper and the duration `timeout`
238
+ * bounds change nothing about what the command deletes, so they are skipped; a segment
239
+ * with no command left has none.
240
+ */
241
+ function commandArguments(segment) {
242
+ // The classifier runs synchronously on every bash row the host repaints, so a value
243
+ // that is not a command line at all — no command text, a number, an object — answers
244
+ // "no evidence" instead of throwing on the row it was asked to draw.
245
+ if (typeof segment !== 'string' || segment.length === 0) return undefined;
246
+ const words = shellWords(segment);
247
+ let cursor = skipAssignments(words, 0);
248
+ while (cursor < words.length) {
249
+ const name = executable(words[cursor]);
250
+ if (!WRAPPERS.has(name)) break;
251
+ cursor = skipAssignments(words, cursor + 1);
252
+ while (cursor < words.length && words[cursor].startsWith('-')) {
253
+ const flag = words[cursor];
254
+ cursor += 1;
255
+ if (flag === '--') break;
256
+ // The table is a plain object, so a program literally named `constructor` or
257
+ // `__proto__` must never resolve to an inherited member: only a name this
258
+ // module declared can consume its next word.
259
+ if (Object.hasOwn(WRAPPER_VALUE_OPTIONS, name) && WRAPPER_VALUE_OPTIONS[name].includes(flag)) cursor += 1;
260
+ }
261
+ // `env FOO=bar rm …` carries its environment after the wrapper's flags.
262
+ cursor = skipAssignments(words, cursor);
263
+ // `timeout 30 rm …` names the duration it bounds before the command.
264
+ if (name === 'timeout') cursor += 1;
265
+ cursor = skipAssignments(words, cursor);
266
+ }
267
+ return cursor < words.length ? words.slice(cursor) : undefined;
268
+ }
269
+
270
+ /** Advance past plain `NAME=value` words, which set the environment rather than a command. */
271
+ function skipAssignments(words, cursor) {
272
+ let next = cursor;
273
+ while (next < words.length && ASSIGNMENT.test(words[next])) next += 1;
274
+ return next;
275
+ }
276
+
277
+ /** The last path segment of a program word: `/usr/bin/rm` is `rm`. */
278
+ function executable(value) {
279
+ return value.split('/').pop();
280
+ }
281
+
282
+ /**
283
+ * One segment as the words the program receives, with the quoting and escaping the
284
+ * shell would remove. Only words matter here: a command is read from its command
285
+ * position, never from a substring of the text.
286
+ */
287
+ function shellWords(segment) {
288
+ const words = [];
289
+ let word = '';
290
+ let started = false;
291
+ const push = () => {
292
+ if (started) words.push(word);
293
+ word = '';
294
+ started = false;
295
+ };
296
+ for (let index = 0; index < segment.length; index += 1) {
297
+ const char = segment[index];
298
+ if (char === '\\') {
299
+ const next = segment[index + 1];
300
+ if (next === undefined) {
301
+ word += char;
302
+ started = true;
303
+ continue;
304
+ }
305
+ index += 1;
306
+ // An escaped newline is a line continuation, not a character.
307
+ if (next !== '\n') word += next;
308
+ started = true;
309
+ continue;
310
+ }
311
+ if (char === "'") {
312
+ // Nothing escapes inside single quotes.
313
+ const close = segment.indexOf("'", index + 1);
314
+ const end = close < 0 ? segment.length : close;
315
+ word += segment.slice(index + 1, end);
316
+ started = true;
317
+ index = end;
318
+ continue;
319
+ }
320
+ if (char === '"') {
321
+ // Inside double quotes only `\X` escapes, and an escaped newline is dropped.
322
+ let inner = '';
323
+ let end = index + 1;
324
+ while (end < segment.length && segment[end] !== '"') {
325
+ const current = segment[end];
326
+ if (current !== '\\') {
327
+ inner += current;
328
+ end += 1;
329
+ continue;
330
+ }
331
+ const next = segment[end + 1];
332
+ if (next === undefined) {
333
+ inner += current;
334
+ end += 1;
335
+ continue;
336
+ }
337
+ end += 2;
338
+ if (next !== '\n') inner += next;
339
+ }
340
+ word += inner;
341
+ started = true;
342
+ index = end;
343
+ continue;
344
+ }
345
+ if (/\s/.test(char)) {
346
+ push();
347
+ continue;
348
+ }
349
+ word += char;
350
+ started = true;
351
+ }
352
+ push();
353
+ return words;
354
+ }
355
+
356
+ // ---- the recognizer ----
357
+
358
+ // Recognizable executable forms only. This is deliberately not a shell/SQL interpreter
359
+ // or a sandbox: no expansion, script loading or remote inspection.
360
+
361
+ const SEPARATORS = new Set([';', '&&', '||', '|', '&', '\n', '(', ')']);
362
+
363
+ /**
364
+ * Programs that run the command after them, and the options that consume the word
365
+ * after them, for the recognizer below. This is a SECOND reading of wrappers, and it
366
+ * is deliberately wider than the segment reader's: the recognizer also looks inside a
367
+ * `xargs`, whose own arguments name what it deletes.
368
+ */
369
+ const RECOGNIZER_WRAPPERS = ['env', 'sudo', 'command', 'exec', 'nohup', 'timeout', 'xargs'];
370
+ const RECOGNIZER_VALUE_OPTIONS = {
371
+ env: ['-u', '--unset', '-C', '--chdir'],
372
+ sudo: ['-u', '-g', '-h', '-p', '-C', '-D', '--user', '--group', '--host', '--prompt', '--chdir'],
373
+ timeout: ['-s', '--signal', '-k', '--kill-after'],
374
+ xargs: ['-n', '-I', '-P', '--max-args', '--replace', '--max-procs'],
375
+ };
376
+ // Unquoted reserved words that open a compound body or a condition are followed by a
377
+ // command in command position.
378
+ const RESERVED_WORDS = new Set(['then', 'else', 'elif', 'do', '{', '!', 'if', 'while', 'until']);
379
+
380
+ /** Literal, named heredocs are data, not executable shell segments; offsets are preserved. */
381
+ function blankHeredocs(command) {
382
+ return command.replace(/<<-?\s*(['"]?)([A-Za-z_]\w*)\1[^\n]*\n[\s\S]*?\n\2(?=\n|$)/g, (raw) => {
383
+ const headerLength = raw.indexOf('\n') + 1;
384
+ return raw.slice(0, headerLength) + ' '.repeat(raw.length - headerLength);
385
+ });
386
+ }
387
+
388
+ /** Keep quoted arguments intact so harmless prose is never treated as a command. */
389
+ function tokenize(command, blank = true) {
390
+ const tokens = [];
391
+ const text = blank ? blankHeredocs(command) : command;
392
+ const pattern = /(?:"(?:\\.|[^"\\])*"|'[^']*'|\\.|[^\s;&|()'"\\])+|&&|\|\||[;&|()\n]/g;
393
+ for (const match of text.matchAll(pattern)) {
394
+ const raw = match[0];
395
+ const value = raw.replace(/"((?:\\.|[^"\\])*)"|'([^']*)'|\\(.)/g,
396
+ (_raw, double, single, escaped) => {
397
+ if (double !== undefined) return double.replace(/\\(["\\$`\n])/g, (_escape, char) => (char === '\n' ? '' : char));
398
+ return single !== undefined ? single : (escaped !== undefined ? escaped : '');
399
+ });
400
+ // Only raw operators are boundaries; quoted or escaped operators are words.
401
+ tokens.push({ value, raw, operator: SEPARATORS.has(raw), index: match.index });
402
+ }
403
+ return tokens;
404
+ }
405
+
406
+ /** Index of the executable token after reserved words, assignments and familiar wrappers. */
407
+ function headCursor(segment) {
408
+ let cursor = 0;
409
+ while (cursor < segment.length && segment[cursor].raw === segment[cursor].value && RESERVED_WORDS.has(segment[cursor].value)) cursor += 1;
410
+ while (cursor < segment.length) {
411
+ const value = segment[cursor].value;
412
+ if (ASSIGNMENT.test(value)) {
413
+ cursor += 1;
414
+ continue;
415
+ }
416
+ const name = executable(value);
417
+ if (!RECOGNIZER_WRAPPERS.includes(name)) break;
418
+ cursor += 1;
419
+ while (cursor < segment.length && segment[cursor].value.startsWith('-')) {
420
+ const flag = segment[cursor].value;
421
+ cursor += 1;
422
+ if (flag === '--') break;
423
+ if (Object.hasOwn(RECOGNIZER_VALUE_OPTIONS, name) && RECOGNIZER_VALUE_OPTIONS[name].includes(flag)) cursor += 1;
424
+ }
425
+ if (name === 'timeout') cursor += 1;
426
+ }
427
+ return cursor;
428
+ }
429
+
430
+ /**
431
+ * The statements one SQL payload deletes. Quoted identifiers are masked as atoms and
432
+ * comments and strings removed first, so a table named `where` is not a predicate and
433
+ * a statement boundary inside a string is not a boundary. `DROP`/`TRUNCATE` always
434
+ * destroy; a `DELETE` destroys only without a clause that picks its rows.
435
+ */
436
+ function sqlDestroys(sql) {
437
+ const code = sql.replace(/--[^\n]*|\/\*[\s\S]*?\*\/|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[(?:\]\]|[^\]])*\]/g,
438
+ (raw) => (/^["`[]/.test(raw) ? 'identifier' : ' '));
439
+ return code.split(';').some((statement) => {
440
+ if (/^\s*(?:DROP\s+(?:TABLE|DATABASE|SCHEMA|INDEX|VIEW)\b|TRUNCATE\s+(?:TABLE\s+)?\S)/i.test(statement)) return true;
441
+ if (!/^\s*DELETE\s+FROM\s+\S/i.test(statement)) return false;
442
+ return !/\bWHERE\b/i.test(statement) || /\bWHERE\s+(?:1\s*=\s*1|TRUE)\s*$/i.test(statement.trim());
443
+ });
444
+ }
445
+
446
+ /**
447
+ * Bodies of backtick command substitutions outside single quotes, with the backslash
448
+ * escapes that backticks remove. An unterminated substitution is a shell syntax error
449
+ * and runs nothing, so it yields no body; heredoc bodies stay data, as elsewhere.
450
+ */
451
+ function backtickBodies(command) {
452
+ const bodies = [];
453
+ const text = blankHeredocs(command);
454
+ let quote;
455
+ for (let index = 0; index < text.length; index += 1) {
456
+ const char = text[index];
457
+ if (quote === "'") {
458
+ if (char === "'") quote = undefined;
459
+ } else if (char === '\\') {
460
+ index += 1;
461
+ } else if (char === "'" && quote === undefined) {
462
+ quote = "'";
463
+ } else if (char === '"') {
464
+ quote = quote === '"' ? undefined : '"';
465
+ } else if (char === '`') {
466
+ let end = index + 1;
467
+ while (end < text.length && text[end] !== '`') end += text[end] === '\\' ? 2 : 1;
468
+ if (end >= text.length) break;
469
+ bodies.push({ body: text.slice(index + 1, end).replace(/\\([\\$`])/g, '$1') });
470
+ index = end;
471
+ }
472
+ }
473
+ return bodies;
474
+ }
475
+
476
+ /**
477
+ * The deletions one command proves, segment by segment: a shell body, an `eval`, a SQL
478
+ * client's statements, `find`'s own `-delete` and `-exec`, a recursive `rm`, and the
479
+ * git verbs that discard work. Each match carries its KIND, so a reader can keep the
480
+ * one reading a segment cannot make (the database payload) without reading anything
481
+ * about whether the command may run.
482
+ */
483
+ function recognizeDestructiveCommands(command, depth = 0) {
484
+ if (depth > 4) return [];
485
+ const tokens = tokenize(command);
486
+ const matches = [];
487
+ let previous = [];
488
+ let previousSeparator = '';
489
+ let start = 0;
490
+ for (let end = 0; end <= tokens.length; end += 1) {
491
+ if (end < tokens.length && !tokens[end].operator) continue;
492
+ const segment = tokens.slice(start, end);
493
+ start = end + 1;
494
+ // Assignments and familiar executable wrappers preserve command position.
495
+ const cursor = headCursor(segment);
496
+ const head = segment[cursor];
497
+ const name = head === undefined ? '' : executable(head.value);
498
+ const args = segment.slice(cursor + 1).map((token) => token.value);
499
+ const add = (kind) => matches.push({ kind });
500
+ if (['sh', 'bash', 'zsh', 'dash'].includes(name)) {
501
+ const flag = args.findIndex((arg) => /^-[a-z]*c[a-z]*$/.test(arg));
502
+ if (flag >= 0 && args[flag + 1]) matches.push(...recognizeDestructiveCommands(args[flag + 1], depth + 1));
503
+ }
504
+ // `eval` runs its arguments joined by spaces, like a literal `sh -c` payload.
505
+ if (name === 'eval') {
506
+ const payload = (args[0] === '--' ? args.slice(1) : args).join(' ');
507
+ matches.push(...recognizeDestructiveCommands(payload, depth + 1));
508
+ }
509
+ if (SQL_CLIENT_PROGRAMS.has(name)) {
510
+ const payloads = args.map((arg) => arg.replace(/^(?:--command|--execute)=/, ''));
511
+ const heredoc = command.slice(head.index).match(/^[^\n]*<<-?\s*(['"]?)([A-Za-z_]\w*)\1[^\n]*\n([\s\S]*?)\n\2(?=\n|$)/);
512
+ if (heredoc) payloads.push(heredoc[3]);
513
+ if (previousSeparator === '|' && ['echo', 'printf'].includes(executable(previous[0] === undefined ? '' : previous[0].value))) {
514
+ payloads.push(previous.slice(1).map((token) => token.value).join(' ').replace(/^%s\s*/, ''));
515
+ }
516
+ if (payloads.some(sqlDestroys)) add(DESTRUCTION_KIND.DATABASE);
517
+ }
518
+ if (name === 'rm' && args.some((arg) => /^-[^-]*[rR]/.test(arg) || arg === '--recursive')) add(DESTRUCTION_KIND.FILESYSTEM);
519
+ if (name === 'find') {
520
+ if (args.includes('-delete')) add(DESTRUCTION_KIND.FILESYSTEM);
521
+ for (let execIndex = 0; execIndex < args.length; execIndex += 1) {
522
+ if (!['-exec', '-execdir'].includes(args[execIndex])) continue;
523
+ const invocation = segment.slice(cursor + execIndex + 2);
524
+ const terminator = invocation.findIndex((arg) => arg.value === ';' || arg.value === '+');
525
+ const nested = (terminator < 0 ? invocation : invocation.slice(0, terminator)).map((arg) => arg.raw).join(' ');
526
+ matches.push(...recognizeDestructiveCommands(nested, depth + 1));
527
+ if (terminator < 0) break;
528
+ execIndex += terminator + 1;
529
+ }
530
+ }
531
+ if (name === 'git') {
532
+ let index = 0;
533
+ while (index < args.length && args[index].startsWith('-')) {
534
+ const flag = args[index];
535
+ index += 1;
536
+ if (GIT_GLOBAL_VALUE_OPTIONS.has(flag)) index += 1;
537
+ }
538
+ const action = args[index];
539
+ const flags = args.slice(index + 1);
540
+ const force = flags.some((arg) => /^--force(?:-with-lease|=|$)/.test(arg) || /^-[^-]*f/.test(arg));
541
+ const hard = (action === 'reset' && flags.includes('--hard')) || (action === 'clean' && force) || (action === 'push' && force);
542
+ const branchDelete = action === 'branch' && (flags.some((arg) => /^-[^-]*D/.test(arg)) || (force && flags.some((arg) => arg === '--delete' || /^-[^-]*d/.test(arg))));
543
+ if (hard || branchDelete || ['reset', 'clean', 'restore', 'rebase'].includes(action)
544
+ || (action === 'checkout' && (force || flags.includes('--')))
545
+ || (action === 'stash' && ['drop', 'clear'].includes(flags[0]))) add(DESTRUCTION_KIND.GIT);
546
+ }
547
+ previous = segment;
548
+ previousSeparator = tokens[end] === undefined ? '' : tokens[end].value;
549
+ }
550
+ // Backtick substitutions run like `$(...)`, also inside double quotes.
551
+ for (const { body } of backtickBodies(command)) matches.push(...recognizeDestructiveCommands(body, depth + 1));
552
+ return matches;
553
+ }
554
+
555
+ module.exports = {
556
+ isDestructiveCommand,
557
+ isDestructiveSegment,
558
+ isSqlClientSegment,
559
+ };