specsmd 0.0.0-dev.54 → 0.0.0-dev.55

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.
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * FIRE Run Initialization Script
5
+ *
6
+ * Creates run record in state.yaml and run folder structure.
7
+ * Ensures deterministic run ID generation by checking BOTH:
8
+ * - runs.completed history in state.yaml
9
+ * - existing run folders in .specs-fire/runs/
10
+ *
11
+ * Usage: node init-run.js <rootPath> <workItemId> <intentId> <mode>
12
+ *
13
+ * Example: node init-run.js /project login-endpoint user-auth confirm
14
+ */
15
+
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const yaml = require('yaml');
19
+
20
+ // =============================================================================
21
+ // Error Helper
22
+ // =============================================================================
23
+
24
+ function fireError(message, code, suggestion) {
25
+ const err = new Error(`FIRE Error [${code}]: ${message} ${suggestion}`);
26
+ err.code = code;
27
+ err.suggestion = suggestion;
28
+ return err;
29
+ }
30
+
31
+ // =============================================================================
32
+ // Validation
33
+ // =============================================================================
34
+
35
+ const VALID_MODES = ['autopilot', 'confirm', 'validate'];
36
+
37
+ function validateInputs(rootPath, workItemId, intentId, mode) {
38
+ if (!rootPath || typeof rootPath !== 'string' || rootPath.trim() === '') {
39
+ throw fireError('rootPath is required.', 'INIT_001', 'Provide a valid project root path.');
40
+ }
41
+
42
+ if (!workItemId || typeof workItemId !== 'string' || workItemId.trim() === '') {
43
+ throw fireError('workItemId is required.', 'INIT_010', 'Provide a valid work item ID.');
44
+ }
45
+
46
+ if (!intentId || typeof intentId !== 'string' || intentId.trim() === '') {
47
+ throw fireError('intentId is required.', 'INIT_020', 'Provide a valid intent ID.');
48
+ }
49
+
50
+ if (!mode || !VALID_MODES.includes(mode)) {
51
+ throw fireError(
52
+ `Invalid mode: "${mode}".`,
53
+ 'INIT_030',
54
+ `Valid modes are: ${VALID_MODES.join(', ')}`
55
+ );
56
+ }
57
+
58
+ if (!fs.existsSync(rootPath)) {
59
+ throw fireError(
60
+ `Project root not found: "${rootPath}".`,
61
+ 'INIT_040',
62
+ 'Ensure the path exists and is accessible.'
63
+ );
64
+ }
65
+ }
66
+
67
+ function validateFireProject(rootPath) {
68
+ const fireDir = path.join(rootPath, '.specs-fire');
69
+ const statePath = path.join(fireDir, 'state.yaml');
70
+ const runsPath = path.join(fireDir, 'runs');
71
+
72
+ if (!fs.existsSync(fireDir)) {
73
+ throw fireError(
74
+ `FIRE project not initialized at: "${rootPath}".`,
75
+ 'INIT_041',
76
+ 'Run fire-init first to initialize the project.'
77
+ );
78
+ }
79
+
80
+ if (!fs.existsSync(statePath)) {
81
+ throw fireError(
82
+ `State file not found at: "${statePath}".`,
83
+ 'INIT_042',
84
+ 'The project may be corrupted. Try re-initializing.'
85
+ );
86
+ }
87
+
88
+ return { fireDir, statePath, runsPath };
89
+ }
90
+
91
+ // =============================================================================
92
+ // State Operations
93
+ // =============================================================================
94
+
95
+ function readState(statePath) {
96
+ try {
97
+ const content = fs.readFileSync(statePath, 'utf8');
98
+ const state = yaml.parse(content);
99
+ if (!state || typeof state !== 'object') {
100
+ throw fireError('State file is empty or invalid.', 'INIT_050', 'Check state.yaml format.');
101
+ }
102
+ return state;
103
+ } catch (err) {
104
+ if (err.code && err.code.startsWith('INIT_')) throw err;
105
+ throw fireError(
106
+ `Failed to read state file: ${err.message}`,
107
+ 'INIT_051',
108
+ 'Check file permissions and YAML syntax.'
109
+ );
110
+ }
111
+ }
112
+
113
+ function writeState(statePath, state) {
114
+ try {
115
+ fs.writeFileSync(statePath, yaml.stringify(state));
116
+ } catch (err) {
117
+ throw fireError(
118
+ `Failed to write state file: ${err.message}`,
119
+ 'INIT_052',
120
+ 'Check file permissions and disk space.'
121
+ );
122
+ }
123
+ }
124
+
125
+ // =============================================================================
126
+ // Run ID Generation (CRITICAL - checks both history and file system)
127
+ // =============================================================================
128
+
129
+ function generateRunId(runsPath, state) {
130
+ // Ensure runs directory exists
131
+ if (!fs.existsSync(runsPath)) {
132
+ fs.mkdirSync(runsPath, { recursive: true });
133
+ }
134
+
135
+ // Source 1: Get max from state.yaml runs.completed history
136
+ let maxFromHistory = 0;
137
+ if (state.runs && Array.isArray(state.runs.completed)) {
138
+ for (const run of state.runs.completed) {
139
+ if (run.id) {
140
+ const match = run.id.match(/^run-(\d+)$/);
141
+ if (match) {
142
+ const num = parseInt(match[1], 10);
143
+ if (num > maxFromHistory) maxFromHistory = num;
144
+ }
145
+ }
146
+ }
147
+ }
148
+
149
+ // Source 2: Get max from file system (defensive)
150
+ let maxFromFileSystem = 0;
151
+ try {
152
+ const entries = fs.readdirSync(runsPath);
153
+ for (const entry of entries) {
154
+ if (/^run-\d{3,}$/.test(entry)) {
155
+ const num = parseInt(entry.replace('run-', ''), 10);
156
+ if (num > maxFromFileSystem) maxFromFileSystem = num;
157
+ }
158
+ }
159
+ } catch (err) {
160
+ throw fireError(
161
+ `Failed to read runs directory: ${err.message}`,
162
+ 'INIT_060',
163
+ 'Check directory permissions.'
164
+ );
165
+ }
166
+
167
+ // Use MAX of both to ensure no duplicates
168
+ const maxNum = Math.max(maxFromHistory, maxFromFileSystem);
169
+ const nextNum = maxNum + 1;
170
+
171
+ return `run-${String(nextNum).padStart(3, '0')}`;
172
+ }
173
+
174
+ // =============================================================================
175
+ // Run Folder Creation
176
+ // =============================================================================
177
+
178
+ function createRunFolder(runPath) {
179
+ try {
180
+ fs.mkdirSync(runPath, { recursive: true });
181
+ } catch (err) {
182
+ throw fireError(
183
+ `Failed to create run folder: ${err.message}`,
184
+ 'INIT_070',
185
+ 'Check directory permissions and disk space.'
186
+ );
187
+ }
188
+ }
189
+
190
+ function createRunLog(runPath, runId, workItemId, intentId, mode, startTime) {
191
+ const runLog = `---
192
+ id: ${runId}
193
+ work_item: ${workItemId}
194
+ intent: ${intentId}
195
+ mode: ${mode}
196
+ status: in_progress
197
+ started: ${startTime}
198
+ completed: null
199
+ ---
200
+
201
+ # Run: ${runId}
202
+
203
+ ## Work Item
204
+ ${workItemId}
205
+
206
+ ## Files Created
207
+ (none yet)
208
+
209
+ ## Files Modified
210
+ (none yet)
211
+
212
+ ## Decisions
213
+ (none yet)
214
+ `;
215
+
216
+ const runLogPath = path.join(runPath, 'run.md');
217
+ try {
218
+ fs.writeFileSync(runLogPath, runLog);
219
+ } catch (err) {
220
+ throw fireError(
221
+ `Failed to create run log: ${err.message}`,
222
+ 'INIT_071',
223
+ 'Check file permissions.'
224
+ );
225
+ }
226
+ }
227
+
228
+ // =============================================================================
229
+ // Main Function
230
+ // =============================================================================
231
+
232
+ function initRun(rootPath, workItemId, intentId, mode) {
233
+ // Validate inputs
234
+ validateInputs(rootPath, workItemId, intentId, mode);
235
+
236
+ // Validate FIRE project structure
237
+ const { statePath, runsPath } = validateFireProject(rootPath);
238
+
239
+ // Read state
240
+ const state = readState(statePath);
241
+
242
+ // Check for existing active run
243
+ if (state.active_run) {
244
+ throw fireError(
245
+ `A run is already active: "${state.active_run.id}".`,
246
+ 'INIT_080',
247
+ `Complete or cancel run "${state.active_run.id}" before starting a new one.`
248
+ );
249
+ }
250
+
251
+ // Generate run ID (checks both history AND file system)
252
+ const runId = generateRunId(runsPath, state);
253
+ const runPath = path.join(runsPath, runId);
254
+
255
+ // Create run folder
256
+ createRunFolder(runPath);
257
+
258
+ // Create run log
259
+ const startTime = new Date().toISOString();
260
+ createRunLog(runPath, runId, workItemId, intentId, mode, startTime);
261
+
262
+ // Update state with active run
263
+ state.active_run = {
264
+ id: runId,
265
+ work_item: workItemId,
266
+ intent: intentId,
267
+ mode: mode,
268
+ started: startTime,
269
+ };
270
+
271
+ // Save state
272
+ writeState(statePath, state);
273
+
274
+ // Return result
275
+ return {
276
+ success: true,
277
+ runId: runId,
278
+ runPath: runPath,
279
+ workItemId: workItemId,
280
+ intentId: intentId,
281
+ mode: mode,
282
+ started: startTime,
283
+ };
284
+ }
285
+
286
+ // =============================================================================
287
+ // CLI Interface
288
+ // =============================================================================
289
+
290
+ if (require.main === module) {
291
+ const args = process.argv.slice(2);
292
+
293
+ if (args.length < 4) {
294
+ console.error('Usage: node init-run.js <rootPath> <workItemId> <intentId> <mode>');
295
+ console.error('');
296
+ console.error('Arguments:');
297
+ console.error(' rootPath - Project root directory');
298
+ console.error(' workItemId - Work item ID to execute');
299
+ console.error(' intentId - Intent ID containing the work item');
300
+ console.error(' mode - Execution mode (autopilot, confirm, validate)');
301
+ console.error('');
302
+ console.error('Example:');
303
+ console.error(' node init-run.js /my/project login-endpoint user-auth confirm');
304
+ process.exit(1);
305
+ }
306
+
307
+ const [rootPath, workItemId, intentId, mode] = args;
308
+
309
+ try {
310
+ const result = initRun(rootPath, workItemId, intentId, mode);
311
+ console.log(JSON.stringify(result, null, 2));
312
+ process.exit(0);
313
+ } catch (err) {
314
+ console.error(err.message);
315
+ process.exit(1);
316
+ }
317
+ }
318
+
319
+ module.exports = { initRun };
@@ -42,6 +42,8 @@ state:
42
42
  - work_items: "List of work items in this run"
43
43
  - current_item: "Work item currently being executed"
44
44
  - started: "ISO 8601 timestamp"
45
+ runs:
46
+ - completed: "List of completed runs with id, work_item, intent, completed timestamp"
45
47
 
46
48
  # Data Conventions
47
49
  conventions:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "specsmd",
3
- "version": "0.0.0-dev.54",
3
+ "version": "0.0.0-dev.55",
4
4
  "description": "Multi-agent orchestration system for AI-native software development. Delivers AI-DLC, Agile, and custom SDLC flows as markdown-based agent systems.",
5
5
  "main": "lib/installer.js",
6
6
  "bin": {