rungate 0.4.0 → 0.4.1

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.
@@ -7,39 +7,12 @@
7
7
  * Orchestrator-only: calls scanner, passes data to generators, writes output.
8
8
  * All logic lives in lib/scaffold/steps.ts and lib/validators/spec-validators.ts.
9
9
  */
10
- import { existsSync, statSync, writeFileSync } from "fs";
11
- import { join, basename } from "path";
10
+ import { existsSync, statSync } from "fs";
11
+ import { basename } from "path";
12
12
  import { detectProjectType } from "../lib/scanner";
13
- import {
14
- safeDir,
15
- safeWrite,
16
- regenerateOwned,
17
- generateAgentsMdContent,
18
- refreshScopedRulesStep,
19
- refreshAgentsMd,
20
- updateSpecsTable,
21
- injectEnvironmentSection,
22
- generateConformityTest,
23
- generateAgentBriefsStep,
24
- generateOrAuditProjectHarness,
25
- generateCodeMapStep,
26
- copySpecTemplateIfEmpty,
27
- createGitignore,
28
- createTsconfig,
29
- generateProjectState,
30
- createClaudeMdBridge,
31
- createCiWorkflows,
32
- createGitHooks,
33
- deployHooksToConsumers,
34
- addPaiHarnessDevDep,
35
- runAuditSpecsFix,
36
- postScaffoldCommit,
37
- reportScaffoldActions,
38
- } from "../lib/scaffold/steps";
39
- import {
40
- addFrontmatterToSpecs, addFrontmatterToAdrs, detectOversizedSpecs,
41
- checkGovernsAlignment, detectMisplacedSpecs, detectUnconvertedSpecs,
42
- } from "../lib/validators/spec-validators";
13
+ import { reportScaffoldActions } from "../lib/scaffold/steps";
14
+ import { runScaffoldWriteSteps } from "../lib/scaffold/write-steps";
15
+ import { cloneForRehearsal, discardRehearsal, rehearsalNotice } from "../lib/scaffold/rehearsal";
43
16
  import type { ProjectType } from "../lib/generators/types";
44
17
 
45
18
  // ── CLI argument parsing ───────────────────────────────────────
@@ -82,115 +55,32 @@ const projectName = basename(projectPath);
82
55
  console.log(`Detected project type: ${projectType}`);
83
56
  console.log(`Project: ${projectName}`);
84
57
  console.log(`Path: ${projectPath}`);
85
- if (!fix) console.log(`Mode: audit (pass --fix to apply changes)`);
86
58
  console.log("---");
87
59
 
