@fission-ai/openspec 0.17.2 → 0.19.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 (89) hide show
  1. package/README.md +52 -0
  2. package/dist/cli/index.js +39 -3
  3. package/dist/commands/artifact-workflow.d.ts +17 -0
  4. package/dist/commands/artifact-workflow.js +823 -0
  5. package/dist/commands/completion.js +42 -6
  6. package/dist/core/archive.d.ts +0 -5
  7. package/dist/core/archive.js +4 -257
  8. package/dist/core/artifact-graph/graph.d.ts +56 -0
  9. package/dist/core/artifact-graph/graph.js +141 -0
  10. package/dist/core/artifact-graph/index.d.ts +7 -0
  11. package/dist/core/artifact-graph/index.js +13 -0
  12. package/dist/core/artifact-graph/instruction-loader.d.ts +130 -0
  13. package/dist/core/artifact-graph/instruction-loader.js +173 -0
  14. package/dist/core/artifact-graph/resolver.d.ts +61 -0
  15. package/dist/core/artifact-graph/resolver.js +187 -0
  16. package/dist/core/artifact-graph/schema.d.ts +13 -0
  17. package/dist/core/artifact-graph/schema.js +108 -0
  18. package/dist/core/artifact-graph/state.d.ts +12 -0
  19. package/dist/core/artifact-graph/state.js +54 -0
  20. package/dist/core/artifact-graph/types.d.ts +45 -0
  21. package/dist/core/artifact-graph/types.js +43 -0
  22. package/dist/core/completions/command-registry.js +7 -1
  23. package/dist/core/completions/factory.d.ts +15 -2
  24. package/dist/core/completions/factory.js +19 -1
  25. package/dist/core/completions/generators/bash-generator.d.ts +32 -0
  26. package/dist/core/completions/generators/bash-generator.js +174 -0
  27. package/dist/core/completions/generators/fish-generator.d.ts +32 -0
  28. package/dist/core/completions/generators/fish-generator.js +157 -0
  29. package/dist/core/completions/generators/powershell-generator.d.ts +32 -0
  30. package/dist/core/completions/generators/powershell-generator.js +198 -0
  31. package/dist/core/completions/generators/zsh-generator.d.ts +0 -14
  32. package/dist/core/completions/generators/zsh-generator.js +55 -124
  33. package/dist/core/completions/installers/bash-installer.d.ts +87 -0
  34. package/dist/core/completions/installers/bash-installer.js +318 -0
  35. package/dist/core/completions/installers/fish-installer.d.ts +43 -0
  36. package/dist/core/completions/installers/fish-installer.js +143 -0
  37. package/dist/core/completions/installers/powershell-installer.d.ts +88 -0
  38. package/dist/core/completions/installers/powershell-installer.js +327 -0
  39. package/dist/core/completions/installers/zsh-installer.d.ts +1 -12
  40. package/dist/core/completions/templates/bash-templates.d.ts +6 -0
  41. package/dist/core/completions/templates/bash-templates.js +24 -0
  42. package/dist/core/completions/templates/fish-templates.d.ts +7 -0
  43. package/dist/core/completions/templates/fish-templates.js +39 -0
  44. package/dist/core/completions/templates/powershell-templates.d.ts +6 -0
  45. package/dist/core/completions/templates/powershell-templates.js +25 -0
  46. package/dist/core/completions/templates/zsh-templates.d.ts +6 -0
  47. package/dist/core/completions/templates/zsh-templates.js +36 -0
  48. package/dist/core/config.js +1 -0
  49. package/dist/core/configurators/slash/codebuddy.js +6 -9
  50. package/dist/core/configurators/slash/continue.d.ts +9 -0
  51. package/dist/core/configurators/slash/continue.js +46 -0
  52. package/dist/core/configurators/slash/registry.js +3 -0
  53. package/dist/core/converters/json-converter.js +2 -1
  54. package/dist/core/global-config.d.ts +10 -0
  55. package/dist/core/global-config.js +28 -0
  56. package/dist/core/index.d.ts +1 -1
  57. package/dist/core/index.js +1 -1
  58. package/dist/core/list.d.ts +6 -1
  59. package/dist/core/list.js +88 -6
  60. package/dist/core/specs-apply.d.ts +73 -0
  61. package/dist/core/specs-apply.js +384 -0
  62. package/dist/core/templates/skill-templates.d.ts +86 -0
  63. package/dist/core/templates/skill-templates.js +1934 -0
  64. package/dist/core/update.js +1 -1
  65. package/dist/core/validation/validator.js +2 -1
  66. package/dist/core/view.js +28 -8
  67. package/dist/telemetry/config.d.ts +32 -0
  68. package/dist/telemetry/config.js +68 -0
  69. package/dist/telemetry/index.d.ts +31 -0
  70. package/dist/telemetry/index.js +145 -0
  71. package/dist/utils/change-metadata.d.ts +47 -0
  72. package/dist/utils/change-metadata.js +130 -0
  73. package/dist/utils/change-utils.d.ts +51 -0
  74. package/dist/utils/change-utils.js +100 -0
  75. package/dist/utils/file-system.d.ts +11 -0
  76. package/dist/utils/file-system.js +50 -2
  77. package/dist/utils/index.d.ts +3 -1
  78. package/dist/utils/index.js +4 -1
  79. package/package.json +5 -1
  80. package/schemas/spec-driven/schema.yaml +148 -0
  81. package/schemas/spec-driven/templates/design.md +19 -0
  82. package/schemas/spec-driven/templates/proposal.md +23 -0
  83. package/schemas/spec-driven/templates/spec.md +8 -0
  84. package/schemas/spec-driven/templates/tasks.md +9 -0
  85. package/schemas/tdd/schema.yaml +213 -0
  86. package/schemas/tdd/templates/docs.md +15 -0
  87. package/schemas/tdd/templates/implementation.md +11 -0
  88. package/schemas/tdd/templates/spec.md +11 -0
  89. package/schemas/tdd/templates/test.md +11 -0
