rungate 0.2.0 → 0.3.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 (282) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/canary.ts +117 -0
  11. package/lib/check-registry.ts +226 -0
  12. package/lib/ci-checkout.ts +400 -0
  13. package/lib/cli-commands.ts +137 -0
  14. package/lib/compliance-backfill.ts +220 -0
  15. package/lib/compliance-report.ts +504 -0
  16. package/lib/compliance.ts +361 -0
  17. package/lib/config-loader.ts +255 -0
  18. package/lib/conformity.ts +1818 -131
  19. package/lib/container-provenance.ts +230 -0
  20. package/lib/create-brief.ts +150 -0
  21. package/lib/create-sc.ts +272 -0
  22. package/lib/deep-merge.ts +69 -0
  23. package/lib/dev-liveness.ts +214 -0
  24. package/lib/directive-extractor.ts +210 -0
  25. package/lib/distribution-standing.ts +113 -0
  26. package/lib/doc-hygiene.ts +238 -0
  27. package/lib/eval-criteria.ts +6 -0
  28. package/lib/evidence-portability.ts +123 -0
  29. package/lib/evidence-prevalidator.ts +390 -0
  30. package/lib/evidence-required.ts +150 -0
  31. package/lib/evidence-satisfiability.ts +288 -0
  32. package/lib/frontmatter.ts +163 -0
  33. package/lib/gap-scanner.ts +348 -0
  34. package/lib/gate-enforcement.ts +366 -0
  35. package/lib/generators/agent-briefs.ts +136 -0
  36. package/lib/generators/agents-md.ts +506 -0
  37. package/lib/generators/code-map.ts +60 -0
  38. package/lib/generators/types.ts +184 -0
  39. package/lib/git-ref-normalizer.ts +107 -0
  40. package/lib/github.ts +539 -0
  41. package/lib/harness-identity.ts +63 -0
  42. package/lib/hill-climb.ts +164 -0
  43. package/lib/instruction-effectiveness.ts +131 -0
  44. package/lib/issue-closure-audit.ts +225 -0
  45. package/lib/issue-create-override.ts +343 -0
  46. package/lib/js-top-level-code.ts +250 -0
  47. package/lib/liveness-contradiction.ts +149 -0
  48. package/lib/organize.ts +505 -0
  49. package/lib/paths.ts +197 -6
  50. package/lib/post-fix-verify.ts +157 -0
  51. package/lib/prior-branch.ts +489 -0
  52. package/lib/project-state-shape.ts +166 -0
  53. package/lib/promote-outputs.ts +156 -0
  54. package/lib/prove-label-gate.ts +35 -0
  55. package/lib/reachability.ts +302 -0
  56. package/lib/release-preflight.ts +186 -0
  57. package/lib/rule-health-pipeline.ts +264 -0
  58. package/lib/rule-health-trend.ts +161 -0
  59. package/lib/rule-provenance.ts +149 -0
  60. package/lib/rule-registry.ts +128 -0
  61. package/lib/rungate-schema.ts +114 -4
  62. package/lib/sc-claim-forms.ts +179 -0
  63. package/lib/sc-cover.ts +150 -0
  64. package/lib/sc-guard.ts +157 -0
  65. package/lib/sc-ids.ts +344 -0
  66. package/lib/scaffold/defaults.ts +165 -0
  67. package/lib/scaffold/managed-workflow.ts +370 -0
  68. package/lib/scaffold/owned-files.ts +265 -0
  69. package/lib/scaffold/steps.ts +2680 -0
  70. package/lib/scanner.ts +701 -0
  71. package/lib/screenshot-upload.ts +73 -0
  72. package/lib/secret-patterns.ts +112 -0
  73. package/lib/security-verdict.ts +616 -0
  74. package/lib/signal-phrases.ts +1 -0
  75. package/lib/spec-change-conformity.ts +80 -0
  76. package/lib/spec-files.ts +62 -0
  77. package/lib/spec-registry.ts +133 -0
  78. package/lib/spec-updater.ts +96 -0
  79. package/lib/stale-cleanup.ts +224 -0
  80. package/lib/stale-issue-scanner.ts +36 -0
  81. package/lib/strip-js-comments.ts +269 -0
  82. package/lib/suite-measurement.ts +228 -0
  83. package/lib/task-completion-checks.ts +177 -0
  84. package/lib/test-suite-lock.ts +1136 -0
  85. package/lib/transcript-checker.ts +1140 -0
  86. package/lib/validators/spec-validators.ts +171 -0
  87. package/lib/verdict-capture.ts +73 -0
  88. package/lib/verified-push.ts +358 -0
  89. package/lib/workflow-security.ts +174 -0
  90. package/lib/worktree-cleanup.ts +250 -0
  91. package/lib/worktree-collect.ts +283 -0
  92. package/lib/worktree-isolation.ts +82 -0
  93. package/package.json +36 -3
  94. package/prompts/ac-adversary.md +14 -2
  95. package/prompts/aditi.md +5 -0
  96. package/prompts/blast-radius.md +5 -0
  97. package/prompts/container-verify.md +5 -0
  98. package/prompts/discovery.md +4 -0
  99. package/prompts/environment.md +5 -0
  100. package/prompts/evidence-hierarchy.md +5 -0
  101. package/prompts/evidence-validator.md +11 -0
  102. package/prompts/marcus.md +5 -0
  103. package/prompts/prevention.md +5 -0
  104. package/prompts/prove-reproducer.md +12 -0
  105. package/prompts/quinn-decision-tree.md +5 -0
  106. package/prompts/quinn-ui-brief.md +5 -0
  107. package/prompts/quinn.md +5 -0
  108. package/prompts/rca.md +5 -0
  109. package/prompts/read-before-write.md +4 -0
  110. package/prompts/regression.md +5 -0
  111. package/prompts/serena.md +5 -0
  112. package/scripts/audit-specs.ts +464 -0
  113. package/scripts/convert-spec.ts +293 -0
  114. package/scripts/create-sc.ts +92 -0
  115. package/scripts/create-spec.ts +166 -0
  116. package/scripts/extract-constraints.ts +4 -3
  117. package/scripts/generate-code-map.ts +1 -1
  118. package/scripts/scaffold-project.ts +138 -1426
  119. package/scripts/sync-spec-tests.ts +211 -126
  120. package/.claude/agents/aditi.md +0 -47
  121. package/.claude/agents/marcus.md +0 -50
  122. package/.claude/agents/quinn.md +0 -58
  123. package/.claude/agents/rook.md +0 -47
  124. package/.claude/agents/serena.md +0 -46
  125. package/.claude/rungate.json +0 -11
  126. package/.fallowrc.json +0 -28
  127. package/.github/copilot-instructions.md +0 -20
  128. package/.rungate/conformity-findings.json +0 -648
  129. package/AGENTS.md +0 -106
  130. package/CODE-MAP.md +0 -50
  131. package/HARNESS.md +0 -88
  132. package/bun.lock +0 -26
  133. package/bunfig.toml +0 -2
  134. package/config/brief-policies.json +0 -28
  135. package/config/ceremony-profiles.json +0 -212
  136. package/config/consumer-cascade-map.json +0 -24
  137. package/config/doc-cascade-map.json +0 -24
  138. package/config/eval.json +0 -84
  139. package/config/profiles/account-plan.yaml +0 -36
  140. package/config/profiles/campaign.yaml +0 -94
  141. package/config/prove-evidence.schema.json +0 -65
  142. package/config/spec-policies.json +0 -36
  143. package/config/workflow-schema.json +0 -281
  144. package/gates/SCHEMA-GUIDE.md +0 -121
  145. package/gates/ac-quality.test.ts +0 -106
  146. package/gates/adversarial.test.ts +0 -274
  147. package/gates/brief-assembler.test.ts +0 -429
  148. package/gates/brief-assembler.ts +0 -334
  149. package/gates/bunfig.toml +0 -2
  150. package/gates/chain.test.ts +0 -91
  151. package/gates/e2e-smoke.test.ts +0 -234
  152. package/gates/error-classifier.test.ts +0 -249
  153. package/gates/error-classifier.ts +0 -89
  154. package/gates/orchestrator.test.ts +0 -950
  155. package/gates/orchestrator.ts +0 -569
  156. package/gates/preload.ts +0 -77
  157. package/gates/prompts/ac-adversary.md +0 -20
  158. package/gates/prompts/evidence-validator.md +0 -22
  159. package/gates/prompts/prove-reproducer.md +0 -53
  160. package/gates/prove.test.ts +0 -164
  161. package/gates/run-gate.ts +0 -936
  162. package/gates/schema-parity.test.ts +0 -197
  163. package/gates/schema.ts +0 -362
  164. package/gates/self-heal.test.ts +0 -511
  165. package/gates/self-heal.ts +0 -121
  166. package/gates/ship-orchestrator.test.ts +0 -379
  167. package/gates/ship-orchestrator.ts +0 -363
  168. package/gates/test-fixtures/broken-no-environments.json +0 -60
  169. package/gates/test-fixtures/valid-standard.json +0 -54
  170. package/gates/test-utils.ts +0 -43
  171. package/gates/witness.ts +0 -220
  172. package/gates/workflow.test.ts +0 -1053
  173. package/hooks/AgentBriefGuard.hook.ts +0 -586
  174. package/hooks/AgentVerdictCapture.hook.ts +0 -134
  175. package/hooks/AutoVerifyGate.hook.ts +0 -76
  176. package/hooks/GateEnforcement.hook.ts +0 -273
  177. package/hooks/IssueCloseGuard.hook.ts +0 -116
  178. package/hooks/MergeGuard.hook.ts +0 -55
  179. package/hooks/StaleTTLCleanup.hook.ts +0 -133
  180. package/hooks/VerifyPhaseLock.hook.ts +0 -81
  181. package/hooks/WorkflowStateGuard.hook.ts +0 -37
  182. package/hooks/lib/agentDetection.ts +0 -70
  183. package/hooks/lib/findWorkflow.ts +0 -101
  184. package/hooks/lib/parseStdin.ts +0 -37
  185. package/hooks/lib/paths.ts +0 -111
  186. package/hooks/lib/utils.ts +0 -81
  187. package/reference/migration-manifest.json +0 -554
  188. package/reference/prompts/agent-aditi.md +0 -38
  189. package/reference/prompts/agent-marcus.md +0 -38
  190. package/reference/prompts/agent-quinn.md +0 -38
  191. package/reference/prompts/agent-rook.md +0 -37
  192. package/reference/prompts/agent-serena.md +0 -37
  193. package/reference/prompts/council-skill.md +0 -170
  194. package/reference/prompts/goal-skill.md +0 -235
  195. package/reference/prompts/prove-skill.md +0 -283
  196. package/reference/prompts/quinn-standard.md +0 -246
  197. package/reference/prompts/ship-convergence.md +0 -65
  198. package/reference/prompts/ship-escalation.md +0 -43
  199. package/reference/prompts/ship-iteration.md +0 -382
  200. package/reference/prompts/ship-pending-patches.md +0 -246
  201. package/reference/prompts/ship-reference.md +0 -250
  202. package/reference/prompts/ship-skill.md +0 -347
  203. package/reference/prompts/ship-templates.md +0 -215
  204. package/reference/scripts/batch-status.sh +0 -68
  205. package/reference/scripts/chain-compat-check.sh +0 -67
  206. package/reference/scripts/context-audit.sh +0 -314
  207. package/reference/scripts/dead-export-check.sh +0 -61
  208. package/reference/scripts/generate-qc-tables.sh +0 -92
  209. package/reference/scripts/harness-init.sh +0 -111
  210. package/reference/scripts/pai-054-baseline-check.sh +0 -40
  211. package/reference/scripts/prove-smoke-test.sh +0 -112
  212. package/reference/scripts/setup-keychain-salt.sh +0 -12
  213. package/reference/scripts/skill-optimizer-friday.sh +0 -88
  214. package/reference/scripts/skill-qc-test.sh +0 -351
  215. package/reference/scripts/skill-synthesize-tonight.sh +0 -66
  216. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +0 -263
  217. package/reference/specs/harness-v3-bash-deletion-plan.md +0 -65
  218. package/reference/specs/harness-v3-migration-plan.md +0 -188
  219. package/scripts/decision-reconcile.sh +0 -74
  220. package/scripts/decision-reconcile.ts +0 -152
  221. package/scripts/git-hooks/pre-commit +0 -76
  222. package/scripts/git-hooks/pre-push +0 -271
  223. package/scripts/harness-skill-check.sh +0 -52
  224. package/scripts/lib/gap-emit.sh +0 -65
  225. package/scripts/lib/jq-update.sh +0 -30
  226. package/scripts/lib/resolve-slug.sh +0 -30
  227. package/scripts/lib/verify-spec-compliance.sh +0 -102
  228. package/scripts/prove-backfill.sh +0 -87
  229. package/scripts/scaffold-rungate-config.ts +0 -91
  230. package/scripts/self-containment-check.sh +0 -109
  231. package/scripts/skill-qc-validator.sh +0 -402
  232. package/scripts/slug-resolver.sh +0 -14
  233. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +0 -2493
  234. package/specs/BOOTSTRAP-TEST-PLAN.md +0 -571
  235. package/specs/HARNESS-GATES.md +0 -256
  236. package/specs/HARNESS-SKILL-CHAIN.md +0 -286
  237. package/specs/HARNESS-SKILL-CONTRACT.md +0 -93
  238. package/specs/HARNESS-STANDARD.md +0 -488
  239. package/specs/SPEC-TEMPLATE.md +0 -53
  240. package/specs/bootstrap-data-flow.png +0 -0
  241. package/specs/harness-automation-matrix.md +0 -314
  242. package/specs/harness-automation-matrix.rules.json +0 -64
  243. package/test/anti.test.ts +0 -80
  244. package/test/contract-negative.test.ts +0 -86
  245. package/test/contract.test.ts +0 -158
  246. package/test/external-deps.test.ts +0 -48
  247. package/test/fixtures/golden-project/.env.example +0 -3
  248. package/test/fixtures/golden-project/Makefile +0 -7
  249. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +0 -23
  250. package/test/fixtures/golden-project/docs/setup-guide.md +0 -10
  251. package/test/fixtures/golden-project/package.json +0 -10
  252. package/test/fixtures/golden-project/specs/api-spec.md +0 -20
  253. package/test/fixtures/golden-project/src/auth.ts +0 -8
  254. package/test/fixtures/golden-project/src/db.ts +0 -11
  255. package/test/fixtures/golden-project/src/index.ts +0 -19
  256. package/test/fixtures/golden-project/src/utils/format.ts +0 -3
  257. package/test/fixtures/golden-project/test/auth.test.ts +0 -15
  258. package/test/fixtures/golden-project/tsconfig.json +0 -12
  259. package/test/meta-sc-coverage.test.ts +0 -159
  260. package/test/phase-0.test.ts +0 -846
  261. package/test/phase-1.test.ts +0 -617
  262. package/test/phase-2.test.ts +0 -620
  263. package/test/phase-3.test.ts +0 -99
  264. package/test/scaffold-conformity.test.ts +0 -8
  265. package/test/schema-canary.test.ts +0 -51
  266. package/test/spec-compliance-auto.test.ts +0 -64
  267. package/test/spec-compliance.test.ts +0 -295
  268. package/test/spec-discovery.test.ts +0 -68
  269. package/test/spec-drift.test.ts +0 -5
  270. package/test/structure.test.ts +0 -165
  271. package/test/unit/agent-brief-guard-ship.test.ts +0 -293
  272. package/test/unit/extract-constraints.test.ts +0 -145
  273. package/test/unit/issue-close-guard.test.ts +0 -204
  274. package/test/unit/scaffold-project.test.ts +0 -417
  275. package/test/unit/skill-cooccurrence.test.ts +0 -177
  276. package/test/unit/skill-sequence-logger.test.ts +0 -244
  277. package/test/unit/workflow-state-guard.test.ts +0 -95
  278. package/workflows/batch-ship.js +0 -295
  279. package/workflows/council.js +0 -481
  280. package/workflows/prove.js +0 -560
  281. package/workflows/ship.js +0 -789
  282. package/workflows/verify.js +0 -236
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Whether a `gh issue create` may run during VERIFY, and why not (#365).
3
+ *
4
+ * `hooks/VerifyPhaseLock.hook.ts` asked the question in eight lines:
5
+ *
6
+ * if (cmd.includes('--label') && cmd.includes('follow-up')) process.exit(0);
7
+ *
8
+ * That is not a test that a label argument equals `follow-up`. It is a test
9
+ * that the string `follow-up` appears SOMEWHERE in the command, so
10
+ *
11
+ * gh issue create --label bug --title "Fix the follow-up handler"
12
+ *
13
+ * bypasses the lock entirely while applying no override label at all. A
14
+ * detector whose input is the whole command string cannot tell an argument
15
+ * from a word in a title — shape two of
16
+ * `.claude/rules/checks-must-be-able-to-fail.md`, pointed outward: the guard
17
+ * is wider than the thing it guards.
18
+ *
19
+ * The same shape hid a second bypass one line down. `cmd.includes('gh issue
20
+ * comment')` is unreachable for a plain comment, because the create check
21
+ * above it has already exited — but it IS reachable for
22
+ * `gh issue comment … && gh issue create …`, where the comment clause
23
+ * exempts the create clause.
24
+ *
25
+ * ## The second defect is about the tracker, not the hook
26
+ *
27
+ * `follow-up` means "follow-up work from a shipped issue", and it was the
28
+ * only override, so anything filed during VERIFY had to claim an origin it
29
+ * did not have. On 2026-10-13 an external audit of two consumer projects
30
+ * surfaced three consumer-blocking defects here; #362, #363 and #364 all
31
+ * wear `follow-up` and not one of them is follow-up work from a shipped
32
+ * issue. An agent filtering that label to find loose ends from recent ships
33
+ * gets three unrelated results. `external-audit` exists for exactly that
34
+ * origin and is accepted here.
35
+ *
36
+ * ## What this is, and what it is not
37
+ *
38
+ * Stated because two rounds of commit security review walked the parser
39
+ * inward and a third would too. **This is workflow discipline over `gh`
40
+ * invocations reaching PreToolUse on Bash. It is not a sandbox.** It exists
41
+ * to catch a reflex — an agent mid-VERIFY reaching for `gh issue create`
42
+ * when `verifyBlockers[]` is the right place — and a reflex is defeated by
43
+ * saying no to the command shapes someone actually types.
44
+ *
45
+ * So the parser is held to ordinary shapes: operators with or without
46
+ * surrounding whitespace, newlines, subshells, command substitution
47
+ * including backticks, a path-qualified binary, quoted arguments, trailing
48
+ * `#` comments, backslash line continuations, and `-c` / `-lc` / `eval`
49
+ * wrappers. **Every one of those was a measured bypass of an earlier version
50
+ * of this file**, and each has a row in `test/verify-phase-lock.test.ts`.
51
+ *
52
+ * Out of scope ON PURPOSE, and not a gap to file:
53
+ *
54
+ * - `curl` against the REST API, or the GitHub MCP tools — neither is Bash,
55
+ * so the hook never sees them.
56
+ * - `ssh host "gh issue create …"` — that runs on another machine against
57
+ * whatever repo it is configured for, and descending into every remote
58
+ * command mentioning `gh` buys false refusals, not safety.
59
+ * - Variable indirection — `GH=gh; $GH issue create`. Resolving it means
60
+ * tracking assignments across clauses, which is the shell interpreter this
61
+ * file is explicitly not, and nobody reaches for `$GH` by reflex.
62
+ * - Here-strings and here-documents — `bash <<< "gh issue create …"`. Same
63
+ * reason: a deliberate construction, not a reflex.
64
+ * - A caller who writes a script and runs it.
65
+ *
66
+ * Each of those takes a decision to get around the lock, and an agent that
67
+ * has made that decision is a problem no matcher fixes. Chasing them trades
68
+ * false refusals — which teach people to work around a guard — for
69
+ * protection against someone already doing so.
70
+ */
71
+
72
+ /** Labels that permit an issue to be filed mid-VERIFY, and what each means. */
73
+ export const OVERRIDE_LABELS: Record<string, string> = {
74
+ "follow-up": "follow-up work from a shipped issue",
75
+ "external-audit": "a defect found outside the ship loop",
76
+ };
77
+
78
+ /**
79
+ * Shell operators that end one command and begin another.
80
+ *
81
+ * Emitted as their OWN tokens, which is the whole point. The first version
82
+ * of this file split on whitespace alone, so `foo;gh issue create` and
83
+ * `gh issue comment 1&&gh issue create` produced the tokens `foo;gh` and
84
+ * `1&&gh` — and since those are not the word `gh`, `createsIssue` said no
85
+ * and the lock allowed both. That is the same defect as the substring
86
+ * matcher this file replaced, one layer in: a parser that disagrees with the
87
+ * shell about where a command begins. Found by the commit security review,
88
+ * not by me.
89
+ *
90
+ * A newline is in the list for the same reason. Without it,
91
+ * `gh issue create --label follow-up` and `gh issue create --label bug` on
92
+ * two lines are one clause, and the first line's override covers the second.
93
+ *
94
+ * Backticks are here for the same reason `(` and `)` are: they delimit a
95
+ * command substitution, and without them `` `gh issue create` `` yields the
96
+ * token `` `gh `` rather than `gh`.
97
+ *
98
+ * Longest first: `&&` must be tried before `&`, `||` before `|`.
99
+ */
100
+ const OPERATORS = ["&&", "||", ";;", ";", "|", "&", "(", ")", "`", "\n"];
101
+
102
+ /**
103
+ * Split a command the way a shell would, so an argument can be told from a
104
+ * word inside a quoted string — and an operator from a word glued to one.
105
+ *
106
+ * Not a full shell parser and does not need to be: the only question is
107
+ * where one command ends and the next begins, and which tokens are its
108
+ * arguments. Unterminated quotes yield the rest of the string as one token,
109
+ * which keeps a malformed command from splitting into things that look like
110
+ * flags nobody wrote.
111
+ */
112
+ export function tokenize(cmd: string): string[] {
113
+ const out: string[] = [];
114
+ let cur = "";
115
+ let quote: '"' | "'" | null = null;
116
+ let started = false;
117
+ const flush = () => {
118
+ if (started) out.push(cur);
119
+ cur = "";
120
+ started = false;
121
+ };
122
+ for (let i = 0; i < cmd.length; i++) {
123
+ const c = cmd[i];
124
+ if (c === "\\" && quote !== "'" && i + 1 < cmd.length) {
125
+ // A backslash-newline is a line continuation: it joins, and adds
126
+ // nothing. Treating it as an escaped character put a literal newline
127
+ // inside the token, so `gh issue \⏎ create` produced `\ncreate` and
128
+ // the lock allowed it — and wrapping a long command across lines is
129
+ // something people do on purpose.
130
+ if (cmd[i + 1] === "\n") {
131
+ i++;
132
+ continue;
133
+ }
134
+ cur += cmd[++i];
135
+ started = true;
136
+ continue;
137
+ }
138
+ // `#` starts a comment only at the start of a word, which is the shell's
139
+ // own rule. Without it, `--label bug # --label follow-up` read the
140
+ // commented-out override as a real one.
141
+ if (!quote && !started && c === "#") {
142
+ while (i < cmd.length && cmd[i] !== "\n") i++;
143
+ i--;
144
+ continue;
145
+ }
146
+ if (quote) {
147
+ if (c === quote) quote = null;
148
+ else cur += c;
149
+ continue;
150
+ }
151
+ if (c === '"' || c === "'") {
152
+ quote = c;
153
+ started = true;
154
+ continue;
155
+ }
156
+ const op = OPERATORS.find(o => cmd.startsWith(o, i));
157
+ if (op) {
158
+ flush();
159
+ out.push(op);
160
+ i += op.length - 1;
161
+ continue;
162
+ }
163
+ if (/\s/.test(c)) {
164
+ flush();
165
+ continue;
166
+ }
167
+ cur += c;
168
+ started = true;
169
+ }
170
+ flush();
171
+ return out;
172
+ }
173
+
174
+ const SEPARATORS = new Set(OPERATORS);
175
+
176
+ /**
177
+ * The command list, one token array per clause, descending into `-c`.
178
+ *
179
+ * The recursion is why `echo 'gh issue create --label bug'` stays allowed
180
+ * while `bash -c 'gh issue create --label bug'` does not. A quoted string is
181
+ * data to `echo` and a command to a shell, and only the second one files an
182
+ * issue. Refusing both would be the safer direction and the wrong one — a
183
+ * guard that refuses commands which create nothing is a guard people learn
184
+ * to work around.
185
+ *
186
+ * **There is deliberately no allowlist of shell names here.** The first
187
+ * version had one — `sh`, `bash`, `zsh`, `dash`, `ksh`, `fish`, with the
188
+ * program name resolved past any `VAR=value` prefix — and removing it
189
+ * scored **0 red of 38**. No command could be written that the allowlist
190
+ * decided: a non-shell interpreter's `-c` argument is source code, and
191
+ * source code quotes the command it runs, so the inner text arrives as one
192
+ * token and `createsIssue` needs three adjacent ones. `python3 -c
193
+ * "print('gh issue create --label bug')"` is a table case and is allowed
194
+ * with or without the allowlist. A branch no input can distinguish is a
195
+ * branch that will be wrong silently, so it is gone rather than kept for
196
+ * reassurance.
197
+ */
198
+ export function clauses(cmd: string, depth = 0): string[][] {
199
+ const flat: string[][] = [[]];
200
+ for (const t of tokenize(cmd)) {
201
+ if (SEPARATORS.has(t)) flat.push([]);
202
+ else flat[flat.length - 1].push(t);
203
+ }
204
+
205
+ const out: string[][] = [];
206
+ for (const c of flat) {
207
+ if (c.length === 0) continue;
208
+ out.push(c);
209
+ if (depth >= 4) continue; // a wrapper chain this deep is not an accident
210
+ for (const inner of commandArguments(c)) out.push(...clauses(inner, depth + 1));
211
+ }
212
+ return out;
213
+ }
214
+
215
+ /** Arguments of this clause that are themselves commands. */
216
+ function commandArguments(tokens: string[]): string[] {
217
+ const out: string[] = [];
218
+ for (let i = 0; i < tokens.length; i++) {
219
+ const t = tokens[i];
220
+ if (COMMAND_FLAG.test(t) || basename(t) === "eval") {
221
+ if (i + 1 < tokens.length) out.push(tokens[i + 1]);
222
+ }
223
+ }
224
+ return out;
225
+ }
226
+
227
+ /** The program a token names, ignoring any path it was reached by. */
228
+ const basename = (t: string) => t.split("/").pop()!;
229
+
230
+ /**
231
+ * Does this clause invoke `gh issue create`?
232
+ *
233
+ * Compared on the basename, because `/usr/bin/gh issue create` and
234
+ * `./gh issue create` are the same command and the first version of this
235
+ * function allowed both.
236
+ */
237
+ export function createsIssue(tokens: string[]): boolean {
238
+ for (let i = 0; i + 2 < tokens.length; i++) {
239
+ if (basename(tokens[i]) === "gh" && tokens[i + 1] === "issue" && tokens[i + 2] === "create") {
240
+ return true;
241
+ }
242
+ }
243
+ return false;
244
+ }
245
+
246
+ /**
247
+ * Flags whose next argument is a command string rather than data.
248
+ *
249
+ * `-c`, but also `-lc` and `-ic`: short flags combine, and only the last
250
+ * letter takes the argument, so `sh -lc "…"` is a login shell running a
251
+ * command. Both of those were allowed until the second security review.
252
+ */
253
+ const COMMAND_FLAG = /^-[A-Za-z]*c$/;
254
+
255
+ /**
256
+ * Flags of `gh issue create` that do NOT consume the following token.
257
+ *
258
+ * Everything else that looks like a flag is assumed to take a value, which
259
+ * is the conservative direction here — see `labelValues`.
260
+ */
261
+ const BOOLEAN_FLAGS = new Set(["-w", "--web", "-h", "--help", "--recover-only"]);
262
+
263
+ /**
264
+ * The values passed to `--label` / `-l`, in both the spaced and `=` forms.
265
+ *
266
+ * `gh` accepts a comma-separated list in one flag, so `--label a,b` is two
267
+ * labels and not one named `a,b`.
268
+ *
269
+ * **A token that is another flag's value is data, not a flag.** Scanning for
270
+ * `--label=` anywhere in the clause reintroduced #365 exactly — the defect
271
+ * this whole file exists to fix — through the back door:
272
+ *
273
+ * gh issue create --label bug --title "--label=follow-up"
274
+ *
275
+ * `gh` gives that title to the issue and applies only `bug`; the old scan
276
+ * read the title as an override and allowed it. Found by the third round of
277
+ * commit security review, and it is the same bypass as the original with one
278
+ * more layer of quoting. The unquoted form is the same command — the shell
279
+ * strips the quotes either way, so the quoting is not what makes it work.
280
+ *
281
+ * So the walk tracks arity the way `gh`'s own flag parser does: a flag
282
+ * consumes the next token unless it is known to be boolean. An unknown flag
283
+ * is assumed to take a value, which can only ever cause a `--label` to be
284
+ * MISSED — and a missed label is a refusal, the direction this guard is
285
+ * allowed to be wrong in.
286
+ */
287
+ export function labelValues(tokens: string[]): string[] {
288
+ const out: string[] = [];
289
+ const add = (v: string) => {
290
+ for (const part of v.split(",")) {
291
+ const t = part.trim();
292
+ if (t) out.push(t);
293
+ }
294
+ };
295
+ for (let i = 0; i < tokens.length; i++) {
296
+ const t = tokens[i];
297
+ if (!t.startsWith("-") || t === "-" || t === "--") continue;
298
+
299
+ const eq = t.indexOf("=");
300
+ if (eq !== -1) {
301
+ const name = t.slice(0, eq);
302
+ if (name === "--label" || name === "-l") add(t.slice(eq + 1));
303
+ continue; // `--flag=value` carries its own value; it consumes nothing
304
+ }
305
+ if (t === "--label" || t === "-l") {
306
+ if (i + 1 < tokens.length) add(tokens[++i]);
307
+ continue;
308
+ }
309
+ // `-lfollow-up` — pflag lets a short flag carry its value attached.
310
+ if (/^-l[^-=]/.test(t)) {
311
+ add(t.slice(2));
312
+ continue;
313
+ }
314
+ if (!BOOLEAN_FLAGS.has(t)) i++; // this flag eats the next token
315
+ }
316
+ return out;
317
+ }
318
+
319
+ /**
320
+ * The single place that decides. `null` means allow.
321
+ *
322
+ * One exported function so there is one binding to mutate. Asked per clause
323
+ * rather than per command: a command that comments on an issue AND creates
324
+ * one is a create, and the old substring form let the first half excuse the
325
+ * second.
326
+ */
327
+ export function verifyPhaseRefusal(cmd: string): string | null {
328
+ const offending = clauses(cmd).filter(createsIssue);
329
+ if (offending.length === 0) return null;
330
+
331
+ const names = Object.keys(OVERRIDE_LABELS);
332
+ const allowed = offending.every(c => labelValues(c).some(l => names.includes(l)));
333
+ if (allowed) return null;
334
+
335
+ return (
336
+ "[VerifyPhaseLock] During VERIFY phase, use verifyBlockers[] in " +
337
+ "workflow-state.json instead of creating new issues. To override, apply a " +
338
+ "label that states where the issue came from: " +
339
+ names.map(n => `--label ${n} (${OVERRIDE_LABELS[n]})`).join(", ") +
340
+ ". The label must be a real --label argument; a matching word in the title " +
341
+ "is not an override."
342
+ );
343
+ }
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Remove string, template, comment and regex-literal CONTENT from JavaScript
3
+ * source, leaving the code that actually executes (#89).
4
+ *
5
+ * This exists because the #69 guard — "ship.js must not call require() at top
6
+ * level, the sandbox has no module loading" — was stripping template literals
7
+ * with a regex:
8
+ *
9
+ * src.replace(/`(?:\\[\s\S]|[^\\`])*`/g, " `` ")
10
+ *
11
+ * ship.js contains backticks that are not template delimiters: inside
12
+ * single-quoted strings, inside comments, inside other templates. A regex has
13
+ * no way to tell which is which, so one stray backtick paired with a later
14
+ * unrelated one and everything between them was deleted — real code included.
15
+ * 61% of the file vanished, and `buildSafeGitAdd` and `validateFilePaths`,
16
+ * the two helpers #69 is actually about, were invisible to the check that
17
+ * protects them. Two functions calling require('path') and require('fs') were
18
+ * added and the suite reported 48 pass, 0 fail.
19
+ *
20
+ * A single-pass tokenizer is not clever, but it is correct for the thing a
21
+ * regex cannot do: it knows what context it is in, so a backtick inside a
22
+ * comment is just a character.
23
+ *
24
+ * TEMPLATE INTERPOLATIONS ARE KEPT. `${...}` evaluates in the enclosing scope,
25
+ * so a require() there is top-level code and must stay visible. That requires
26
+ * tracking brace depth per template, which is the other thing the regex could
27
+ * not express.
28
+ */
29
+
30
+ /** Characters after which a `/` begins a regex literal rather than division. */
31
+ function regexCanFollow(prev: string): boolean {
32
+ // Scanning back over the last significant character is enough in practice:
33
+ // after a value (identifier, number, closing bracket) a slash is division;
34
+ // after an operator, keyword or opening bracket it starts a regex.
35
+ return !/[A-Za-z0-9_$)\]]/.test(prev);
36
+ }
37
+
38
+ export function stripStringsAndComments(src: string): string {
39
+ let out = "";
40
+ let i = 0;
41
+ // Stack of brace depths, one entry per template literal currently open. An
42
+ // entry is pushed on ` and popped on the matching `; while inside an
43
+ // interpolation the depth counts { } so the template's closing backtick is
44
+ // not confused with a backtick in nested code.
45
+ const templates: number[] = [];
46
+ let lastSignificant = "\n";
47
+
48
+ while (i < src.length) {
49
+ const c = src[i];
50
+ const next = src[i + 1];
51
+
52
+ // Inside a template, but NOT inside one of its interpolations.
53
+ if (templates.length > 0 && templates[templates.length - 1] === 0) {
54
+ if (c === "\\") {
55
+ i += 2;
56
+ continue;
57
+ }
58
+ if (c === "`") {
59
+ templates.pop();
60
+ out += "`";
61
+ lastSignificant = "`";
62
+ i++;
63
+ continue;
64
+ }
65
+ if (c === "$" && next === "{") {
66
+ templates[templates.length - 1] = 1;
67
+ out += "${";
68
+ lastSignificant = "{";
69
+ i += 2;
70
+ continue;
71
+ }
72
+ // Template text: drop it, but keep newlines so line numbers survive.
73
+ out += c === "\n" ? "\n" : "";
74
+ i++;
75
+ continue;
76
+ }
77
+
78
+ // Block comment.
79
+ if (c === "/" && next === "*") {
80
+ const end = src.indexOf("*/", i + 2);
81
+ const body = src.slice(i, end === -1 ? src.length : end + 2);
82
+ out += body.replace(/[^\n]/g, " ");
83
+ i = end === -1 ? src.length : end + 2;
84
+ continue;
85
+ }
86
+
87
+ // Line comment.
88
+ if (c === "/" && next === "/") {
89
+ let end = src.indexOf("\n", i);
90
+ if (end === -1) end = src.length;
91
+ out += " ".repeat(end - i);
92
+ i = end;
93
+ continue;
94
+ }
95
+
96
+ // Quoted string.
97
+ if (c === '"' || c === "'") {
98
+ const quote = c;
99
+ out += quote;
100
+ i++;
101
+ while (i < src.length) {
102
+ if (src[i] === "\\") {
103
+ i += 2;
104
+ continue;
105
+ }
106
+ if (src[i] === quote) break;
107
+ // Unterminated strings must not swallow the rest of the file.
108
+ if (src[i] === "\n") break;
109
+ out += src[i] === "\n" ? "\n" : "";
110
+ i++;
111
+ }
112
+ if (src[i] === quote) {
113
+ out += quote;
114
+ i++;
115
+ }
116
+ lastSignificant = quote;
117
+ continue;
118
+ }
119
+
120
+ // Regex literal. Only when a `/` cannot be division here.
121
+ if (c === "/" && regexCanFollow(lastSignificant)) {
122
+ let j = i + 1;
123
+ let inClass = false;
124
+ let closed = false;
125
+ while (j < src.length) {
126
+ const d = src[j];
127
+ if (d === "\\") {
128
+ j += 2;
129
+ continue;
130
+ }
131
+ if (d === "\n") break; // not a regex after all
132
+ if (d === "[") inClass = true;
133
+ else if (d === "]") inClass = false;
134
+ else if (d === "/" && !inClass) {
135
+ closed = true;
136
+ break;
137
+ }
138
+ j++;
139
+ }
140
+ if (closed) {
141
+ while (j + 1 < src.length && /[a-z]/.test(src[j + 1])) j++; // flags
142
+ // Emit a valid placeholder, not spaces. Blanking the literal leaves
143
+ // `const SHELL_METACHARACTERS = ` with no right-hand side, which makes
144
+ // the output unparseable — and the output has to stay parseable,
145
+ // because "does a real parser still accept this?" is the only
146
+ // independent check that the tokenizer did not mangle the file.
147
+ // The shortest possible regex literal is 3 characters, so this always
148
+ // fits.
149
+ out += "/x/" + " ".repeat(Math.max(0, j - i + 1 - 3));
150
+ i = j + 1;
151
+ lastSignificant = ")"; // a regex is a value
152
+ continue;
153
+ }
154
+ // Fall through: it was division.
155
+ }
156
+
157
+ // Template start.
158
+ if (c === "`") {
159
+ templates.push(0);
160
+ out += "`";
161
+ lastSignificant = "`";
162
+ i++;
163
+ continue;
164
+ }
165
+
166
+ // Brace tracking so an interpolation knows where it ends.
167
+ if (templates.length > 0) {
168
+ if (c === "{") templates[templates.length - 1]++;
169
+ else if (c === "}") {
170
+ templates[templates.length - 1]--;
171
+ if (templates[templates.length - 1] === 0) {
172
+ // Closing `}` of the interpolation: back to template text.
173
+ out += "}";
174
+ lastSignificant = "}";
175
+ i++;
176
+ continue;
177
+ }
178
+ }
179
+ }
180
+
181
+ out += c;
182
+ if (!/\s/.test(c)) lastSignificant = c;
183
+ i++;
184
+ }
185
+
186
+ // Unbalanced state at EOF is the signature of a mis-parse: a template that
187
+ // was opened by something that was not a template delimiter, and therefore a
188
+ // run of real code consumed as template text. That is precisely the failure
189
+ // this module exists to end, so refuse rather than hand back a plausible
190
+ // looking fragment.
191
+ if (templates.length > 0) {
192
+ throw new Error(
193
+ `stripStringsAndComments: ${templates.length} template literal(s) still open at end of input — ` +
194
+ `the tokenizer mis-parsed and the result cannot be trusted`,
195
+ );
196
+ }
197
+
198
+ return out;
199
+ }
200
+
201
+ export interface SyntaxWitness {
202
+ /** True only for `clean`. Both failure modes are failures. */
203
+ ok: boolean;
204
+ verdict: "clean" | "input-unparseable" | "stripping-broke-syntax";
205
+ detail?: string;
206
+ }
207
+
208
+ /**
209
+ * Check the stripper against a real parser.
210
+ *
211
+ * Removing string and comment CONTENT must not change whether the source is
212
+ * syntactically valid. If the stripped output stops parsing, the tokenizer ate
213
+ * something it should not have — which is the whole defect being fixed here,
214
+ * and exactly the parser-differential risk of hand-rolling a lexer.
215
+ *
216
+ * `new Function` here is a PARSER, not an evaluator. Construction compiles the
217
+ * body and stops; the resulting function is discarded without ever being
218
+ * called, so nothing in the input runs. That distinction is the only reason
219
+ * this is acceptable at all — if the result were invoked, feeding it a repo
220
+ * file would be arbitrary code execution. It must stay uninvoked.
221
+ *
222
+ * The wrapping neutralises `export` and makes ship.js's top-level `return`
223
+ * legal; both sides get identical treatment, so only a DIFFERENCE is reported.
224
+ */
225
+ export function strippingPreservesSyntax(src: string): SyntaxWitness {
226
+ const prep = (c: string) => "(async function(){" + c.replace(/^export\s+/gm, "") + "\n})";
227
+ const parses = (c: string): string | null => {
228
+ try {
229
+ new Function(prep(c));
230
+ return null;
231
+ } catch (e) {
232
+ return (e as Error).message;
233
+ }
234
+ };
235
+
236
+ // If the input does not parse, there is no differential to draw — but that
237
+ // is NOT a pass. Returning ok here would mean an unparseable ship.js
238
+ // silently turns the witness into a no-op, which is the exact failure this
239
+ // module was written to end: a check reporting green because of what it
240
+ // could not look at. The caller has to decide, so say which case it is.
241
+ const before = parses(src);
242
+ if (before !== null) {
243
+ return { ok: false, verdict: "input-unparseable", detail: before };
244
+ }
245
+
246
+ const after = parses(stripStringsAndComments(src));
247
+ return after === null
248
+ ? { ok: true, verdict: "clean" }
249
+ : { ok: false, verdict: "stripping-broke-syntax", detail: after };
250
+ }