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,293 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Convert freeform documents into RunGate spec format.
4
+ *
5
+ * Takes a file containing numbered rules, design guidelines, or requirements
6
+ * and converts it into a proper RunGate spec with frontmatter and SC checkboxes.
7
+ *
8
+ * Usage:
9
+ * bun scripts/convert-spec.ts <input-file> [options]
10
+ * bun scripts/convert-spec.ts rules.md # writes to specs/RULES-SPEC.md
11
+ * bun scripts/convert-spec.ts rules.md --dry-run # preview without writing
12
+ * bun scripts/convert-spec.ts rules.md --title "My Spec" # custom title
13
+ * bun scripts/convert-spec.ts rules.md --governs "input validation" # custom governs
14
+ */
15
+
16
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
17
+ import { join, basename, dirname } from "path";
18
+ import { SIGNAL_PHRASE_PATTERNS } from "../lib/signal-phrases";
19
+
20
+ // ── Argument parsing ──────────────────────────────────────────
21
+
22
+ const rawArgs = process.argv.slice(2);
23
+
24
+ let inputFile: string | undefined;
25
+ let dryRun = false;
26
+ let customTitle: string | undefined;
27
+ let customGoverns: string | undefined;
28
+ let projectRoot: string | undefined;
29
+
30
+ for (let i = 0; i < rawArgs.length; i++) {
31
+ const arg = rawArgs[i];
32
+ if (arg === "--dry-run") {
33
+ dryRun = true;
34
+ } else if (arg === "--title" && i + 1 < rawArgs.length) {
35
+ customTitle = rawArgs[++i];
36
+ } else if (arg === "--governs" && i + 1 < rawArgs.length) {
37
+ customGoverns = rawArgs[++i];
38
+ } else if (arg === "--project-root" && i + 1 < rawArgs.length) {
39
+ projectRoot = rawArgs[++i];
40
+ } else if (!inputFile) {
41
+ inputFile = arg;
42
+ }
43
+ }
44
+
45
+ if (!inputFile) {
46
+ console.error('Usage: bun scripts/convert-spec.ts <input-file> [--dry-run] [--title "Title"] [--governs "description"]');
47
+ process.exit(1);
48
+ }
49
+
50
+ if (!existsSync(inputFile)) {
51
+ console.error(`ERROR: Input file not found: ${inputFile}`);
52
+ process.exit(1);
53
+ }
54
+
55
+ // ── Rule extraction ───────────────────────────────────────────
56
+
57
+ interface ExtractedRule {
58
+ text: string;
59
+ testable: boolean;
60
+ source: "numbered" | "signal-phrase" | "bullet";
61
+ }
62
+
63
+ /**
64
+ * Determine whether a rule statement is mechanically testable.
65
+ *
66
+ * Testable rules contain actionable signal words (must, never, always, shall, required)
67
+ * and describe a concrete, verifiable behavior.
68
+ *
69
+ * Non-testable rules are subjective, vague, or advisory (should, think, consider, elegant).
70
+ */
71
+ function isTestable(text: string): boolean {
72
+ const lower = text.toLowerCase();
73
+
74
+ // Non-testable indicators: subjective or advisory language
75
+ const nonTestablePatterns = [
76
+ /\bshould\b/,
77
+ /\bthink\b/,
78
+ /\bconsider\b/,
79
+ /\belegant\b/,
80
+ /\breadable\b/,
81
+ /\bclean\b(?![\s-]*up)/, // "clean" as adjective, not "clean up"
82
+ /\bcareful(?:ly)?\b/,
83
+ /\bideally\b/,
84
+ /\bpreferable\b/,
85
+ /\bnice\b/,
86
+ /\bgood practice\b/,
87
+ /\bbest practice\b/,
88
+ /\btry to\b/,
89
+ /\baim to\b/,
90
+ /\bstrive\b/,
91
+ ];
92
+
93
+ // Testable indicators: mandatory/prohibitive language
94
+ const testablePatterns = [
95
+ /\bmust\b/,
96
+ /\bmust not\b/,
97
+ /\bnever\b/,
98
+ /\balways\b/,
99
+ /\bshall\b/,
100
+ /\brequired\b/,
101
+ /\bdo not\b/,
102
+ /\bprefer\b/,
103
+ /\beliminate\b/,
104
+ ];
105
+
106
+ const hasNonTestable = nonTestablePatterns.some((p) => p.test(lower));
107
+ const hasTestable = testablePatterns.some((p) => p.test(lower));
108
+
109
+ // If it has testable language, it's testable even if it also has non-testable words
110
+ if (hasTestable) return true;
111
+
112
+ // If it only has non-testable language, it's non-testable
113
+ if (hasNonTestable) return false;
114
+
115
+ // Default: numbered rules without signal phrases are potentially testable
116
+ // if they describe a concrete action
117
+ const concreteActionPatterns = [
118
+ /\brun\b/,
119
+ /\buse\b/,
120
+ /\bwrite\b/,
121
+ /\bcreate\b/,
122
+ /\btest\b/,
123
+ /\bvalidate\b/,
124
+ /\bcheck\b/,
125
+ /\breview\b/,
126
+ /\bensure\b/,
127
+ /\bimplement\b/,
128
+ /\breturn\b/,
129
+ /\binclude\b/,
130
+ /\bexport\b/,
131
+ /\bimport\b/,
132
+ /\blog\b/,
133
+ ];
134
+
135
+ return concreteActionPatterns.some((p) => p.test(lower));
136
+ }
137
+
138
+ /**
139
+ * Extract rules from freeform text.
140
+ *
141
+ * Detects:
142
+ * 1. Numbered rules: "1. Rule text"
143
+ * 2. Bullet rules with signal phrases: "- Must do X", "- Never do Y"
144
+ * 3. Signal phrase patterns from SIGNAL_PHRASE_PATTERNS
145
+ */
146
+ function extractRules(content: string): ExtractedRule[] {
147
+ const lines = content.split("\n");
148
+ const rules: ExtractedRule[] = [];
149
+ const seenTexts = new Set<string>();
150
+
151
+ const normalizeKey = (t: string) => t.toLowerCase().replace(/[.;,\s]+$/, "");
152
+
153
+ // Pass 1: Extract numbered rules
154
+ for (const line of lines) {
155
+ const numbered = line.match(/^\d+\.\s+(.+)$/);
156
+ if (numbered) {
157
+ const text = numbered[1].replace(/\*\*/g, "").trim();
158
+ if (text && !seenTexts.has(normalizeKey(text))) {
159
+ seenTexts.add(normalizeKey(text));
160
+ rules.push({
161
+ text,
162
+ testable: isTestable(text),
163
+ source: "numbered",
164
+ });
165
+ }
166
+ }
167
+ }
168
+
169
+ // Pass 2: Extract bullet items with signal phrases
170
+ for (const line of lines) {
171
+ const bullet = line.match(/^[-*]\s+(.+)$/);
172
+ if (bullet) {
173
+ const text = bullet[1].trim();
174
+ const lower = text.toLowerCase();
175
+ const hasSignal = /\b(must not|never|must|always|required|shall|prefer|eliminate|do not)\b/.test(lower);
176
+ if (hasSignal && !seenTexts.has(normalizeKey(text))) {
177
+ seenTexts.add(normalizeKey(text));
178
+ rules.push({
179
+ text,
180
+ testable: isTestable(text),
181
+ source: "bullet",
182
+ });
183
+ }
184
+ }
185
+ }
186
+
187
+ // Pass 3: Use SIGNAL_PHRASE_PATTERNS for any remaining matches
188
+ for (const pattern of SIGNAL_PHRASE_PATTERNS) {
189
+ const re = new RegExp(pattern.source, pattern.flags);
190
+ for (const m of content.matchAll(re)) {
191
+ const text = m[0]
192
+ .replace(/^[-*]\s+/, "")
193
+ .replace(/^\d+\.\s+/, "")
194
+ .replace(/\*\*/g, "")
195
+ .replace(/^[.;,\s]+/, "") // strip leading punctuation/whitespace
196
+ .trim()
197
+ .replace(/[.;]$/, "");
198
+ if (text && text.length >= 10 && !seenTexts.has(normalizeKey(text))) {
199
+ seenTexts.add(normalizeKey(text));
200
+ rules.push({
201
+ text,
202
+ testable: isTestable(text),
203
+ source: "signal-phrase",
204
+ });
205
+ }
206
+ }
207
+ }
208
+
209
+ return rules;
210
+ }
211
+
212
+ // ── Title derivation ──────────────────────────────────────────
213
+
214
+ function deriveTitle(filePath: string): string {
215
+ const name = basename(filePath, ".md")
216
+ .replace(/[-_]+/g, " ")
217
+ .replace(/\b\w/g, (c) => c.toUpperCase());
218
+ return name;
219
+ }
220
+
221
+ function deriveSlug(title: string): string {
222
+ return title.toUpperCase().replace(/[^A-Z0-9]+/g, "-").replace(/(^-|-$)/g, "");
223
+ }
224
+
225
+ // ── Spec generation ───────────────────────────────────────────
226
+
227
+ function generateSpec(rules: ExtractedRule[], title: string, governs: string): string {
228
+ const today = new Date().toISOString().split("T")[0];
229
+
230
+ // Build SC lines
231
+ const scLines = rules.map((rule, i) => {
232
+ const scId = `SC-${i + 1}`;
233
+ const annotation = rule.testable ? "" : " (non-testable)";
234
+ return `- [ ] ${scId}: ${rule.text}${annotation}`;
235
+ });
236
+
237
+ // If no rules were extracted, add a placeholder
238
+ if (scLines.length === 0) {
239
+ scLines.push("- [ ] SC-1: [first criterion -- atomic, verifiable, 8-12 words]");
240
+ }
241
+
242
+ return `---
243
+ doc-type: spec
244
+ status: draft
245
+ owner: TODO
246
+ created: ${today}
247
+ updated: ${today}
248
+ governs: ${governs}
249
+ testable: true
250
+ ---
251
+
252
+ # ${title}
253
+
254
+ ## Context
255
+
256
+ Converted from freeform document. Review and refine the success criteria below.
257
+
258
+ ## Success Criteria
259
+
260
+ ${scLines.join("\n")}
261
+ `;
262
+ }
263
+
264
+ // ── Main ──────────────────────────────────────────────────────
265
+
266
+ const content = readFileSync(inputFile, "utf-8");
267
+ const rules = extractRules(content);
268
+ const title = customTitle ?? deriveTitle(inputFile);
269
+ const governs = customGoverns ?? "TODO -- describe what this spec governs";
270
+ const specContent = generateSpec(rules, title, governs);
271
+
272
+ if (dryRun) {
273
+ process.stdout.write(specContent);
274
+ process.exit(0);
275
+ }
276
+
277
+ // Write to specs/ directory
278
+ const root = projectRoot ?? join(dirname(import.meta.dir), "");
279
+ const specsDir = join(root, "specs");
280
+ const slug = deriveSlug(title);
281
+ const filename = `${slug}-SPEC.md`;
282
+ const outputPath = join(specsDir, filename);
283
+
284
+ if (!existsSync(specsDir)) mkdirSync(specsDir, { recursive: true });
285
+
286
+ if (existsSync(outputPath)) {
287
+ console.error(`ERROR: ${filename} already exists`);
288
+ process.exit(1);
289
+ }
290
+
291
+ writeFileSync(outputPath, specContent);
292
+ console.log(`Created specs/${filename}`);
293
+ console.log(` ${rules.length} rules extracted (${rules.filter((r) => !r.testable).length} non-testable)`);
@@ -0,0 +1,92 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * create-sc CLI — Generate matchable SC lines from structured input.
4
+ *
5
+ * Usage:
6
+ * bun scripts/create-sc.ts --pattern file-exists --params '{"file":"AGENTS.md"}'
7
+ * bun scripts/create-sc.ts --pattern file-exists --params '{"file":"AGENTS.md"}' --spec specs/MY-SPEC.md
8
+ * bun scripts/create-sc.ts --list
9
+ *
10
+ * Thin CLI consumer — all logic lives in lib/create-sc.ts.
11
+ */
12
+ import { readFileSync, writeFileSync, existsSync } from "fs";
13
+ import {
14
+ generateSCText,
15
+ listPatterns,
16
+ nextSCNumber,
17
+ formatSCLine,
18
+ } from "../lib/create-sc";
19
+ import { readScRegistry } from "./sync-sc-status";
20
+
21
+ // ── Argument parsing ──────────────────────────────────────────
22
+
23
+ const args = process.argv.slice(2);
24
+
25
+ function getFlag(name: string): string | undefined {
26
+ const idx = args.indexOf(`--${name}`);
27
+ if (idx === -1 || idx + 1 >= args.length) return undefined;
28
+ return args[idx + 1];
29
+ }
30
+
31
+ function hasFlag(name: string): boolean {
32
+ return args.includes(`--${name}`);
33
+ }
34
+
35
+ // ── Main ──────────────────────────────────────────────────────
36
+
37
+ if (hasFlag("list")) {
38
+ console.log(listPatterns());
39
+ process.exit(0);
40
+ }
41
+
42
+ const patternName = getFlag("pattern");
43
+ if (!patternName) {
44
+ console.error("Usage: bun scripts/create-sc.ts --pattern <name> --params '<json>'");
45
+ console.error(" bun scripts/create-sc.ts --list");
46
+ process.exit(1);
47
+ }
48
+
49
+ // Parse params
50
+ const paramsRaw = getFlag("params");
51
+ let params: Record<string, string> = {};
52
+ if (paramsRaw) {
53
+ try {
54
+ params = JSON.parse(paramsRaw);
55
+ } catch {
56
+ console.error(`ERROR: Invalid JSON in --params: ${paramsRaw}`);
57
+ process.exit(1);
58
+ }
59
+ }
60
+
61
+ // Validate and generate
62
+ try {
63
+ const statement = generateSCText(patternName, params);
64
+ const specPath = getFlag("spec");
65
+
66
+ if (specPath) {
67
+ // Append to spec file
68
+ if (!existsSync(specPath)) {
69
+ console.error(`ERROR: Spec file not found: ${specPath}`);
70
+ process.exit(1);
71
+ }
72
+ const content = readFileSync(specPath, "utf-8");
73
+ // The whole namespace, not just this file: SC ids are global, and
74
+ // allocating from one spec's content is what produced ten collisions
75
+ // (#392). A spec outside specs/ still gets the local answer.
76
+ const scNumber = nextSCNumber(content, readScRegistry());
77
+ const scLine = formatSCLine(scNumber, statement);
78
+
79
+ // Append SC line to the end of the file
80
+ const newContent = content.trimEnd() + "\n" + scLine + "\n";
81
+ writeFileSync(specPath, newContent);
82
+ console.log(`Appended to ${specPath}: ${scLine}`);
83
+ } else {
84
+ // Output to stdout for piping
85
+ const scLine = formatSCLine(0, statement);
86
+ console.log(scLine);
87
+ }
88
+ } catch (err: unknown) {
89
+ const message = err instanceof Error ? err.message : String(err);
90
+ console.error(`ERROR: ${message}`);
91
+ process.exit(1);
92
+ }
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Create a new spec file with required frontmatter including governs.
4
+ *
5
+ * Usage:
6
+ * bun scripts/create-spec.ts "Title of the spec" "What this spec governs"
7
+ * bun scripts/create-spec.ts "Title of the spec" # governs defaults to TODO
8
+ * bun scripts/create-spec.ts "Title" "governs" --sc "AGENTS.md exists" --sc "specs/ directory exists"
9
+ *
10
+ * SC validation:
11
+ * --sc flags provide SC statements that are validated against matchPattern()
12
+ * before the spec is saved. Unmatched SCs block save with pattern suggestions.
13
+ * SCs tagged with (behavioral) bypass matchPattern validation.
14
+ */
15
+
16
+ import { existsSync, writeFileSync, mkdirSync } from "fs";
17
+ import { join } from "path";
18
+ import { isMatchablePattern, isBehavioralSC, type ParsedSC } from "../lib/conformity";
19
+ import { loadRegistry, type RegistryEntry } from "../lib/create-sc";
20
+
21
+ // ── Argument parsing ──────────────────────────────────────────
22
+
23
+ const rawArgs = process.argv.slice(2);
24
+
25
+ // Extract --sc and --project-root flags before positional args
26
+ const scStatements: string[] = [];
27
+ const positionalArgs: string[] = [];
28
+ let projectRoot: string | undefined;
29
+
30
+ for (let i = 0; i < rawArgs.length; i++) {
31
+ if (rawArgs[i] === "--sc" && i + 1 < rawArgs.length) {
32
+ scStatements.push(rawArgs[i + 1]);
33
+ i++; // skip the value
34
+ } else if (rawArgs[i] === "--project-root" && i + 1 < rawArgs.length) {
35
+ projectRoot = rawArgs[i + 1];
36
+ i++; // skip the value
37
+ } else {
38
+ positionalArgs.push(rawArgs[i]);
39
+ }
40
+ }
41
+
42
+ if (positionalArgs.length === 0) {
43
+ console.error('Usage: bun scripts/create-spec.ts "Title" ["governs description"] [--sc "SC statement"]...');
44
+ process.exit(1);
45
+ }
46
+
47
+ const title = positionalArgs[0];
48
+ const governs = positionalArgs[1] || "TODO — describe what this spec governs";
49
+ const slug = title.toUpperCase().replace(/[^A-Z0-9]+/g, "-").replace(/(^-|-$)/g, "");
50
+ const filename = `${slug}-SPEC.md`;
51
+ const root = projectRoot ?? join(import.meta.dir, "..");
52
+ const specsDir = join(root, "specs");
53
+ const filePath = join(specsDir, filename);
54
+
55
+ if (!existsSync(specsDir)) mkdirSync(specsDir, { recursive: true });
56
+
57
+ if (existsSync(filePath)) {
58
+ console.error(`ERROR: ${filename} already exists`);
59
+ process.exit(1);
60
+ }
61
+
62
+ // ── SC validation ─────────────────────────────────────────────
63
+
64
+ /**
65
+ * Find the closest matching patterns for an unmatched SC statement.
66
+ * Returns up to 3 pattern suggestions based on keyword overlap.
67
+ */
68
+ function suggestClosestPatterns(statement: string): RegistryEntry[] {
69
+ const registry = loadRegistry(projectRoot);
70
+ const words = statement.toLowerCase().split(/\s+/);
71
+
72
+ const scored = registry.map((entry) => {
73
+ const syntaxWords = entry.syntax.toLowerCase().split(/\s+/);
74
+ const exampleWords = entry.example.toLowerCase().split(/\s+/);
75
+ const allWords = [...syntaxWords, ...exampleWords, ...entry.name.split("-")];
76
+ const overlap = words.filter((w) => allWords.some((aw) => aw.includes(w) || w.includes(aw))).length;
77
+ return { entry, score: overlap };
78
+ });
79
+
80
+ return scored
81
+ .sort((a, b) => b.score - a.score)
82
+ .slice(0, 3)
83
+ .filter((s) => s.score > 0)
84
+ .map((s) => s.entry);
85
+ }
86
+
87
+ if (scStatements.length > 0) {
88
+ const failures: Array<{ statement: string; suggestions: RegistryEntry[] }> = [];
89
+
90
+ for (const statement of scStatements) {
91
+ const sc: ParsedSC = { id: "SC-DRAFT", statement, specFile: filename };
92
+
93
+ // Behavioral SCs bypass matchPattern validation
94
+ if (isBehavioralSC(sc)) {
95
+ continue;
96
+ }
97
+
98
+ // Validate against registry patterns (regex match only, no handler required)
99
+ if (!isMatchablePattern(sc, projectRoot)) {
100
+ const suggestions = suggestClosestPatterns(statement);
101
+ failures.push({ statement, suggestions });
102
+ }
103
+ }
104
+
105
+ if (failures.length > 0) {
106
+ console.error(`ERROR: ${failures.length} SC(s) do not match any pattern in matcher-registry.json:\n`);
107
+ for (const { statement, suggestions } of failures) {
108
+ console.error(` Unmatched: "${statement}"`);
109
+ if (suggestions.length > 0) {
110
+ console.error(` Closest matching patterns:`);
111
+ for (const s of suggestions) {
112
+ console.error(` - ${s.name}: ${s.syntax}`);
113
+ console.error(` Example: ${s.example}`);
114
+ }
115
+ }
116
+ console.error("");
117
+ }
118
+ console.error("Tip: Use `bun scripts/create-sc.ts --list` to see all available patterns.");
119
+ console.error(" Tag behavioral SCs with (behavioral) suffix to bypass validation.");
120
+ process.exit(1);
121
+ }
122
+ }
123
+
124
+ // ── Generate spec content ─────────────────────────────────────
125
+
126
+ const today = new Date().toISOString().split("T")[0];
127
+
128
+ // Build SC lines from validated --sc statements, or use placeholder
129
+ let scSection: string;
130
+ if (scStatements.length > 0) {
131
+ scSection = scStatements
132
+ .map((stmt, i) => `- [ ] SC-TODO-${i + 1}: ${stmt}`)
133
+ .join("\n");
134
+ } else {
135
+ scSection = "- [ ] SC-TODO: [first criterion — atomic, verifiable, 8-12 words]";
136
+ }
137
+
138
+ const content = `---
139
+ doc-type: spec
140
+ status: draft
141
+ owner: TODO
142
+ created: ${today}
143
+ updated: ${today}
144
+ governs: ${governs}
145
+ testable: true
146
+ compliance: strict
147
+ ---
148
+
149
+ # ${title}
150
+
151
+ ## Context
152
+
153
+ [Why this spec exists and what problem it solves]
154
+
155
+ ## Success Criteria
156
+
157
+ ${scSection}
158
+ `;
159
+
160
+ writeFileSync(filePath, content);
161
+ console.log(`Created specs/${filename}`);
162
+ if (governs.startsWith("TODO")) {
163
+ console.log(` governs: is TODO — update it before scaffolding`);
164
+ console.log(` Tip: describe what this spec governs in one line, e.g.:`);
165
+ console.log(` governs: API authentication flow — token issuance, refresh, and revocation`);
166
+ }
@@ -45,10 +45,11 @@ function surroundingContext(lines: string[], lineIdx: number): string {
45
45
  function collectScanTargets(projectPath: string): string[] {
46
46
  const targets: string[] = [];
47
47
 
48
- const rootFiles = ["ARCHITECTURE.md", "PRINCIPLES.md", "CONTRIBUTING.md", "CLAUDE.md"];
49
- for (const f of rootFiles) {
48
+ // Scan all root-level .md files (not just hardcoded names)
49
+ for (const f of readdirSync(projectPath)) {
50
+ if (!f.endsWith(".md")) continue;
50
51
  const p = join(projectPath, f);
51
- if (existsSync(p)) targets.push(p);
52
+ targets.push(p);
52
53
  }
53
54
 
54
55
  const docsDir = join(projectPath, "docs");
@@ -102,7 +102,7 @@ function scanDirectories(): DirSummary[] {
102
102
  try {
103
103
  if (!statSync(full).isDirectory()) continue;
104
104
  const files = readdirSync(full, { recursive: true }).map(String);
105
- const exts = new Set(files.map(f => f.split(".").pop()).filter(Boolean));
105
+ const exts = new Set(files.map(f => f.split(".").pop()).filter((e): e is string => Boolean(e)));
106
106
  dirs.push({ name: entry, fileCount: files.length, types: [...exts].slice(0, 5) });
107
107
  } catch {}
108
108
  }