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,230 @@
1
+ /**
2
+ * Is the promoted container built from the commit under test? (#341)
3
+ *
4
+ * `container-has-fix` in `gates/workflow.test.ts` asked that, and every way
5
+ * of failing to find out returned a pass:
6
+ *
7
+ * const runtime = exec("command -v podman").ok ? "podman" : "docker";
8
+ * const inspect = execArgvOf(runtime, ["inspect", "--format=…revision", "--", name]);
9
+ * if (!inspect.ok || !inspect.output) return; // container absent, daemon down,
10
+ * const head = exec("git rev-parse HEAD", root); // no revision label,
11
+ * if (!head.ok) return; // neither runtime installed
12
+ *
13
+ * Four separate unmeasurable states, one observable outcome: PASS.
14
+ *
15
+ * Two of them are *more likely* exactly when the check matters. An image that
16
+ * was never rebuilt may not exist under the expected name; a stopped runtime
17
+ * is the normal state on a machine where promotion did not happen. The check
18
+ * was quietest in precisely the situation it exists to catch — shape one in
19
+ * `.claude/rules/checks-must-be-able-to-fail.md`.
20
+ *
21
+ * The runtime was also chosen by probe rather than by config: absent podman
22
+ * silently fell through to docker, and with neither installed the inspect
23
+ * failed and the check passed. A consumer with no container runtime at all
24
+ * got a green `container-has-fix` on every run, for ever.
25
+ *
26
+ * ## What this does and deliberately does not do
27
+ *
28
+ * It makes the states **distinguishable and recorded** (#341 criteria 2 and 3)
29
+ * and resolves the runtime from config with the probe as a fallback
30
+ * (criterion 4).
31
+ *
32
+ * The criteria are written out longhand rather than as `SC-2`, `SC-4` and so
33
+ * on, because the registry owns those ids: every single-digit `SC-N` is a real
34
+ * entry in `specs/`, and `scripts/sync-sc-status.ts` credits any comment
35
+ * mentioning one as coverage of it. A sentence about this issue's second
36
+ * criterion would certify an unrelated bootstrap criterion as tested.
37
+ *
38
+ * It does **not** decide that an unreadable inspect FAILS the run. That is
39
+ * criterion 1's question — how often each state is taken across real runs on a real
40
+ * consumer — and #341 exists as a separate issue precisely because turning
41
+ * runs red on a consumer whose runtime happens to be down is a behaviour
42
+ * change that needs its blast radius measured rather than guessed. The
43
+ * verdicts below carry `blocking: false` for every unmeasurable state, and
44
+ * the day criterion 1 is answered that is the one field to change.
45
+ *
46
+ * Recording without deciding is normally the failure mode #346 was about —
47
+ * a reading nothing consumes. The difference is that here the reading is the
48
+ * deliverable: criterion 1 cannot be answered without it, and the issue says so.
49
+ */
50
+
51
+ export type ProvenanceOutcome =
52
+ | "MATCH"
53
+ | "BEHIND"
54
+ | "NO_RUNTIME"
55
+ | "RUNTIME_DOWN"
56
+ | "CONTAINER_ABSENT"
57
+ | "INSPECT_FAILED"
58
+ | "NO_REVISION_LABEL"
59
+ | "HEAD_UNREADABLE";
60
+
61
+ export interface ProvenanceVerdict {
62
+ outcome: ProvenanceOutcome;
63
+ /** Does this stop the run? Only BEHIND does, pending #341 criterion 1. */
64
+ blocking: boolean;
65
+ /** Was anything actually measured? */
66
+ measured: boolean;
67
+ detail: string;
68
+ }
69
+
70
+ /** The runtimes this knows how to inspect, in probe order. */
71
+ export const KNOWN_RUNTIMES = ["podman", "docker"] as const;
72
+
73
+ export type RuntimeResolution =
74
+ | { kind: "resolved"; runtime: string; source: "config" | "probe" }
75
+ | { kind: "none"; detail: string };
76
+
77
+ /**
78
+ * Which container runtime to ask, config first.
79
+ *
80
+ * The old line was `exec("command -v podman").ok ? "podman" : "docker"`,
81
+ * which has no way to say "neither" — docker was the answer whether docker
82
+ * was installed or not, and the resulting inspect failure read as a pass.
83
+ */
84
+ export function resolveContainerRuntime(
85
+ configured: string | null | undefined,
86
+ available: (name: string) => boolean,
87
+ ): RuntimeResolution {
88
+ if (typeof configured === "string" && configured.trim() !== "") {
89
+ const name = configured.trim();
90
+ if (available(name)) return { kind: "resolved", runtime: name, source: "config" };
91
+ return {
92
+ kind: "none",
93
+ detail:
94
+ `the project configures \`prod.containerRuntime: "${name}"\` and it is not on PATH, ` +
95
+ `so the container could not be inspected. Nothing was measured.`,
96
+ };
97
+ }
98
+ for (const name of KNOWN_RUNTIMES) {
99
+ if (available(name)) return { kind: "resolved", runtime: name, source: "probe" };
100
+ }
101
+ return {
102
+ kind: "none",
103
+ detail:
104
+ `no container runtime is available (looked for ${KNOWN_RUNTIMES.join(", ")}) and the ` +
105
+ `project configures none, so the container could not be inspected. Nothing was ` +
106
+ `measured — this is UNMEASURED, not a container that matches.`,
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Tell "there is no such container" from "the daemon is not answering".
112
+ *
113
+ * Both used to be one silent return, and they mean opposite things: the
114
+ * first is evidence the promotion never happened, the second is evidence
115
+ * about the machine. Matching on the runtime's own words is a narrow
116
+ * detector, so an unrecognised failure stays `INSPECT_FAILED` and keeps its
117
+ * stderr rather than being filed under whichever branch is closer.
118
+ */
119
+ export function classifyInspectFailure(stderr: string): "CONTAINER_ABSENT" | "RUNTIME_DOWN" | "INSPECT_FAILED" {
120
+ const s = stderr.toLowerCase();
121
+ if (/no such (object|container|image)|unable to find|not found/.test(s)) return "CONTAINER_ABSENT";
122
+ if (/cannot connect|connection refused|daemon|is the docker daemon running|dial unix|service not available/.test(s)) {
123
+ return "RUNTIME_DOWN";
124
+ }
125
+ return "INSPECT_FAILED";
126
+ }
127
+
128
+ export interface ProvenanceReading {
129
+ runtime: RuntimeResolution;
130
+ containerName: string;
131
+ /** The inspect result, absent when no runtime resolved. */
132
+ inspect?: { ok: boolean; output: string; stderr: string };
133
+ /** `git rev-parse HEAD` in the tree under test. */
134
+ head?: { ok: boolean; output: string };
135
+ /** The `environments.prod.rebuild` verdict the run recorded. */
136
+ prodRebuild?: unknown;
137
+ }
138
+
139
+ /**
140
+ * One reading in, one named outcome out.
141
+ *
142
+ * Every branch produces a verdict. There is no path that returns nothing,
143
+ * which is the whole change: the previous body had four, and they were
144
+ * indistinguishable from a container that matched.
145
+ */
146
+ export function classifyContainerProvenance(r: ProvenanceReading): ProvenanceVerdict {
147
+ if (r.runtime.kind === "none") {
148
+ return { outcome: "NO_RUNTIME", blocking: false, measured: false, detail: r.runtime.detail };
149
+ }
150
+ const runtime = r.runtime.runtime;
151
+
152
+ if (!r.inspect) {
153
+ return {
154
+ outcome: "INSPECT_FAILED",
155
+ blocking: false,
156
+ measured: false,
157
+ detail: `${runtime} inspect was never run for ${r.containerName}. Nothing was measured.`,
158
+ };
159
+ }
160
+
161
+ if (!r.inspect.ok) {
162
+ const outcome = classifyInspectFailure(r.inspect.stderr);
163
+ const detail =
164
+ outcome === "CONTAINER_ABSENT"
165
+ ? `${runtime} has no container named ${r.containerName}. An image that was never ` +
166
+ `rebuilt does not exist under the expected name, so this is the state the check ` +
167
+ `exists to catch — recorded, not yet blocking (#341 criterion 1).`
168
+ : outcome === "RUNTIME_DOWN"
169
+ ? `${runtime} is installed but not answering, so ${r.containerName} could not be ` +
170
+ `inspected. This says nothing about the container.`
171
+ : `${runtime} inspect of ${r.containerName} failed for a reason this does not ` +
172
+ `recognise: ${r.inspect.stderr.trim().slice(0, 200)}`;
173
+ return { outcome, blocking: false, measured: false, detail };
174
+ }
175
+
176
+ const sha = r.inspect.output.replace(/'/g, "").trim();
177
+ if (sha === "") {
178
+ return {
179
+ outcome: "NO_REVISION_LABEL",
180
+ blocking: false,
181
+ measured: false,
182
+ detail:
183
+ `${r.containerName} carries no org.opencontainers.image.revision label, so the ` +
184
+ `commit it was built from is unknown. The image exists; its provenance does not.`,
185
+ };
186
+ }
187
+
188
+ if (!r.head?.ok || !r.head.output.trim()) {
189
+ return {
190
+ outcome: "HEAD_UNREADABLE",
191
+ blocking: false,
192
+ measured: false,
193
+ detail:
194
+ `the tree under test did not yield a HEAD commit, so there is nothing to compare ` +
195
+ `${r.containerName}'s revision ${sha.slice(0, 8)} against.`,
196
+ };
197
+ }
198
+
199
+ const head = r.head.output.trim();
200
+ if (sha === head) {
201
+ return {
202
+ outcome: "MATCH",
203
+ blocking: false,
204
+ measured: true,
205
+ detail: `${r.containerName} is built from ${head.slice(0, 8)}, the commit under test.`,
206
+ };
207
+ }
208
+
209
+ // The one blocking case, unchanged from before: a measured mismatch with
210
+ // no recorded rebuild. Narrowed to `blocking` so #341 criterion 1 has exactly one
211
+ // field to flip when the blast radius of the others is known.
212
+ const rebuilt = r.prodRebuild === "PASS";
213
+ return {
214
+ outcome: "BEHIND",
215
+ blocking: !rebuilt,
216
+ measured: true,
217
+ detail:
218
+ `${r.containerName} is built from ${sha.slice(0, 8)} and the commit under test is ` +
219
+ `${head.slice(0, 8)}` +
220
+ (rebuilt
221
+ ? `, but the run records prod.rebuild PASS, so the promotion is accounted for.`
222
+ : `, and the run records no prod.rebuild PASS. The promoted container does not ` +
223
+ `contain the change being shipped.`),
224
+ };
225
+ }
226
+
227
+ /** The gate's refusal: empty unless something measured and blocking was found. */
228
+ export function containerProvenanceViolations(v: ProvenanceVerdict): string[] {
229
+ return v.blocking ? [`container-has-fix: ${v.detail}`] : [];
230
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * create-brief — Generate agent brief templates and register roles in config.
3
+ *
4
+ * Deep module: all logic here, CLI is a thin consumer.
5
+ */
6
+
7
+ import { readFileSync, writeFileSync, existsSync } from "fs";
8
+ import type { AgentMeta } from "./generators/types";
9
+
10
+ /**
11
+ * Generate an agent brief markdown template with standard sections and variable placeholders.
12
+ */
13
+ export function generateBriefTemplate(
14
+ roleName: string,
15
+ description: string,
16
+ forbiddenCommands?: string[],
17
+ ): string {
18
+ const today = new Date().toISOString().split("T")[0];
19
+ const displayName = roleName.charAt(0).toUpperCase() + roleName.slice(1);
20
+
21
+ return `---
22
+ doc-type: reference
23
+ status: active
24
+ owner: TODO
25
+ updated: ${today}
26
+ ---
27
+
28
+ You are ${displayName}, ${description}.
29
+
30
+ ## Context (READ THIS FIRST)
31
+
32
+ 1. **PROJECT-STATE.md** — current priorities, session handoff
33
+ 2. **Governing spec** — look up in specs-routing rule for the area you're changing
34
+
35
+ ## Workflow
36
+
37
+ 1. Read the governing spec if your task touches a spec'd area
38
+ 3. Execute your task following project conventions
39
+ 4. Report results with evidence
40
+
41
+ ## Never Do
42
+
43
+ - Read the same file twice — get what you need in one pass
44
+ - Use \`cat\`, \`head\`, or \`tail\` via Bash — use the Read tool instead
45
+ - Run \`pwd\` or \`ls -la\` for orientation — your CWD is always the project root
46
+ - Guess at file structure — use AGENTS.md routing table
47
+
48
+ ## Report
49
+
50
+ - PASS/FAIL per AC with evidence (command output or screenshots)
51
+ - Any new findings flagged as blocking or non-blocking
52
+
53
+ ## Rules
54
+
55
+ ${forbiddenRules(forbiddenCommands)}- Verify before asserting — try it first, report what actually happened
56
+ `;
57
+ }
58
+
59
+ /**
60
+ * #343 — this template hardcoded "Never run \`make rebuild\`".
61
+ *
62
+ * That is one consumer's rule, emitted into every consumer's brief template.
63
+ * It comes from the project's own \`forbiddenCommands\` now, and nothing is
64
+ * emitted when none is configured: a guessed prohibition is worse than
65
+ * silence, because the agent obeys it and nobody finds out it was invented.
66
+ */
67
+ function forbiddenRules(commands: string[] | undefined): string {
68
+ if (!commands || commands.length === 0) return "";
69
+ return commands.map(c => `- Never run \\\`${c}\\\` — only the DA does that\n`).join("");
70
+ }
71
+
72
+ /**
73
+ * Write a generated brief template to the templates directory.
74
+ * Returns the file path written to.
75
+ */
76
+ export function writeBriefTemplate(templatesDir: string, roleName: string, description: string): string {
77
+ const filePath = `${templatesDir}/${roleName}.md`;
78
+ if (existsSync(filePath)) {
79
+ throw new Error(`Template already exists: ${filePath}`);
80
+ }
81
+ const content = generateBriefTemplate(roleName, description);
82
+ writeFileSync(filePath, content);
83
+ return filePath;
84
+ }
85
+
86
+ /**
87
+ * Add a new role to the project's rungate.json config.
88
+ * Adds brief path, isolation: worktree, and a standardTask.
89
+ */
90
+ export function addRoleToConfig(configPath: string, roleName: string, description: string): void {
91
+ if (!existsSync(configPath)) {
92
+ throw new Error(`Config file not found: ${configPath}`);
93
+ }
94
+ const config = JSON.parse(readFileSync(configPath, "utf-8"));
95
+ if (!config.roles) {
96
+ config.roles = {};
97
+ }
98
+ if (config.roles[roleName]) {
99
+ throw new Error(`Role '${roleName}' already exists in ${configPath}`);
100
+ }
101
+ config.roles[roleName] = {
102
+ brief: `.claude/agents/${roleName}.md`,
103
+ isolation: "worktree",
104
+ standardTask: `Perform ${description.toLowerCase()} tasks as assigned`,
105
+ description,
106
+ tools: "[Bash, Read]",
107
+ model: "sonnet",
108
+ };
109
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
110
+ }
111
+
112
+ export const DEFAULT_AGENT_META: Record<string, AgentMeta> = {
113
+ // discovery and marcus run opus: discovery authors the ACs and evidence
114
+ // commands (the "unwinnable AC" pattern that SHIP_FAILED #42/#43/#45
115
+ // originates there), and marcus does multi-file TDD implementation. Both
116
+ // clear the "multi-file architectural reasoning" bar in the model routing
117
+ // guidance; the read-only and checklist roles below stay on sonnet.
118
+ discovery: { description: "Discovery agent — reads issue, sizes work, writes ACs with evidence methods", tools: "[Bash, Read]", model: "opus", effort: "low", disallowedTools: ["Write", "Edit"], omitClaudeMd: true, tiers: { reinforcement: ["Discovery Rules"] } },
119
+ marcus: { description: "Principal engineer — implements code changes with TDD, writes tests, commits", tools: "[Bash, Read, Write, Edit]", model: "opus", memory: "project", maxTurns: 30, effort: "high", isolation: "worktree", tiers: { reinforcement: ["Testing Rules"], mechanical: ["Workflow"] } },
120
+ quinn: { description: "QA engineer — tests as a brand-new user using Playwright MCP tools", tools: "[Bash, Read, mcp__playwright__*]", model: "sonnet", effort: "high", disallowedTools: ["Write", "Edit"], omitClaudeMd: true, tiers: { reinforcement: ["Project Type Detection", "CLI Testing Mode"] } },
121
+ rook: { description: "Security engineer — scans changed files for vulnerabilities", tools: "[Bash, Read]", model: "sonnet", effort: "low", disallowedTools: ["Write", "Edit"], omitClaudeMd: true },
122
+ serena: { description: "Software architect — structural decisions, ADRs, module boundary review", tools: "[Read]", model: "sonnet", disallowedTools: ["Write", "Edit"] },
123
+ aditi: { description: "UX/UI designer — component specs, visual review, accessibility", tools: "[Read]", model: "sonnet", disallowedTools: ["Write", "Edit"], tiers: { reinforcement: ["Project Type Detection"] } },
124
+ };
125
+
126
+ /**
127
+ * Build agentMeta record from harness roles config.
128
+ * Returns only config-sourced entries — callers merge with DEFAULT_AGENT_META if needed.
129
+ */
130
+ export function buildAgentMeta(harnessConfig: Record<string, any> | null): Record<string, AgentMeta> {
131
+ const result: Record<string, AgentMeta> = {};
132
+ if (!harnessConfig?.roles) return result;
133
+
134
+ for (const [roleName, roleConfig] of Object.entries(harnessConfig.roles as Record<string, any>)) {
135
+ result[roleName] = {
136
+ description: roleConfig.description || `${roleName} agent`,
137
+ tools: roleConfig.tools || "[Bash, Read]",
138
+ model: roleConfig.model || "sonnet",
139
+ ...(roleConfig.tiers ? { tiers: roleConfig.tiers } : {}),
140
+ ...(roleConfig.memory ? { memory: roleConfig.memory } : {}),
141
+ ...(roleConfig.maxTurns ? { maxTurns: roleConfig.maxTurns } : {}),
142
+ ...(roleConfig.effort ? { effort: roleConfig.effort } : {}),
143
+ ...(roleConfig.disallowedTools ? { disallowedTools: roleConfig.disallowedTools } : {}),
144
+ ...(roleConfig.omitClaudeMd ? { omitClaudeMd: roleConfig.omitClaudeMd } : {}),
145
+ ...(roleConfig.isolation ? { isolation: roleConfig.isolation } : {}),
146
+ ...(roleConfig.hooks ? { hooks: roleConfig.hooks } : {}),
147
+ };
148
+ }
149
+ return result;
150
+ }
@@ -0,0 +1,272 @@
1
+ /**
2
+ * create-sc — Generate matchable SC lines from structured input.
3
+ *
4
+ * Deep module: all pattern-to-text logic lives here.
5
+ * Thin consumer: scripts/create-sc.ts is the CLI wrapper.
6
+ */
7
+ import { readFileSync, existsSync } from "fs";
8
+ import { join, dirname } from "path";
9
+ import { fileURLToPath } from "url";
10
+
11
+ import type { ScRegistry } from "./sc-ids";
12
+
13
+ // ── Types ─────────────────────────────────────────────────────
14
+
15
+ export interface RegistryEntry {
16
+ name: string;
17
+ syntax: string;
18
+ regex: string;
19
+ example: string;
20
+ notes: string;
21
+ }
22
+
23
+ interface ParamDef {
24
+ required: string[];
25
+ generate: (params: Record<string, string>) => string;
26
+ }
27
+
28
+ // ── Registry loading ──────────────────────────────────────────
29
+
30
+ const _registryCache = new Map<string, RegistryEntry[]>();
31
+
32
+ function loadBuiltInRegistry(): RegistryEntry[] {
33
+ const key = "__builtin__";
34
+ if (_registryCache.has(key)) return _registryCache.get(key)!;
35
+ const configPath = join(dirname(fileURLToPath(import.meta.url)), "..", "config", "matcher-registry.json");
36
+ const entries: RegistryEntry[] = JSON.parse(readFileSync(configPath, "utf-8"));
37
+ _registryCache.set(key, entries);
38
+ return entries;
39
+ }
40
+
41
+ /**
42
+ * Load the matcher registry, optionally merging consumer-defined custom matchers.
43
+ *
44
+ * When projectRoot is provided, looks for .claude/rungate.json in that directory
45
+ * and merges any `customMatchers` array entries with the built-in registry.
46
+ * Consumer entries with the same `name` as a built-in entry override the built-in.
47
+ */
48
+ export function loadRegistry(projectRoot?: string): RegistryEntry[] {
49
+ const cacheKey = projectRoot ?? "__builtin__";
50
+ if (_registryCache.has(cacheKey)) return _registryCache.get(cacheKey)!;
51
+
52
+ const builtIn = loadBuiltInRegistry();
53
+ if (!projectRoot) {
54
+ return builtIn;
55
+ }
56
+
57
+ // Look for consumer custom matchers in .claude/rungate.json
58
+ const configPath = join(projectRoot, ".claude", "rungate.json");
59
+ if (!existsSync(configPath)) {
60
+ _registryCache.set(cacheKey, builtIn);
61
+ return builtIn;
62
+ }
63
+
64
+ try {
65
+ const config = JSON.parse(readFileSync(configPath, "utf-8"));
66
+ const customMatchers: RegistryEntry[] = config.customMatchers ?? [];
67
+ if (customMatchers.length === 0) {
68
+ _registryCache.set(cacheKey, builtIn);
69
+ return builtIn;
70
+ }
71
+
72
+ // Merge: consumer entries override built-in entries with same name
73
+ const merged = builtIn.filter(
74
+ (entry) => !customMatchers.some((c) => c.name === entry.name)
75
+ );
76
+ merged.push(...customMatchers);
77
+
78
+ _registryCache.set(cacheKey, merged);
79
+ return merged;
80
+ } catch {
81
+ _registryCache.set(cacheKey, builtIn);
82
+ return builtIn;
83
+ }
84
+ }
85
+
86
+ // ── Pattern param definitions ─────────────────────────────────
87
+
88
+ const patternDefs: Record<string, ParamDef> = {
89
+ "file-exists": {
90
+ required: ["file"],
91
+ generate: (p) => `${p.file} exists`,
92
+ },
93
+ "dir-exists": {
94
+ required: ["dir"],
95
+ generate: (p) => `${p.dir}/ directory exists`,
96
+ },
97
+ "all-specs-frontmatter": {
98
+ required: [],
99
+ generate: () => "all specs have frontmatter",
100
+ },
101
+ "paths-resolve": {
102
+ required: ["file"],
103
+ generate: (p) => `all paths referenced in ${p.file} resolve`,
104
+ },
105
+ "root-clean": {
106
+ required: [],
107
+ generate: () => "root is clean",
108
+ },
109
+ "pointer-exists": {
110
+ required: ["file", "target"],
111
+ generate: (p) => `${p.file} exists with pointer to ${p.target}`,
112
+ },
113
+ "canary": {
114
+ required: [],
115
+ generate: () => "canary test exists",
116
+ },
117
+ "content-contains": {
118
+ required: ["file", "items"],
119
+ generate: (p) => `${p.file} contains [${p.items}]`,
120
+ },
121
+ "content-not-contains": {
122
+ required: ["file", "items"],
123
+ generate: (p) => `${p.file} must NOT contain [${p.items}]`,
124
+ },
125
+ "count-threshold": {
126
+ required: ["file", "count", "unit"],
127
+ generate: (p) => `${p.file} is under [${p.count}] ${p.unit}`,
128
+ },
129
+ "json-field-equals": {
130
+ required: ["file", "field", "value"],
131
+ generate: (p) => `${p.file} ${p.field} field equals [${p.value}]`,
132
+ },
133
+ "section-exists": {
134
+ required: ["file", "section"],
135
+ generate: (p) => `${p.file} has section [${p.section}]`,
136
+ },
137
+ "regex-match": {
138
+ required: ["file", "pattern"],
139
+ generate: (p) => `${p.file} matches /${p.pattern}/${p.flags ?? ""}`,
140
+ },
141
+ "source-contains": {
142
+ required: ["file", "keywords"],
143
+ generate: (p) => `harness ${p.file} contains [${p.keywords}]`,
144
+ },
145
+ "json-has-field": {
146
+ required: ["file", "field"],
147
+ generate: (p) => `${p.file} has field ${p.field}`,
148
+ },
149
+ "scaffold-produces": {
150
+ required: ["file"],
151
+ generate: (p) => `scaffold output ${p.file} exists`,
152
+ },
153
+ "frontmatter-field": {
154
+ required: ["file", "field"],
155
+ generate: (p) => p.value
156
+ ? `${p.file} frontmatter has ${p.field} = ${p.value}`
157
+ : `${p.file} frontmatter has ${p.field}`,
158
+ },
159
+ "file-line-range": {
160
+ required: ["file", "min", "max"],
161
+ generate: (p) => `${p.file} is between [${p.min}] and [${p.max}] lines`,
162
+ },
163
+ "command-output": {
164
+ required: ["command", "expected"],
165
+ generate: (p) => `command-output \`${p.command}\` contains [${p.expected}]`,
166
+ },
167
+ };
168
+
169
+ // ── Core functions ────────────────────────────────────────────
170
+
171
+ function validatePattern(name: string): RegistryEntry {
172
+ const registry = loadRegistry();
173
+ const entry = registry.find(e => e.name === name);
174
+ if (!entry) {
175
+ const validNames = registry.map(e => e.name).join(", ");
176
+ throw new Error(`Unknown pattern: "${name}". Valid patterns: ${validNames}`);
177
+ }
178
+ return entry;
179
+ }
180
+
181
+ function validateParams(patternName: string, params: Record<string, string>): void {
182
+ const def = patternDefs[patternName];
183
+ if (!def) {
184
+ throw new Error(`No parameter definition for pattern: "${patternName}"`);
185
+ }
186
+ const missing = def.required.filter(k => !params[k]);
187
+ if (missing.length > 0) {
188
+ throw new Error(
189
+ `Missing required params for "${patternName}": ${missing.join(", ")}. ` +
190
+ `Required: ${def.required.join(", ")}`
191
+ );
192
+ }
193
+ }
194
+
195
+ export function generateSCText(patternName: string, params: Record<string, string>): string {
196
+ // Validate pattern exists in registry
197
+ const entry = validatePattern(patternName);
198
+
199
+ // Validate required params
200
+ validateParams(patternName, params);
201
+
202
+ // Generate the statement text
203
+ const def = patternDefs[patternName];
204
+ const statement = def.generate(params);
205
+
206
+ // Validate round-trip: generated text must match the pattern's regex
207
+ const regex = new RegExp(entry.regex, "i");
208
+ if (!regex.test(statement)) {
209
+ throw new Error(
210
+ `Internal error: generated text "${statement}" does not match pattern regex /${entry.regex}/i`
211
+ );
212
+ }
213
+
214
+ return statement;
215
+ }
216
+
217
+ export function listPatterns(): string {
218
+ const registry = loadRegistry();
219
+ const lines: string[] = ["Available patterns:", ""];
220
+ for (const entry of registry) {
221
+ const def = patternDefs[entry.name];
222
+ const required = def ? def.required : [];
223
+ lines.push(` ${entry.name}`);
224
+ lines.push(` Syntax: ${entry.syntax}`);
225
+ lines.push(` Example: ${entry.example}`);
226
+ lines.push(` Required: ${required.length > 0 ? required.join(", ") : "(none)"}`);
227
+ lines.push("");
228
+ }
229
+ return lines.join("\n");
230
+ }
231
+
232
+ /**
233
+ * The next free SC number.
234
+ *
235
+ * `SC-<n>` is a GLOBAL id — `lib/sc-ids.ts` says so, and
236
+ * `test/spec-sc-ids-unique.test.ts` enforces it. This function read ONE
237
+ * spec's content, which in a global namespace is not an allocator but a
238
+ * collision generator, and it generated ten (#392): GATE-CONTRACTS-SPEC.md
239
+ * counted up to 378 in its own file and took 379..388 for its per-gate
240
+ * subsections, while CONFIG-DRIVEN-TESTING-SPEC.md independently counted up
241
+ * to 378 in ITS own file and took 379 next. Both were locally correct and
242
+ * neither could see the other.
243
+ *
244
+ * Pass the registry and the whole namespace is consulted, headings included —
245
+ * a number owned by a `### SC-N:` section is just as taken as a tracked one.
246
+ *
247
+ * `reg` is optional so the one-argument answer is unchanged for any caller
248
+ * that has no registry to hand; silently changing that would be a different
249
+ * bug. It is the wrong answer in a shared namespace, which is why
250
+ * `scripts/create-sc.ts` passes one.
251
+ */
252
+ export function nextSCNumber(specContent: string, reg?: ScRegistry): number {
253
+ const ids: number[] = [];
254
+ const pattern = /SC-(\d+)/g;
255
+ let match;
256
+ while ((match = pattern.exec(specContent)) !== null) {
257
+ ids.push(parseInt(match[1]));
258
+ }
259
+ for (const id of reg?.declaredById.keys() ?? []) {
260
+ const n = Number(id.replace(/^SC-[A-Z]?/, ""));
261
+ if (Number.isFinite(n)) ids.push(n);
262
+ }
263
+ if (ids.length === 0) return 1;
264
+ return Math.max(...ids) + 1;
265
+ }
266
+
267
+ /**
268
+ * Format an SC line for appending to a spec file.
269
+ */
270
+ export function formatSCLine(scNumber: number, statement: string): string {
271
+ return `- [ ] SC-${scNumber}: ${statement}`;
272
+ }