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