rungate 0.2.1 → 0.4.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 (129) 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/brief-precedence.ts +114 -0
  11. package/lib/canary.ts +117 -0
  12. package/lib/check-registry.ts +226 -0
  13. package/lib/ci-checkout.ts +426 -0
  14. package/lib/cli-commands.ts +137 -0
  15. package/lib/compliance-backfill.ts +232 -0
  16. package/lib/compliance-report.ts +605 -0
  17. package/lib/compliance.ts +361 -0
  18. package/lib/config-loader.ts +255 -0
  19. package/lib/config-readers.ts +86 -0
  20. package/lib/conformity.ts +2161 -137
  21. package/lib/container-provenance.ts +230 -0
  22. package/lib/create-brief.ts +150 -0
  23. package/lib/create-sc.ts +267 -0
  24. package/lib/decomposition-waves.ts +197 -0
  25. package/lib/deep-merge.ts +69 -0
  26. package/lib/dev-liveness.ts +214 -0
  27. package/lib/directive-extractor.ts +210 -0
  28. package/lib/distribution-standing.ts +113 -0
  29. package/lib/doc-hygiene.ts +238 -0
  30. package/lib/eval-criteria.ts +6 -0
  31. package/lib/evidence-portability.ts +123 -0
  32. package/lib/evidence-prevalidator.ts +390 -0
  33. package/lib/evidence-required.ts +150 -0
  34. package/lib/evidence-satisfiability.ts +288 -0
  35. package/lib/frontmatter.ts +163 -0
  36. package/lib/gap-scanner.ts +348 -0
  37. package/lib/gate-check-audit.ts +190 -0
  38. package/lib/gate-enforcement.ts +366 -0
  39. package/lib/generators/agent-briefs.ts +136 -0
  40. package/lib/generators/agents-md.ts +511 -0
  41. package/lib/generators/code-map.ts +60 -0
  42. package/lib/generators/types.ts +184 -0
  43. package/lib/git-ref-normalizer.ts +107 -0
  44. package/lib/github.ts +539 -0
  45. package/lib/harness-identity.ts +63 -0
  46. package/lib/hill-climb.ts +164 -0
  47. package/lib/instruction-effectiveness.ts +131 -0
  48. package/lib/issue-closure-audit.ts +225 -0
  49. package/lib/issue-create-override.ts +343 -0
  50. package/lib/issue-extraction.ts +368 -0
  51. package/lib/js-top-level-code.ts +250 -0
  52. package/lib/liveness-contradiction.ts +149 -0
  53. package/lib/organize.ts +505 -0
  54. package/lib/paths.ts +197 -6
  55. package/lib/phase2-decomposition.ts +270 -0
  56. package/lib/post-fix-verify.ts +157 -0
  57. package/lib/prior-branch.ts +512 -0
  58. package/lib/project-state-shape.ts +166 -0
  59. package/lib/promote-outputs.ts +156 -0
  60. package/lib/prove-label-gate.ts +128 -0
  61. package/lib/reachability.ts +302 -0
  62. package/lib/release-preflight.ts +288 -0
  63. package/lib/rule-health-pipeline.ts +264 -0
  64. package/lib/rule-health-trend.ts +161 -0
  65. package/lib/rule-provenance.ts +149 -0
  66. package/lib/rule-registry.ts +128 -0
  67. package/lib/rungate-schema.ts +127 -5
  68. package/lib/sc-claim-forms.ts +179 -0
  69. package/lib/sc-cover.ts +150 -0
  70. package/lib/sc-guard.ts +157 -0
  71. package/lib/sc-ids.ts +344 -0
  72. package/lib/scaffold/defaults.ts +165 -0
  73. package/lib/scaffold/managed-workflow.ts +370 -0
  74. package/lib/scaffold/owned-files.ts +265 -0
  75. package/lib/scaffold/pre-push-hook.ts +165 -0
  76. package/lib/scaffold/steps.ts +2621 -0
  77. package/lib/scanner.ts +701 -0
  78. package/lib/scope-denylist.ts +258 -0
  79. package/lib/screenshot-upload.ts +73 -0
  80. package/lib/secret-patterns.ts +112 -0
  81. package/lib/security-verdict.ts +616 -0
  82. package/lib/signal-phrases.ts +1 -0
  83. package/lib/spec-change-conformity.ts +80 -0
  84. package/lib/spec-files.ts +62 -0
  85. package/lib/spec-registry.ts +133 -0
  86. package/lib/spec-updater.ts +96 -0
  87. package/lib/stale-cleanup.ts +224 -0
  88. package/lib/stale-issue-scanner.ts +36 -0
  89. package/lib/strip-js-comments.ts +269 -0
  90. package/lib/suite-measurement.ts +228 -0
  91. package/lib/task-completion-checks.ts +224 -0
  92. package/lib/test-suite-lock.ts +1136 -0
  93. package/lib/transcript-checker.ts +1140 -0
  94. package/lib/typescript-project.ts +233 -0
  95. package/lib/validators/spec-validators.ts +171 -0
  96. package/lib/verdict-capture.ts +73 -0
  97. package/lib/verified-push.ts +535 -0
  98. package/lib/workflow-security.ts +174 -0
  99. package/lib/worktree-cleanup.ts +432 -0
  100. package/lib/worktree-collect.ts +283 -0
  101. package/lib/worktree-isolation.ts +82 -0
  102. package/lib/worktree-repo.ts +300 -0
  103. package/package.json +27 -3
  104. package/prompts/ac-adversary.md +14 -2
  105. package/prompts/aditi.md +5 -0
  106. package/prompts/blast-radius.md +5 -0
  107. package/prompts/container-verify.md +5 -0
  108. package/prompts/discovery.md +4 -0
  109. package/prompts/environment.md +5 -0
  110. package/prompts/evidence-hierarchy.md +5 -0
  111. package/prompts/evidence-validator.md +11 -0
  112. package/prompts/marcus.md +5 -0
  113. package/prompts/prevention.md +5 -0
  114. package/prompts/prove-reproducer.md +12 -0
  115. package/prompts/quinn-decision-tree.md +5 -0
  116. package/prompts/quinn-ui-brief.md +5 -0
  117. package/prompts/quinn.md +5 -0
  118. package/prompts/rca.md +5 -0
  119. package/prompts/read-before-write.md +4 -0
  120. package/prompts/regression.md +5 -0
  121. package/prompts/serena.md +5 -0
  122. package/scripts/audit-specs.ts +464 -0
  123. package/scripts/convert-spec.ts +293 -0
  124. package/scripts/create-sc.ts +92 -0
  125. package/scripts/create-spec.ts +166 -0
  126. package/scripts/extract-constraints.ts +4 -3
  127. package/scripts/generate-code-map.ts +1 -1
  128. package/scripts/scaffold-project.ts +138 -1426
  129. package/scripts/sync-spec-tests.ts +211 -126
