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
package/lib/sc-ids.ts ADDED
@@ -0,0 +1,344 @@
1
+ /**
2
+ * One owner for what an SC id is, and what a mention of one means
3
+ * (#330, #352, #358).
4
+ *
5
+ * Three files parsed SC ids with three different regexes:
6
+ *
7
+ * lib/conformity.ts extractSCs `SC-\w+` declarations
8
+ * scripts/sync-sc-status.ts coverageClaimIds `SC-\d+(?!\d)` mentions
9
+ * test/spec-sc-ids-unique.ts DECLARATION `SC-\d+` duplicates
10
+ *
11
+ * #330 called the divergence the root cause and named two of the three. The
12
+ * consequences are the three issues this module closes:
13
+ *
14
+ * - The uniqueness guard cannot see `SC-A1`, so three specs declare it and
15
+ * nothing notices.
16
+ * - The coverage lookup cannot see `SC-A1` either, so six anti-criteria are
17
+ * invisible — but widening it naively is worse, see below.
18
+ * - Every single-digit id is a real registry entry owned by
19
+ * `specs/bootstrap-data-flow/success-criteria.md`, and issues number their
20
+ * own criteria from 1. A comment about an issue's first criterion was
21
+ * credited as covering a behavioural, unimplemented bootstrap criterion.
22
+ *
23
+ * ## The notation, stated rather than assumed
24
+ *
25
+ * `SC-<n>` is a **global** id. The registry owns the number; exactly one spec
26
+ * may declare it.
27
+ *
28
+ * `SC-A<n>` is an **anti-criterion**, and `specs/SPEC-TEMPLATE.md` says what
29
+ * it is for: "anti-criterion — must NOT happen". Every spec numbers its own
30
+ * from A1, so the id is **per-spec by design**. Three specs declaring `SC-A1`
31
+ * is correct; three specs declaring `SC-640` would not be.
32
+ *
33
+ * Issue success criteria are **not** SC ids. The harness numbers them
34
+ * positionally when an issue does not number its own, so `#341 SC-1` and
35
+ * `#194 SC-640` look identical and mean opposite things — the first is this
36
+ * issue's first criterion, the second is a reference to the registry entry
37
+ * the file genuinely covers. Written as `AC-n` or longhand they are
38
+ * distinguishable; written as `SC-n` they are not, and no reader of the text
39
+ * can recover which was meant.
40
+ *
41
+ * ## Why crediting is gated on the registry
42
+ *
43
+ * #330 measured what `SC-\w+` additionally matches across `test/`:
44
+ * `SC-ID`, `SC-NNN`, `SC-TEST`, `SC-X`, `SC-guard`, `SC-numbered`, `SC-to`,
45
+ * `SC-S01`, `SC-S53` — prose fragments and placeholders. Crediting those
46
+ * manufactures coverage out of English, which is the flattering direction.
47
+ *
48
+ * So the pattern widens and the **credit** narrows: an id is creditable only
49
+ * if the registry declares it. `SC-guard` is not a registry id and never
50
+ * becomes one, so the widening cannot reach it. That is a property of the
51
+ * data rather than of the regex, which is the point — a regex narrow enough
52
+ * to exclude prose is also narrow enough to exclude `SC-A1`.
53
+ */
54
+
55
+ /**
56
+ * How a spec declared an id. Two forms, two different questions (#392).
57
+ *
58
+ * `checkbox` is a TRACKED criterion — `- [ ] SC-N: ...` — and the only form
59
+ * the status flipper can tick.
60
+ *
61
+ * `heading` is `### SC-N: ...`, a documentation subsection. It tracks nothing,
62
+ * but it OWNS the number just as firmly, and ignoring that is what produced
63
+ * ten collisions: GATE-CONTRACTS-SPEC.md headed ten consecutive subsections
64
+ * whose numbers four other specs later reissued as tracked checkboxes. Those
65
+ * headings have since been renumbered into a block nobody else holds, so the
66
+ * example is history rather than live — but the rule it bought is not, and
67
+ * `crossFormCollisions` is what keeps the bank at zero.
68
+ */
69
+ export type ScDeclarationForm = "checkbox" | "heading";
70
+
71
+ export interface ScDeclaration {
72
+ id: string;
73
+ specFile: string;
74
+ checked: boolean;
75
+ statement: string;
76
+ form: ScDeclarationForm;
77
+ }
78
+
79
+ /**
80
+ * The id itself: `SC-`, an optional uppercase class letter, digits.
81
+ *
82
+ * Not `\w+`. A class letter is part of the notation (`A` for anti-criterion);
83
+ * an arbitrary word is a prose fragment. Kept as a source string so the
84
+ * declaration and mention patterns are built from one definition and cannot
85
+ * drift — the drift is what #330 is about.
86
+ */
87
+ export const SC_ID_SOURCE = "SC-[A-Z]?\\d+";
88
+
89
+ /** A declared id: a checklist line opening with one. Not a mention. */
90
+ export function scDeclarationPattern(): RegExp {
91
+ return new RegExp(`^- \\[([ xX])\\] (${SC_ID_SOURCE}):\\s*(.+)$`, "gm");
92
+ }
93
+
94
+ /**
95
+ * A declared id in heading form: `### SC-N: what this section is about`.
96
+ *
97
+ * Same anchoring discipline as the checklist pattern — the id must OPEN the
98
+ * heading. A heading that merely mentions one ("### Why SC-640 was wrong") is
99
+ * prose, and crediting it would be the citation-vs-claim trap that
100
+ * `.claude/rules/claiming-sc-coverage.md` exists about.
101
+ */
102
+ export function scHeadingDeclarationPattern(): RegExp {
103
+ return new RegExp(`^#{1,6}[ \\t]+(${SC_ID_SOURCE}):\\s*(.+)$`, "gm");
104
+ }
105
+
106
+ /**
107
+ * A mention of an id, anywhere.
108
+ *
109
+ * The trailing boundary is "not a word character and not a hyphen": `SC-1`
110
+ * must not match inside `SC-15` (#148) or inside `SC-1-draft`. The leading
111
+ * `\b` keeps `MISC-1` out.
112
+ */
113
+ export function scMentionPattern(): RegExp {
114
+ return new RegExp(`\\b${SC_ID_SOURCE}(?![\\w-])`, "g");
115
+ }
116
+
117
+ /** One specific id, for asking "does this text name THIS criterion". */
118
+ export function oneScMentionPattern(id: string): RegExp {
119
+ return new RegExp(`\\b${id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w-])`);
120
+ }
121
+
122
+ /**
123
+ * Anti-criteria are numbered per spec, so the id alone does not identify one.
124
+ * `specs/SPEC-TEMPLATE.md` ships `- [ ] SC-A1: [anti-criterion — must NOT
125
+ * happen]`, which is where every spec's A1 comes from.
126
+ */
127
+ export function isAntiCriterion(id: string): boolean {
128
+ return /^SC-[A-Z]\d+$/.test(id);
129
+ }
130
+
131
+ /**
132
+ * Could this id equally be an issue's own criterion?
133
+ *
134
+ * The harness numbers an issue's criteria from 1, so every id a short issue
135
+ * produces is `SC-1`..`SC-9` — and all nine are declared by
136
+ * `specs/bootstrap-data-flow/success-criteria.md`. The overlap is exactly the
137
+ * single-digit numerics; `SC-640` cannot be an issue's 640th criterion.
138
+ */
139
+ export function isIssueShaped(id: string): boolean {
140
+ return /^SC-\d$/.test(id);
141
+ }
142
+
143
+ /**
144
+ * The registry: which spec files declare each id.
145
+ *
146
+ * TWO maps, because "may this be ticked" and "does this id name one
147
+ * criterion" are different questions and conflating them is #392 (#330 only
148
+ * ever needed the first, so there was only ever one map).
149
+ *
150
+ * byId CHECKBOX declarations only. The flipper's view, and
151
+ * `crossSpecCollisions`'s. Unchanged semantics — a heading
152
+ * must never become tickable.
153
+ * declaredById EVERY form. The namespace as it actually is, which is what
154
+ * ambiguity and allocation have to be computed over.
155
+ */
156
+ export interface ScRegistry {
157
+ byId: Map<string, string[]>;
158
+ declaredById: Map<string, string[]>;
159
+ }
160
+
161
+ /** The template's ids are placeholders — `isTemplateSpec` already skips it. */
162
+ export function isTemplateSpec(specFile: string): boolean {
163
+ return specFile.includes("SPEC-TEMPLATE");
164
+ }
165
+
166
+ /**
167
+ * The TRACKED criteria a spec declares. Checkbox form only.
168
+ *
169
+ * This is `extractSCs` — `lib/conformity.ts:339` returns it verbatim, which
170
+ * is #330's "one owner for what a declaration is" and must stay that way.
171
+ *
172
+ * Headings are deliberately NOT here, and the first version of #392 put them
173
+ * here and was wrong: the conformity engine runs an assertion against every
174
+ * declaration it is handed, so a `### SC-N: gate-executor pass/fail criteria`
175
+ * section title became a criterion to satisfy, and ten of them joined the
176
+ * corpus of things that can fail a gate. A heading owns a NUMBER; it does not
177
+ * state a checkable claim. Two questions, two parsers — see
178
+ * `parseScHeadingDeclarations`.
179
+ */
180
+ export function parseScDeclarations(content: string, specFile: string): ScDeclaration[] {
181
+ const out: ScDeclaration[] = [];
182
+ for (const m of content.matchAll(scDeclarationPattern())) {
183
+ out.push({
184
+ id: m[2],
185
+ specFile,
186
+ checked: m[1].toLowerCase() === "x",
187
+ statement: m[3].trim(),
188
+ form: "checkbox",
189
+ });
190
+ }
191
+ return out;
192
+ }
193
+
194
+ /**
195
+ * The ids a spec OWNS without tracking — `### SC-N: ...` subsection titles.
196
+ *
197
+ * Only the registry wants these, and only for the namespace question: is this
198
+ * id ambiguous, and is this number free. Nothing may tick one and nothing may
199
+ * assert against one.
200
+ */
201
+ export function parseScHeadingDeclarations(content: string, specFile: string): ScDeclaration[] {
202
+ const out: ScDeclaration[] = [];
203
+ for (const m of content.matchAll(scHeadingDeclarationPattern())) {
204
+ out.push({
205
+ id: m[1],
206
+ specFile,
207
+ // A heading tracks nothing, so it is never "done".
208
+ checked: false,
209
+ statement: m[2].trim(),
210
+ form: "heading",
211
+ });
212
+ }
213
+ return out;
214
+ }
215
+
216
+ export function buildScRegistry(specs: Array<{ file: string; content: string }>): ScRegistry {
217
+ const byId = new Map<string, string[]>();
218
+ const declaredById = new Map<string, string[]>();
219
+ const record = (map: Map<string, string[]>, id: string, file: string) => {
220
+ const seen = map.get(id) ?? [];
221
+ // By FILE, not by declaration: a spec that heads a section with the id it
222
+ // also tracks is one declarer, and counting it twice would make every
223
+ // such spec collide with itself.
224
+ if (!seen.includes(file)) seen.push(file);
225
+ map.set(id, seen);
226
+ };
227
+ for (const { file, content } of specs) {
228
+ if (isTemplateSpec(file)) continue;
229
+ for (const d of parseScDeclarations(content, file)) {
230
+ record(byId, d.id, file);
231
+ record(declaredById, d.id, file);
232
+ }
233
+ // Headings reach `declaredById` ONLY. A heading that became tickable
234
+ // would let the status flipper tick a section title.
235
+ for (const d of parseScHeadingDeclarations(content, file)) {
236
+ record(declaredById, d.id, file);
237
+ }
238
+ }
239
+ return { byId, declaredById };
240
+ }
241
+
242
+ /**
243
+ * A GLOBAL id declared by more than one spec. Anti-criteria are exempt
244
+ * because being per-spec is their definition, not their defect.
245
+ *
246
+ * `test/spec-sc-ids-unique.test.ts` checks each spec against itself and so
247
+ * cannot see this: two specs each declaring `SC-2` once are each internally
248
+ * consistent.
249
+ */
250
+ export function crossSpecCollisions(reg: ScRegistry): string[] {
251
+ return [...reg.byId.entries()]
252
+ .filter(([id, specs]) => !isAntiCriterion(id) && specs.length > 1)
253
+ .map(([id, specs]) => `${id} declared by ${specs.join(" and ")}`)
254
+ .sort();
255
+ }
256
+
257
+ /**
258
+ * The same collision, counted over EVERY declaration form (#392).
259
+ *
260
+ * Separate from `crossSpecCollisions` rather than folded into it, and the
261
+ * separation is the decision: widening that function would turn
262
+ * `test/spec-sc-ids-unique.test.ts`'s real-tree assertion red over ten ids,
263
+ * and the remedy it prescribes — "renumber the later claimant" — is a
264
+ * spec-content call about who moves, not something to take while fixing a
265
+ * credit bug.
266
+ *
267
+ * So the tracked-criterion guard stays at zero and this one ships as a
268
+ * counted ratchet, per `.claude/rules/checks-must-be-able-to-fail.md`.
269
+ * Qualification (`ambiguityOf` reads `declaredById`) already stops the known
270
+ * ten doing harm; this stops an eleventh arriving unnoticed.
271
+ */
272
+ export function crossFormCollisions(reg: ScRegistry): string[] {
273
+ return [...reg.declaredById.entries()]
274
+ .filter(([id, specs]) => !isAntiCriterion(id) && specs.length > 1)
275
+ .map(([id, specs]) => `${id} declared by ${specs.join(" and ")}`)
276
+ .sort();
277
+ }
278
+
279
+ /**
280
+ * Does a bare mention of this id say which criterion it means?
281
+ *
282
+ * Three ways it does not, and they are different facts:
283
+ * per-spec an anti-criterion, numbered from A1 in every spec
284
+ * multi-spec a global id two specs both claim — a collision, not a scope
285
+ * issue-shaped a number an issue's own criteria also use
286
+ */
287
+ export type Ambiguity = "none" | "per-spec" | "multi-spec" | "issue-shaped" | "not-a-criterion";
288
+
289
+ /**
290
+ * `declaredById`, not `byId` (#392). An id is ambiguous when two specs
291
+ * DECLARE it, and a `### SC-N:` heading declares one — the reported case was
292
+ * a number naming both a GATE-CONTRACTS subsection and a
293
+ * SCAFFOLD-DECOMPOSITION criterion, read as unambiguous because only the
294
+ * second form was being counted, so a comment that said
295
+ * "GATE-CONTRACTS-SPEC.md" in as many words ticked the other one. That pair
296
+ * has since been renumbered apart; the rule outlives the example.
297
+ */
298
+ export function ambiguityOf(id: string, reg: ScRegistry): Ambiguity {
299
+ const specs = reg.declaredById.get(id);
300
+ if (!specs || specs.length === 0) return "not-a-criterion";
301
+ if (isAntiCriterion(id)) return "per-spec";
302
+ if (specs.length > 1) return "multi-spec";
303
+ if (isIssueShaped(id)) return "issue-shaped";
304
+ return "none";
305
+ }
306
+
307
+ export function requiresQualification(id: string, reg: ScRegistry): boolean {
308
+ const a = ambiguityOf(id, reg);
309
+ return a === "per-spec" || a === "multi-spec" || a === "issue-shaped";
310
+ }
311
+
312
+ /**
313
+ * The tokens that name a spec in prose.
314
+ *
315
+ * `specs/bootstrap-data-flow/success-criteria.md` is cited as
316
+ * "bootstrap-data-flow" far more often than by its filename, so the
317
+ * containing directory counts too. Both are compared case-insensitively
318
+ * because prose capitalises.
319
+ */
320
+ export function qualifierTokens(specFile: string): string[] {
321
+ const parts = specFile.replace(/^specs\//, "").split("/");
322
+ const base = parts[parts.length - 1].replace(/\.md$/, "");
323
+ const tokens = [base];
324
+ if (parts.length > 1) tokens.push(parts[parts.length - 2]);
325
+ return tokens;
326
+ }
327
+
328
+ /** How far either side of a mention a qualifier is allowed to sit. */
329
+ export const QUALIFIER_WINDOW_BEFORE = 240;
330
+ export const QUALIFIER_WINDOW_AFTER = 120;
331
+
332
+ /**
333
+ * Is the mention at `at` qualified by a token naming `specFile`?
334
+ *
335
+ * A window rather than a sentence, because the mention may be in a `describe`
336
+ * title whose spec is named in the docblock above it — which is the project's
337
+ * most common way of saying which spec a file is about.
338
+ */
339
+ export function isQualifiedBy(source: string, at: number, specFile: string): boolean {
340
+ const window = source
341
+ .slice(Math.max(0, at - QUALIFIER_WINDOW_BEFORE), at + QUALIFIER_WINDOW_AFTER)
342
+ .toLowerCase();
343
+ return qualifierTokens(specFile).some(t => window.includes(t.toLowerCase()));
344
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * scaffold/defaults.ts — what a GREENFIELD scaffold writes into
3
+ * `.claude/rungate/roles.json` and `.claude/rungate/hooks.json`.
4
+ *
5
+ * Both scaffold entry points (lib/scaffold/steps.ts and
6
+ * scripts/scaffold-rungate-config.ts) used to hardcode `{}` and `[]` here.
7
+ * A project scaffolded that way looks configured and is not: ship.js finds no
8
+ * role to dispatch and no hook to deploy, and nothing says so out loud (#70).
9
+ *
10
+ * Roles are DERIVED from DEFAULT_AGENT_META rather than restated, so the role
11
+ * set a project is scaffolded with and the role set brief generation falls back
12
+ * to cannot drift apart. Only the two fields DEFAULT_AGENT_META has no opinion
13
+ * about — the brief path and the standard task — are added here.
14
+ *
15
+ * The migration path (splitMonolithToDirectory) must NOT use any of this: an
16
+ * existing project's roles and hooks are the answer, and injecting defaults
17
+ * into a split would silently rewrite someone's config.
18
+ */
19
+ import { DEFAULT_AGENT_META } from "../create-brief";
20
+
21
+ export interface HookRegistration {
22
+ name: string;
23
+ hookFor: string;
24
+ command: string;
25
+ enabled: boolean;
26
+ matcher?: string;
27
+ description: string;
28
+ deployToConsumers?: boolean;
29
+ }
30
+
31
+ /**
32
+ * Project-agnostic smoke task per role, used by `test-brief` and
33
+ * `fresh-eyes-test` when no task is given. Deliberately phrased against things
34
+ * every scaffolded project has (a test command, a source tree, a brief) rather
35
+ * than against rungate's own files.
36
+ */
37
+ const DEFAULT_STANDARD_TASKS: Record<string, string> = {
38
+ discovery: "Read the issue, size the work, and write ACs with evidence commands",
39
+ marcus: "Add config/test.json with {name: test} and write a unit test for it",
40
+ quinn: "Validate the latest commit passes all tests and type checks, report AC evidence",
41
+ rook: "Review the changed files for input validation, path traversal, and command injection",
42
+ serena: "Review the largest source module and propose a decomposition into smaller modules",
43
+ aditi: "Review the primary user-facing surface for layout, hierarchy, and accessibility",
44
+ };
45
+
46
+ function standardTaskFor(role: string, description: string): string {
47
+ return DEFAULT_STANDARD_TASKS[role] ?? `Perform ${description.toLowerCase()} tasks as assigned`;
48
+ }
49
+
50
+ /**
51
+ * The role map a greenfield `.claude/rungate/roles.json` is written with.
52
+ *
53
+ * Every entry satisfies RoleSchema (brief + standardTask required) and carries
54
+ * the full agent meta, because buildAgentMeta fills a missing `tools`/`model`
55
+ * with its own generic default — an entry that omits them would quietly
56
+ * downgrade marcus from opus to sonnet on the next brief generation.
57
+ */
58
+ export function buildDefaultRoles(): Record<string, Record<string, unknown>> {
59
+ const roles: Record<string, Record<string, unknown>> = {};
60
+
61
+ for (const [name, meta] of Object.entries(DEFAULT_AGENT_META)) {
62
+ roles[name] = {
63
+ brief: `.claude/agents/${name}.md`,
64
+ ...(meta.isolation ? { isolation: meta.isolation } : {}),
65
+ standardTask: standardTaskFor(name, meta.description),
66
+ description: meta.description,
67
+ tools: meta.tools,
68
+ model: meta.model,
69
+ ...(meta.tiers ? { tiers: meta.tiers } : {}),
70
+ ...(meta.memory ? { memory: meta.memory } : {}),
71
+ ...(meta.maxTurns ? { maxTurns: meta.maxTurns } : {}),
72
+ ...(meta.effort ? { effort: meta.effort } : {}),
73
+ ...(meta.disallowedTools ? { disallowedTools: meta.disallowedTools } : {}),
74
+ ...(meta.omitClaudeMd ? { omitClaudeMd: meta.omitClaudeMd } : {}),
75
+ };
76
+ }
77
+
78
+ return roles;
79
+ }
80
+
81
+ /**
82
+ * Hook registrations a greenfield `.claude/rungate/hooks.json` is written with.
83
+ *
84
+ * Curated rather than "every file in hooks/": each entry below names a hook
85
+ * implementation that ships with the harness AND is meaningful in a project
86
+ * that has no specs, no issue tracker wiring and no gates configured yet.
87
+ * Spec- and issue-coupled hooks (SpecSCGuard, IssueCloseGuard, MergeGuard, …)
88
+ * are left for a project to opt into once it has the thing they guard.
89
+ *
90
+ * `${RUNGATE_HOOKS_DIR}` stays unexpanded on disk — deployHooksToConsumers
91
+ * resolves it at deploy time, so the file survives the harness moving.
92
+ */
93
+ export function buildDefaultHooks(): HookRegistration[] {
94
+ return [
95
+ {
96
+ name: "BashToolGuard",
97
+ hookFor: "PreToolUse",
98
+ command: "bun ${RUNGATE_HOOKS_DIR}/BashToolGuard.hook.ts",
99
+ enabled: true,
100
+ matcher: "Bash",
101
+ description: "Blocks cat/head/tail file reading — agents must use the Read tool",
102
+ },
103
+ {
104
+ name: "TestSuiteGuard",
105
+ hookFor: "PreToolUse",
106
+ command: "bun ${RUNGATE_HOOKS_DIR}/TestSuiteGuard.hook.ts",
107
+ enabled: true,
108
+ matcher: "Bash",
109
+ description: "Blocks a third full test suite run in one session — forces targeted tests",
110
+ },
111
+ {
112
+ name: "AgentBriefGuard",
113
+ hookFor: "PreToolUse",
114
+ command: "bun ${RUNGATE_HOOKS_DIR}/AgentBriefGuard.hook.ts",
115
+ enabled: true,
116
+ matcher: "Agent",
117
+ description: "Validates agent brief templates and enforces the ship-active marker",
118
+ },
119
+ {
120
+ name: "AgentVerdictCapture",
121
+ hookFor: "SubagentStop",
122
+ command: "bun ${RUNGATE_HOOKS_DIR}/AgentVerdictCapture.hook.ts",
123
+ enabled: true,
124
+ description: "Captures agent verdicts and writes them to workflow-state.json",
125
+ },
126
+ {
127
+ name: "AutoVerifyGate",
128
+ hookFor: "PostToolUse",
129
+ command: "bun ${RUNGATE_HOOKS_DIR}/AutoVerifyGate.hook.ts",
130
+ enabled: true,
131
+ matcher: "Agent",
132
+ description: "Nudges the DA to run the verify gate after an agent completes",
133
+ },
134
+ {
135
+ name: "CommitEnforcement",
136
+ hookFor: "PostToolUse",
137
+ command: "bun ${RUNGATE_HOOKS_DIR}/CommitEnforcement.hook.ts",
138
+ enabled: true,
139
+ matcher: "Agent",
140
+ description: "Detects uncommitted changes left behind in agent worktrees",
141
+ },
142
+ {
143
+ name: "GateEnforcement",
144
+ hookFor: "PreToolUse",
145
+ command: "bun ${RUNGATE_HOOKS_DIR}/GateEnforcement.hook.ts",
146
+ enabled: true,
147
+ matcher: ".*",
148
+ description: "Nags on gate failures and blocks Skill calls after max strikes",
149
+ },
150
+ {
151
+ name: "PostCompact",
152
+ hookFor: "PostCompact",
153
+ command: "bun ${RUNGATE_HOOKS_DIR}/PostCompact.hook.ts",
154
+ enabled: true,
155
+ description: "Re-injects critical rules after context window compaction",
156
+ },
157
+ {
158
+ name: "StaleTTLCleanup",
159
+ hookFor: "SessionStart",
160
+ command: "bun ${RUNGATE_HOOKS_DIR}/StaleTTLCleanup.hook.ts",
161
+ enabled: true,
162
+ description: "Cleans up stale workflow-state.json and ship-active files",
163
+ },
164
+ ];
165
+ }