@@ -0,0 +1,823 @@
1
+ /**
2
+ * Artifact Workflow CLI Commands (Experimental)
3
+ *
4
+ * This file contains all artifact workflow commands in isolation for easy removal.
5
+ * Commands expose the ArtifactGraph and InstructionLoader APIs to users and agents.
6
+ *
7
+ * To remove this feature:
8
+ * 1. Delete this file
9
+ * 2. Remove the registerArtifactWorkflowCommands() call from src/cli/index.ts
10
+ */
11
+ import ora from 'ora';
12
+ import chalk from 'chalk';
13
+ import path from 'path';
14
+ import * as fs from 'fs';
15
+ import { loadChangeContext, formatChangeStatus, generateInstructions, listSchemas, listSchemasWithInfo, getSchemaDir, resolveSchema, ArtifactGraph, } from '../core/artifact-graph/index.js';
16
+ import { createChange, validateChangeName } from '../utils/change-utils.js';
17
+ import { getExploreSkillTemplate, getNewChangeSkillTemplate, getContinueChangeSkillTemplate, getApplyChangeSkillTemplate, getFfChangeSkillTemplate, getSyncSpecsSkillTemplate, getArchiveChangeSkillTemplate, getOpsxExploreCommandTemplate, getOpsxNewCommandTemplate, getOpsxContinueCommandTemplate, getOpsxApplyCommandTemplate, getOpsxFfCommandTemplate, getOpsxSyncCommandTemplate, getOpsxArchiveCommandTemplate } from '../core/templates/skill-templates.js';
18
+ import { FileSystemUtils } from '../utils/file-system.js';
19
+ const DEFAULT_SCHEMA = 'spec-driven';
20
+ /**
21
+ * Checks if color output is disabled via NO_COLOR env or --no-color flag.
22
+ */
23
+ function isColorDisabled() {
24
+ return process.env.NO_COLOR === '1' || process.env.NO_COLOR === 'true';
25
+ }
26
+ /**
27
+ * Gets the color function based on status.
28
+ */
29
+ function getStatusColor(status) {
30
+ if (isColorDisabled()) {
31
+ return (text) => text;
32
+ }
33
+ switch (status) {
34
+ case 'done':
35
+ return chalk.green;
36
+ case 'ready':
37
+ return chalk.yellow;
38
+ case 'blocked':
39
+ return chalk.red;
40
+ }
41
+ }
42
+ /**
43
+ * Gets the status indicator for an artifact.
44
+ */
45
+ function getStatusIndicator(status) {
46
+ const color = getStatusColor(status);
47
+ switch (status) {
48
+ case 'done':
49
+ return color('[x]');
50
+ case 'ready':
51
+ return color('[ ]');
52
+ case 'blocked':
53
+ return color('[-]');
54
+ }
55
+ }
56
+ /**
57
+ * Validates that a change exists and returns available changes if not.
58
+ * Checks directory existence directly to support scaffolded changes (without proposal.md).
59
+ */
60
+ async function validateChangeExists(changeName, projectRoot) {
61
+ const changesPath = path.join(projectRoot, 'openspec', 'changes');
62
+ // Get all change directories (not just those with proposal.md)
63
+ const getAvailableChanges = async () => {
64
+ try {
65
+ const entries = await fs.promises.readdir(changesPath, { withFileTypes: true });
66
+ return entries
67
+ .filter((e) => e.isDirectory() && e.name !== 'archive' && !e.name.startsWith('.'))
68
+ .map((e) => e.name);
69
+ }
70
+ catch {
71
+ return [];
72
+ }
73
+ };
74
+ if (!changeName) {
75
+ const available = await getAvailableChanges();
76
+ if (available.length === 0) {
77
+ throw new Error('No changes found. Create one with: openspec new change <name>');
78
+ }
79
+ throw new Error(`Missing required option --change. Available changes:\n ${available.join('\n ')}`);
80
+ }
81
+ // Validate change name format to prevent path traversal
82
+ const nameValidation = validateChangeName(changeName);
83
+ if (!nameValidation.valid) {
84
+ throw new Error(`Invalid change name '${changeName}': ${nameValidation.error}`);
85
+ }
86
+ // Check directory existence directly
87
+ const changePath = path.join(changesPath, changeName);
88
+ const exists = fs.existsSync(changePath) && fs.statSync(changePath).isDirectory();
89
+ if (!exists) {
90
+ const available = await getAvailableChanges();
91
+ if (available.length === 0) {
92
+ throw new Error(`Change '${changeName}' not found. No changes exist. Create one with: openspec new change <name>`);
93
+ }
94
+ throw new Error(`Change '${changeName}' not found. Available changes:\n ${available.join('\n ')}`);
95
+ }
96
+ return changeName;
97
+ }
98
+ /**
99
+ * Validates that a schema exists and returns available schemas if not.
100
+ */
101
+ function validateSchemaExists(schemaName) {
102
+ const schemaDir = getSchemaDir(schemaName);
103
+ if (!schemaDir) {
104
+ const availableSchemas = listSchemas();
105
+ throw new Error(`Schema '${schemaName}' not found. Available schemas:\n ${availableSchemas.join('\n ')}`);
106
+ }
107
+ return schemaName;
108
+ }
109
+ async function statusCommand(options) {
110
+ const spinner = ora('Loading change status...').start();
111
+ try {
112
+ const projectRoot = process.cwd();
113
+ const changeName = await validateChangeExists(options.change, projectRoot);
114
+ // Validate schema if explicitly provided
115
+ if (options.schema) {
116
+ validateSchemaExists(options.schema);
117
+ }
118
+ // loadChangeContext will auto-detect schema from metadata if not provided
119
+ const context = loadChangeContext(projectRoot, changeName, options.schema);
120
+ const status = formatChangeStatus(context);
121
+ spinner.stop();
122
+ if (options.json) {
123
+ console.log(JSON.stringify(status, null, 2));
124
+ return;
125
+ }
126
+ printStatusText(status);
127
+ }
128
+ catch (error) {
129
+ spinner.stop();
130
+ throw error;
131
+ }
132
+ }
133
+ function printStatusText(status) {
134
+ const doneCount = status.artifacts.filter((a) => a.status === 'done').length;
135
+ const total = status.artifacts.length;
136
+ console.log(`Change: ${status.changeName}`);
137
+ console.log(`Schema: ${status.schemaName}`);
138
+ console.log(`Progress: ${doneCount}/${total} artifacts complete`);
139
+ console.log();
140
+ for (const artifact of status.artifacts) {
141
+ const indicator = getStatusIndicator(artifact.status);
142
+ const color = getStatusColor(artifact.status);
143
+ let line = `${indicator} ${artifact.id}`;
144
+ if (artifact.status === 'blocked' && artifact.missingDeps && artifact.missingDeps.length > 0) {
145
+ line += color(` (blocked by: ${artifact.missingDeps.join(', ')})`);
146
+ }
147
+ console.log(line);
148
+ }
149
+ if (status.isComplete) {
150
+ console.log();
151
+ console.log(chalk.green('All artifacts complete!'));
152
+ }
153
+ }
154
+ async function instructionsCommand(artifactId, options) {
155
+ const spinner = ora('Generating instructions...').start();
156
+ try {
157
+ const projectRoot = process.cwd();
158
+ const changeName = await validateChangeExists(options.change, projectRoot);
159
+ // Validate schema if explicitly provided
160
+ if (options.schema) {
161
+ validateSchemaExists(options.schema);
162
+ }
163
+ // loadChangeContext will auto-detect schema from metadata if not provided
164
+ const context = loadChangeContext(projectRoot, changeName, options.schema);
165
+ if (!artifactId) {
166
+ spinner.stop();
167
+ const validIds = context.graph.getAllArtifacts().map((a) => a.id);
168
+ throw new Error(`Missing required argument <artifact>. Valid artifacts:\n ${validIds.join('\n ')}`);
169
+ }
170
+ const artifact = context.graph.getArtifact(artifactId);
171
+ if (!artifact) {
172
+ spinner.stop();
173
+ const validIds = context.graph.getAllArtifacts().map((a) => a.id);
174
+ throw new Error(`Artifact '${artifactId}' not found in schema '${context.schemaName}'. Valid artifacts:\n ${validIds.join('\n ')}`);
175
+ }
176
+ const instructions = generateInstructions(context, artifactId);
177
+ const isBlocked = instructions.dependencies.some((d) => !d.done);
178
+ spinner.stop();
179
+ if (options.json) {
180
+ console.log(JSON.stringify(instructions, null, 2));
181
+ return;
182
+ }
183
+ printInstructionsText(instructions, isBlocked);
184
+ }
185
+ catch (error) {
186
+ spinner.stop();
187
+ throw error;
188
+ }
189
+ }
190
+ function printInstructionsText(instructions, isBlocked) {
191
+ const { artifactId, changeName, schemaName, changeDir, outputPath, description, instruction, template, dependencies, unlocks, } = instructions;
192
+ // Opening tag
193
+ console.log(`<artifact id="${artifactId}" change="${changeName}" schema="${schemaName}">`);
194
+ console.log();
195
+ // Warning for blocked artifacts
196
+ if (isBlocked) {
197
+ const missing = dependencies.filter((d) => !d.done).map((d) => d.id);
198
+ console.log('<warning>');
199
+ console.log('This artifact has unmet dependencies. Complete them first or proceed with caution.');
200
+ console.log(`Missing: ${missing.join(', ')}`);
201
+ console.log('</warning>');
202
+ console.log();
203
+ }
204
+ // Task directive
205
+ console.log('<task>');
206
+ console.log(`Create the ${artifactId} artifact for change "${changeName}".`);
207
+ console.log(description);
208
+ console.log('</task>');
209
+ console.log();
210
+ // Context (dependencies)
211
+ if (dependencies.length > 0) {
212
+ console.log('<context>');
213
+ console.log('Read these files for context before creating this artifact:');
214
+ console.log();
215
+ for (const dep of dependencies) {
216
+ const status = dep.done ? 'done' : 'missing';
217
+ const fullPath = path.join(changeDir, dep.path);
218
+ console.log(`<dependency id="${dep.id}" status="${status}">`);
219
+ console.log(` <path>${fullPath}</path>`);
220
+ console.log(` <description>${dep.description}</description>`);
221
+ console.log('</dependency>');
222
+ }
223
+ console.log('</context>');
224
+ console.log();
225
+ }
226
+ // Output location
227
+ console.log('<output>');
228
+ console.log(`Write to: ${path.join(changeDir, outputPath)}`);
229
+ console.log('</output>');
230
+ console.log();
231
+ // Instruction (guidance)
232
+ if (instruction) {
233
+ console.log('<instruction>');
234
+ console.log(instruction.trim());
235
+ console.log('</instruction>');
236
+ console.log();
237
+ }
238
+ // Template
239
+ console.log('<template>');
240
+ console.log(template.trim());
241
+ console.log('</template>');
242
+ console.log();
243
+ // Success criteria placeholder
244
+ console.log('<success_criteria>');
245
+ console.log('<!-- To be defined in schema validation rules -->');
246
+ console.log('</success_criteria>');
247
+ console.log();
248
+ // Unlocks
249
+ if (unlocks.length > 0) {
250
+ console.log('<unlocks>');
251
+ console.log(`Completing this artifact enables: ${unlocks.join(', ')}`);
252
+ console.log('</unlocks>');
253
+ console.log();
254
+ }
255
+ // Closing tag
256
+ console.log('</artifact>');
257
+ }
258
+ /**
259
+ * Parses tasks.md content and extracts task items with their completion status.
260
+ */
261
+ function parseTasksFile(content) {
262
+ const tasks = [];
263
+ const lines = content.split('\n');
264
+ let taskIndex = 0;
265
+ for (const line of lines) {
266
+ // Match checkbox patterns: - [ ] or - [x] or - [X]
267
+ const checkboxMatch = line.match(/^[-*]\s*\[([ xX])\]\s*(.+)$/);
268
+ if (checkboxMatch) {
269
+ taskIndex++;
270
+ const done = checkboxMatch[1].toLowerCase() === 'x';
271
+ const description = checkboxMatch[2].trim();
272
+ tasks.push({
273
+ id: `${taskIndex}`,
274
+ description,
275
+ done,
276
+ });
277
+ }
278
+ }
279
+ return tasks;
280
+ }
281
+ /**
282
+ * Checks if an artifact output exists in the change directory.
283
+ * Supports glob patterns (e.g., "specs/*.md") by verifying at least one matching file exists.
284
+ */
285
+ function artifactOutputExists(changeDir, generates) {
286
+ // Normalize the generates path to use platform-specific separators
287
+ const normalizedGenerates = generates.split('/').join(path.sep);
288
+ const fullPath = path.join(changeDir, normalizedGenerates);
289
+ // If it's a glob pattern (contains ** or *), check for matching files
290
+ if (generates.includes('*')) {
291
+ // Extract the directory part before the glob pattern
292
+ const parts = normalizedGenerates.split(path.sep);
293
+ const dirParts = [];
294
+ let patternPart = '';
295
+ for (const part of parts) {
296
+ if (part.includes('*')) {
297
+ patternPart = part;
298
+ break;
299
+ }
300
+ dirParts.push(part);
301
+ }
302
+ const dirPath = path.join(changeDir, ...dirParts);
303
+ // Check if directory exists
304
+ if (!fs.existsSync(dirPath) || !fs.statSync(dirPath).isDirectory()) {
305
+ return false;
306
+ }
307
+ // Extract expected extension from pattern (e.g., "*.md" -> ".md")
308
+ const extMatch = patternPart.match(/\*(\.[a-zA-Z0-9]+)$/);
309
+ const expectedExt = extMatch ? extMatch[1] : null;
310
+ // Recursively check for matching files
311
+ const hasMatchingFiles = (dir) => {
312
+ try {
313
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
314
+ for (const entry of entries) {
315
+ if (entry.isDirectory()) {
316
+ // For ** patterns, recurse into subdirectories
317
+ if (generates.includes('**') && hasMatchingFiles(path.join(dir, entry.name))) {
318
+ return true;
319
+ }
320
+ }
321
+ else if (entry.isFile()) {
322
+ // Check if file matches expected extension (or any file if no extension specified)
323
+ if (!expectedExt || entry.name.endsWith(expectedExt)) {
324
+ return true;
325
+ }
326
+ }
327
+ }
328
+ }
329
+ catch {
330
+ return false;
331
+ }
332
+ return false;
333
+ };
334
+ return hasMatchingFiles(dirPath);
335
+ }
336
+ return fs.existsSync(fullPath);
337
+ }
338
+ /**
339
+ * Generates apply instructions for implementing tasks from a change.
340
+ * Schema-aware: reads apply phase configuration from schema to determine
341
+ * required artifacts, tracking file, and instruction.
342
+ */
343
+ async function generateApplyInstructions(projectRoot, changeName, schemaName) {
344
+ // loadChangeContext will auto-detect schema from metadata if not provided
345
+ const context = loadChangeContext(projectRoot, changeName, schemaName);
346
+ const changeDir = path.join(projectRoot, 'openspec', 'changes', changeName);
347
+ // Get the full schema to access the apply phase configuration
348
+ const schema = resolveSchema(context.schemaName);
349
+ const applyConfig = schema.apply;
350
+ // Determine required artifacts and tracking file from schema
351
+ // Fallback: if no apply block, require all artifacts
352
+ const requiredArtifactIds = applyConfig?.requires ?? schema.artifacts.map((a) => a.id);
353
+ const tracksFile = applyConfig?.tracks ?? null;
354
+ const schemaInstruction = applyConfig?.instruction ?? null;
355
+ // Check which required artifacts are missing
356
+ const missingArtifacts = [];
357
+ for (const artifactId of requiredArtifactIds) {
358
+ const artifact = schema.artifacts.find((a) => a.id === artifactId);
359
+ if (artifact && !artifactOutputExists(changeDir, artifact.generates)) {
360
+ missingArtifacts.push(artifactId);
361
+ }
362
+ }
363
+ // Build context files from all existing artifacts in schema
364
+ const contextFiles = {};
365
+ for (const artifact of schema.artifacts) {
366
+ if (artifactOutputExists(changeDir, artifact.generates)) {
367
+ contextFiles[artifact.id] = path.join(changeDir, artifact.generates);
368
+ }
369
+ }
370
+ // Parse tasks if tracking file exists
371
+ let tasks = [];
372
+ let tracksFileExists = false;
373
+ if (tracksFile) {
374
+ const tracksPath = path.join(changeDir, tracksFile);
375
+ tracksFileExists = fs.existsSync(tracksPath);
376
+ if (tracksFileExists) {
377
+ const tasksContent = await fs.promises.readFile(tracksPath, 'utf-8');
378
+ tasks = parseTasksFile(tasksContent);
379
+ }
380
+ }
381
+ // Calculate progress
382
+ const total = tasks.length;
383
+ const complete = tasks.filter((t) => t.done).length;
384
+ const remaining = total - complete;
385
+ // Determine state and instruction
386
+ let state;
387
+ let instruction;
388
+ if (missingArtifacts.length > 0) {
389
+ state = 'blocked';
390
+ instruction = `Cannot apply this change yet. Missing artifacts: ${missingArtifacts.join(', ')}.\nUse the openspec-continue-change skill to create the missing artifacts first.`;
391
+ }
392
+ else if (tracksFile && !tracksFileExists) {
393
+ // Tracking file configured but doesn't exist yet
394
+ const tracksFilename = path.basename(tracksFile);
395
+ state = 'blocked';
396
+ instruction = `The ${tracksFilename} file is missing and must be created.\nUse openspec-continue-change to generate the tracking file.`;
397
+ }
398
+ else if (tracksFile && tracksFileExists && total === 0) {
399
+ // Tracking file exists but contains no tasks
400
+ const tracksFilename = path.basename(tracksFile);
401
+ state = 'blocked';
402
+ instruction = `The ${tracksFilename} file exists but contains no tasks.\nAdd tasks to ${tracksFilename} or regenerate it with openspec-continue-change.`;
403
+ }
404
+ else if (tracksFile && remaining === 0 && total > 0) {
405
+ state = 'all_done';
406
+ instruction = 'All tasks are complete! This change is ready to be archived.\nConsider running tests and reviewing the changes before archiving.';
407
+ }
408
+ else if (!tracksFile) {
409
+ // No tracking file (e.g., TDD schema) - ready to apply
410
+ state = 'ready';
411
+ instruction = schemaInstruction?.trim() ?? 'All required artifacts complete. Proceed with implementation.';
412
+ }
413
+ else {
414
+ state = 'ready';
415
+ instruction = schemaInstruction?.trim() ?? 'Read context files, work through pending tasks, mark complete as you go.\nPause if you hit blockers or need clarification.';
416
+ }
417
+ return {
418
+ changeName,
419
+ changeDir,
420
+ schemaName: context.schemaName,
421
+ contextFiles,
422
+ progress: { total, complete, remaining },
423
+ tasks,
424
+ state,
425
+ missingArtifacts: missingArtifacts.length > 0 ? missingArtifacts : undefined,
426
+ instruction,
427
+ };
428
+ }
429
+ async function applyInstructionsCommand(options) {
430
+ const spinner = ora('Generating apply instructions...').start();
431
+ try {
432
+ const projectRoot = process.cwd();
433
+ const changeName = await validateChangeExists(options.change, projectRoot);
434
+ // Validate schema if explicitly provided
435
+ if (options.schema) {
436
+ validateSchemaExists(options.schema);
437
+ }
438
+ // generateApplyInstructions uses loadChangeContext which auto-detects schema
439
+ const instructions = await generateApplyInstructions(projectRoot, changeName, options.schema);
440
+ spinner.stop();
441
+ if (options.json) {
442
+ console.log(JSON.stringify(instructions, null, 2));
443
+ return;
444
+ }
445
+ printApplyInstructionsText(instructions);
446
+ }
447
+ catch (error) {
448
+ spinner.stop();
449
+ throw error;
450
+ }
451
+ }
452
+ function printApplyInstructionsText(instructions) {
453
+ const { changeName, schemaName, contextFiles, progress, tasks, state, missingArtifacts, instruction } = instructions;
454
+ console.log(`## Apply: ${changeName}`);
455
+ console.log(`Schema: ${schemaName}`);
456
+ console.log();
457
+ // Warning for blocked state
458
+ if (state === 'blocked' && missingArtifacts) {
459
+ console.log('### ⚠️ Blocked');
460
+ console.log();
461
+ console.log(`Missing artifacts: ${missingArtifacts.join(', ')}`);
462
+ console.log('Use the openspec-continue-change skill to create these first.');
463
+ console.log();
464
+ }
465
+ // Context files (dynamically from schema)
466
+ const contextFileEntries = Object.entries(contextFiles);
467
+ if (contextFileEntries.length > 0) {
468
+ console.log('### Context Files');
469
+ for (const [artifactId, filePath] of contextFileEntries) {
470
+ console.log(`- ${artifactId}: ${filePath}`);
471
+ }
472
+ console.log();
473
+ }
474
+ // Progress (only show if we have tracking)
475
+ if (progress.total > 0 || tasks.length > 0) {
476
+ console.log('### Progress');
477
+ if (state === 'all_done') {
478
+ console.log(`${progress.complete}/${progress.total} complete ✓`);
479
+ }
480
+ else {
481
+ console.log(`${progress.complete}/${progress.total} complete`);
482
+ }
483
+ console.log();
484
+ }
485
+ // Tasks
486
+ if (tasks.length > 0) {
487
+ console.log('### Tasks');
488
+ for (const task of tasks) {
489
+ const checkbox = task.done ? '[x]' : '[ ]';
490
+ console.log(`- ${checkbox} ${task.description}`);
491
+ }
492
+ console.log();
493
+ }
494
+ // Instruction
495
+ console.log('### Instruction');
496
+ console.log(instruction);
497
+ }
498
+ async function templatesCommand(options) {
499
+ const spinner = ora('Loading templates...').start();
500
+ try {
501
+ const schemaName = validateSchemaExists(options.schema ?? DEFAULT_SCHEMA);
502
+ const schema = resolveSchema(schemaName);
503
+ const graph = ArtifactGraph.fromSchema(schema);
504
+ const schemaDir = getSchemaDir(schemaName);
505
+ // Determine if this is a user override or package built-in
506
+ const { getUserSchemasDir } = await import('../core/artifact-graph/resolver.js');
507
+ const userSchemasDir = getUserSchemasDir();
508
+ const isUserOverride = schemaDir.startsWith(userSchemasDir);
509
+ const templates = graph.getAllArtifacts().map((artifact) => ({
510
+ artifactId: artifact.id,
511
+ templatePath: path.join(schemaDir, 'templates', artifact.template),
512
+ source: isUserOverride ? 'user' : 'package',
513
+ }));
514
+ spinner.stop();
515
+ if (options.json) {
516
+ const output = {};
517
+ for (const t of templates) {
518
+ output[t.artifactId] = { path: t.templatePath, source: t.source };
519
+ }
520
+ console.log(JSON.stringify(output, null, 2));
521
+ return;
522
+ }
523
+ console.log(`Schema: ${schemaName}`);
524
+ console.log(`Source: ${isUserOverride ? 'user override' : 'package built-in'}`);
525
+ console.log();
526
+ for (const t of templates) {
527
+ console.log(`${t.artifactId}:`);
528
+ console.log(` ${t.templatePath}`);
529
+ }
530
+ }
531
+ catch (error) {
532
+ spinner.stop();
533
+ throw error;
534
+ }
535
+ }
536
+ async function newChangeCommand(name, options) {
537
+ if (!name) {
538
+ throw new Error('Missing required argument <name>');
539
+ }
540
+ const validation = validateChangeName(name);
541
+ if (!validation.valid) {
542
+ throw new Error(validation.error);
543
+ }
544
+ // Validate schema if provided
545
+ if (options.schema) {
546
+ validateSchemaExists(options.schema);
547
+ }
548
+ const schemaDisplay = options.schema ? ` with schema '${options.schema}'` : '';
549
+ const spinner = ora(`Creating change '${name}'${schemaDisplay}...`).start();
550
+ try {
551
+ const projectRoot = process.cwd();
552
+ await createChange(projectRoot, name, { schema: options.schema });
553
+ // If description provided, create README.md with description
554
+ if (options.description) {
555
+ const { promises: fs } = await import('fs');
556
+ const changeDir = path.join(projectRoot, 'openspec', 'changes', name);
557
+ const readmePath = path.join(changeDir, 'README.md');
558
+ await fs.writeFile(readmePath, `# ${name}\n\n${options.description}\n`, 'utf-8');
559
+ }
560
+ const schemaUsed = options.schema ?? DEFAULT_SCHEMA;
561
+ spinner.succeed(`Created change '${name}' at openspec/changes/${name}/ (schema: ${schemaUsed})`);
562
+ }
563
+ catch (error) {
564
+ spinner.fail(`Failed to create change '${name}'`);
565
+ throw error;
566
+ }
567
+ }
568
+ // -----------------------------------------------------------------------------
569
+ // Artifact Experimental Setup Command
570
+ // -----------------------------------------------------------------------------
571
+ /**
572
+ * Generates Agent Skills and slash commands for the experimental artifact workflow.
573
+ * Creates .claude/skills/ directory with SKILL.md files following Agent Skills spec.
574
+ * Creates .claude/commands/opsx/ directory with slash command files.
575
+ */
576
+ async function artifactExperimentalSetupCommand() {
577
+ const spinner = ora('Setting up experimental artifact workflow...').start();
578
+ try {
579
+ const projectRoot = process.cwd();
580
+ const skillsDir = path.join(projectRoot, '.claude', 'skills');
581
+ const commandsDir = path.join(projectRoot, '.claude', 'commands', 'opsx');
582
+ // Get skill templates
583
+ const exploreSkill = getExploreSkillTemplate();
584
+ const newChangeSkill = getNewChangeSkillTemplate();
585
+ const continueChangeSkill = getContinueChangeSkillTemplate();
586
+ const applyChangeSkill = getApplyChangeSkillTemplate();
587
+ const ffChangeSkill = getFfChangeSkillTemplate();
588
+ const syncSpecsSkill = getSyncSpecsSkillTemplate();
589
+ const archiveChangeSkill = getArchiveChangeSkillTemplate();
590
+ // Get command templates
591
+ const exploreCommand = getOpsxExploreCommandTemplate();
592
+ const newCommand = getOpsxNewCommandTemplate();
593
+ const continueCommand = getOpsxContinueCommandTemplate();
594
+ const applyCommand = getOpsxApplyCommandTemplate();
595
+ const ffCommand = getOpsxFfCommandTemplate();
596
+ const syncCommand = getOpsxSyncCommandTemplate();
597
+ const archiveCommand = getOpsxArchiveCommandTemplate();
598
+ // Create skill directories and SKILL.md files
599
+ const skills = [
600
+ { template: exploreSkill, dirName: 'openspec-explore' },
601
+ { template: newChangeSkill, dirName: 'openspec-new-change' },
602
+ { template: continueChangeSkill, dirName: 'openspec-continue-change' },
603
+ { template: applyChangeSkill, dirName: 'openspec-apply-change' },
604
+ { template: ffChangeSkill, dirName: 'openspec-ff-change' },
605
+ { template: syncSpecsSkill, dirName: 'openspec-sync-specs' },
606
+ { template: archiveChangeSkill, dirName: 'openspec-archive-change' },
607
+ ];
608
+ const createdSkillFiles = [];
609
+ for (const { template, dirName } of skills) {
610
+ const skillDir = path.join(skillsDir, dirName);
611
+ const skillFile = path.join(skillDir, 'SKILL.md');
612
+ // Generate SKILL.md content with YAML frontmatter
613
+ const skillContent = `---
614
+ name: ${template.name}
615
+ description: ${template.description}
616
+ ---
617
+
618
+ ${template.instructions}
619
+ `;
620
+ // Write the skill file
621
+ await FileSystemUtils.writeFile(skillFile, skillContent);
622
+ createdSkillFiles.push(path.relative(projectRoot, skillFile));
623
+ }
624
+ // Create slash command files
625
+ const commands = [
626
+ { template: exploreCommand, fileName: 'explore.md' },
627
+ { template: newCommand, fileName: 'new.md' },
628
+ { template: continueCommand, fileName: 'continue.md' },
629
+ { template: applyCommand, fileName: 'apply.md' },
630
+ { template: ffCommand, fileName: 'ff.md' },
631
+ { template: syncCommand, fileName: 'sync.md' },
632
+ { template: archiveCommand, fileName: 'archive.md' },
633
+ ];
634
+ const createdCommandFiles = [];
635
+ for (const { template, fileName } of commands) {
636
+ const commandFile = path.join(commandsDir, fileName);
637
+ // Generate command content with YAML frontmatter
638
+ const commandContent = `---
639
+ name: ${template.name}
640
+ description: ${template.description}
641
+ category: ${template.category}
642
+ tags: [${template.tags.join(', ')}]
643
+ ---
644
+
645
+ ${template.content}
646
+ `;
647
+ // Write the command file
648
+ await FileSystemUtils.writeFile(commandFile, commandContent);
649
+ createdCommandFiles.push(path.relative(projectRoot, commandFile));
650
+ }
651
+ spinner.succeed('Experimental artifact workflow setup complete!');
652
+ // Print success message
653
+ console.log();
654
+ console.log(chalk.bold('🧪 Experimental Artifact Workflow Setup Complete'));
655
+ console.log();
656
+ console.log(chalk.bold('Skills Created:'));
657
+ for (const file of createdSkillFiles) {
658
+ console.log(chalk.green(' ✓ ' + file));
659
+ }
660
+ console.log();
661
+ console.log(chalk.bold('Slash Commands Created:'));
662
+ for (const file of createdCommandFiles) {
663
+ console.log(chalk.green(' ✓ ' + file));
664
+ }
665
+ console.log();
666
+ console.log(chalk.bold('📖 Usage:'));
667
+ console.log();
668
+ console.log(' ' + chalk.cyan('Skills') + ' work automatically in compatible editors:');
669
+ console.log(' • Claude Code - Auto-detected, ready to use');
670
+ console.log(' • Cursor - Enable in Settings → Rules → Import Settings');
671
+ console.log(' • Windsurf - Auto-imports from .claude directory');
672
+ console.log();
673
+ console.log(' Ask Claude naturally:');
674
+ console.log(' • "I want to start a new OpenSpec change to add <feature>"');
675
+ console.log(' • "Continue working on this change"');
676
+ console.log(' • "Implement the tasks for this change"');
677
+ console.log();
678
+ console.log(' ' + chalk.cyan('Slash Commands') + ' for explicit invocation:');
679
+ console.log(' • /opsx:explore - Think through ideas, investigate problems');
680
+ console.log(' • /opsx:new - Start a new change');
681
+ console.log(' • /opsx:continue - Create the next artifact');
682
+ console.log(' • /opsx:apply - Implement tasks');
683
+ console.log(' • /opsx:ff - Fast-forward: create all artifacts at once');
684
+ console.log(' • /opsx:sync - Sync delta specs to main specs');
685
+ console.log(' • /opsx:archive - Archive a completed change');
686
+ console.log();
687
+ console.log(chalk.yellow('💡 This is an experimental feature.'));
688
+ console.log(' Feedback welcome at: https://github.com/Fission-AI/OpenSpec/issues');
689
+ console.log();
690
+ }
691
+ catch (error) {
692
+ spinner.fail('Failed to setup experimental artifact workflow');
693
+ throw error;
694
+ }
695
+ }
696
+ async function schemasCommand(options) {
697
+ const schemas = listSchemasWithInfo();
698
+ if (options.json) {
699
+ console.log(JSON.stringify(schemas, null, 2));
700
+ return;
701
+ }
702
+ console.log('Available schemas:');
703
+ console.log();
704
+ for (const schema of schemas) {
705
+ const sourceLabel = schema.source === 'user' ? chalk.dim(' (user override)') : '';
706
+ console.log(` ${chalk.bold(schema.name)}${sourceLabel}`);
707
+ console.log(` ${schema.description}`);
708
+ console.log(` Artifacts: ${schema.artifacts.join(' → ')}`);
709
+ console.log();
710
+ }
711
+ }
712
+ // -----------------------------------------------------------------------------
713
+ // Command Registration
714
+ // -----------------------------------------------------------------------------
715
+ /**
716
+ * Registers all artifact workflow commands on the given program.
717
+ * All commands are marked as experimental in their help text.
718
+ */
719
+ export function registerArtifactWorkflowCommands(program) {
720
+ // Status command
721
+ program
722
+ .command('status')
723
+ .description('[Experimental] Display artifact completion status for a change')
724
+ .option('--change <id>', 'Change name to show status for')
725
+ .option('--schema <name>', 'Schema override (auto-detected from .openspec.yaml)')
726
+ .option('--json', 'Output as JSON')
727
+ .action(async (options) => {
728
+ try {
729
+ await statusCommand(options);
730
+ }
731
+ catch (error) {
732
+ console.log();
733
+ ora().fail(`Error: ${error.message}`);
734
+ process.exit(1);
735
+ }
736
+ });
737
+ // Instructions command
738
+ program
739
+ .command('instructions [artifact]')
740
+ .description('[Experimental] Output enriched instructions for creating an artifact or applying tasks')
741
+ .option('--change <id>', 'Change name')
742
+ .option('--schema <name>', 'Schema override (auto-detected from .openspec.yaml)')
743
+ .option('--json', 'Output as JSON')
744
+ .action(async (artifactId, options) => {
745
+ try {
746
+ // Special case: "apply" is not an artifact, but a command to get apply instructions
747
+ if (artifactId === 'apply') {
748
+ await applyInstructionsCommand(options);
749
+ }
750
+ else {
751
+ await instructionsCommand(artifactId, options);
752
+ }
753
+ }
754
+ catch (error) {
755
+ console.log();
756
+ ora().fail(`Error: ${error.message}`);
757
+ process.exit(1);
758
+ }
759
+ });
760
+ // Templates command
761
+ program
762
+ .command('templates')
763
+ .description('[Experimental] Show resolved template paths for all artifacts in a schema')
764
+ .option('--schema <name>', `Schema to use (default: ${DEFAULT_SCHEMA})`)
765
+ .option('--json', 'Output as JSON mapping artifact IDs to template paths')
766
+ .action(async (options) => {
767
+ try {
768
+ await templatesCommand(options);
769
+ }
770
+ catch (error) {
771
+ console.log();
772
+ ora().fail(`Error: ${error.message}`);
773
+ process.exit(1);
774
+ }
775
+ });
776
+ // Schemas command
777
+ program
778
+ .command('schemas')
779
+ .description('[Experimental] List available workflow schemas with descriptions')
780
+ .option('--json', 'Output as JSON (for agent use)')
781
+ .action(async (options) => {
782
+ try {
783
+ await schemasCommand(options);
784
+ }
785
+ catch (error) {
786
+ console.log();
787
+ ora().fail(`Error: ${error.message}`);
788
+ process.exit(1);
789
+ }
790
+ });
791
+ // New command group with change subcommand
792
+ const newCmd = program.command('new').description('[Experimental] Create new items');
793
+ newCmd
794
+ .command('change <name>')
795
+ .description('[Experimental] Create a new change directory')
796
+ .option('--description <text>', 'Description to add to README.md')
797
+ .option('--schema <name>', `Workflow schema to use (default: ${DEFAULT_SCHEMA})`)
798
+ .action(async (name, options) => {
799
+ try {
800
+ await newChangeCommand(name, options);
801
+ }
802
+ catch (error) {
803
+ console.log();
804
+ ora().fail(`Error: ${error.message}`);
805
+ process.exit(1);
806
+ }
807
+ });
808
+ // Artifact experimental setup command
809
+ program
810
+ .command('artifact-experimental-setup')
811
+ .description('[Experimental] Setup Agent Skills for the experimental artifact workflow')
812
+ .action(async () => {
813
+ try {
814
+ await artifactExperimentalSetupCommand();
815
+ }
816
+ catch (error) {
817
+ console.log();
818
+ ora().fail(`Error: ${error.message}`);
819
+ process.exit(1);
820
+ }
821
+ });
822
+ }
823
+ //# sourceMappingURL=artifact-workflow.js.map