88
60
  if (fix) {
89
- // Phase 0: Security and directory setup
90
- createGitignore(projectPath, actions);
91
- safeDir(join(projectPath, "specs"), "specs", actions);
92
- safeDir(join(projectPath, "reference"), "reference", actions);
93
- safeDir(join(projectPath, ".github"), ".github", actions);
94
- safeDir(join(projectPath, ".github", "workflows"), ".github/workflows", actions);
95
- safeDir(join(projectPath, "scripts"), "scripts", actions);
96
- safeDir(join(projectPath, "docs"), "docs", actions);
97
- safeDir(join(projectPath, "docs", "adr"), "docs/adr", actions);
98
-
99
- const testDirName = existsSync(join(projectPath, "test")) ? "test" : "tests";
100
- safeDir(join(projectPath, testDirName), testDirName, actions);
101
-
102
- // Before Phase 0.5 and before createCiWorkflows on purpose (#72): both decide
103
- // whether to emit a type check by looking for tsconfig.json on disk.
104
- createTsconfig(projectPath, actions);
105
-
106
- // Phase 0.5: Generate AGENTS.md
107
- const agentsMd = generateAgentsMdContent(projectPath, projectType, actions);
108
- writeFileSync(join(projectPath, "AGENTS.md"), agentsMd);
109
- actions.push("REGENERATED: AGENTS.md");
110
- refreshAgentsMd(projectPath, projectType, actions);
111
- updateSpecsTable(join(projectPath, "AGENTS.md"), actions);
112
-
113
- // Phase 0.6: Create copilot instructions
114
- const copilotInstructions = `# Copilot Instructions\n\nRead [AGENTS.md](../AGENTS.md) for project context, key files, specs, and workflow.\n\nAll project knowledge lives in AGENTS.md. Start there.\n`;
115
- safeWrite(join(projectPath, ".github", "copilot-instructions.md"), copilotInstructions, ".github/copilot-instructions.md", actions);
116
-
117
- // Phase 0.7: regenerate the conformity test. Strategy passed, not looked up — the label carries the project's own test dir, which may not be `test/` (#208).
118
- regenerateOwned(join(projectPath, testDirName, "scaffold-conformity.test.ts"), generateConformityTest(projectPath), `${testDirName}/scaffold-conformity.test.ts`, actions, "regenerate");
119
- }
120
-
121
- // Validators always run — only write when --fix is passed
122
- addFrontmatterToSpecs(join(projectPath, "specs"), actions, { fix });
123
- addFrontmatterToAdrs(join(projectPath, "docs", "adr"), actions, { fix });
124
- detectOversizedSpecs(join(projectPath, "specs"), actions);
125
- checkGovernsAlignment(join(projectPath, "specs"), actions);
126
- detectMisplacedSpecs(projectPath, actions);
127
- detectUnconvertedSpecs(join(projectPath, "specs"), actions);
128
-
129
- if (fix) {
130
- // Phase 0.8: Workflow project setup
131
- if (projectType === "workflow") {
132
- const workflowDef = `---
133
- doc-type: spec
134
- testable: no
135
- governs: workflow-definition
136
- ---
137
-
138
- # Workflow Definition
139
-
140
- ## Trigger
141
-
142
- When should this workflow run?
143
-
144
- ## Inputs
145
-
146
- What inputs does this workflow require?
147
-
148
- ## Process
149
-
150
- What steps does this workflow perform?
151
-
152
- ## Output
153
-
154
- What does this workflow produce?
155
- `;
156
- safeWrite(join(projectPath, "specs", "WORKFLOW-DEFINITION.md"), workflowDef, "specs/WORKFLOW-DEFINITION.md", actions);
157
- }
158
-
159
- // Phase 1.5: Harness config + briefs for ALL project types
160
- generateOrAuditProjectHarness(projectPath, actions);
161
- injectEnvironmentSection(projectPath, actions);
162
- generateAgentBriefsStep(projectPath, actions);
163
-
164
- // Phase 3: Final setup
165
- copySpecTemplateIfEmpty(join(projectPath, "specs"), actions);
166
- generateProjectState(projectPath, actions);
167
- runAuditSpecsFix(projectPath, actions);
168
- addPaiHarnessDevDep(projectPath, actions);
169
- createClaudeMdBridge(projectPath, actions);
170
- createCiWorkflows(projectPath, actions, { force });
171
- createGitHooks(projectPath, actions);
172
- deployHooksToConsumers(projectPath, actions);
173
-
174
- // Phase 3.5: steps that DESCRIBE the project run last, so they describe the tree this run left (#123).
175
- refreshScopedRulesStep(projectPath, projectType, actions);
176
- if (projectType === "code") {
177
- generateCodeMapStep(projectPath, actions);
178
- }
179
-
180
- postScaffoldCommit(projectPath, actions, { commit });
61
+ runScaffoldWriteSteps(projectPath, projectType, actions, { force, commit });
181
62
  } else {
182
- // Dry-run: report gaps for items that --fix would generate
183
- if (projectType === "code" && !existsSync(join(projectPath, "CODE-MAP.md"))) {
184
- actions.push("GAP: CODE-MAP.md missing — run with --fix to generate");
185
- }
186
- if (!existsSync(join(projectPath, ".claude", "rules", "docs-routing.md"))) {
187
- actions.push("GAP: .claude/rules/docs-routing.md missing — run with --fix to generate");
188
- }
189
- if (!existsSync(join(projectPath, "AGENTS.md"))) {
190
- actions.push("GAP: AGENTS.md missing — run with --fix to generate");
63
+ // Audit does not PREDICT what --fix would do; it does it, against a clone,
64
+ // and reports what the real steps said (#398). The previous audit branch was
65
+ // four existsSync checks against twenty-five write steps and reported 0
66
+ // changes on a tree --fix rewrote in 28 places.
67
+ //
68
+ // A rehearsal that cannot be set up safely REFUSES rather than falling
69
+ // back to the old guesswork. An audit that reports nothing because it
70
+ // could not look is indistinguishable from an audit that found nothing,
71
+ // and that is the defect, not a lesser version of it.
72
+ let rehearsal;
73
+ try {
74
+ rehearsal = cloneForRehearsal(projectPath);
75
+ } catch (err) {
76
+ console.error(`ERROR: ${(err as Error).message}`);
77
+ process.exit(1);
191
78
  }
192
- if (!existsSync(join(projectPath, "specs"))) {
193
- actions.push("GAP: specs/ directory missing — run with --fix to create");
79
+ try {
80
+ console.log(rehearsalNotice(rehearsal));
81
+ runScaffoldWriteSteps(rehearsal.dir, projectType, actions, { force, commit: false, rehearsing: true });
82
+ } finally {
83
+ discardRehearsal(rehearsal);
194
84
  }
195
85
  }
196
86
 
@@ -0,0 +1,315 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { readFileSync, writeFileSync, mkdirSync } from "fs";
4
+ import { join, dirname } from "path";
5
+
6
+ export interface SplitBoundary {
7
+ heading: string;
8
+ startLine: number;
9
+ lineCount: number;
10
+ }
11
+
12
+ export interface SplitFile {
13
+ filename: string;
14
+ content: string;
15
+ governs: string;
16
+ lineCount: number;
17
+ }
18
+
19
+ export function deriveDirectoryName(filename: string): string {
20
+ // Strip .md extension
21
+ let name = filename.replace(/\.md$/i, "");
22
+ // Strip -spec suffix (case insensitive)
23
+ name = name.replace(/-spec$/i, "");
24
+ // Lowercase
25
+ return name.toLowerCase();
26
+ }
27
+
28
+ export function detectSplitBoundaries(content: string): SplitBoundary[] {
29
+ const lines = content.split("\n");
30
+ const boundaries: SplitBoundary[] = [];
31
+
32
+ // Find all ## headings (but not ### or deeper)
33
+ for (let i = 0; i < lines.length; i++) {
34
+ const line = lines[i];
35
+ // Match ## followed by space, but not ###
36
+ if (/^## (?!#)/.test(line)) {
37
+ const heading = line.replace(/^## /, "").trim();
38
+ boundaries.push({
39
+ heading,
40
+ startLine: i + 1, // 1-indexed
41
+ lineCount: 0, // Will calculate below
42
+ });
43
+ }
44
+ }
45
+
46
+ // Calculate line counts for each section
47
+ for (let i = 0; i < boundaries.length; i++) {
48
+ const boundary = boundaries[i];
49
+ const nextBoundary = boundaries[i + 1];
50
+ const startIdx = boundary.startLine - 1; // Convert to 0-indexed
51
+ const endIdx = nextBoundary ? nextBoundary.startLine - 1 : lines.length;
52
+ boundary.lineCount = endIdx - startIdx;
53
+ }
54
+
55
+ return boundaries;
56
+ }
57
+
58
+ export function shouldSplit(content: string): boolean {
59
+ // Check if already split
60
+ if (content.includes("status: split")) {
61
+ return false;
62
+ }
63
+
64
+ const lines = content.split("\n");
65
+ const totalLines = lines.length;
66
+
67
+ // If under 500 lines, no split needed
68
+ if (totalLines < 500) {
69
+ return false;
70
+ }
71
+
72
+ // Detect boundaries to check section sizes
73
+ const boundaries = detectSplitBoundaries(content);
74
+
75
+ // If any individual section exceeds 500 lines, split
76
+ for (const boundary of boundaries) {
77
+ if (boundary.lineCount > 500) {
78
+ return true;
79
+ }
80
+ }
81
+
82
+ // If over 500 lines total with multiple sections, split
83
+ if (totalLines >= 500 && boundaries.length > 1) {
84
+ return true;
85
+ }
86
+
87
+ return false;
88
+ }
89
+
90
+ function slugify(text: string): string {
91
+ return text
92
+ .toLowerCase()
93
+ .replace(/[^a-z0-9]+/g, "-")
94
+ .replace(/^-|-$/g, "");
95
+ }
96
+
97
+ function parseFrontmatter(content: string): {
98
+ frontmatter: Record<string, any>;
99
+ body: string;
100
+ } {
101
+ const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
102
+ if (!match) {
103
+ return { frontmatter: {}, body: content };
104
+ }
105
+
106
+ const yaml = match[1];
107
+ const body = match[2];
108
+ const frontmatter: Record<string, any> = {};
109
+
110
+ for (const line of yaml.split("\n")) {
111
+ const colonIdx = line.indexOf(":");
112
+ if (colonIdx > 0) {
113
+ const key = line.slice(0, colonIdx).trim();
114
+ const value = line.slice(colonIdx + 1).trim();
115
+ frontmatter[key] = value;
116
+ }
117
+ }
118
+
119
+ return { frontmatter, body };
120
+ }
121
+
122
+ export interface GroupedBoundary {
123
+ headings: string[];
124
+ startLine: number;
125
+ endLine: number;
126
+ lineCount: number;
127
+ }
128
+
129
+ export function groupBoundaries(boundaries: SplitBoundary[], totalLines: number, maxLines: number = 500): GroupedBoundary[] {
130
+ if (boundaries.length === 0) return [];
131
+
132
+ const groups: GroupedBoundary[] = [];
133
+ let currentGroup: GroupedBoundary = {
134
+ headings: [boundaries[0].heading],
135
+ startLine: boundaries[0].startLine,
136
+ endLine: 0,
137
+ lineCount: boundaries[0].lineCount,
138
+ };
139
+
140
+ for (let i = 1; i < boundaries.length; i++) {
141
+ const boundary = boundaries[i];
142
+ if (currentGroup.lineCount + boundary.lineCount <= maxLines) {
143
+ currentGroup.headings.push(boundary.heading);
144
+ currentGroup.lineCount += boundary.lineCount;
145
+ } else {
146
+ const prevBoundary = boundaries[i - 1];
147
+ currentGroup.endLine = boundary.startLine - 1;
148
+ groups.push(currentGroup);
149
+ currentGroup = {
150
+ headings: [boundary.heading],
151
+ startLine: boundary.startLine,
152
+ endLine: 0,
153
+ lineCount: boundary.lineCount,
154
+ };
155
+ }
156
+ }
157
+ currentGroup.endLine = totalLines;
158
+ groups.push(currentGroup);
159
+
160
+ return groups;
161
+ }
162
+
163
+ export function generateSplitFiles(
164
+ content: string,
165
+ boundaries: SplitBoundary[],
166
+ metadata: { owner: string; testable: boolean }
167
+ ): SplitFile[] {
168
+ const lines = content.split("\n");
169
+ const now = new Date().toISOString().split("T")[0];
170
+ const groups = groupBoundaries(boundaries, lines.length);
171
+
172
+ return groups.map((group) => {
173
+ const filename = `${slugify(group.headings[0])}.md`;
174
+ const governs = group.headings.length === 1
175
+ ? group.headings[0]
176
+ : `${group.headings[0]} + ${group.headings.length - 1} more`;
177
+
178
+ const startIdx = group.startLine - 1;
179
+ const endIdx = group.endLine;
180
+ const sectionLines = lines.slice(startIdx, endIdx);
181
+
182
+ const frontmatter = `---
183
+ doc-type: spec
184
+ status: active
185
+ owner: ${metadata.owner}
186
+ created: ${now}
187
+ updated: ${now}
188
+ governs: ${governs}
189
+ testable: ${metadata.testable}
190
+ ---`;
191
+
192
+ const fileContent = `${frontmatter}\n\n${sectionLines.join("\n")}`;
193
+
194
+ return {
195
+ filename,
196
+ content: fileContent,
197
+ governs,
198
+ lineCount: fileContent.split("\n").length,
199
+ };
200
+ });
201
+ }
202
+
203
+ export function generateRedirect(
204
+ originalPath: string,
205
+ splitDir: string,
206
+ splitFiles: SplitFile[]
207
+ ): string {
208
+ const frontmatter = `---
209
+ status: split
210
+ ---`;
211
+
212
+ const fileList = splitFiles
213
+ .map((f) => `- [${f.filename}](${splitDir}/${f.filename}) — ${f.governs}`)
214
+ .join("\n");
215
+
216
+ return `${frontmatter}
217
+
218
+ This file has been split. See:
219
+
220
+ ${fileList}`;
221
+ }
222
+
223
+ export function generateIndex(
224
+ splitFiles: SplitFile[],
225
+ originalGoverns: string
226
+ ): string {
227
+ const frontmatter = `---
228
+ doc-type: index
229
+ governs: ${originalGoverns}
230
+ ---`;
231
+
232
+ const tableHeader = `| File | Governs | Lines |
233
+ |------|---------|-------|`;
234
+
235
+ const tableRows = splitFiles
236
+ .map(
237
+ (f) => `| [${f.filename}](${f.filename}) | ${f.governs} | ${f.lineCount} |`
238
+ )
239
+ .join("\n");
240
+
241
+ return `${frontmatter}
242
+
243
+ # INDEX.md
244
+
245
+ ${tableHeader}
246
+ ${tableRows}`;
247
+ }
248
+
249
+ // CLI entry point
250
+ if (import.meta.main) {
251
+ const args = process.argv.slice(2);
252
+ if (args.length === 0) {
253
+ console.error("Usage: bun scripts/split-spec.ts <spec-file.md>");
254
+ process.exit(1);
255
+ }
256
+
257
+ const specPath = args[0];
258
+ const content = readFileSync(specPath, "utf-8");
259
+
260
+ // Check if split needed
261
+ if (!shouldSplit(content)) {
262
+ console.log("File does not need splitting (< 500 lines or already split)");
263
+ process.exit(0);
264
+ }
265
+
266
+ // Detect boundaries
267
+ const boundaries = detectSplitBoundaries(content);
268
+ if (boundaries.length === 0) {
269
+ console.log("No ## sections found to split");
270
+ process.exit(0);
271
+ }
272
+
273
+ // Parse original frontmatter for metadata
274
+ const { frontmatter } = parseFrontmatter(content);
275
+ const owner = frontmatter.owner || "jason";
276
+ const testable = frontmatter.testable === "true" || frontmatter.testable === true;
277
+ const originalGoverns = frontmatter.governs || "Spec content";
278
+
279
+ // Generate split files
280
+ const splitFiles = generateSplitFiles(content, boundaries, {
281
+ owner,
282
+ testable,
283
+ });
284
+
285
+ // Derive directory name
286
+ const filename = specPath.split("/").pop() || "";
287
+ const dirName = deriveDirectoryName(filename);
288
+ const parentDir = dirname(specPath);
289
+ const splitDir = join(parentDir, dirName);
290
+
291
+ // Create directory
292
+ mkdirSync(splitDir, { recursive: true });
293
+
294
+ // Write split files
295
+ for (const file of splitFiles) {
296
+ const filePath = join(splitDir, file.filename);
297
+ writeFileSync(filePath, file.content);
298
+ console.log(`Created: ${filePath} (${file.lineCount} lines)`);
299
+ }
300
+
301
+ // Write INDEX.md
302
+ const indexContent = generateIndex(splitFiles, originalGoverns);
303
+ const indexPath = join(splitDir, "INDEX.md");
304
+ writeFileSync(indexPath, indexContent);
305
+ console.log(`Created: ${indexPath}`);
306
+
307
+ // Replace original with redirect
308
+ const redirectContent = generateRedirect(specPath, splitDir, splitFiles);
309
+ writeFileSync(specPath, redirectContent);
310
+ console.log(`Updated: ${specPath} (now a redirect)`);
311
+
312
+ console.log(
313
+ `\nSplit ${filename} into ${splitFiles.length} files in ${splitDir}/`
314
+ );
315
+ }