@ddtcorex/dsh-maestro-core 0.10.0

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 (285) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +209 -0
  3. package/cordis.patch.yml +43 -0
  4. package/lib/bin.d.ts +2 -0
  5. package/lib/bin.js +3 -0
  6. package/lib/boot-guard.d.ts +33 -0
  7. package/lib/boot-guard.js +68 -0
  8. package/lib/boot-lock.d.ts +56 -0
  9. package/lib/boot-lock.js +155 -0
  10. package/lib/cli.d.ts +31 -0
  11. package/lib/cli.js +336 -0
  12. package/lib/client.js +2901 -0
  13. package/lib/config/index.d.ts +34 -0
  14. package/lib/config/index.js +62 -0
  15. package/lib/config/service.d.ts +18 -0
  16. package/lib/config/service.js +28 -0
  17. package/lib/config.d.ts +1 -0
  18. package/lib/config.js +19 -0
  19. package/lib/daemon-freshness.d.ts +48 -0
  20. package/lib/daemon-freshness.js +122 -0
  21. package/lib/debug-agent.d.ts +17 -0
  22. package/lib/debug-agent.js +144 -0
  23. package/lib/dsh-session.d.ts +26 -0
  24. package/lib/dsh-session.js +45 -0
  25. package/lib/guard/config.d.ts +82 -0
  26. package/lib/guard/config.js +211 -0
  27. package/lib/guard/decide.d.ts +30 -0
  28. package/lib/guard/decide.js +38 -0
  29. package/lib/guard/full-scan-tool.d.ts +6 -0
  30. package/lib/guard/full-scan-tool.js +65 -0
  31. package/lib/guard/index.d.ts +85 -0
  32. package/lib/guard/index.js +254 -0
  33. package/lib/guard/journal.d.ts +146 -0
  34. package/lib/guard/journal.js +398 -0
  35. package/lib/guard/migrate.d.ts +15 -0
  36. package/lib/guard/migrate.js +42 -0
  37. package/lib/guard/parse.d.ts +193 -0
  38. package/lib/guard/parse.js +1103 -0
  39. package/lib/guard/paths.d.ts +104 -0
  40. package/lib/guard/paths.js +254 -0
  41. package/lib/guard/permission-policy.d.ts +10 -0
  42. package/lib/guard/permission-policy.js +21 -0
  43. package/lib/guard/redact.d.ts +25 -0
  44. package/lib/guard/redact.js +52 -0
  45. package/lib/guard/rules.d.ts +65 -0
  46. package/lib/guard/rules.js +832 -0
  47. package/lib/guard/status-tool.d.ts +54 -0
  48. package/lib/guard/status-tool.js +195 -0
  49. package/lib/guard/tiers.d.ts +2 -0
  50. package/lib/guard/tiers.js +1 -0
  51. package/lib/guard/validators.d.ts +4 -0
  52. package/lib/guard/validators.js +45 -0
  53. package/lib/health-poller.d.ts +90 -0
  54. package/lib/health-poller.js +430 -0
  55. package/lib/index.d.ts +7 -0
  56. package/lib/index.js +7 -0
  57. package/lib/intents.d.ts +32 -0
  58. package/lib/intents.js +49 -0
  59. package/lib/notifier.d.ts +12 -0
  60. package/lib/notifier.js +62 -0
  61. package/lib/paths.d.ts +13 -0
  62. package/lib/paths.js +70 -0
  63. package/lib/plugin.d.ts +250 -0
  64. package/lib/plugin.js +1126 -0
  65. package/lib/preset.d.ts +73 -0
  66. package/lib/preset.js +158 -0
  67. package/lib/report.d.ts +11 -0
  68. package/lib/report.js +58 -0
  69. package/lib/restart-exec.d.ts +35 -0
  70. package/lib/restart-exec.js +60 -0
  71. package/lib/restart-guards.d.ts +39 -0
  72. package/lib/restart-guards.js +150 -0
  73. package/lib/restart-tool.d.ts +124 -0
  74. package/lib/restart-tool.js +539 -0
  75. package/lib/restart-web.d.ts +26 -0
  76. package/lib/restart-web.js +58 -0
  77. package/lib/resume-log.d.ts +24 -0
  78. package/lib/resume-log.js +18 -0
  79. package/lib/resume-tools.d.ts +131 -0
  80. package/lib/resume-tools.js +337 -0
  81. package/lib/resume.d.ts +33 -0
  82. package/lib/resume.js +221 -0
  83. package/lib/scan.d.ts +20 -0
  84. package/lib/scan.js +71 -0
  85. package/lib/self-kill-guard.d.ts +81 -0
  86. package/lib/self-kill-guard.js +208 -0
  87. package/lib/session-health.d.ts +89 -0
  88. package/lib/session-health.js +274 -0
  89. package/lib/session-log-file.d.ts +22 -0
  90. package/lib/session-log-file.js +74 -0
  91. package/lib/skill-provider.d.ts +6 -0
  92. package/lib/skill-provider.js +73 -0
  93. package/lib/snapshot.d.ts +59 -0
  94. package/lib/snapshot.js +358 -0
  95. package/lib/source.d.ts +19 -0
  96. package/lib/source.js +19 -0
  97. package/lib/store/index.d.ts +42 -0
  98. package/lib/store/index.js +340 -0
  99. package/lib/store/legacy.d.ts +17 -0
  100. package/lib/store/legacy.js +85 -0
  101. package/lib/supervisor.d.ts +119 -0
  102. package/lib/supervisor.js +741 -0
  103. package/lib/sync/backup-config.d.ts +55 -0
  104. package/lib/sync/backup-config.js +119 -0
  105. package/lib/sync/backup-service.d.ts +110 -0
  106. package/lib/sync/backup-service.js +440 -0
  107. package/lib/sync/bidirectional.d.ts +39 -0
  108. package/lib/sync/bidirectional.js +25 -0
  109. package/lib/sync/cli.d.ts +38 -0
  110. package/lib/sync/cli.js +536 -0
  111. package/lib/sync/config.d.ts +77 -0
  112. package/lib/sync/config.js +90 -0
  113. package/lib/sync/fingerprint.d.ts +29 -0
  114. package/lib/sync/fingerprint.js +65 -0
  115. package/lib/sync/hashing.d.ts +9 -0
  116. package/lib/sync/hashing.js +47 -0
  117. package/lib/sync/index.d.ts +6 -0
  118. package/lib/sync/index.js +634 -0
  119. package/lib/sync/machine-id.d.ts +29 -0
  120. package/lib/sync/machine-id.js +66 -0
  121. package/lib/sync/merge.d.ts +33 -0
  122. package/lib/sync/merge.js +88 -0
  123. package/lib/sync/peer-host.d.ts +22 -0
  124. package/lib/sync/peer-host.js +62 -0
  125. package/lib/sync/process-runner.d.ts +31 -0
  126. package/lib/sync/process-runner.js +161 -0
  127. package/lib/sync/remote-agent.d.ts +42 -0
  128. package/lib/sync/remote-agent.js +217 -0
  129. package/lib/sync/remote-cache.d.ts +18 -0
  130. package/lib/sync/remote-cache.js +60 -0
  131. package/lib/sync/remote-manifest.d.ts +8 -0
  132. package/lib/sync/remote-manifest.js +64 -0
  133. package/lib/sync/s3-object-store.d.ts +38 -0
  134. package/lib/sync/s3-object-store.js +126 -0
  135. package/lib/sync/session-merge.d.ts +18 -0
  136. package/lib/sync/session-merge.js +191 -0
  137. package/lib/sync/session-plan.d.ts +29 -0
  138. package/lib/sync/session-plan.js +213 -0
  139. package/lib/sync/sigv4.d.ts +20 -0
  140. package/lib/sync/sigv4.js +57 -0
  141. package/lib/sync/snapshot.d.ts +21 -0
  142. package/lib/sync/snapshot.js +176 -0
  143. package/lib/sync/ssh-mux.d.ts +12 -0
  144. package/lib/sync/ssh-mux.js +48 -0
  145. package/lib/sync/sync-plan.d.ts +24 -0
  146. package/lib/sync/sync-plan.js +366 -0
  147. package/lib/sync/sync-service.d.ts +177 -0
  148. package/lib/sync/sync-service.js +819 -0
  149. package/lib/sync/sync-types.d.ts +87 -0
  150. package/lib/sync/sync-types.js +1 -0
  151. package/lib/sync/transport.d.ts +75 -0
  152. package/lib/sync/transport.js +200 -0
  153. package/lib/sync/tunnel-restore.d.ts +77 -0
  154. package/lib/sync/tunnel-restore.js +142 -0
  155. package/lib/sync/validation.d.ts +10 -0
  156. package/lib/sync/validation.js +83 -0
  157. package/lib/tool-view.d.ts +62 -0
  158. package/lib/tool-view.js +70 -0
  159. package/lib/types/client/auto-reload.d.ts +8 -0
  160. package/lib/types/client/auto-reload.d.ts.map +1 -0
  161. package/lib/types/client/config/MaestroSettings.d.ts +25 -0
  162. package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
  163. package/lib/types/client/config/components/BrandMark.d.ts +50 -0
  164. package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
  165. package/lib/types/client/config/guard-view.d.ts +83 -0
  166. package/lib/types/client/config/guard-view.d.ts.map +1 -0
  167. package/lib/types/client/config/index.d.ts +20 -0
  168. package/lib/types/client/config/index.d.ts.map +1 -0
  169. package/lib/types/client/config/maestro-mark.d.ts +29 -0
  170. package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
  171. package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
  172. package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
  173. package/lib/types/client/index.d.ts +16 -0
  174. package/lib/types/client/index.d.ts.map +1 -0
  175. package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
  176. package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
  177. package/lib/types/client/sync/SyncPanel.d.ts +12 -0
  178. package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
  179. package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
  180. package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
  181. package/lib/types/client/sync/index.d.ts +10 -0
  182. package/lib/types/client/sync/index.d.ts.map +1 -0
  183. package/lib/types/client/sync/ui.d.ts +79 -0
  184. package/lib/types/client/sync/ui.d.ts.map +1 -0
  185. package/lib/types/client/sync/use-backup.d.ts +50 -0
  186. package/lib/types/client/sync/use-backup.d.ts.map +1 -0
  187. package/lib/types/client/sync/use-sync.d.ts +88 -0
  188. package/lib/types/client/sync/use-sync.d.ts.map +1 -0
  189. package/package.json +89 -0
  190. package/skills/dsh-safe-restart/SKILL.md +206 -0
  191. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
  192. package/src/client/auto-reload.ts +104 -0
  193. package/src/client/config/MaestroSettings.tsx +892 -0
  194. package/src/client/config/components/BrandMark.tsx +94 -0
  195. package/src/client/config/guard-view.ts +187 -0
  196. package/src/client/config/index.tsx +109 -0
  197. package/src/client/config/maestro-mark.ts +37 -0
  198. package/src/client/config/settings-nav-icon.ts +68 -0
  199. package/src/client/index.tsx +33 -0
  200. package/src/client/sync/R2SyncPanel.tsx +260 -0
  201. package/src/client/sync/SyncPanel.tsx +422 -0
  202. package/src/client/sync/confirm-dialog.tsx +202 -0
  203. package/src/client/sync/index.tsx +336 -0
  204. package/src/client/sync/ui.tsx +313 -0
  205. package/src/client/sync/use-backup.ts +207 -0
  206. package/src/client/sync/use-sync.ts +502 -0
  207. package/src/host/bin.ts +3 -0
  208. package/src/host/boot-guard.ts +76 -0
  209. package/src/host/boot-lock.ts +155 -0
  210. package/src/host/cli.ts +288 -0
  211. package/src/host/config/index.ts +78 -0
  212. package/src/host/config/service.ts +40 -0
  213. package/src/host/config.ts +18 -0
  214. package/src/host/daemon-freshness.ts +143 -0
  215. package/src/host/debug-agent.ts +145 -0
  216. package/src/host/dsh-session.ts +56 -0
  217. package/src/host/dsh-skill.d.ts +44 -0
  218. package/src/host/guard/augment.d.ts +33 -0
  219. package/src/host/guard/config.ts +244 -0
  220. package/src/host/guard/decide.ts +40 -0
  221. package/src/host/guard/full-scan-tool.ts +61 -0
  222. package/src/host/guard/index.ts +281 -0
  223. package/src/host/guard/journal.ts +440 -0
  224. package/src/host/guard/migrate.ts +41 -0
  225. package/src/host/guard/parse.ts +1150 -0
  226. package/src/host/guard/paths.ts +239 -0
  227. package/src/host/guard/permission-policy.ts +15 -0
  228. package/src/host/guard/redact.ts +64 -0
  229. package/src/host/guard/rules.ts +891 -0
  230. package/src/host/guard/status-tool.ts +229 -0
  231. package/src/host/guard/tiers.ts +2 -0
  232. package/src/host/guard/validators.ts +29 -0
  233. package/src/host/health-poller.ts +446 -0
  234. package/src/host/index.ts +7 -0
  235. package/src/host/intents.ts +67 -0
  236. package/src/host/notifier.ts +71 -0
  237. package/src/host/paths.ts +70 -0
  238. package/src/host/plugin.ts +1097 -0
  239. package/src/host/preset.ts +170 -0
  240. package/src/host/report.ts +71 -0
  241. package/src/host/restart-exec.ts +81 -0
  242. package/src/host/restart-guards.ts +150 -0
  243. package/src/host/restart-tool.ts +483 -0
  244. package/src/host/restart-web.ts +72 -0
  245. package/src/host/resume-log.ts +39 -0
  246. package/src/host/resume-tools.ts +385 -0
  247. package/src/host/resume.ts +204 -0
  248. package/src/host/scan.ts +61 -0
  249. package/src/host/self-kill-guard.ts +216 -0
  250. package/src/host/session-health.ts +236 -0
  251. package/src/host/session-log-file.ts +77 -0
  252. package/src/host/skill-provider.ts +69 -0
  253. package/src/host/snapshot.ts +337 -0
  254. package/src/host/source.ts +19 -0
  255. package/src/host/store/index.ts +348 -0
  256. package/src/host/store/legacy.ts +96 -0
  257. package/src/host/supervisor.ts +720 -0
  258. package/src/host/sync/backup-config.ts +159 -0
  259. package/src/host/sync/backup-service.ts +453 -0
  260. package/src/host/sync/bidirectional.ts +66 -0
  261. package/src/host/sync/cli.ts +539 -0
  262. package/src/host/sync/config.ts +119 -0
  263. package/src/host/sync/fingerprint.ts +83 -0
  264. package/src/host/sync/hashing.ts +58 -0
  265. package/src/host/sync/index.ts +737 -0
  266. package/src/host/sync/machine-id.ts +81 -0
  267. package/src/host/sync/merge.ts +102 -0
  268. package/src/host/sync/peer-host.ts +65 -0
  269. package/src/host/sync/process-runner.ts +177 -0
  270. package/src/host/sync/remote-agent.ts +213 -0
  271. package/src/host/sync/remote-cache.ts +68 -0
  272. package/src/host/sync/remote-manifest.ts +70 -0
  273. package/src/host/sync/s3-object-store.ts +144 -0
  274. package/src/host/sync/session-merge.ts +220 -0
  275. package/src/host/sync/session-plan.ts +237 -0
  276. package/src/host/sync/sigv4.ts +81 -0
  277. package/src/host/sync/snapshot.ts +162 -0
  278. package/src/host/sync/ssh-mux.ts +56 -0
  279. package/src/host/sync/sync-plan.ts +366 -0
  280. package/src/host/sync/sync-service.ts +855 -0
  281. package/src/host/sync/sync-types.ts +102 -0
  282. package/src/host/sync/transport.ts +261 -0
  283. package/src/host/sync/tunnel-restore.ts +160 -0
  284. package/src/host/sync/validation.ts +91 -0
  285. package/src/host/tool-view.ts +98 -0
