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