@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,832 @@
1
+ import { parseCommand, unwrapSegments, extractCommandText, extractPathField, getCommandWorkingDir, stripQuoted, EXEC_WRAPPERS, FIND_ACTION_FLAGS, MENTION_VERBS, OPAQUE_VERBS, SHELL_COMMAND_FLAG, SHELL_VERBS, } from './parse.js';
2
+ import { isBlockedPath, isOutsideCwd, isRuntimeSpillPath, isWithinTempDir, pathSpellings } from './paths.js';
3
+ /**
4
+ * The closed set of rule ids the classifier can emit (the empty id is the
5
+ * allow verdict, deliberately not listed — there is no allow "rule").
6
+ * Rule ids are the stable contract: config overrides, journal entries and
7
+ * approval reasons all key on them, so they are never renamed casually.
8
+ */
9
+ export const RULE_IDS = [
10
+ 'git.push.protected',
11
+ 'git.merge.protected',
12
+ 'git.tag.release',
13
+ 'git.push.force',
14
+ 'gh.release.create',
15
+ 'gh.protection.delete',
16
+ 'pkg.publish',
17
+ 'secret.access',
18
+ 'fs.write.outside',
19
+ 'net.exec.remote',
20
+ 'guard.tamper',
21
+ ];
22
+ /** Default tier per rule id, before any config override (see `decide`). */
23
+ export const DEFAULT_TIERS = {
24
+ 'git.push.protected': 'ask',
25
+ 'git.merge.protected': 'journal',
26
+ 'git.tag.release': 'ask',
27
+ 'git.push.force': 'ask',
28
+ 'gh.release.create': 'ask',
29
+ 'gh.protection.delete': 'ask',
30
+ 'pkg.publish': 'ask',
31
+ 'secret.access': 'ask',
32
+ 'fs.write.outside': 'ask',
33
+ 'net.exec.remote': 'ask',
34
+ 'guard.tamper': 'deny',
35
+ };
36
+ const FILE_TOOLS = new Set([
37
+ 'read',
38
+ 'write',
39
+ 'edit',
40
+ 'maestro_read_file',
41
+ 'maestro_write_file',
42
+ 'fs_read',
43
+ 'fs_write',
44
+ 'read_file',
45
+ 'write_file',
46
+ ]);
47
+ const WRITE_FILE_TOOLS = new Set(['write', 'edit', 'maestro_write_file', 'fs_write', 'write_file']);
48
+ /** Verbs that actually touch file contents — a protected path next to one is an access. */
49
+ const ACCESS_VERBS = /\b(cat|bat|head|tail|less|more|cp|scp|rsync|curl|wget|source|tee|dd|install|xxd|base64|openssl|gpg|tar|zip)\b/;
50
+ /**
51
+ * Verbs that WRITE the file they name. A guard path next to one of these is an
52
+ * EDIT, which is what the spec's deny tier covers (§5.4/§5.6: "a segment that
53
+ * edits the guard's own settings/config or truncates/removes the journal").
54
+ * Reads (`cat`, `tail`, `head`, `grep`, `less`) are deliberately absent: the
55
+ * guard's own deny text tells the agent to "see the guard journal", so a read
56
+ * has to fall through to the ordinary rules.
57
+ */
58
+ const MUTATION_VERBS = new Set([
59
+ 'rm',
60
+ 'mv',
61
+ 'cp',
62
+ 'ln',
63
+ 'truncate',
64
+ 'shred',
65
+ 'dd',
66
+ 'tee',
67
+ 'install',
68
+ 'chmod',
69
+ 'chown',
70
+ // Writers with no read form: a transfer that overwrites its target, an in-place
71
+ // patcher, a source-soaking filter, a remover.
72
+ 'patch',
73
+ 'sponge',
74
+ 'unlink',
75
+ 'rmdir',
76
+ // GNU `ed` has no read-only mode — any invocation that names a file opens it
77
+ // for editing — so it belongs with the unconditional writers, not the shapes.
78
+ 'ed',
79
+ ]);
80
+ /**
81
+ * Verbs that write ONLY in their write shape, and whose other forms read the very
82
+ * path they name. A bare membership in {@link MUTATION_VERBS} made every read form
83
+ * of these an unappealable deny (`curl -I <journal>`, `wget -O - <journal>`,
84
+ * `rsync --list-only <journal> /tmp/`, `vi -R <journal>`), which contradicts the
85
+ * denial tier's own contract that a read falls through; {@link writesByShape}
86
+ * decides each one from its flags and operands.
87
+ */
88
+ const SHAPE_WRITERS = new Set(['curl', 'wget', 'rsync', 'scp', 'vi', 'vim', 'nano']);
89
+ /** The read-only forms of the shape writers, per verb (`-v` means Ex mode in vim). */
90
+ const READ_ONLY_FLAGS = {
91
+ vi: new Set(['-R', '-M', '--readonly']),
92
+ vim: new Set(['-R', '-M', '--readonly']),
93
+ nano: new Set(['-v', '--view']),
94
+ };
95
+ /** Editors that write only when their in-place switch is present. */
96
+ const IN_PLACE_EDITORS = new Set(['sed', 'perl']);
97
+ /** `-i`, `-ni`, `-i.bak`, `--in-place` — the in-place switch of those editors. */
98
+ const IN_PLACE_FLAG = /^--in-place(?:=.*)?$|^-[A-Za-z]*i/;
99
+ /**
100
+ * A redirection that WRITES its target (`>`, `>>`, `2>`, `&>`, and the `>|`
101
+ * clobber override). Not `>&2`, not `<`. `>|` used to be split into `>` + `|`
102
+ * by the tokenizer, which moved its target into a segment of its own.
103
+ */
104
+ const WRITE_REDIRECT = /^(?:[0-9]+)?(?:&>>?|>>?|>\|)$/;
105
+ /**
106
+ * `fs.write.outside` covers the whole write family — the DSH-native `write` and
107
+ * `edit` tools as well as the legacy Maestro writers. Scoping the rule to the
108
+ * legacy names alone is what made the original cwd containment inert: the tools
109
+ * actually in use (`read`/`write`/`edit`) were never matched. The OS temp dir is
110
+ * exempt (`isWithinTempDir`) so scratch work stays frictionless; the runtime
111
+ * spill dir is a subdirectory of it and keeps its explicit exemption while
112
+ * `workingDirContainment.spillReads` is on. Both exemptions are resolved against
113
+ * the SAME base as the containment test — the session cwd — so the two can never
114
+ * disagree about a relative target.
115
+ *
116
+ * The spill switch is why {@link isExemptWritePath} tests the spill path BEFORE
117
+ * the temp dir: the spill dir lives under `os.tmpdir()`, so testing the temp
118
+ * exemption first would make `spillReads: false` a no-op for every absolute
119
+ * spill path — the "documented but inert" failure the wiring closes.
120
+ */
121
+ function isExemptWritePath(path, cwd, containment) {
122
+ if (isRuntimeSpillPath(path, cwd))
123
+ return containment?.spillReads !== false;
124
+ return isWithinTempDir(path, cwd);
125
+ }
126
+ /* ------------------------------------------------------------------ *
127
+ * Protected operations, resolved from parsed segments
128
+ * ------------------------------------------------------------------ */
129
+ /** Package managers whose `publish` verb is gated. */
130
+ const PACKAGE_MANAGERS = new Set(['pnpm', 'npm', 'yarn']);
131
+ /**
132
+ * Package-manager verbs that run a named SCRIPT or package: `npm run publish`
133
+ * runs a script called `publish` and `yarn dlx publish` runs a package, so in
134
+ * neither is `publish` the verb that publishes THIS project.
135
+ */
136
+ const SCRIPT_RUNNER_VERBS = new Set(['run', 'run-script', 'exec', 'dlx']);
137
+ /** Shells whose `-c`/stdin argument the parser can read (see `parse.ts`'s SHELLS). */
138
+ const SHELL_NAMES = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'ash', 'fish', 'csh', 'tcsh']);
139
+ /** `source`/`.` execute the process substitution they are handed, like a shell does. */
140
+ const SOURCE_VERBS = new Set(['source', '.']);
141
+ /** `vX.Y.Z` / `X.Y.Z` plus an optional prerelease or build suffix — a release tag, not a branch. */
142
+ const SEMVER_REF = /^v?\d+\.\d+\.\d+(?:[-+][0-9a-z.]+)?$/i;
143
+ /**
144
+ * Raw-text shapes for the ambiguity escalation. A segment the parser could not
145
+ * resolve (an exec-like wrapper, an expansion, an unknown option) is escalated
146
+ * only when its own raw text carries one of these — otherwise `ssh host ls`
147
+ * would prompt on every call. They are deliberately the same shapes the rule
148
+ * layer resolves from a parsed segment, applied to the text the parser refused
149
+ * to resolve — read through `rawSurface`, so quoted data cannot fire one.
150
+ */
151
+ const RAW_GH_PR_MERGE = /\bgh\s+pr\s+merge\b/;
152
+ const RAW_GH_RELEASE = /\bgh\s+release\s+(?:create|publish)\b/i;
153
+ /** `gh api … DELETE …` — the protected branch it runs on is checked separately. */
154
+ const RAW_GH_API_DELETE = /\bgh\s+api\b[\s\S]*\bdelete\b/i;
155
+ const RAW_PUBLISH = /\b(pnpm|npm|yarn)\b[^\n]*\bpublish\b/;
156
+ const RAW_GIT_PUSH = /\bgit\s+push\b/;
157
+ const RAW_RELEASE_TAG = /refs\/tags\/|(?:^|\s)v?\d+\.\d+\.\d+(?:[-+][0-9a-z.]+)?(?:\s|$)/;
158
+ const RAW_FORCE_PUSH = /(?:^|\s)(?:--force(?:-with-lease)?|-f)(?:=|\s|$)/;
159
+ const RAW_REMOTE_EXEC = /\b(curl|wget)\b[^\n|]*\|\s*(?:sudo\s+)?(?:ba|z|da)?sh\b|\b(source|\.)\s*<\(\s*(curl|wget)\b|\b(?:ba|z|da)?sh\s*<\(\s*(curl|wget)\b/;
160
+ /** The verb without its directory (`/bin/bash` → `bash`). */
161
+ function baseName(verb) {
162
+ if (verb === undefined)
163
+ return undefined;
164
+ const cut = verb.lastIndexOf('/');
165
+ return cut === -1 ? verb : verb.slice(cut + 1);
166
+ }
167
+ /** The shell a verb names, bare or by path (`/bin/bash` → `bash`). */
168
+ function shellName(verb) {
169
+ const base = baseName(verb);
170
+ return base !== undefined && SHELL_NAMES.has(base) ? base : undefined;
171
+ }
172
+ /**
173
+ * True when a verb RUNS a command of its own: an exec-like wrapper the parser
174
+ * deliberately does not unwrap (`ssh host CMD`, `timeout 5 CMD`, `script -c
175
+ * CMD`) or an opaque runner (`eval`, `exec`, `xargs`). Both classes are exactly
176
+ * the segments the parser marks `ambiguous` on the verb alone, and in both the
177
+ * quoted span is the command being run, not data about it. The sets live in
178
+ * `parse.ts`, which owns the ambiguity classification.
179
+ */
180
+ function runsOwnCommand(verb) {
181
+ const base = baseName(verb);
182
+ return base !== undefined && (EXEC_WRAPPERS.has(base) || OPAQUE_VERBS.has(base));
183
+ }
184
+ /**
185
+ * The text a raw-shape matcher reads for one segment: `seg.raw` with its quoted
186
+ * spans collapsed, because the batch contract is that quotes are DATA. A quoted
187
+ * mention therefore never fires a rule — `gh pr create --body "gh release create
188
+ * v1"` is a description, and a quoted task or program body that happens to hold
189
+ * `git push origin v1.0.0` is text, not a push.
190
+ *
191
+ * The one exception is a verb that runs its own argument (`runsOwnCommand`):
192
+ * `ssh host "git push origin main"` really does push, so collapsing that quote
193
+ * would turn the fail-closed ambiguity escalation into an allow.
194
+ *
195
+ * KNOWN, DELIBERATE `allow` — interpreter inline programs: `python3 -c "…"`,
196
+ * `node -e "…"`, `perl -e "…"`, `php -r "…"` are not in either unwrap set, so
197
+ * the quoted program is data and a protected operation spelled inside it is
198
+ * allowed (`python3 -c "…os.system('git push origin master')"`). That is
199
+ * accepted rather than overlooked: an inline program is lexically
200
+ * indistinguishable from the `node -e` MENTION case the deleted
201
+ * `multiline-quoted` suite pinned as not-gated (`node -e "… git push origin
202
+ * v1.0.0 …"` must stay quiet), and the guard never reads a script file's
203
+ * contents either way — `python3 deploy.py` is equally opaque. Gating it would
204
+ * require the guard to interpret the interpreter's language. Task B5 must pin
205
+ * this residual as an explicit `allow` row in the golden corpus.
206
+ */
207
+ function rawSurface(seg) {
208
+ return runsOwnCommand(seg.verb) ? seg.raw : stripQuoted(seg.raw);
209
+ }
210
+ /** Both sides of a refspec: `+refs/heads/x:refs/heads/y` → `['x', 'y']`. */
211
+ function refNames(refspec) {
212
+ return refspec
213
+ .replace(/^\+/, '')
214
+ .split(':')
215
+ .map((side) => side.replace(/^refs\/(?:heads|tags|remotes)\//, '').replace(/^refs\//, ''))
216
+ .filter((side) => side !== '');
217
+ }
218
+ /** True when any refspec this push names is one of the protected branches. */
219
+ function namesProtectedBranch(seg, branches) {
220
+ const wanted = new Set(branches.map((b) => b.toLowerCase()));
221
+ return seg.refspecs.some((r) => refNames(r).some((name) => wanted.has(name.toLowerCase())));
222
+ }
223
+ /** True for `refs/tags/*` and for a bare semver tag (`v1.2.3`, `1.2.3-rc.2`). */
224
+ function isTagRefspec(refspec) {
225
+ if (refspec.replace(/^\+/, '').split(':').some((side) => side.startsWith('refs/tags/')))
226
+ return true;
227
+ return refNames(refspec).some((name) => SEMVER_REF.test(name));
228
+ }
229
+ /** `--force`, `--force-with-lease[=…]`, a `-f` (alone or in a short cluster), or a `+refspec`. */
230
+ function isForcePush(seg) {
231
+ if (seg.refspecs.some((r) => r.startsWith('+')))
232
+ return true;
233
+ return seg.flags.some((f) => f === '--force' || f.startsWith('--force-with-lease') || (/^-[A-Za-z]+$/.test(f) && f.includes('f')));
234
+ }
235
+ /**
236
+ * `HEAD` (and `@`) alone name no target of their own: they push the branch the
237
+ * repository is checked out on, so they are resolved through `branchOf` rather
238
+ * than read as an explicit, safe refspec. `HEAD:feature/x` is explicit — its
239
+ * destination names the target.
240
+ */
241
+ function isImplicitRefspec(refspec) {
242
+ const bare = refspec.replace(/^\+/, '');
243
+ if (bare.includes(':'))
244
+ return false;
245
+ return bare === 'HEAD' || bare === '@';
246
+ }
247
+ /**
248
+ * `git push`, refspec-first (spec §5.4): an explicit refspec is the target, so a
249
+ * protected name or a release tag in it decides the verdict; only a push with
250
+ * nothing but the remote (or `HEAD`) falls back to the branch the target repo is
251
+ * checked out on. A branch that cannot be resolved is fail-closed: `cd "$D" &&
252
+ * git push origin HEAD` must ask because the branch cannot be proven safe.
253
+ */
254
+ function classifyPush(seg, command, ctx, cwd) {
255
+ const branches = ctx.settings.protectedBranches;
256
+ if (namesProtectedBranch(seg, branches)) {
257
+ return { ruleId: 'git.push.protected', tier: 'ask', target: command };
258
+ }
259
+ if (seg.refspecs.some(isTagRefspec)) {
260
+ return { ruleId: 'git.tag.release', tier: 'ask', target: command };
261
+ }
262
+ // Flag targets, checked before the refspec reading: `--all`/`--mirror` push
263
+ // every local branch — including a protected one — and `--mirror` can also
264
+ // force-update or delete remote refs, while `--tags` means `refs/tags/*`.
265
+ // None of them carries a refspec, so the flag itself is the target and the
266
+ // branch fallback must never see them.
267
+ if (seg.flags.includes('--all') || seg.flags.includes('--mirror')) {
268
+ return { ruleId: 'git.push.protected', tier: 'ask', target: command };
269
+ }
270
+ if (seg.flags.includes('--tags')) {
271
+ return { ruleId: 'git.tag.release', tier: 'ask', target: command };
272
+ }
273
+ if (isForcePush(seg)) {
274
+ return { ruleId: 'git.push.force', tier: 'ask', target: command };
275
+ }
276
+ const explicit = seg.refspecs.slice(1).filter((r) => !isImplicitRefspec(r));
277
+ if (explicit.length > 0)
278
+ return undefined;
279
+ // The repo the push actually runs in: `cd <dir>` / `git -C <dir>` when the
280
+ // command names one, the session cwd otherwise — never an empty-dir sentinel.
281
+ const repo = getCommandWorkingDir(command, cwd);
282
+ const branch = repo === undefined ? undefined : ctx.branchOf?.(repo);
283
+ if (branch !== undefined && branches.some((b) => b.toLowerCase() === branch.toLowerCase())) {
284
+ return { ruleId: 'git.push.protected', tier: 'ask', target: command, repo, branch };
285
+ }
286
+ if (branch === undefined) {
287
+ // A repo that names a working directory the guard cannot read, or a branch
288
+ // `branchOf` cannot resolve, must not be treated as safe: ask.
289
+ return { ruleId: 'git.push.protected', tier: 'ask', target: command, repo };
290
+ }
291
+ return undefined;
292
+ }
293
+ /** `gh pr merge` — parsed, not matched against the raw text. */
294
+ function isGhPrMerge(seg) {
295
+ if (baseName(seg.verb) !== 'gh')
296
+ return false;
297
+ return seg.argv.some((word, i) => word === 'pr' && seg.argv[i + 1] === 'merge');
298
+ }
299
+ /**
300
+ * A `gh` statement read from the segment that carries it. A RESOLVED segment
301
+ * must name `gh` as its verb, so a quoted mention inside a resolved
302
+ * `echo "gh release create v1"` stays data; a segment the parser could not
303
+ * resolve is judged on its raw text — the same fail-closed reading every other
304
+ * ambiguity escalation uses — because the command it really runs was never
305
+ * parsed. Neither shape needs parser support beyond the segment boundary, and
306
+ * both read `rawSurface` so a quoted mention (`gh pr create --body "… gh release
307
+ * create …"`) cannot fire the rule it is describing.
308
+ */
309
+ function namesGhStatement(seg, shape) {
310
+ if (!seg.ambiguous && baseName(seg.verb) !== 'gh')
311
+ return false;
312
+ return shape.test(rawSurface(seg));
313
+ }
314
+ /**
315
+ * `gh api … delete … /branches/<protected>/protection` removes the gate the
316
+ * workspace relies on, so it asks. The branch set is the same one `git push`
317
+ * uses; the match is a plain lowercased substring so a branch name carrying
318
+ * regex characters cannot change the result.
319
+ *
320
+ * The shape gate reads `rawSurface` (quotes are data), but the branch LOCATOR is
321
+ * a target lookup, not a shape match: it must read the RAW segment text. People
322
+ * quote the path precisely because it is built (`{}`, `$VAR`, a URL), and on the
323
+ * stripped surface `gh api -X DELETE "<path>"` collapses to `gh api -X DELETE`,
324
+ * so the locator would find no branch and allow the deletion.
325
+ */
326
+ function deletesProtectedBranchProtection(seg, branches) {
327
+ if (!namesGhStatement(seg, RAW_GH_API_DELETE))
328
+ return false;
329
+ const lower = seg.raw.toLowerCase();
330
+ return branches.some((b) => {
331
+ const name = b.trim().toLowerCase();
332
+ return name !== '' && lower.includes(`/branches/${name}/protection`);
333
+ });
334
+ }
335
+ /**
336
+ * True when the segment is a `git push`. The resolved reading is the parser's
337
+ * subcommand; a segment the parser could not resolve still names `push` in its
338
+ * `argv`/`refspecs` (`git $GITS push origin master` — an expansion between the
339
+ * verb and the subcommand), and that shape is routed to the same push
340
+ * classifier rather than allowed.
341
+ */
342
+ function isPushSegment(seg) {
343
+ if (seg.subcommand === 'push')
344
+ return true;
345
+ return seg.ambiguous && (seg.argv.includes('push') || seg.refspecs.includes('push'));
346
+ }
347
+ /**
348
+ * A package-manager publish. The publish verb is looked up among the segment's
349
+ * non-flag words instead of `subcommand`, because an untabled value-taking short
350
+ * option occupies that slot (`npm -w <name> publish` reads `subcommand '<name>'`).
351
+ * Two shapes are excluded so the word `publish` alone is not enough:
352
+ *
353
+ * - a `publish` word sitting BEFORE the resolved subcommand is the value of a
354
+ * value-taking option (`pnpm --filter publish test`), never the verb;
355
+ * - a SCRIPT RUNNER occupying the resolved subcommand slot (`npm run publish`,
356
+ * `npm exec publish`, `yarn dlx publish`) makes every later `publish` word the
357
+ * name of a script or a package. The test is positional, never a scan of the
358
+ * words before `publish`: a value-taking option's VALUE can read `run`
359
+ * (`pnpm --filter run publish` filters the package named `run` and then really
360
+ * publishes), and the parser has already consumed that value, so the slot
361
+ * holds `publish` and the publish must fire. A scan of the raw argv read the
362
+ * option value as a runner and allowed a real publish — the B3/B4 finding this
363
+ * positional reading closes.
364
+ */
365
+ function classifyPublish(seg, command) {
366
+ const verb = baseName(seg.verb);
367
+ if (verb === undefined || !PACKAGE_MANAGERS.has(verb))
368
+ return undefined;
369
+ const argv = seg.argv;
370
+ const subIndex = seg.subcommand === undefined ? -1 : argv.indexOf(seg.subcommand, 1);
371
+ // Only a runner in the subcommand SLOT makes `publish` a script/package name.
372
+ // Reading the slot (not the words before `publish`) is what keeps a flag
373
+ // between the two (`npm run --silent publish`) suppressed as well.
374
+ const runnerIsSubcommand = subIndex >= 0 && SCRIPT_RUNNER_VERBS.has(argv[subIndex]);
375
+ const isPublishVerb = argv.some((word, i) => {
376
+ if (i < 1 || word !== 'publish')
377
+ return false;
378
+ if (subIndex >= 0 && i < subIndex)
379
+ return false;
380
+ return !runnerIsSubcommand;
381
+ });
382
+ if (!isPublishVerb)
383
+ return undefined;
384
+ const dryRun = seg.flags.some((f) => f === '--dry-run' || f === '--dryRun' || f.startsWith('--dry-run=') || f.startsWith('--dryRun='));
385
+ return { ruleId: 'pkg.publish', tier: dryRun ? 'journal' : 'ask', target: command };
386
+ }
387
+ /** True when the token names the local `curl`/`wget` binary (a URL is not a fetcher). */
388
+ function isNetworkFetcher(token) {
389
+ if (token.includes('://'))
390
+ return false;
391
+ const base = baseName(token);
392
+ return base === 'curl' || base === 'wget';
393
+ }
394
+ /**
395
+ * `curl … | bash` / `wget … | sh` (the pipe token stays on the fetcher's own
396
+ * segment) and `source <(curl …)` / `bash <(curl …)` (the process substitution
397
+ * is one segment, so its `<` and `(curl` tokens are both visible).
398
+ */
399
+ function isRemoteExecPair(segs, i) {
400
+ const seg = segs[i];
401
+ if (seg.argv.includes('|') && seg.argv.some(isNetworkFetcher)) {
402
+ const next = segs[i + 1];
403
+ if (next !== undefined && shellName(next.verb) !== undefined)
404
+ return true;
405
+ }
406
+ const consumer = baseName(seg.verb);
407
+ const shellConsumer = shellName(seg.verb) !== undefined || (consumer !== undefined && SOURCE_VERBS.has(consumer));
408
+ return (shellConsumer &&
409
+ seg.argv.includes('<') &&
410
+ seg.argv.some((t) => t.startsWith('(curl') || t.startsWith('(wget')));
411
+ }
412
+ /**
413
+ * The verdict for a segment the parser could not resolve: `ask` for the rule its
414
+ * `rawSurface` names, `undefined` when it names none. This is the §5.3
415
+ * escalation, scoped so that an unresolved wrapper around a harmless command
416
+ * stays quiet.
417
+ */
418
+ function ambiguousVerdict(seg, command) {
419
+ const raw = rawSurface(seg);
420
+ if (RAW_GH_PR_MERGE.test(raw))
421
+ return { ruleId: 'git.merge.protected', tier: 'ask', target: command };
422
+ if (RAW_PUBLISH.test(raw))
423
+ return { ruleId: 'pkg.publish', tier: 'ask', target: command };
424
+ if (RAW_GIT_PUSH.test(raw)) {
425
+ if (RAW_RELEASE_TAG.test(raw))
426
+ return { ruleId: 'git.tag.release', tier: 'ask', target: command };
427
+ if (RAW_FORCE_PUSH.test(raw))
428
+ return { ruleId: 'git.push.force', tier: 'ask', target: command };
429
+ return { ruleId: 'git.push.protected', tier: 'ask', target: command };
430
+ }
431
+ if (RAW_REMOTE_EXEC.test(raw))
432
+ return { ruleId: 'net.exec.remote', tier: 'ask', target: command };
433
+ return undefined;
434
+ }
435
+ const ALLOW = (target) => ({ ruleId: '', tier: 'allow', target });
436
+ /**
437
+ * Every spelling of the guard's own paths: the absolute forms from config plus
438
+ * their `~`/`$HOME`/`${HOME}` forms (`pathSpellings`). A command can reach a
439
+ * guarded file through any of them, and the previous absolute-only test missed
440
+ * exactly that.
441
+ */
442
+ function guardPathMatchers(guardPaths) {
443
+ const out = new Set();
444
+ for (const p of guardPaths) {
445
+ if (typeof p !== 'string' || p === '')
446
+ continue;
447
+ for (const s of pathSpellings(p))
448
+ out.add(s);
449
+ }
450
+ return [...out];
451
+ }
452
+ /**
453
+ * True when this parsed segment EDITS one of the guard's own paths.
454
+ *
455
+ * The deny tier is scoped to edits, not mentions: a raw-text match refused every
456
+ * read (`tail -n 5 <journal>`, `cat <profile package.json>`) even though the
457
+ * guard's own deny text tells the agent to "see the guard journal".
458
+ *
459
+ * An edit is a mutation the segment can PROVE, in any of four shapes:
460
+ *
461
+ * - the segment's own verb is a mutating verb ({@link MUTATION_VERBS}) or an
462
+ * in-place editor ({@link IN_PLACE_EDITORS} with {@link IN_PLACE_FLAG});
463
+ * - a mutation sits in a DESCENDANT command the segment hands to something else
464
+ * (`nice rm -f <journal>`, `timeout 5 rm -f <journal>`, `flock L rm …`,
465
+ * `ssh host rm …`, `xargs rm …`, `eval rm …`, `find … -exec rm … +`), which the
466
+ * pre-fix build denied as a bare mention and the first narrowing then missed —
467
+ * an allow on a wipe of the guard's own journal;
468
+ * - a mutation sits in a `-c` script handed to a shell, one level deeper when a
469
+ * `find` action flag is what hands it over (`find … -exec bash -c "rm …" +`);
470
+ * - a redirection ({@link WRITE_REDIRECT}) whose TARGET is a guard path.
471
+ *
472
+ * Every surface is `argv`, where quotes are already gone and their content kept,
473
+ * so a quoted path cannot hide a mutation — and where a quoted MENTION
474
+ * (`git commit -m "rm -f <journal>"`) stays a single data token, so it cannot
475
+ * fake one. A mutation WORD is therefore only read at a position that IS a
476
+ * command: the whole argv for the parser's own "runs a trailing command" class
477
+ * ({@link EXEC_WRAPPERS} ∪ {@link OPAQUE_VERBS}), and the tokens after a `find`
478
+ * action flag for a mention-led segment. Every other segment — `less -p rm
479
+ * <journal>`, `ag rm <journal>`, `docker rm <journal>` — is judged on its own
480
+ * verb only, so a mutation word in its arguments stays the data it is.
481
+ *
482
+ * Two recorded trade-offs. An interpreter inline program
483
+ * (`python -c "open(p,'w')"`) is NOT a mutation here: the guard does not interpret
484
+ * the program's language, and the shape is lexically indistinguishable from the
485
+ * `node -e "… mention …"` allow case. And an UNKNOWN runner around a mutating verb
486
+ * (`my-custom-runner rm -f <journal>`) is not read either, because nothing
487
+ * distinguishes it from a tool whose argument merely spells `rm` (`ag rm <journal>`).
488
+ * The deny tier therefore covers the mutation shapes the parser can prove; see the
489
+ * module's `rawSurface` note for the same choice on shape rules.
490
+ */
491
+ function mutatesGuardPath(seg, names, pipedFromGuardPath, depth = 0) {
492
+ if (writesSurface(seg.argv, names))
493
+ return true;
494
+ if (depth < 2) {
495
+ for (const script of scriptSegments(seg)) {
496
+ if (mutatesGuardPath(script, names, pipedFromGuardPath, depth + 1))
497
+ return true;
498
+ }
499
+ }
500
+ // An OPAQUE verb runs whatever its arguments say, and xargs takes its target
501
+ // from the segment PIPED into it (`echo <journal> | xargs rm -f`), where the
502
+ // path is named and the mutation verb is not. Only a real pipe carries it: an
503
+ // `&&`/`;`/`||` sibling does not, and `eval`/`exec` never read stdin as argv.
504
+ const verb = baseName(seg.verb);
505
+ return (!seg.argv.some(names) &&
506
+ pipedFromGuardPath &&
507
+ verb !== undefined &&
508
+ OPAQUE_VERBS.has(verb) &&
509
+ !ignoresPipedInput(seg.argv, verb) &&
510
+ seg.argv.some((_, i) => isMutationWord(seg.argv, i, names)));
511
+ }
512
+ /** True when ONE token list proves an edit of a path {@link names} matches. */
513
+ function writesSurface(argv, names) {
514
+ if (!argv.some(names))
515
+ return false;
516
+ const verb = baseName(argv[0] ?? '');
517
+ if (verb !== undefined && writesOwnTarget(verb, argv, names))
518
+ return true;
519
+ for (const start of descendantStarts(argv, verb)) {
520
+ if (argv.slice(start).some((_, k) => isMutationWord(argv, start + k, names)))
521
+ return true;
522
+ }
523
+ return argv.some((word, i) => WRITE_REDIRECT.test(word) && i + 1 < argv.length && names(argv[i + 1]));
524
+ }
525
+ /**
526
+ * True when the verb leading `argv` writes a path {@link names} matches.
527
+ *
528
+ * A mutating verb always does; an in-place editor does when its flag is present;
529
+ * a {@link SHAPE_WRITERS} member only in the form that writes (`curl -o <path>`,
530
+ * `wget -O <path>`, a `rsync`/`scp` DESTINATION, an editor without its read-only
531
+ * switch).
532
+ */
533
+ function writesOwnTarget(verb, argv, names) {
534
+ if (MUTATION_VERBS.has(verb))
535
+ return true;
536
+ if (IN_PLACE_EDITORS.has(verb) && argv.some((f) => IN_PLACE_FLAG.test(f)))
537
+ return true;
538
+ return writesByShape(verb, argv, names);
539
+ }
540
+ /** True when `argv[i]` starts a writer whose target in this command is a guard path. */
541
+ function isMutationWord(argv, i, names) {
542
+ const base = baseName(argv[i] ?? '');
543
+ if (base === undefined)
544
+ return false;
545
+ return writesOwnTarget(base, argv.slice(i), names);
546
+ }
547
+ /**
548
+ * The write shape of a {@link SHAPE_WRITERS} verb, read from the command it leads
549
+ * (`tail[0]` is the verb itself). Reads are decided here rather than by the verb
550
+ * alone: `curl -I`, `wget -O -`, `rsync --list-only <path> <dir>`, `scp host:<path>
551
+ > /tmp/`, `vi -R` and `nano -v` all name a guard path without writing it.
552
+ */
553
+ function writesByShape(verb, tail, names) {
554
+ // A `find … -exec CMD … +` tail carries the action terminator, not an operand.
555
+ let end = tail.length;
556
+ while (end > 1 && (tail[end - 1] === '+' || tail[end - 1] === ';'))
557
+ end--;
558
+ const words = tail.slice(1, end);
559
+ switch (verb) {
560
+ case 'curl':
561
+ return outputFlagTargets(words, ['-o', '--output'], names);
562
+ case 'wget':
563
+ return outputFlagTargets(words, ['-O', '--output-document'], names);
564
+ case 'rsync':
565
+ case 'scp': {
566
+ // The destination is every operand but the FIRST: a guard path in source
567
+ // position is being read out (`rsync --list-only <journal> /tmp/`), while
568
+ // one anywhere after it is where the transfer lands. `--exclude <path>` is
569
+ // covered by the same rule because it would be the first operand.
570
+ const operands = words.filter((w) => !w.startsWith('-'));
571
+ return operands.slice(1).some(names);
572
+ }
573
+ case 'vi':
574
+ case 'vim':
575
+ case 'nano': {
576
+ const readOnly = READ_ONLY_FLAGS[verb] ?? new Set();
577
+ if (words.some((w) => readOnly.has(w)))
578
+ return false;
579
+ return words.some((w) => !w.startsWith('-') && names(w));
580
+ }
581
+ default:
582
+ return false;
583
+ }
584
+ }
585
+ /** True when an output flag's value is a guard path (`-o <path>`, `-o<path>`, `--output=<path>`). */
586
+ function outputFlagTargets(words, flags, names) {
587
+ for (let i = 0; i < words.length; i++) {
588
+ const flag = words[i] ?? '';
589
+ const long = flags.find((f) => f.startsWith('--') && flag.startsWith(`${f}=`));
590
+ if (long !== undefined) {
591
+ if (names(flag.slice(long.length + 1)))
592
+ return true;
593
+ continue;
594
+ }
595
+ if (!flags.includes(flag)) {
596
+ const short = flags.find((f) => !f.startsWith('--') && flag.startsWith(f) && flag.length > f.length);
597
+ if (short !== undefined && names(flag.slice(short.length)))
598
+ return true;
599
+ continue;
600
+ }
601
+ const next = words[i + 1];
602
+ if (next !== undefined && names(next))
603
+ return true;
604
+ }
605
+ return false;
606
+ }
607
+ /**
608
+ * The argv index a DESCENDANT command can start at, over exactly the verbs whose
609
+ * grammar is "run what follows me": the exec wrappers the parser deliberately does
610
+ * not unwrap (`nice`, `timeout`, `flock`, `ssh`, `watch`, …) and the opaque ones
611
+ * (`xargs`, `eval`, `exec`). A plain verb — including a mention verb, a real tool
612
+ * the guard does not know (`ag`, `docker`, `my-custom-runner`) — hands nothing over
613
+ * through its own argv, so it gets no range here; a mention verb still hands one
614
+ * over through a `find` action flag.
615
+ */
616
+ function descendantStarts(argv, verb) {
617
+ const out = [];
618
+ if (verb !== undefined && (EXEC_WRAPPERS.has(verb) || OPAQUE_VERBS.has(verb)))
619
+ out.push(0);
620
+ if (verb !== undefined && MENTION_VERBS.has(verb)) {
621
+ for (let i = 0; i < argv.length; i++) {
622
+ if (FIND_ACTION_FLAGS.has(argv[i]))
623
+ out.push(i + 1);
624
+ }
625
+ }
626
+ return out;
627
+ }
628
+ /**
629
+ * True when the piped input never reaches the command `argv[0]` runs, so the path
630
+ * named upstream cannot be that command's target.
631
+ *
632
+ * `xargs -I{}` (and `-i`/`--replace`) substitutes the input line only where the
633
+ * placeholder appears: `echo <journal> | xargs -I{} rm -rf /tmp/junk` removes
634
+ * `/tmp/junk` and never names the journal, so denying it would be a false deny on
635
+ * an unappealable tier. `eval` and `exec` do not turn stdin into argv at all, so
636
+ * for them the borrowed target is never real either.
637
+ *
638
+ * The test is deliberately the weaker "the placeholder appears ANYWHERE in the
639
+ * command", not "the placeholder is the target": `xargs -I{} rm -rf /tmp/{}` denies,
640
+ * because the path the substitution builds is not the path the pipeline named and
641
+ * the guard does not track operand positions. Weaker here means fail-closed, which
642
+ * is the direction this tier must err in.
643
+ */
644
+ function ignoresPipedInput(argv, verb) {
645
+ if (verb !== 'xargs')
646
+ return true;
647
+ for (let i = 0; i < argv.length; i++) {
648
+ const flag = argv[i] ?? '';
649
+ let placeholder;
650
+ if (flag === '-i' || flag === '--replace')
651
+ placeholder = '{}';
652
+ else if (flag.startsWith('-I'))
653
+ placeholder = flag.length > 2 ? flag.slice(2) : (argv[i + 1] ?? '');
654
+ else if (flag.startsWith('--replace='))
655
+ placeholder = flag.slice('--replace='.length);
656
+ if (placeholder === undefined)
657
+ continue;
658
+ if (placeholder === '')
659
+ return true;
660
+ return !argv.some((word, k) => k !== i && word.includes(placeholder));
661
+ }
662
+ return false;
663
+ }
664
+ /**
665
+ * The parsed segments of every `-c` script this segment hands to a shell: the
666
+ * script token is a command LINE, not an argument, and the tokenizer keeps it as
667
+ * one word. Only a shell (or a wrapper that runs one) can be handed a script, so
668
+ * `gcc -c foo.c` and `tar -c -f x` are not command surfaces.
669
+ */
670
+ function scriptSegments(seg) {
671
+ const out = [];
672
+ for (let i = 1; i < seg.argv.length - 1; i++) {
673
+ if (!SHELL_COMMAND_FLAG.test(seg.argv[i]))
674
+ continue;
675
+ const runner = baseName(seg.argv[i - 1] ?? '');
676
+ if (runner === undefined || (!SHELL_VERBS.has(runner) && !EXEC_WRAPPERS.has(runner)))
677
+ continue;
678
+ out.push(...parseCommand(seg.argv[i + 1]));
679
+ }
680
+ return out;
681
+ }
682
+ /**
683
+ * The `secret.access` decision for ONE parsed segment. Two tables decide it, and
684
+ * both read the segment's own verb:
685
+ *
686
+ * - a MENTION verb (`grep`, `ls`, `printf`, `find`, …) only scans or prints its
687
+ * arguments, so a protected path in its argv is a mention, never an access;
688
+ * - otherwise the segment's argv must hold BOTH an access verb and a protected
689
+ * path.
690
+ *
691
+ * The surface is `seg.argv`, never `stripQuoted(command)`. That text-based
692
+ * surface was the 0.2.3 fail-open: it erased a QUOTED protected path before the
693
+ * rule looked, so `cat <path>` asked while `cat "<path>"`, `cp "<path>" /tmp/x`,
694
+ * `curl -T "<path>" …` and `cp /tmp/x "<path>"` were all allowed. The tokenizer
695
+ * already removed the quotes and kept their content, so quoting cannot hide an
696
+ * access from argv.
697
+ *
698
+ * A segment the parser could not resolve (`seg.ambiguous`: an interpreter inline
699
+ * program, an unknown wrapper, an expansion) cannot be proven to be a mention,
700
+ * so a protected path in its argv is an access on its own. That is the intended
701
+ * fail-closed trade-off — `python3 -c "… '<path>' …"` asks again.
702
+ *
703
+ * `seg.heredoc` is never read: a heredoc body is data, not argv, so a body that
704
+ * merely names a protected path stays quiet.
705
+ *
706
+ * The access VERB is read from the segment's command, never from the joined
707
+ * argv: a commit message or a PR body that merely writes the words "do not cat
708
+ * <path>" is text ABOUT the path, and testing the whole surface made it ask.
709
+ * The path detection stays over the argv, so quoting cannot hide a real access.
710
+ */
711
+ function isAccess(seg, protectedPaths) {
712
+ const verb = baseName(seg.verb);
713
+ if (verb !== undefined && MENTION_VERBS.has(verb))
714
+ return false;
715
+ const argvSurface = seg.argv.join(' ');
716
+ if (!isBlockedPath(argvSurface, protectedPaths))
717
+ return false;
718
+ return seg.ambiguous || (verb !== undefined && ACCESS_VERBS.test(verb));
719
+ }
720
+ /**
721
+ * Classify one tool call into a rule id + default tier.
722
+ *
723
+ * Precision rule: only a real ACCESS is gated. A shell command is judged on its
724
+ * parsed segments' argv (a mention-only verb is never an access, and a heredoc
725
+ * body is data); a non-shell tool is judged on the path it targets, never on its
726
+ * content — a document that *discusses* a protected path, or a write that happens
727
+ * to contain secret-looking text, is not an access.
728
+ *
729
+ * `guard.tamper` is the deliberate exception on one count: it is the only deny
730
+ * rule and the spec treats deny as unappealable self-protection. It therefore
731
+ * judges the segment that EDITS a guard path, not only the resolved rule shapes
732
+ * — but it is still scoped to an edit (a mutating verb or a write redirection
733
+ * targeting a guard path), never to a bare mention. A read of the journal must
734
+ * fall through, because the guard's own deny text says "see the guard journal".
735
+ */
736
+ export function classify(ctx) {
737
+ const { tool, args, cwd, settings } = ctx;
738
+ const command = extractCommandText(args);
739
+ const path = extractPathField(args);
740
+ const target = command ?? path ?? tool;
741
+ const guardSpellings = guardPathMatchers(settings.guardPaths);
742
+ const touchesGuardConfig = (text) => guardSpellings.some((p) => text.includes(p));
743
+ // Parsed once and shared: the tamper check and the rule loop judge the same
744
+ // segments, wrappers already removed.
745
+ const segs = command !== undefined ? unwrapSegments(parseCommand(command)) : [];
746
+ // An OPAQUE verb's target may arrive from the segment PIPED into it
747
+ // (`echo <journal> | xargs rm -f`), so the tamper check needs to know whether a
748
+ // guard path was named upstream AND carried here. The parser keeps the operator
749
+ // as the previous segment's last token, so `&&`/`;`/`||` cannot borrow a path.
750
+ const namesGuardPath = (text) => guardSpellings.some((p) => text.includes(p));
751
+ const pipedFromGuardPath = (i) => {
752
+ // Walk LEFT while the chain is still one pipeline: the operator carrying a
753
+ // segment's stdout is kept as its last argv token, so the first segment in that
754
+ // chain to name a guard path proves the path reaches this one — however many
755
+ // pass-through commands (`tee`, `grep`, `sort`) sit between them.
756
+ for (let k = i - 1; k >= 0; k--) {
757
+ const prev = segs[k];
758
+ if (prev === undefined || prev.argv[prev.argv.length - 1] !== '|')
759
+ return false;
760
+ if (prev.argv.some(namesGuardPath))
761
+ return true;
762
+ }
763
+ return false;
764
+ };
765
+ // guard.tamper — highest priority, never approvable, scoped to EDITS (above).
766
+ if (WRITE_FILE_TOOLS.has(tool) && path && touchesGuardConfig(path)) {
767
+ return { ruleId: 'guard.tamper', tier: 'deny', target, detail: { reason: 'guard configuration write' } };
768
+ }
769
+ if (segs.some((seg, i) => mutatesGuardPath(seg, namesGuardPath, pipedFromGuardPath(i)))) {
770
+ return { ruleId: 'guard.tamper', tier: 'deny', target, detail: { reason: 'guard configuration access' } };
771
+ }
772
+ if (FILE_TOOLS.has(tool)) {
773
+ if (path && isBlockedPath(path, settings.protectedPaths)) {
774
+ return { ruleId: 'secret.access', tier: 'ask', target: path };
775
+ }
776
+ if (WRITE_FILE_TOOLS.has(tool) && path && cwd && settings.workingDirContainment?.enabled !== false
777
+ && isOutsideCwd(path, cwd) && !isExemptWritePath(path, cwd, settings.workingDirContainment)) {
778
+ return { ruleId: 'fs.write.outside', tier: 'ask', target: path };
779
+ }
780
+ // Tool content is never scanned — an analysis/write call is not an access.
781
+ return ALLOW(target);
782
+ }
783
+ if (command) {
784
+ // Protected operations are resolved from parsed segments, never from a
785
+ // regex over the raw text: the parser sees past value-taking global options
786
+ // (`git -C <dir> push …`, `npm -w <name> publish`) and wrappers
787
+ // (`bash -c …`), which is where the raw matchers lost them.
788
+ // secret.access is checked over every segment BEFORE the rule loop, so an
789
+ // access verdict keeps outranking an ordinary rule match on the same
790
+ // command (its historical precedence).
791
+ for (const seg of segs) {
792
+ if (isAccess(seg, settings.protectedPaths)) {
793
+ return { ruleId: 'secret.access', tier: 'ask', target: command };
794
+ }
795
+ }
796
+ for (let i = 0; i < segs.length; i++) {
797
+ const seg = segs[i];
798
+ // Ambiguity escalates first: a segment the parser could not resolve is
799
+ // asked about whenever its own raw text names a verb the rules resolve.
800
+ if (seg.ambiguous) {
801
+ const escalated = ambiguousVerdict(seg, command);
802
+ if (escalated)
803
+ return escalated;
804
+ }
805
+ if (isRemoteExecPair(segs, i)) {
806
+ return { ruleId: 'net.exec.remote', tier: 'ask', target: command };
807
+ }
808
+ if (isGhPrMerge(seg)) {
809
+ return { ruleId: 'git.merge.protected', tier: 'journal', target: command };
810
+ }
811
+ if (namesGhStatement(seg, RAW_GH_RELEASE)) {
812
+ return { ruleId: 'gh.release.create', tier: 'ask', target: command };
813
+ }
814
+ if (deletesProtectedBranchProtection(seg, settings.protectedBranches)) {
815
+ return { ruleId: 'gh.protection.delete', tier: 'ask', target: command };
816
+ }
817
+ if (baseName(seg.verb) === 'git' && isPushSegment(seg)) {
818
+ const push = classifyPush(seg, command, ctx, cwd);
819
+ if (push)
820
+ return push;
821
+ // An ambiguous segment cannot be proven to push a safe refspec, so it
822
+ // is answered like an unprovable branch: ask, never allow.
823
+ if (seg.ambiguous)
824
+ return { ruleId: 'git.push.protected', tier: 'ask', target: command };
825
+ }
826
+ const publish = classifyPublish(seg, command);
827
+ if (publish)
828
+ return publish;
829
+ }
830
+ }
831
+ return ALLOW(target);
832
+ }