@@ -0,0 +1,1103 @@
1
+ /**
2
+ * Shell-aware tokenizer and segmenter for the guard's command surface.
3
+ *
4
+ * The guard judges a command by what it actually executes, and a regex over the
5
+ * raw string cannot do that. It splits on operators that sit inside quotes, and
6
+ * — the live bypass this module exists to close — it cannot see the subcommand
7
+ * of `git -C /repo push origin v1.2.3`, because a value-taking global option
8
+ * sits between `git` and `push`.
9
+ *
10
+ * The parse is deliberately shallow: just enough structure (segments, argv, the
11
+ * verb/subcommand, flags, refspecs, paths, ambiguity) for the rule layer, never
12
+ * a POSIX implementation. Two invariants hold:
13
+ *
14
+ * - nothing is silently dropped — every word, operator, redirection operator and
15
+ * redirection target appears exactly once across the segments' `argv`, so a
16
+ * rule can always re-derive the text it needs (an operator keeps its own
17
+ * token kind and is never read as a word). The one deliberate exception is a
18
+ * heredoc BODY: it is not command surface, so it leaves the token stream and
19
+ * is attached to its owning segment as `Segment.heredoc` instead;
20
+ * - anything unresolvable is marked `ambiguous` rather than guessed, and the
21
+ * rule layer treats ambiguity as "ask", never as "allow".
22
+ *
23
+ * Two consequences of that second invariant are worth naming, because both were
24
+ * live bypasses before they were closed:
25
+ *
26
+ * - an option the tables do not know is NOT assumed valueless when a word
27
+ * follows it. `git --bare push` (valueless) and `git --shallow-file x push`
28
+ * (value-taking) differ only in git's own option table, so the parser cannot
29
+ * resolve the subcommand and marks the segment `ambiguous` instead of reading
30
+ * `x` as the subcommand and losing the push;
31
+ * - a backtick substitutes a command exactly like `$(...)` does, so it sets the
32
+ * same expandable signal — otherwise `` echo `git -C /repo push origin v1.2.3`
33
+ * `` reads as a resolved `echo` and the push never reaches a rule.
34
+ *
35
+ * `unwrapSegments` is the layer above that parse. It removes the wrappers that
36
+ * only change WHO runs a command (`env VAR=…`, `sudo`, `nohup`, `time`), replaces
37
+ * a shell wrapper with the script it runs (`bash -c <script>`, `bash -s`, and a
38
+ * `bash <<EOF` body), and tags every segment it derives with `wrappedBy`. A body
39
+ * fed to a non-shell — `cat`, `tee`, an interpreter — stays data and is never
40
+ * turned into segments; it is attached as `Segment.heredoc` so a rule can inspect
41
+ * it without parsing it. A wrapper whose script cannot be read (a script file, a
42
+ * `-c` with no argument, a nest deeper than `MAX_WRAP_DEPTH`, an interpreter's
43
+ * inline program) marks its segments `ambiguous` instead of being treated as
44
+ * resolved — and so does an exec-like wrapper the guard deliberately does not
45
+ * unwrap (`timeout`, `nice`, `setsid`, `watch`, …), which runs a command of its
46
+ * own that would otherwise never reach a rule.
47
+ *
48
+ * Pure with respect to the environment it inspects: string in, data out. It
49
+ * writes no file, starts no child process, opens no socket and never expands
50
+ * `$VAR`/backticks — an unexpanded token is exactly what `ambiguous` records.
51
+ * Reading the ambient environment is allowed where the caller cannot supply it:
52
+ * `node:os` `homedir()` and `node:path` resolve a `~`-relative `cd` target in
53
+ * `getCommandWorkingDir`, which is the only reason either is imported.
54
+ */
55
+ import { homedir } from 'node:os';
56
+ import { join, resolve } from 'node:path';
57
+ /** How many shell-wrapper levels `parseCommand` will descend before giving up. */
58
+ export const MAX_WRAP_DEPTH = 3;
59
+ /** Verbs whose meaning is entirely "run whatever the arguments say". */
60
+ export const OPAQUE_VERBS = new Set(['eval', 'exec', 'xargs']);
61
+ /**
62
+ * Verbs that run a trailing COMMAND of their own — after their own options and,
63
+ * for most of them, a leading duration/priority/pid argument. The verb the guard
64
+ * reads is therefore not the verb that executes: `timeout 5 bash -c '…'` runs
65
+ * bash, never `timeout`, and the real command is invisible to a rule keyed on it.
66
+ *
67
+ * `unwrapSegments` does not unwrap these forms, because their argument grammar
68
+ * is per-verb (`timeout 5 CMD`, `nice -n 5 CMD`, `stdbuf -o0 CMD`, `flock FILE
69
+ * CMD`, …) and a wrong guess would hide the command rather than reveal it. Each
70
+ * one is marked `ambiguous` instead, which the rule layer answers with a prompt,
71
+ * never an allow. `xargs` is the same shape and is already in `OPAQUE_VERBS`.
72
+ *
73
+ * The class is closed over that SHAPE, not over a hand-picked sample: a verb that
74
+ * runs a trailing command belongs here even when it is a tracer (`strace`,
75
+ * `ltrace`), a sandbox/root switcher (`chroot`, `setarch`, `bwrap`, `fakeroot`),
76
+ * a remote runner (`ssh`), or a scheduler/multiplexer (`parallel`, `unbuffer`,
77
+ * `script`, `caffeinate`). Leaving one out does not fail safe: the segment reads
78
+ * as a resolved verb and the command it really runs never reaches a rule.
79
+ *
80
+ * Exported (with `OPAQUE_VERBS`) so the rule layer can tell which segments hold a
81
+ * COMMAND in their quoted spans rather than data — see `rawSurface` in `rules.ts`.
82
+ */
83
+ export const EXEC_WRAPPERS = new Set([
84
+ 'bwrap',
85
+ 'caffeinate',
86
+ 'chpst',
87
+ 'chroot',
88
+ 'chrt',
89
+ 'cpulimit',
90
+ 'daemonize',
91
+ 'doas',
92
+ 'eatmydata',
93
+ 'fakeroot',
94
+ 'firejail',
95
+ 'flock',
96
+ 'gosu',
97
+ 'ionice',
98
+ 'ltrace',
99
+ 'nice',
100
+ 'nsenter',
101
+ 'parallel',
102
+ 'perf',
103
+ 'pkexec',
104
+ 'run0',
105
+ 'runuser',
106
+ 'script',
107
+ 'setarch',
108
+ 'setpriv',
109
+ 'setsid',
110
+ 'ssh',
111
+ 'sshpass',
112
+ 'stdbuf',
113
+ 'strace',
114
+ 'su',
115
+ 'systemd-run',
116
+ 'taskset',
117
+ 'timeout',
118
+ 'unbuffer',
119
+ 'unshare',
120
+ 'valgrind',
121
+ 'watch',
122
+ 'watchexec',
123
+ 'xvfb-run',
124
+ ]);
125
+ /**
126
+ * Global options that consume the FOLLOWING token as their value, per verb.
127
+ * `git` is the one that matters for safety: without this table `git -C <dir>
128
+ * push` has subcommand `<dir>`, which is how the previous regex matcher let a
129
+ * protected-branch push through. The package managers are listed for the same
130
+ * reason — a publish hidden behind `--dir` must still be seen as a publish.
131
+ *
132
+ * Every entry here is verified against the real tool, separated form included.
133
+ * `--shallow-file` and `--attr-source` are git's undocumented-but-real globals
134
+ * (`git --shallow-file /tmp/x rev-parse --is-inside-work-tree` prints `true`,
135
+ * i.e. git ate `/tmp/x`) and they hid the subcommand exactly like `-C` did.
136
+ * `--list-cmds` is deliberately absent: git rejects the separated form
137
+ * ("unknown option: --list-cmds"), so only `--list-cmds=<group>` exists and the
138
+ * self-contained `--name=value` rule already covers it.
139
+ */
140
+ const VALUE_FLAGS = {
141
+ git: [
142
+ '-C',
143
+ '-c',
144
+ '--git-dir',
145
+ '--work-tree',
146
+ '--namespace',
147
+ '--exec-path',
148
+ '--config-env',
149
+ '--shallow-file',
150
+ '--attr-source',
151
+ ],
152
+ pnpm: ['--dir', '-C', '--prefix', '--cwd', '--config', '--filter', '-F', '--registry', '--reporter'],
153
+ npm: ['--prefix', '-C', '--cwd', '--registry', '--userconfig', '--cache', '--loglevel'],
154
+ yarn: ['--cwd', '--modules-folder', '--cache-folder'],
155
+ };
156
+ /**
157
+ * Global options that take no value, so only the flag itself is consumed.
158
+ * Verified against the real tool: `git <flag> rev-parse …` still runs the
159
+ * subcommand, which is what makes it safe to keep resolving past these instead
160
+ * of asking. Anything not listed here and not in `VALUE_FLAGS` is unreadable.
161
+ */
162
+ const BARE_FLAGS = {
163
+ git: [
164
+ '-p',
165
+ '-P',
166
+ '--paginate',
167
+ '--no-pager',
168
+ '--bare',
169
+ '--no-replace-objects',
170
+ '--literal-pathspecs',
171
+ '--glob-pathspecs',
172
+ '--noglob-pathspecs',
173
+ '--icase-pathspecs',
174
+ '--no-optional-locks',
175
+ ],
176
+ };
177
+ /** Read one redirection at `i`: `>`, `>>`, `>|`, `<`, `<<`, `<<<`, `N>&M`, `&>`. */
178
+ function scanRedirect(input, i) {
179
+ const c = input[i];
180
+ let j = i + 1;
181
+ let op = c;
182
+ // `>|` is the noclobber override and one operator, not a redirect followed by a
183
+ // pipe: splitting it moved the target into a segment of its own, so a clobber
184
+ // of the guard's journal reached no rule at all.
185
+ if (c === '>' && input[j] === '|')
186
+ return { op: '>|', dup: false, next: j + 1 };
187
+ if (input[j] === c && c !== '&') {
188
+ op += c;
189
+ j++;
190
+ }
191
+ if (c === '<' && input[j] === '<') {
192
+ op += '<';
193
+ j++;
194
+ }
195
+ if (input[j] === '&') {
196
+ op += '&';
197
+ j++;
198
+ while (j < input.length && /[0-9-]/.test(input[j])) {
199
+ op += input[j];
200
+ j++;
201
+ }
202
+ return { op, dup: true, next: j };
203
+ }
204
+ return { op, dup: false, next: j };
205
+ }
206
+ /**
207
+ * Read the body of one heredoc: every line after `pos` up to the line that holds
208
+ * only the delimiter. Returns the body (terminator excluded, each line keeping
209
+ * its newline) and where tokenizing resumes. An unterminated heredoc consumes
210
+ * the rest of the input — a body must never leak back out as argv.
211
+ */
212
+ function readHeredocBody(input, pos, delim, stripTabs) {
213
+ if (pos >= input.length)
214
+ return { body: '', next: input.length };
215
+ let body = '';
216
+ let p = pos;
217
+ for (;;) {
218
+ const nl = input.indexOf('\n', p);
219
+ const end = nl === -1 ? input.length : nl;
220
+ const line = input.slice(p, end);
221
+ const compared = stripTabs ? line.replace(/^\t+/, '') : line;
222
+ if (compared === delim)
223
+ return { body, next: nl === -1 ? input.length : nl + 1 };
224
+ body += compared + '\n';
225
+ if (nl === -1)
226
+ return { body, next: input.length };
227
+ p = nl + 1;
228
+ }
229
+ }
230
+ /** Split the command into tokens, keeping separators as their own tokens. */
231
+ function tokenize(input) {
232
+ const toks = [];
233
+ let buf = '';
234
+ let bufStart = 0;
235
+ let expandable = false;
236
+ let quote = null;
237
+ // 'file' → the next word is a redirection target; 'heredoc' → it is a heredoc
238
+ // delimiter (a word, never a path); null → nothing pending.
239
+ let pending = null;
240
+ // Delimiters seen but not yet fed. Their bodies start after the next newline,
241
+ // so the queue is drained at the newline that ends the current line.
242
+ let heredocs = [];
243
+ let heredocTabs = false;
244
+ let i = 0;
245
+ const emit = (text, kind, start, end) => {
246
+ const k = kind === 'word' && pending === 'file' ? 'target' : kind;
247
+ const delimiter = kind === 'word' && pending === 'heredoc';
248
+ if (delimiter) {
249
+ heredocs.push({ index: toks.length, delim: text, stripTabs: heredocTabs });
250
+ pending = null;
251
+ heredocTabs = false;
252
+ }
253
+ else if (kind === 'word' && pending !== null) {
254
+ pending = null;
255
+ heredocTabs = false;
256
+ }
257
+ toks.push({
258
+ text,
259
+ kind: k,
260
+ start,
261
+ end,
262
+ expandable,
263
+ // For a delimiter the source slice still holds the quotes, so it says
264
+ // whether the shell expands the body (`<<EOF`) or reads it literally
265
+ // (`<<'EOF'`).
266
+ ...(delimiter ? { heredocQuoted: /['"]/.test(input.slice(start, end)) } : {}),
267
+ });
268
+ expandable = false;
269
+ };
270
+ const flush = (end) => {
271
+ if (buf === '')
272
+ return;
273
+ const text = buf;
274
+ buf = '';
275
+ emit(text, 'word', bufStart, end);
276
+ };
277
+ const sep = (text, end) => {
278
+ flush(i);
279
+ pending = null;
280
+ toks.push({ text, kind: 'sep', start: i, end, expandable: false });
281
+ };
282
+ while (i < input.length) {
283
+ const ch = input[i];
284
+ if (quote === "'") {
285
+ if (ch === "'")
286
+ quote = null;
287
+ else
288
+ buf += ch;
289
+ i++;
290
+ continue;
291
+ }
292
+ if (quote === '"') {
293
+ if (ch === '\\') {
294
+ const nx = input[i + 1];
295
+ if (nx === '"' || nx === '\\' || nx === '$' || nx === '`') {
296
+ buf += nx;
297
+ i += 2;
298
+ continue;
299
+ }
300
+ }
301
+ else if (ch === '"') {
302
+ quote = null;
303
+ i++;
304
+ continue;
305
+ }
306
+ else if (ch === '$' || ch === '`') {
307
+ // Double quotes still substitute: both `$VAR` and `` `cmd` `` execute.
308
+ expandable = true;
309
+ }
310
+ buf += ch;
311
+ i++;
312
+ continue;
313
+ }
314
+ if (ch === '\\') {
315
+ const nx = input[i + 1];
316
+ if (nx === '\n') {
317
+ i += 2;
318
+ continue;
319
+ }
320
+ if (buf === '')
321
+ bufStart = i;
322
+ buf += nx === undefined ? ch : nx;
323
+ i += nx === undefined ? 1 : 2;
324
+ continue;
325
+ }
326
+ if (ch === "'" || ch === '"') {
327
+ if (buf === '')
328
+ bufStart = i;
329
+ quote = ch;
330
+ i++;
331
+ continue;
332
+ }
333
+ if (ch === ' ' || ch === '\t' || ch === '\r') {
334
+ flush(i);
335
+ i++;
336
+ continue;
337
+ }
338
+ if (ch === '\n' || ch === ';') {
339
+ sep(ch, i + 1);
340
+ i++;
341
+ // Heredoc bodies begin on the line after the delimiter; consume them here
342
+ // so no body word is ever read as argv of the segment that owns them.
343
+ if (ch === '\n' && heredocs.length > 0) {
344
+ const queue = heredocs;
345
+ heredocs = [];
346
+ for (const h of queue) {
347
+ const read = readHeredocBody(input, i, h.delim, h.stripTabs);
348
+ toks[h.index].heredoc = read.body;
349
+ i = read.next;
350
+ }
351
+ }
352
+ continue;
353
+ }
354
+ if (ch === '#' && buf === '') {
355
+ while (i < input.length && input[i] !== '\n')
356
+ i++;
357
+ continue;
358
+ }
359
+ if (ch === '&' || ch === '|') {
360
+ if (input[i + 1] === ch) {
361
+ sep(ch + ch, i + 2);
362
+ i += 2;
363
+ continue;
364
+ }
365
+ if (ch === '&' && input[i + 1] === '>') {
366
+ flush(i);
367
+ const r = scanRedirect(input, i + 1);
368
+ toks.push({ text: '&' + r.op, kind: 'redir', start: i, end: r.next, expandable: false });
369
+ pending = 'file';
370
+ i = r.next;
371
+ continue;
372
+ }
373
+ sep(ch, i + 1);
374
+ i++;
375
+ continue;
376
+ }
377
+ if (ch === '>' || ch === '<') {
378
+ const fold = buf !== '' && /^[0-9]+$/.test(buf);
379
+ const start = fold ? bufStart : i;
380
+ if (fold) {
381
+ buf = '';
382
+ expandable = false;
383
+ }
384
+ else
385
+ flush(i);
386
+ const r = scanRedirect(input, i);
387
+ // `<<-` is a heredoc too; its body is indented with tabs, which both the
388
+ // body lines and the terminator may carry.
389
+ const tabs = r.op === '<<' && input[r.next] === '-';
390
+ const op = tabs ? '<<-' : r.op;
391
+ const next = tabs ? r.next + 1 : r.next;
392
+ // Only `<<` and `<<-` introduce a body. `<<<` is a here-string: its
393
+ // argument is one ordinary word, so queueing it as a delimiter would let
394
+ // the body reader eat every following line as a "body" and hide the
395
+ // commands after it from every downstream rule.
396
+ const heredoc = op === '<<' || op === '<<-';
397
+ toks.push({ text: input.slice(start, i) + op, kind: 'redir', start, end: next, expandable: false });
398
+ pending = r.dup ? null : heredoc ? 'heredoc' : 'file';
399
+ heredocTabs = pending === 'heredoc' && tabs;
400
+ i = next;
401
+ continue;
402
+ }
403
+ if (buf === '')
404
+ bufStart = i;
405
+ // A backtick runs a command exactly like `$(...)`, so it is expandable too;
406
+ // single-quoted and escaped backticks never reach here.
407
+ if (ch === '$' || ch === '`')
408
+ expandable = true;
409
+ buf += ch;
410
+ i++;
411
+ }
412
+ flush(i);
413
+ // A delimiter at the end of the input still owns a (possibly empty) body.
414
+ for (const h of heredocs) {
415
+ toks[h.index].heredoc = readHeredocBody(input, input.length, h.delim, h.stripTabs).body;
416
+ }
417
+ return toks;
418
+ }
419
+ /** A word that names a path: absolute, explicitly relative, or containing `/`. */
420
+ function looksLikePath(text) {
421
+ return text.startsWith('/') || text.startsWith('./') || text.startsWith('../') || text.startsWith('~/') || text.includes('/');
422
+ }
423
+ /**
424
+ * Resolve the subcommand: the first non-flag token once the verb's value-taking
425
+ * global options (and its known valueless ones) are consumed.
426
+ *
427
+ * Fail-closed on an unknown long option. When `git --totally-unknown x …` is
428
+ * seen, `--totally-unknown` may be valueless (`x` is the subcommand) or
429
+ * value-taking (`x` is its value and the real subcommand follows); nothing short
430
+ * of git's own option table can decide. The parser keeps resolving with the
431
+ * valueless reading — the optimistic one, which still surfaces a later `push`
432
+ * via `refspecs` — but reports `unknownOption`, so `buildSegment` marks the
433
+ * segment ambiguous and the rule layer asks instead of allowing.
434
+ */
435
+ function subcommandIndex(toks, verb) {
436
+ if (verb === undefined)
437
+ return { index: -1, unknownOption: false };
438
+ const values = VALUE_FLAGS[verb] ?? [];
439
+ const bares = BARE_FLAGS[verb] ?? [];
440
+ let i = 1;
441
+ let unknownOption = false;
442
+ while (i < toks.length) {
443
+ const t = toks[i];
444
+ if (t.kind !== 'word' || !t.text.startsWith('-'))
445
+ break;
446
+ const next = toks[i + 1];
447
+ if (bares.includes(t.text)) {
448
+ i++; // -p / --paginate / --no-pager / --bare: the flag is the whole option
449
+ }
450
+ else if (t.text.startsWith('--') && t.text.indexOf('=') > 0) {
451
+ i++; // --name=value is self-contained
452
+ }
453
+ else if (values.includes(t.text) && next !== undefined && next.kind === 'word') {
454
+ i += 2; // the option and the value it consumes
455
+ }
456
+ else {
457
+ // Unknown option. A following word is exactly the token that would be
458
+ // misread as the subcommand, so record that the reading is unprovable.
459
+ if (t.text.startsWith('--') && next !== undefined && next.kind === 'word' && !next.text.startsWith('-')) {
460
+ unknownOption = true;
461
+ }
462
+ i++; // assume it takes no value; the ambiguity above carries the doubt
463
+ }
464
+ }
465
+ return { index: i < toks.length && toks[i].kind === 'word' ? i : -1, unknownOption };
466
+ }
467
+ /**
468
+ * Shell reserved words that can lead a segment without being the command it
469
+ * runs. The token after one of them is never that segment's command either, so
470
+ * a segment led by one cannot be resolved from its first word.
471
+ */
472
+ const SHELL_KEYWORDS = new Set([
473
+ 'if', 'then', 'else', 'elif', 'fi', 'while', 'until', 'do', 'done', 'for',
474
+ 'case', 'esac', 'select', 'function', 'in', '!', '[[', ']]',
475
+ ]);
476
+ /** `VAR=value` — an assignment the shell evaluates before any command runs. */
477
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
478
+ /**
479
+ * Verbs the rule layer resolves as a command's own first word. A segment whose
480
+ * first token cannot be a command (a `VAR=value` assignment, a `(`/`{` group
481
+ * opener, a shell keyword), or whose LATER tokens name one of these while its
482
+ * first does not, is a command the parser failed to resolve — not a mention.
483
+ *
484
+ * This is a SHAPE test on purpose. `verb = argv[0]` plus exact-verb rule matches
485
+ * meant `FOO=bar git push origin master`, `(git push origin master)`,
486
+ * `if true; then git push origin master; fi` and every exec-like wrapper outside
487
+ * the table (`pkexec git push origin master`) were silently ALLOWED, and a longer
488
+ * denylist of wrapper names cannot close that class — `my-custom-runner git push`
489
+ * has the same shape. Marking the segment `ambiguous` hands it to the rule
490
+ * layer's escalation, which asks, never allows.
491
+ */
492
+ const RULE_VERBS = new Set(['git', 'gh', 'pnpm', 'npm', 'yarn', 'curl', 'wget', 'source', '.']);
493
+ /**
494
+ * Verbs that only SCAN or PRINT their arguments, never execute them: the
495
+ * protected phrase in `grep -rn npm publish docs` is the pattern being searched
496
+ * for, not a command. They lead a segment whose later words name a rule verb
497
+ * without running it, so the later-token shape test must not apply to them.
498
+ *
499
+ * `find` is the one verb here that CAN run a command — but only through one of
500
+ * its action flags ({@link FIND_ACTION_FLAGS}), which {@link unresolvedCommand}
501
+ * treats separately. The set is exported so the rule layer applies the same
502
+ * reading to a protected path.
503
+ */
504
+ export const MENTION_VERBS = new Set([
505
+ 'grep',
506
+ 'egrep',
507
+ 'fgrep',
508
+ 'rg',
509
+ 'sed',
510
+ 'awk',
511
+ 'echo',
512
+ 'printf',
513
+ 'find',
514
+ 'ls',
515
+ 'test',
516
+ 'wc',
517
+ 'sort',
518
+ 'uniq',
519
+ 'jq',
520
+ ]);
521
+ /**
522
+ * The `find` actions that really RUN the command they name (every other find
523
+ * predicate only tests the entry). `-exec` alone was recognized, so a protected
524
+ * push or a protected-path mutation under `-execdir`/`-ok`/`-okdir` reached no
525
+ * rule — the escalation found nothing and the call was allowed.
526
+ */
527
+ export const FIND_ACTION_FLAGS = new Set(['-exec', '-execdir', '-ok', '-okdir']);
528
+ /**
529
+ * A shell's "run this script text" switch (`-c`, `-lc`, `--command`). The token
530
+ * after it is a COMMAND LINE, not an argument: `bash -c "rm -f <path>"` hands the
531
+ * mutation to a shell, and `find -exec bash -c "…" +` hides it one level deeper.
532
+ */
533
+ export const SHELL_COMMAND_FLAG = /^(?:-[A-Za-z]*c|--command)$/;
534
+ /** The shells that read `{@link SHELL_COMMAND_FLAG}`; a wrapper may hand them the script. */
535
+ export const SHELL_VERBS = new Set(['ash', 'bash', 'busybox', 'dash', 'ksh', 'sh', 'zsh']);
536
+ /** The verb without its directory (`/bin/git` → `git`). */
537
+ function commandBase(text) {
538
+ const cut = text.lastIndexOf('/');
539
+ return cut === -1 ? text : text.slice(cut + 1);
540
+ }
541
+ /**
542
+ * True when this segment's first token cannot be the command it claims to be, or
543
+ * when a later token names a verb the rules resolve while the first does not.
544
+ * See {@link RULE_VERBS} for why this is a shape test.
545
+ *
546
+ * A MENTION verb as the first token opts out of the later-token rule: `echo`,
547
+ * `printf`, `grep`, `rg`, `awk`, `ls` and friends only scan or print their
548
+ * arguments, so a rule phrase in them is a documented mention (`rg git push
549
+ * docs/`), not a hidden command — treating it as one was the over-block this
550
+ * exemption closes. `find` is the exception, and only through `-exec`, because
551
+ * that form really does run the command it names.
552
+ */
553
+ function unresolvedCommand(toks) {
554
+ const first = toks[0];
555
+ const firstWord = first !== undefined && first.kind === 'word' ? first.text : undefined;
556
+ if (firstWord !== undefined) {
557
+ if (ASSIGNMENT.test(firstWord) || SHELL_KEYWORDS.has(firstWord))
558
+ return true;
559
+ if (firstWord.startsWith('(') || firstWord.startsWith('{'))
560
+ return true;
561
+ // A known prefix verb (`env`, `sudo`, `nohup`, `time`, `command`, `busybox`)
562
+ // is stripped by `unwrapSegments`, which re-derives the segment afterwards.
563
+ // It must not make the raw reading look unresolved, or every `sudo git push`
564
+ // would be flagged ambiguous on the strength of the prefix alone.
565
+ const base = commandBase(firstWord);
566
+ if (RULE_VERBS.has(base) || PREFIX_VERBS.has(base))
567
+ return false;
568
+ if (MENTION_VERBS.has(base)) {
569
+ return base === 'find' && toks.some((t) => t.kind === 'word' && FIND_ACTION_FLAGS.has(t.text));
570
+ }
571
+ }
572
+ return toks.some((t, i) => i > 0 && t.kind === 'word' && RULE_VERBS.has(commandBase(t.text)));
573
+ }
574
+ function buildSegment(source, toks, exhausted) {
575
+ const argv = toks.map((t) => t.text);
576
+ const verb = argv[0];
577
+ const flags = [];
578
+ const paths = [];
579
+ for (const t of toks) {
580
+ if (t.kind === 'sep')
581
+ continue;
582
+ if (t.kind === 'redir' || t.text.startsWith('-'))
583
+ flags.push(t.text);
584
+ else if (t.kind === 'target' || looksLikePath(t.text))
585
+ paths.push(t.text);
586
+ }
587
+ const sub = subcommandIndex(toks, verb);
588
+ const refspecs = sub.index < 0
589
+ ? []
590
+ : toks
591
+ .slice(sub.index + 1)
592
+ .filter((t) => t.kind === 'word' && !t.text.startsWith('-'))
593
+ .map((t) => t.text);
594
+ const ambiguous = exhausted ||
595
+ sub.unknownOption ||
596
+ unresolvedCommand(toks) ||
597
+ toks.some((t) => t.expandable) ||
598
+ (verb !== undefined && (OPAQUE_VERBS.has(verb) || EXEC_WRAPPERS.has(verb)));
599
+ const words = toks.filter((t) => t.kind !== 'sep');
600
+ const segment = {
601
+ raw: source.slice(words[0].start, words[words.length - 1].end).trim(),
602
+ argv,
603
+ verb,
604
+ subcommand: sub.index < 0 ? undefined : toks[sub.index].text,
605
+ flags,
606
+ refspecs,
607
+ paths: [...new Set(paths)],
608
+ ambiguous,
609
+ };
610
+ // Bodies stay in order for the (exotic) segment that owns more than one.
611
+ const bodies = toks.filter((t) => t.heredoc !== undefined).map((t) => t.heredoc);
612
+ if (bodies.length > 0)
613
+ segment.heredoc = bodies.join('\n');
614
+ return segment;
615
+ }
616
+ /**
617
+ * Parse a shell command into its segments. `depth` is the shell-wrapper nesting
618
+ * level: once it reaches `MAX_WRAP_DEPTH` the segments are marked ambiguous
619
+ * instead of parsed, so an unreadable wrapper can never be treated as harmless.
620
+ *
621
+ * The operator that ends a segment stays in that segment's `argv` (its kind is
622
+ * `sep`, so no rule reads it as a word): splitting must not drop tokens, and the
623
+ * concatenated `argv` still holds every word, operator and redirection target of
624
+ * the command. A heredoc BODY is the one deliberate exception — it is not argv —
625
+ * so the round trip covers the command surface only: every body is removed from
626
+ * the token stream and attached to its owning segment as `Segment.heredoc`.
627
+ */
628
+ export function parseCommand(command, depth = 0) {
629
+ const exhausted = depth >= MAX_WRAP_DEPTH;
630
+ const segments = [];
631
+ let group = [];
632
+ const flushGroup = () => {
633
+ if (group.length > 0)
634
+ segments.push(buildSegment(command, group, exhausted));
635
+ group = [];
636
+ };
637
+ for (const t of tokenize(command)) {
638
+ if (t.kind === 'sep') {
639
+ if (group.length > 0) {
640
+ group.push(t);
641
+ flushGroup();
642
+ }
643
+ continue;
644
+ }
645
+ group.push(t);
646
+ }
647
+ flushGroup();
648
+ return segments;
649
+ }
650
+ /* ------------------------------------------------------------------ *
651
+ * Wrapper unwrapping and heredoc classification
652
+ * ------------------------------------------------------------------ */
653
+ /**
654
+ * Shells whose `-c <script>` argument the guard can parse as a script itself,
655
+ * plus the same shape under other POSIX-ish names. A verb outside this set is
656
+ * judged as itself: the guard never guesses that some other program runs its
657
+ * argument as a shell script — only the interpreters below are known to run an
658
+ * argument as a program, and those stay ambiguous instead.
659
+ */
660
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'ash', 'fish', 'csh', 'tcsh']);
661
+ /**
662
+ * Verbs that run an inline program in another language. `python -c`, `node -e`
663
+ * and friends are wrapper forms the guard cannot read: the segment stays
664
+ * ambiguous, because "the program is opaque" must never read as "nothing runs".
665
+ */
666
+ const INTERPRETER_SCRIPT_FLAGS = {
667
+ python: ['-c'],
668
+ python3: ['-c'],
669
+ node: ['-e', '-p'],
670
+ perl: ['-e', '-E'],
671
+ ruby: ['-e'],
672
+ php: ['-r'],
673
+ };
674
+ /**
675
+ * Prefixes that change WHO runs a command, never what it is. Stripping them is
676
+ * what keeps `sudo git push` and the bare `git push` judged by the same rule.
677
+ * `command` is the POSIX builtin prefix; `busybox` is a multi-call dispatcher
678
+ * whose first word is the applet that really runs (`busybox sh -c …`).
679
+ */
680
+ const PREFIX_VERBS = new Set(['env', 'sudo', 'nohup', 'time', 'command', 'busybox']);
681
+ /** Valueless short options, per prefix verb. */
682
+ const PREFIX_BARE_SHORT = {
683
+ env: 'i0v',
684
+ sudo: 'EHinSbkKAelsV',
685
+ time: 'pvaq',
686
+ nohup: '',
687
+ command: 'pVv',
688
+ busybox: '',
689
+ };
690
+ /** Short options that consume a value (glued or separated), per prefix verb. */
691
+ const PREFIX_VALUE_SHORT = {
692
+ env: 'uCS',
693
+ sudo: 'ughpCTrRtUDZ',
694
+ time: 'o',
695
+ nohup: '',
696
+ command: '',
697
+ busybox: '',
698
+ };
699
+ const PREFIX_BARE_LONG = {
700
+ env: ['--ignore-environment', '--null', '--debug'],
701
+ sudo: [
702
+ '--preserve-env',
703
+ '--login',
704
+ '--shell',
705
+ '--stdin',
706
+ '--non-interactive',
707
+ '--set-home',
708
+ '--reset-timestamp',
709
+ '--validate',
710
+ '--list',
711
+ '--edit',
712
+ '--askpass',
713
+ '--background',
714
+ '--version',
715
+ '--help',
716
+ ],
717
+ time: ['--portability', '--verbose', '--append', '--quiet'],
718
+ nohup: ['--help', '--version'],
719
+ command: [],
720
+ busybox: ['--help', '--version'],
721
+ };
722
+ const PREFIX_VALUE_LONG = {
723
+ env: ['--unset', '--chdir', '--split-string'],
724
+ sudo: [
725
+ '--user',
726
+ '--group',
727
+ '--host',
728
+ '--prompt',
729
+ '--close-from',
730
+ '--command-timeout',
731
+ '--role',
732
+ '--type',
733
+ '--other-user',
734
+ '--chdir',
735
+ '--chroot',
736
+ ],
737
+ time: ['--output'],
738
+ nohup: [],
739
+ command: [],
740
+ busybox: ['--install'],
741
+ };
742
+ /** `env FOO=1 …` — an assignment the prefix exports, never the command's verb. */
743
+ const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
744
+ /**
745
+ * Consume a prefix verb's own options and assignments.
746
+ *
747
+ * Fail-closed like `subcommandIndex`: an option that is in neither table may or
748
+ * may not consume the next word. The optimistic reading skips the pair (which
749
+ * keeps the real verb visible) and records `ambiguous`, so the rule layer asks
750
+ * rather than allows.
751
+ */
752
+ function skipPrefixOptions(verb, toks, start) {
753
+ const bareShort = PREFIX_BARE_SHORT[verb] ?? '';
754
+ const valueShort = PREFIX_VALUE_SHORT[verb] ?? '';
755
+ const bareLong = PREFIX_BARE_LONG[verb] ?? [];
756
+ const valueLong = PREFIX_VALUE_LONG[verb] ?? [];
757
+ let i = start;
758
+ let ambiguous = false;
759
+ while (i < toks.length) {
760
+ const t = toks[i];
761
+ if (t.kind !== 'word')
762
+ break;
763
+ if (verb === 'env' && ENV_ASSIGNMENT.test(t.text)) {
764
+ i++;
765
+ continue;
766
+ }
767
+ if (t.text === '--') {
768
+ i++;
769
+ break;
770
+ }
771
+ if (!t.text.startsWith('-') || t.text === '-')
772
+ break;
773
+ const next = toks[i + 1];
774
+ const consumeValue = () => {
775
+ if (next !== undefined && next.kind === 'word')
776
+ i += 2;
777
+ else {
778
+ ambiguous = true;
779
+ i++;
780
+ }
781
+ };
782
+ if (t.text.startsWith('--')) {
783
+ if (t.text.indexOf('=') > 0)
784
+ i++; // --name=value is self-contained
785
+ else if (bareLong.includes(t.text))
786
+ i++;
787
+ else if (valueLong.includes(t.text))
788
+ consumeValue();
789
+ else if (next !== undefined && next.kind === 'word' && !next.text.startsWith('-')) {
790
+ ambiguous = true;
791
+ i += 2;
792
+ }
793
+ else
794
+ i++;
795
+ continue;
796
+ }
797
+ // A single-dash cluster: every character before a value-taking one is a flag.
798
+ const chars = t.text.slice(1);
799
+ let done = false;
800
+ for (let k = 0; k < chars.length && !done; k++) {
801
+ const c = chars[k];
802
+ if (verb === 'command' && (c === 'v' || c === 'V')) {
803
+ // `command -v ls` / `command -V ls` only report where `ls` resolves to
804
+ // (or describe it); they execute nothing. The guard has no "word that is
805
+ // not a command" shape, so the reading is recorded as unprovable rather
806
+ // than derived as a resolved `ls` execution that never happens.
807
+ // `command -p ls` DOES run `ls`, so it stays resolvable.
808
+ ambiguous = true;
809
+ continue;
810
+ }
811
+ if (bareShort.includes(c))
812
+ continue;
813
+ if (valueShort.includes(c)) {
814
+ if (k + 1 < chars.length)
815
+ i++; // -uroot: the rest of the cluster is the value
816
+ else
817
+ consumeValue(); // -u root: the value is the next word
818
+ done = true;
819
+ break;
820
+ }
821
+ ambiguous = true;
822
+ i++;
823
+ done = true;
824
+ break;
825
+ }
826
+ if (!done)
827
+ i++;
828
+ }
829
+ return { index: i, ambiguous };
830
+ }
831
+ /** Drop the leading `env …` / `sudo …` / `nohup …` / `time …` prefixes. */
832
+ function stripPrefixes(toks) {
833
+ let i = 0;
834
+ let ambiguous = false;
835
+ for (;;) {
836
+ const t = toks[i];
837
+ if (t === undefined || t.kind !== 'word' || !PREFIX_VERBS.has(t.text))
838
+ break;
839
+ i++;
840
+ const skipped = skipPrefixOptions(t.text, toks, i);
841
+ i = skipped.index;
842
+ ambiguous = ambiguous || skipped.ambiguous;
843
+ }
844
+ return { toks: toks.slice(i), dropped: i, ambiguous };
845
+ }
846
+ /**
847
+ * The script a shell was told to run with `-c`: `-c cmd`, `-c'cmd'`, `-lc cmd`.
848
+ * `found: false` means no `-c` appears at all (a script file, `-s`, a bare
849
+ * shell), and `script: undefined` means `-c` had no argument — both unreadable.
850
+ */
851
+ function shellCommandArg(toks) {
852
+ for (let i = 1; i < toks.length; i++) {
853
+ const t = toks[i];
854
+ if (t.kind !== 'word')
855
+ break;
856
+ if (t.text === '--')
857
+ break;
858
+ if (!t.text.startsWith('-') || t.text === '-')
859
+ break;
860
+ if (t.text.startsWith('--')) {
861
+ if (t.text === '--rcfile' || t.text === '--init-file')
862
+ i++; // takes a value
863
+ continue;
864
+ }
865
+ const chars = t.text.slice(1);
866
+ for (let k = 0; k < chars.length; k++) {
867
+ const c = chars[k];
868
+ if (c === 'c') {
869
+ const inline = chars.slice(k + 1);
870
+ if (inline !== '')
871
+ return { found: true, script: inline };
872
+ const next = toks[i + 1];
873
+ return { found: true, script: next !== undefined && next.kind === 'word' ? next.text : undefined };
874
+ }
875
+ if (c === 'o' || c === 'O') {
876
+ if (k + 1 === chars.length)
877
+ i++; // -o pipefail: the value is the next word
878
+ break;
879
+ }
880
+ }
881
+ }
882
+ return { found: false };
883
+ }
884
+ /** True when an interpreter carries an inline program (`python -c`, `node -e`). */
885
+ function hasInterpreterScript(toks) {
886
+ const verb = toks[0]?.text;
887
+ if (verb === undefined)
888
+ return false;
889
+ const flags = INTERPRETER_SCRIPT_FLAGS[verb];
890
+ if (flags === undefined)
891
+ return false;
892
+ for (let i = 1; i < toks.length; i++) {
893
+ const t = toks[i];
894
+ if (t.kind !== 'word')
895
+ break;
896
+ if (t.text === '--')
897
+ break;
898
+ if (!t.text.startsWith('-') || t.text === '-')
899
+ break;
900
+ if (flags.includes(t.text))
901
+ return true;
902
+ if (!t.text.startsWith('--')) {
903
+ for (const c of t.text.slice(1))
904
+ if (flags.includes('-' + c))
905
+ return true;
906
+ }
907
+ }
908
+ return false;
909
+ }
910
+ /** The tokens of one segment again, so its fields can be re-derived. */
911
+ function segmentTokens(seg) {
912
+ return tokenize(seg.raw).filter((t) => t.kind !== 'sep');
913
+ }
914
+ /** Re-derive a segment from a token subset of its own source text. */
915
+ function rebuild(seg, toks, forced) {
916
+ const words = toks.filter((t) => t.kind !== 'sep');
917
+ if (words.length === 0) {
918
+ return { raw: seg.raw, argv: [], flags: [], refspecs: [], paths: [], ambiguous: true };
919
+ }
920
+ const built = buildSegment(seg.raw, words, forced);
921
+ if (seg.heredoc !== undefined)
922
+ built.heredoc = seg.heredoc;
923
+ return built;
924
+ }
925
+ /**
926
+ * True when the guard has no reading for this verb at all: not a rule verb, not
927
+ * a mention-only verb, not a prefix, not an exec-like wrapper, not a shell. Only
928
+ * such a segment is re-read for a later `shell -c` script — a verb the guard DOES
929
+ * know is judged by its own rules and its own wrapper handling.
930
+ */
931
+ function isUnknownVerb(verb) {
932
+ const base = commandBase(verb);
933
+ return (!RULE_VERBS.has(base) &&
934
+ !PREFIX_VERBS.has(base) &&
935
+ !MENTION_VERBS.has(base) &&
936
+ !SHELLS.has(base) &&
937
+ !OPAQUE_VERBS.has(base) &&
938
+ !EXEC_WRAPPERS.has(base));
939
+ }
940
+ /**
941
+ * The tokens from a SHELL that appears after the segment's own verb, when that
942
+ * shell carries a readable `-c` script: `my-custom-runner bash -c "git push
943
+ * origin master"`. The runner is opaque to the guard, but the script it hands to
944
+ * the shell is exactly what runs, so the shell invocation takes the place of the
945
+ * unreadable argument list (the caller feeds it through the same shell-wrapper
946
+ * path). Returns `undefined` when no later token is a shell with a `-c` script.
947
+ */
948
+ function laterShellTokens(toks) {
949
+ for (let i = 1; i < toks.length; i++) {
950
+ const t = toks[i];
951
+ if (t.kind !== 'word' || !SHELLS.has(commandBase(t.text)))
952
+ continue;
953
+ const rest = toks.slice(i);
954
+ const command = shellCommandArg(rest);
955
+ if (command.found && command.script !== undefined)
956
+ return rest;
957
+ }
958
+ return undefined;
959
+ }
960
+ /**
961
+ * Remove every wrapper around a parsed command and return the segments that
962
+ * actually run.
963
+ *
964
+ * A segment that is not a wrapper is returned unchanged — same object, no
965
+ * re-derivation — so the common path costs nothing and cannot drift. A shell
966
+ * wrapper (`bash -c …`, `bash -s`, a `bash <<EOF` body) is REPLACED by the
967
+ * segments of its script, each tagged `wrappedBy`. A wrapper that cannot be read
968
+ * — unknown nesting past `MAX_WRAP_DEPTH`, a `-c` with no argument, a script file
969
+ * the guard cannot open, an interpreter's inline program — stays in the result
970
+ * marked `ambiguous`, which the rule layer answers with a prompt, never an allow.
971
+ * An exec-like wrapper (`timeout`, `nice`, `setsid`, `watch`, …) is not unwrapped
972
+ * at all and is `ambiguous` for the same reason: the command it runs is not the
973
+ * command the guard read.
974
+ */
975
+ export function unwrapSegments(segs, depth = 0) {
976
+ const out = [];
977
+ for (const seg of segs)
978
+ out.push(...unwrapSegment(seg, depth));
979
+ return out;
980
+ }
981
+ function unwrapSegment(seg, depth) {
982
+ const toks = segmentTokens(seg);
983
+ const stripped = stripPrefixes(toks);
984
+ const declared = stripped.toks[0] !== undefined && stripped.toks[0].kind === 'word' ? stripped.toks[0].text : undefined;
985
+ // A verb the guard cannot name may still hand a `-c` script to a shell that
986
+ // appears later (`my-custom-runner bash -c "git push origin master"`): the
987
+ // script is what runs, so its shell invocation replaces the opaque argument
988
+ // list and is handled exactly like a shell-first segment.
989
+ const hidden = declared !== undefined && !SHELLS.has(commandBase(declared)) && isUnknownVerb(declared)
990
+ ? laterShellTokens(stripped.toks)
991
+ : undefined;
992
+ const rest = hidden ?? stripped.toks;
993
+ const verb = rest[0] !== undefined && rest[0].kind === 'word' ? rest[0].text : undefined;
994
+ // The shell is read by its BASE name, so `/bin/bash -c …` is unwrapped exactly
995
+ // like `bash -c …` (the path-qualified form is the same command).
996
+ if (verb !== undefined && SHELLS.has(commandBase(verb))) {
997
+ const command = shellCommandArg(rest);
998
+ const script = command.found ? command.script : seg.heredoc;
999
+ if (script === undefined || depth >= MAX_WRAP_DEPTH)
1000
+ return [rebuild(seg, rest, true)];
1001
+ // Two readings stay approximations even with a script in hand: a `-c` script
1002
+ // that is also fed a heredoc may run whatever that body holds, and an
1003
+ // UNQUOTED heredoc delimiter lets the outer shell expand the body first. Mark
1004
+ // the derived segments ambiguous rather than present the text as exact.
1005
+ const delimiters = toks.filter((t) => t.heredoc !== undefined);
1006
+ const expanded = delimiters.length > 0 && !delimiters.every((t) => t.heredocQuoted === true) && /[$`]/.test(script);
1007
+ const approximate = (command.found && seg.heredoc !== undefined) || (!command.found && expanded);
1008
+ const inner = unwrapSegments(parseCommand(script, depth + 1), depth + 1);
1009
+ if (inner.length === 0)
1010
+ return [rebuild(seg, rest, true)];
1011
+ const ambiguous = seg.ambiguous || stripped.ambiguous || approximate;
1012
+ return inner.map((s) => ({ ...s, wrappedBy: verb, ambiguous: s.ambiguous || ambiguous }));
1013
+ }
1014
+ const opaque = stripped.ambiguous ||
1015
+ (verb !== undefined &&
1016
+ INTERPRETER_SCRIPT_FLAGS[verb] !== undefined &&
1017
+ (hasInterpreterScript(rest) || seg.heredoc !== undefined));
1018
+ if (stripped.dropped === 0 && !opaque)
1019
+ return [seg];
1020
+ return [rebuild(seg, rest, seg.ambiguous || opaque)];
1021
+ }
1022
+ /* ------------------------------------------------------------------ *
1023
+ * Command and tool-argument interpretation
1024
+ * ------------------------------------------------------------------ */
1025
+ /**
1026
+ * Collapse quoted spans — text inside quotes is data (echo/printf/script
1027
+ * bodies), not argv.
1028
+ */
1029
+ export function stripQuoted(cmd) {
1030
+ return cmd.replace(/"[^"]*"/g, ' ').replace(/'[^']*'/g, ' ');
1031
+ }
1032
+ /**
1033
+ * Collapse heredoc bodies — the lines fed to a command's stdin are data, not
1034
+ * argv. A heredoc body routinely contains protected path literals (setup
1035
+ * scripts, config generators) which must not be mistaken for an access.
1036
+ * Run this AFTER `stripQuoted` so a quoted delimiter (`<<'EOF'`) is already
1037
+ * reduced to its bare form.
1038
+ */
1039
+ export function stripHeredocs(cmd) {
1040
+ return cmd.replace(/<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?[^\r\n]*\r?\n[\s\S]*?^\1\s*$/gm, ' ');
1041
+ }
1042
+ /**
1043
+ * The executed command surface of a tool call. Shell-style tools carry their
1044
+ * script in `args.command` (bash/exec/shell/govard_shell); bare string args are
1045
+ * the command itself. Tools with no command field (read/write/memory/...) have
1046
+ * no execution surface, so protected-op detection must not apply to their
1047
+ * content — that was the source of the analysis-tool false positives.
1048
+ */
1049
+ export function extractCommandText(args) {
1050
+ if (args == null)
1051
+ return undefined;
1052
+ if (typeof args === 'string')
1053
+ return args;
1054
+ if (typeof args === 'object' && typeof args.command === 'string') {
1055
+ return args.command;
1056
+ }
1057
+ return undefined;
1058
+ }
1059
+ /**
1060
+ * The path a file-oriented tool call targets, from the args shapes the DSH and
1061
+ * Maestro file tools use (`path` / `file` / `file_path` / `filePath`, or a bare
1062
+ * string arg). Returns undefined when the call carries no path.
1063
+ */
1064
+ export function extractPathField(args) {
1065
+ if (args == null)
1066
+ return undefined;
1067
+ if (typeof args === 'string')
1068
+ return args;
1069
+ if (typeof args !== 'object')
1070
+ return undefined;
1071
+ const a = args;
1072
+ const v = a.path ?? a.file ?? a.file_path ?? a.filePath;
1073
+ return typeof v === 'string' ? v : undefined;
1074
+ }
1075
+ /**
1076
+ * Resolve the working directory a command actually executes in, when it names
1077
+ * one explicitly (cd <dir> / git -C <dir>). Falls back to the passed cwd when
1078
+ * the command has no explicit target — preserving the historical session-cwd
1079
+ * semantics for commands that run in place.
1080
+ */
1081
+ export function getCommandWorkingDir(command, cwd) {
1082
+ if (!command || !cwd)
1083
+ return cwd ?? undefined;
1084
+ const hasCdVerb = /\bcd\b/.test(command) || /\bgit\s+-C\b/.test(command);
1085
+ const cd = /\bcd\s+([^\s;&|"'`${}]+)(?:\s*(?:[;&|]|$))/.exec(command);
1086
+ const c = /\bgit\s+-C\s+([^\s;&|"'`${}]+)/.exec(command);
1087
+ const dir = cd?.[1] ?? c?.[1];
1088
+ if (!dir) {
1089
+ // A cd/-C verb is present but its target cannot be parsed (quoted, $VAR,
1090
+ // wildcard, bare `cd`): do NOT assume the session cwd — that reintroduces
1091
+ // the false positive when the session cwd repo sits on a protected branch.
1092
+ // Unknown target means no protected-branch assumption (segment word checks
1093
+ // still apply); commands with no cd verb keep the session-cwd semantics.
1094
+ if (hasCdVerb)
1095
+ return undefined;
1096
+ return cwd;
1097
+ }
1098
+ if (dir === '~')
1099
+ return homedir();
1100
+ if (dir.startsWith('~/'))
1101
+ return join(homedir(), dir.slice(2));
1102
+ return resolve(cwd, dir);
1103
+ }