rungate 0.2.1 → 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 (119) 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 +24 -2
  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
@@ -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
  }