@@ -0,0 +1,233 @@
1
+ /**
2
+ * One fact, one decider: "is this a TypeScript project, and what type-checks it?" (#87)
3
+ *
4
+ * Four places answered the first question and three answered the second, and
5
+ * they disagreed — which is the whole of #87:
6
+ *
7
+ * | Site | Asked | Answered |
8
+ * |---|---|---|
9
+ * | `createTsconfig` | is there TypeScript source? | skip the tsconfig if not |
10
+ * | `createCiWorkflows` | is there a tsconfig? | skip the CI step if not |
11
+ * | `generateAgentsMd` | is there a tsconfig? | skip the doc row if not |
12
+ * | `scanProject` → `dev.typeCheck` | nothing | `bunx tsc --noEmit`, always |
13
+ * | `runTsconfigValidation` (TSC-1) | nothing | the tsconfig MUST exist |
14
+ *
15
+ * So a consumer with no TypeScript source got no tsconfig from the generator
16
+ * that decided it did not need one, no CI step and no doc row from the two
17
+ * that agreed — and then a conformity suite that hard-failed TSC-1 over the
18
+ * absent file, plus a `dev.typeCheck` of `bunx tsc --noEmit` written into its
19
+ * config, which `gates/gate-executor.ts` runs. Without a tsconfig tsc prints
20
+ * 147 lines of help text and exits 1, so that is #65/#76 reintroduced in the
21
+ * one place #65/#76 never looked.
22
+ *
23
+ * THE DECISION #87 ASKED FOR
24
+ *
25
+ * > Either consumers are allowed to be non-TypeScript projects (then TSC-1
26
+ * > must become conditional or a warning), or they are not (then the scaffold
27
+ * > should generate a tsconfig and TSC-1 is right). Pick one; today both are
28
+ * > asserted.
29
+ *
30
+ * Consumers ARE allowed to be non-TypeScript projects. Two generators had
31
+ * already voted that way and shipped, and writing a tsconfig into a project
32
+ * with no TypeScript in it produces `include: []` — tsc error TS18003, a type
33
+ * check that reads as broken rather than as "nothing to check". So TSC-1
34
+ * becomes conditional on the predicate `createTsconfig` already used, and the
35
+ * conditional arm RECORDS why it did not measure instead of passing quietly:
36
+ * `.claude/rules/config-access.md` calls the silent form out by name, and a
37
+ * check that cannot fail is indistinguishable from a check that is satisfied.
38
+ *
39
+ * WHY THE COMMAND LIVES HERE TOO
40
+ *
41
+ * `typecheckDecision` exists because the three command sites were a worse
42
+ * version of the same problem: they agreed on the question and still produced
43
+ * different answers, and one of their branches was unreachable. `files:` in
44
+ * package.json ships neither `scripts/typecheck.ts` nor `tsconfig.json`, so no
45
+ * consumer could ever land on the ratchet branch — it was dead code that read
46
+ * as a supported configuration. A consumer's own `package.json` `scripts.
47
+ * typecheck` is checked first, which is the escape hatch that was missing: the
48
+ * ratchet is reachable by any project that writes one, and a project with a
49
+ * tsconfig full of pre-existing errors is no longer handed a CI step that can
50
+ * only be red over a generated file it is told not to edit.
51
+ */
52
+
53
+ import { existsSync, readdirSync, readFileSync } from "fs";
54
+ import { join } from "path";
55
+
56
+ /**
57
+ * Where a consumer keeps hand-written TypeScript.
58
+ *
59
+ * The scanner's source directories plus `scripts/` — a consumer keeps real
60
+ * TypeScript there and nothing else would check it.
61
+ *
62
+ * `test/` is deliberately absent. The conformity test rungate generates into
63
+ * every consumer imports `bun:test` and `rungate/lib/conformity`, and neither
64
+ * resolves for tsc without `@types/bun` and an installed `rungate` — so
65
+ * including the test tree would hand a freshly scaffolded project a type check
66
+ * that reports 4 errors it did not cause and cannot fix. That is the #65/#76
67
+ * defect again in the other direction: a documented command whose result says
68
+ * nothing about the project's code.
69
+ */
70
+ export const TS_SOURCE_DIRS = ["src", "lib", "scripts", "gates", "hooks", "workflows"] as const;
71
+
72
+ /** True when `dir` holds at least one hand-written .ts/.tsx file. */
73
+ export function containsTypeScript(dir: string): boolean {
74
+ let stack = [dir];
75
+ while (stack.length > 0) {
76
+ const current = stack.pop()!;
77
+ let entries;
78
+ try {
79
+ entries = readdirSync(current, { withFileTypes: true });
80
+ } catch {
81
+ continue;
82
+ }
83
+ for (const entry of entries) {
84
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
85
+ if (entry.isDirectory()) {
86
+ stack.push(join(current, entry.name));
87
+ } else if (/\.tsx?$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
88
+ return true;
89
+ }
90
+ }
91
+ }
92
+ return false;
93
+ }
94
+
95
+ /**
96
+ * The source directories that actually hold TypeScript, in TS_SOURCE_DIRS order.
97
+ *
98
+ * The include list and the "is this a TypeScript project" test are the same
99
+ * question, answered once. Deriving them separately is how you get a tsconfig
100
+ * whose include matches no files — tsc error TS18003, which reads as a broken
101
+ * type check rather than as "nothing to check".
102
+ */
103
+ export function typeScriptSourceDirs(root: string): string[] {
104
+ return TS_SOURCE_DIRS.filter(dir => containsTypeScript(join(root, dir)));
105
+ }
106
+
107
+ /** True when the project has hand-written TypeScript anywhere a type check would look. */
108
+ export function isTypeScriptProject(root: string): boolean {
109
+ return typeScriptSourceDirs(root).length > 0;
110
+ }
111
+
112
+ export interface TsconfigVerdict {
113
+ /** Does this project need a tsconfig.json at all? */
114
+ applicable: boolean;
115
+ /** Is one there? */
116
+ present: boolean;
117
+ /** The source directories that made it applicable — empty when it is not. */
118
+ dirs: string[];
119
+ /** Why, in the words the finding and the failure message both use. */
120
+ reason: string;
121
+ }
122
+
123
+ /**
124
+ * Whether TSC-1 has anything to assert, and why.
125
+ *
126
+ * Never returns a bare boolean: a check that skips has to be able to say what
127
+ * it skipped over, or its silence is indistinguishable from a pass.
128
+ */
129
+ export function tsconfigVerdict(root: string): TsconfigVerdict {
130
+ const dirs = typeScriptSourceDirs(root);
131
+ const present = existsSync(join(root, "tsconfig.json"));
132
+ const applicable = dirs.length > 0;
133
+
134
+ if (!applicable) {
135
+ return {
136
+ applicable,
137
+ present,
138
+ dirs,
139
+ reason:
140
+ `NOT APPLICABLE: no hand-written TypeScript in ${TS_SOURCE_DIRS.join("/, ")}/, ` +
141
+ `so no tsconfig.json is required and the scaffold did not write one (#87)`,
142
+ };
143
+ }
144
+ if (!present) {
145
+ return {
146
+ applicable,
147
+ present,
148
+ dirs,
149
+ reason:
150
+ `TypeScript source in ${dirs.join("/, ")}/ and no tsconfig.json — ` +
151
+ `\`bunx tsc --noEmit\` would print its help text and exit 1 (#65/#76). ` +
152
+ `Run \`bunx rungate scaffold .\` to create one`,
153
+ };
154
+ }
155
+ return {
156
+ applicable,
157
+ present,
158
+ dirs,
159
+ reason: `tsconfig.json is present and ${dirs.length} source director${dirs.length === 1 ? "y" : "ies"} need it`,
160
+ };
161
+ }
162
+
163
+ /** Where the type-check command came from. `none` means there is nothing to run. */
164
+ export type TypecheckSource = "package-script" | "ratchet" | "tsc" | "none";
165
+
166
+ export interface TypecheckDecision {
167
+ /** The shell command, or null when the project has nothing to type-check. */
168
+ command: string | null;
169
+ source: TypecheckSource;
170
+ /** Why this command and not another. Carried into the generated comment. */
171
+ reason: string;
172
+ }
173
+
174
+ /**
175
+ * The one type-check command for a project — CI step, AGENTS.md row and
176
+ * `dev.typeCheck` all read this.
177
+ *
178
+ * Order matters and each step earns its place:
179
+ *
180
+ * 1. **No tsconfig → no command.** Not a default, an absence. `bunx tsc
181
+ * --noEmit` without one prints help and exits 1, and three of the four
182
+ * former call sites had already learned that separately.
183
+ * 2. **The project's own `scripts.typecheck`.** A project that has thought
184
+ * about its type check has said so in package.json; overriding that with a
185
+ * guess is the thing `scanProject` was doing wrong in the other direction.
186
+ * This is also what makes the ratchet form reachable at all — `files:`
187
+ * ships neither `scripts/typecheck.ts` nor `tsconfig.json`, so a consumer
188
+ * gets a ratchet only by writing one, and then only this branch sees it.
189
+ * 3. **`scripts/typecheck.ts` on disk.** How the harness itself and anyone who
190
+ * copied its ratchet is served when package.json does not mention it.
191
+ * 4. **Plain `bunx tsc --noEmit`.** Honest for a project with a clean tree.
192
+ */
193
+ export function typecheckDecision(root: string): TypecheckDecision {
194
+ if (!existsSync(join(root, "tsconfig.json"))) {
195
+ return {
196
+ command: null,
197
+ source: "none",
198
+ reason: "no tsconfig.json — tsc would print its help text and check nothing (#65/#76)",
199
+ };
200
+ }
201
+
202
+ const pkgPath = join(root, "package.json");
203
+ if (existsSync(pkgPath)) {
204
+ try {
205
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
206
+ if (typeof pkg?.scripts?.typecheck === "string" && pkg.scripts.typecheck.trim() !== "") {
207
+ return {
208
+ command: "bun run typecheck",
209
+ source: "package-script",
210
+ reason: "the project declares its own `typecheck` script, which beats anything inferred",
211
+ };
212
+ }
213
+ } catch {
214
+ // An unreadable package.json is not a reason to lose the type check. The
215
+ // two branches below need no package.json at all, and `createTsconfig`'s
216
+ // neighbours already shrug at this rather than killing the scaffold (#380).
217
+ }
218
+ }
219
+
220
+ if (existsSync(join(root, "scripts", "typecheck.ts"))) {
221
+ return {
222
+ command: "bun scripts/typecheck.ts",
223
+ source: "ratchet",
224
+ reason: "the project has a ratchet script, which fails in both directions",
225
+ };
226
+ }
227
+
228
+ return {
229
+ command: "bunx tsc --noEmit",
230
+ source: "tsc",
231
+ reason: "a tsconfig.json exists and the project declares no type-check script of its own",
232
+ };
233
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * spec-validators.ts — Spec validation functions extracted from scaffold-project.ts
3
+ *
4
+ * Handles frontmatter injection, oversized spec detection, and governs alignment checks.
5
+ * All functions take a directory path and an actions array for reporting.
6
+ */
7
+ import { existsSync, readFileSync, writeFileSync, readdirSync } from "fs";
8
+ import { join } from "path";
9
+
10
+ /**
11
+ * SC-278: Detect specs that exceed 500 lines and suggest splitting.
12
+ */
13
+ export function detectOversizedSpecs(specsDir: string, actions: string[]): void {
14
+ if (!existsSync(specsDir)) return;
15
+ for (const file of new Bun.Glob("**/*.md").scanSync({ cwd: specsDir, absolute: false })) {
16
+ const content = readFileSync(join(specsDir, file), "utf-8");
17
+ const lineCount = content.split("\n").length;
18
+ if (lineCount > 500) {
19
+ actions.push(`WARN: specs/${file} is ${lineCount} lines (>500) — consider splitting with \`bun scripts/split-spec.ts specs/${file}\``);
20
+ }
21
+ }
22
+ }
23
+
24
+ /**
25
+ * SC-279: Check that spec content aligns with its governs field.
26
+ * Warns when a spec has too many H2 sections relative to its governs scope.
27
+ */
28
+ export function checkGovernsAlignment(specsDir: string, actions: string[]): void {
29
+ if (!existsSync(specsDir)) return;
30
+ for (const file of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
31
+ const content = readFileSync(join(specsDir, file), "utf-8");
32
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
33
+ if (!fmMatch) continue;
34
+ const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
35
+ if (!gMatch || gMatch[1].trim().startsWith("TODO")) continue;
36
+ // Check if the file has multiple unrelated H2 sections that don't match governs
37
+ const h2s = content.match(/^## .+/gm) || [];
38
+ if (h2s.length > 8) {
39
+ actions.push(`WARN: specs/${file} has ${h2s.length} sections — may cover more than its governs ("${gMatch[1].trim().slice(0, 60)}"). Consider splitting.`);
40
+ }
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Add or complete frontmatter on spec files.
46
+ * Injects doc-type, testable, governs fields if missing.
47
+ * When opts.fix is false, reports gaps without modifying files.
48
+ */
49
+ export function addFrontmatterToSpecs(specsDir: string, actions: string[], opts?: { fix?: boolean }): void {
50
+ if (!existsSync(specsDir)) return;
51
+
52
+ const fixMode = opts?.fix ?? true;
53
+ const today = new Date().toISOString().split("T")[0];
54
+
55
+ for (const file of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
56
+ const filePath = join(specsDir, file);
57
+ const content = readFileSync(filePath, "utf-8");
58
+
59
+ if (!content.startsWith("---\n")) {
60
+ if (fixMode) {
61
+ const frontmatter = `---\ndoc-type: spec\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\ngoverns: TODO — describe what this spec governs\ntestable: false\n---\n\n`;
62
+ writeFileSync(filePath, frontmatter + content);
63
+ actions.push(`UPDATED: specs/${file} (added frontmatter)`);
64
+ } else {
65
+ actions.push(`GAP: specs/${file} missing frontmatter — run with --fix to add`);
66
+ }
67
+ } else {
68
+ // Validate existing frontmatter has required fields
69
+ const fmEnd = content.indexOf("\n---", 4);
70
+ if (fmEnd === -1) continue;
71
+ const fm = content.substring(4, fmEnd);
72
+ const missing: string[] = [];
73
+ if (!fm.includes("testable:")) missing.push(`testable: false`);
74
+ if (!fm.includes("created:")) missing.push(`created: ${today}`);
75
+ if (!fm.includes("governs:")) missing.push(`governs: TODO`);
76
+ if (missing.length > 0) {
77
+ if (fixMode) {
78
+ const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
79
+ writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
80
+ actions.push(`UPDATED: specs/${file} (added missing frontmatter fields: ${missing.map(m => m.split(":")[0]).join(", ")})`);
81
+ } else {
82
+ actions.push(`GAP: specs/${file} missing fields: ${missing.map(m => m.split(":")[0]).join(", ")} — run with --fix to add`);
83
+ }
84
+ }
85
+ // SC-269: WARN for specs with missing or TODO governs
86
+ const governsMatch = fm.match(/governs:\s*(.+)/);
87
+ if (!governsMatch || governsMatch[1].trim() === "TODO" || governsMatch[1].trim().startsWith("TODO")) {
88
+ actions.push(`WARN: specs/${file} has no governs: field (or governs: TODO) — add a one-line description of what this spec governs`);
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Issue #41: Detect spec files in docs/specs/ and suggest migration to specs/.
96
+ * Takes a project root (not specs dir) since it needs to check docs/specs/.
97
+ */
98
+ export function detectMisplacedSpecs(projectRoot: string, actions: string[]): void {
99
+ const docsSpecsDir = join(projectRoot, "docs", "specs");
100
+ if (!existsSync(docsSpecsDir)) return;
101
+ const specFiles = readdirSync(docsSpecsDir).filter(f => f.endsWith(".md"));
102
+ if (specFiles.length === 0) return;
103
+ for (const file of specFiles) {
104
+ actions.push(
105
+ `WARN: docs/specs/${file} should be in specs/ — run \`bun scripts/migrate-specs.ts .\` to migrate`
106
+ );
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Issue #41: Detect specs in specs/ that lack SC checkbox lines and suggest conversion.
112
+ */
113
+ export function detectUnconvertedSpecs(specsDir: string, actions: string[]): void {
114
+ if (!existsSync(specsDir)) return;
115
+ for (const file of readdirSync(specsDir).filter(f => f.endsWith(".md") && f !== "SPEC-TEMPLATE.md")) {
116
+ const content = readFileSync(join(specsDir, file), "utf-8");
117
+ // Check if this spec has frontmatter with testable field
118
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
119
+ if (!fmMatch) continue;
120
+ // Check if file has any SC checkbox lines
121
+ const hasSCLines = /^- \[[ x]\] SC-\d+:/m.test(content);
122
+ if (!hasSCLines) {
123
+ actions.push(
124
+ `WARN: specs/${file} has no SC checkboxes — run \`bun scripts/convert-spec.ts specs/${file}\` to convert`
125
+ );
126
+ }
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Add or complete frontmatter on ADR files.
132
+ * Injects doc-type, created fields if missing.
133
+ * When opts.fix is false, reports gaps without modifying files.
134
+ */
135
+ export function addFrontmatterToAdrs(adrDir: string, actions: string[], opts?: { fix?: boolean }): void {
136
+ if (!existsSync(adrDir)) return;
137
+
138
+ const fixMode = opts?.fix ?? true;
139
+ const today = new Date().toISOString().split("T")[0];
140
+
141
+ for (const file of readdirSync(adrDir).filter(f => f.endsWith(".md"))) {
142
+ const filePath = join(adrDir, file);
143
+ const content = readFileSync(filePath, "utf-8");
144
+
145
+ if (!content.startsWith("---\n")) {
146
+ if (fixMode) {
147
+ const frontmatter = `---\ndoc-type: adr\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\n---\n\n`;
148
+ writeFileSync(filePath, frontmatter + content);
149
+ actions.push(`UPDATED: docs/adr/${file} (added frontmatter)`);
150
+ } else {
151
+ actions.push(`GAP: docs/adr/${file} missing frontmatter — run with --fix to add`);
152
+ }
153
+ } else {
154
+ const fmEnd = content.indexOf("\n---", 4);
155
+ if (fmEnd === -1) continue;
156
+ const fm = content.substring(4, fmEnd);
157
+ const missing: string[] = [];
158
+ if (!fm.includes("doc-type:")) missing.push(`doc-type: adr`);
159
+ if (!fm.includes("created:")) missing.push(`created: ${today}`);
160
+ if (missing.length > 0) {
161
+ if (fixMode) {
162
+ const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
163
+ writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
164
+ actions.push(`UPDATED: docs/adr/${file} (added missing: ${missing.map(m => m.split(":")[0]).join(", ")})`);
165
+ } else {
166
+ actions.push(`GAP: docs/adr/${file} missing fields: ${missing.map(m => m.split(":")[0]).join(", ")} — run with --fix to add`);
167
+ }
168
+ }
169
+ }
170
+ }
171
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Verdict capture logic — extracted from AgentVerdictCapture.hook.ts
3
+ *
4
+ * Deep module: contains workflow discovery and verdict parsing.
5
+ * The hook file is a thin trigger that delegates here.
6
+ *
7
+ * Issue: #544
8
+ */
9
+
10
+ import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
11
+ import { join } from 'path';
12
+
13
+ export interface ActiveWorkflow {
14
+ path: string;
15
+ data: any;
16
+ }
17
+
18
+ /**
19
+ * Find the most recently modified active workflow-state.json.
20
+ * Scans 1 and 2 levels deep under workDir for BUILD/VERIFY/SHIP phases.
21
+ */
22
+ export function findActiveWorkflow(workDir: string): ActiveWorkflow | null {
23
+ if (!existsSync(workDir)) return null;
24
+ let best: { path: string; data: any; mtime: number } | null = null;
25
+
26
+ try {
27
+ for (const entry of readdirSync(workDir, { withFileTypes: true })) {
28
+ if (!entry.isDirectory()) continue;
29
+ // Level 1
30
+ const wfPath = join(workDir, entry.name, 'workflow-state.json');
31
+ if (existsSync(wfPath)) {
32
+ try {
33
+ const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
34
+ if (['BUILD', 'VERIFY', 'SHIP'].includes(data.phase)) {
35
+ const mtime = statSync(wfPath).mtimeMs;
36
+ if (!best || mtime > best.mtime) best = { path: wfPath, data, mtime };
37
+ }
38
+ } catch {}
39
+ }
40
+ // Level 2
41
+ try {
42
+ for (const sub of readdirSync(join(workDir, entry.name), { withFileTypes: true })) {
43
+ if (!sub.isDirectory()) continue;
44
+ const nestedWf = join(workDir, entry.name, sub.name, 'workflow-state.json');
45
+ if (!existsSync(nestedWf)) continue;
46
+ try {
47
+ const data = JSON.parse(readFileSync(nestedWf, 'utf-8'));
48
+ if (['BUILD', 'VERIFY', 'SHIP'].includes(data.phase)) {
49
+ const mtime = statSync(nestedWf).mtimeMs;
50
+ if (!best || mtime > best.mtime) best = { path: nestedWf, data, mtime };
51
+ }
52
+ } catch {}
53
+ }
54
+ } catch {}
55
+ }
56
+ } catch {}
57
+
58
+ return best ? { path: best.path, data: best.data } : null;
59
+ }
60
+
61
+ /**
62
+ * Extract a structured verdict block from agent output text.
63
+ * Looks for "## Verdict\n{...}" pattern.
64
+ */
65
+ export function extractVerdict(text: string): any | null {
66
+ const match = text.match(/## Verdict\n(\{[\s\S]*?\n\})/);
67
+ if (!match) return null;
68
+ try {
69
+ return JSON.parse(match[1]);
70
+ } catch {
71
+ return null;
72
+ }
73
+ }