@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
@@ -4,6 +4,7 @@ import * as os from 'node:os';
4
4
  // Constants
5
5
  export const GLOBAL_CONFIG_DIR_NAME = 'openspec';
6
6
  export const GLOBAL_CONFIG_FILE_NAME = 'config.json';
7
+ export const GLOBAL_DATA_DIR_NAME = 'openspec';
7
8
  const DEFAULT_CONFIG = {
8
9
  featureFlags: {}
9
10
  };
@@ -33,6 +34,33 @@ export function getGlobalConfigDir() {
33
34
  // Unix/macOS fallback: ~/.config
34
35
  return path.join(os.homedir(), '.config', GLOBAL_CONFIG_DIR_NAME);
35
36
  }
37
+ /**
38
+ * Gets the global data directory path following XDG Base Directory Specification.
39
+ * Used for user data like schema overrides.
40
+ *
41
+ * - All platforms: $XDG_DATA_HOME/openspec/ if XDG_DATA_HOME is set
42
+ * - Unix/macOS fallback: ~/.local/share/openspec/
43
+ * - Windows fallback: %LOCALAPPDATA%/openspec/
44
+ */
45
+ export function getGlobalDataDir() {
46
+ // XDG_DATA_HOME takes precedence on all platforms when explicitly set
47
+ const xdgDataHome = process.env.XDG_DATA_HOME;
48
+ if (xdgDataHome) {
49
+ return path.join(xdgDataHome, GLOBAL_DATA_DIR_NAME);
50
+ }
51
+ const platform = os.platform();
52
+ if (platform === 'win32') {
53
+ // Windows: use %LOCALAPPDATA%
54
+ const localAppData = process.env.LOCALAPPDATA;
55
+ if (localAppData) {
56
+ return path.join(localAppData, GLOBAL_DATA_DIR_NAME);
57
+ }
58
+ // Fallback for Windows if LOCALAPPDATA is not set
59
+ return path.join(os.homedir(), 'AppData', 'Local', GLOBAL_DATA_DIR_NAME);
60
+ }
61
+ // Unix/macOS fallback: ~/.local/share
62
+ return path.join(os.homedir(), '.local', 'share', GLOBAL_DATA_DIR_NAME);
63
+ }
36
64
  /**
37
65
  * Gets the path to the global config file.
38
66
  */
@@ -1,2 +1,2 @@
1
- export { GLOBAL_CONFIG_DIR_NAME, GLOBAL_CONFIG_FILE_NAME, type GlobalConfig, getGlobalConfigDir, getGlobalConfigPath, getGlobalConfig, saveGlobalConfig } from './global-config.js';
1
+ export { GLOBAL_CONFIG_DIR_NAME, GLOBAL_CONFIG_FILE_NAME, GLOBAL_DATA_DIR_NAME, type GlobalConfig, getGlobalConfigDir, getGlobalConfigPath, getGlobalConfig, saveGlobalConfig, getGlobalDataDir } from './global-config.js';
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1,3 +1,3 @@
1
1
  // Core OpenSpec logic will be implemented here
2
- export { GLOBAL_CONFIG_DIR_NAME, GLOBAL_CONFIG_FILE_NAME, getGlobalConfigDir, getGlobalConfigPath, getGlobalConfig, saveGlobalConfig } from './global-config.js';
2
+ export { GLOBAL_CONFIG_DIR_NAME, GLOBAL_CONFIG_FILE_NAME, GLOBAL_DATA_DIR_NAME, getGlobalConfigDir, getGlobalConfigPath, getGlobalConfig, saveGlobalConfig, getGlobalDataDir } from './global-config.js';
3
3
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,9 @@
1
+ interface ListOptions {
2
+ sort?: 'recent' | 'name';
3
+ json?: boolean;
4
+ }
1
5
  export declare class ListCommand {
2
- execute(targetPath?: string, mode?: 'changes' | 'specs'): Promise<void>;
6
+ execute(targetPath?: string, mode?: 'changes' | 'specs', options?: ListOptions): Promise<void>;
3
7
  }
8
+ export {};
4
9
  //# sourceMappingURL=list.d.ts.map
package/dist/core/list.js CHANGED
@@ -4,8 +4,64 @@ import { getTaskProgressForChange, formatTaskStatus } from '../utils/task-progre
4
4
  import { readFileSync } from 'fs';
5
5
  import { join } from 'path';
6
6
  import { MarkdownParser } from './parsers/markdown-parser.js';
7
+ /**
8
+ * Get the most recent modification time of any file in a directory (recursive).
9
+ * Falls back to the directory's own mtime if no files are found.
10
+ */
11
+ async function getLastModified(dirPath) {
12
+ let latest = null;
13
+ async function walk(dir) {
14
+ const entries = await fs.readdir(dir, { withFileTypes: true });
15
+ for (const entry of entries) {
16
+ const fullPath = path.join(dir, entry.name);
17
+ if (entry.isDirectory()) {
18
+ await walk(fullPath);
19
+ }
20
+ else {
21
+ const stat = await fs.stat(fullPath);
22
+ if (latest === null || stat.mtime > latest) {
23
+ latest = stat.mtime;
24
+ }
25
+ }
26
+ }
27
+ }
28
+ await walk(dirPath);
29
+ // If no files found, use the directory's own modification time
30
+ if (latest === null) {
31
+ const dirStat = await fs.stat(dirPath);
32
+ return dirStat.mtime;
33
+ }
34
+ return latest;
35
+ }
36
+ /**
37
+ * Format a date as relative time (e.g., "2 hours ago", "3 days ago")
38
+ */
39
+ function formatRelativeTime(date) {
40
+ const now = new Date();
41
+ const diffMs = now.getTime() - date.getTime();
42
+ const diffSecs = Math.floor(diffMs / 1000);
43
+ const diffMins = Math.floor(diffSecs / 60);
44
+ const diffHours = Math.floor(diffMins / 60);
45
+ const diffDays = Math.floor(diffHours / 24);
46
+ if (diffDays > 30) {
47
+ return date.toLocaleDateString();
48
+ }
49
+ else if (diffDays > 0) {
50
+ return `${diffDays}d ago`;
51
+ }
52
+ else if (diffHours > 0) {
53
+ return `${diffHours}h ago`;
54
+ }
55
+ else if (diffMins > 0) {
56
+ return `${diffMins}m ago`;
57
+ }
58
+ else {
59
+ return 'just now';
60
+ }
61
+ }
7
62
  export class ListCommand {
8
- async execute(targetPath = '.', mode = 'changes') {
63
+ async execute(targetPath = '.', mode = 'changes', options = {}) {
64
+ const { sort = 'recent', json = false } = options;
9
65
  if (mode === 'changes') {
10
66
  const changesDir = path.join(targetPath, 'openspec', 'changes');
11
67
  // Check if changes directory exists
@@ -21,21 +77,46 @@ export class ListCommand {
21
77
  .filter(entry => entry.isDirectory() && entry.name !== 'archive')
22
78
  .map(entry => entry.name);
23
79
  if (changeDirs.length === 0) {
24
- console.log('No active changes found.');
80
+ if (json) {
81
+ console.log(JSON.stringify({ changes: [] }));
82
+ }
83
+ else {
84
+ console.log('No active changes found.');
85
+ }
25
86
  return;
26
87
  }
27
88
  // Collect information about each change
28
89
  const changes = [];
29
90
  for (const changeDir of changeDirs) {
30
91
  const progress = await getTaskProgressForChange(changesDir, changeDir);
92
+ const changePath = path.join(changesDir, changeDir);
93
+ const lastModified = await getLastModified(changePath);
31
94
  changes.push({
32
95
  name: changeDir,
33
96
  completedTasks: progress.completed,
34
- totalTasks: progress.total
97
+ totalTasks: progress.total,
98
+ lastModified
35
99
  });
36
100
  }
37
- // Sort alphabetically by name
38
- changes.sort((a, b) => a.name.localeCompare(b.name));
101
+ // Sort by preference (default: recent first)
102
+ if (sort === 'recent') {
103
+ changes.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
104
+ }
105
+ else {
106
+ changes.sort((a, b) => a.name.localeCompare(b.name));
107
+ }
108
+ // JSON output for programmatic use
109
+ if (json) {
110
+ const jsonOutput = changes.map(c => ({
111
+ name: c.name,
112
+ completedTasks: c.completedTasks,
113
+ totalTasks: c.totalTasks,
114
+ lastModified: c.lastModified.toISOString(),
115
+ status: c.totalTasks === 0 ? 'no-tasks' : c.completedTasks === c.totalTasks ? 'complete' : 'in-progress'
116
+ }));
117
+ console.log(JSON.stringify({ changes: jsonOutput }, null, 2));
118
+ return;
119
+ }
39
120
  // Display results
40
121
  console.log('Changes:');
41
122
  const padding = ' ';
@@ -43,7 +124,8 @@ export class ListCommand {
43
124
  for (const change of changes) {
44
125
  const paddedName = change.name.padEnd(nameWidth);
45
126
  const status = formatTaskStatus({ total: change.totalTasks, completed: change.completedTasks });
46
- console.log(`${padding}${paddedName} ${status}`);
127
+ const timeAgo = formatRelativeTime(change.lastModified);
128
+ console.log(`${padding}${paddedName} ${status.padEnd(12)} ${timeAgo}`);
47
129
  }
48
130
  return;
49
131
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Spec Application Logic
3
+ *
4
+ * Extracted from ArchiveCommand to enable standalone spec application.
5
+ * Applies delta specs from a change to main specs without archiving.
6
+ */
7
+ export interface SpecUpdate {
8
+ source: string;
9
+ target: string;
10
+ exists: boolean;
11
+ }
12
+ export interface ApplyResult {
13
+ capability: string;
14
+ added: number;
15
+ modified: number;
16
+ removed: number;
17
+ renamed: number;
18
+ }
19
+ export interface SpecsApplyOutput {
20
+ changeName: string;
21
+ capabilities: ApplyResult[];
22
+ totals: {
23
+ added: number;
24
+ modified: number;
25
+ removed: number;
26
+ renamed: number;
27
+ };
28
+ noChanges: boolean;
29
+ }
30
+ /**
31
+ * Find all delta spec files that need to be applied from a change.
32
+ */
33
+ export declare function findSpecUpdates(changeDir: string, mainSpecsDir: string): Promise<SpecUpdate[]>;
34
+ /**
35
+ * Build an updated spec by applying delta operations.
36
+ * Returns the rebuilt content and counts of operations.
37
+ */
38
+ export declare function buildUpdatedSpec(update: SpecUpdate, changeName: string): Promise<{
39
+ rebuilt: string;
40
+ counts: {
41
+ added: number;
42
+ modified: number;
43
+ removed: number;
44
+ renamed: number;
45
+ };
46
+ }>;
47
+ /**
48
+ * Write an updated spec to disk.
49
+ */
50
+ export declare function writeUpdatedSpec(update: SpecUpdate, rebuilt: string, counts: {
51
+ added: number;
52
+ modified: number;
53
+ removed: number;
54
+ renamed: number;
55
+ }): Promise<void>;
56
+ /**
57
+ * Build a skeleton spec for new capabilities.
58
+ */
59
+ export declare function buildSpecSkeleton(specFolderName: string, changeName: string): string;
60
+ /**
61
+ * Apply all delta specs from a change to main specs.
62
+ *
63
+ * @param projectRoot - The project root directory
64
+ * @param changeName - The name of the change to apply
65
+ * @param options - Options for the operation
66
+ * @returns Result of the operation with counts
67
+ */
68
+ export declare function applySpecs(projectRoot: string, changeName: string, options?: {
69
+ dryRun?: boolean;
70
+ skipValidation?: boolean;
71
+ silent?: boolean;
72
+ }): Promise<SpecsApplyOutput>;
73
+ //# sourceMappingURL=specs-apply.d.ts.map
@@ -0,0 +1,384 @@
1
+ /**
2
+ * Spec Application Logic
3
+ *
4
+ * Extracted from ArchiveCommand to enable standalone spec application.
5
+ * Applies delta specs from a change to main specs without archiving.
6
+ */
7
+ import { promises as fs } from 'fs';
8
+ import path from 'path';
9
+ import chalk from 'chalk';
10
+ import { extractRequirementsSection, parseDeltaSpec, normalizeRequirementName, } from './parsers/requirement-blocks.js';
11
+ import { Validator } from './validation/validator.js';
12
+ // -----------------------------------------------------------------------------
13
+ // Public API
14
+ // -----------------------------------------------------------------------------
15
+ /**
16
+ * Find all delta spec files that need to be applied from a change.
17
+ */
18
+ export async function findSpecUpdates(changeDir, mainSpecsDir) {
19
+ const updates = [];
20
+ const changeSpecsDir = path.join(changeDir, 'specs');
21
+ try {
22
+ const entries = await fs.readdir(changeSpecsDir, { withFileTypes: true });
23
+ for (const entry of entries) {
24
+ if (entry.isDirectory()) {
25
+ const specFile = path.join(changeSpecsDir, entry.name, 'spec.md');
26
+ const targetFile = path.join(mainSpecsDir, entry.name, 'spec.md');
27
+ try {
28
+ await fs.access(specFile);
29
+ // Check if target exists
30
+ let exists = false;
31
+ try {
32
+ await fs.access(targetFile);
33
+ exists = true;
34
+ }
35
+ catch {
36
+ exists = false;
37
+ }
38
+ updates.push({
39
+ source: specFile,
40
+ target: targetFile,
41
+ exists,
42
+ });
43
+ }
44
+ catch {
45
+ // Source spec doesn't exist, skip
46
+ }
47
+ }
48
+ }
49
+ }
50
+ catch {
51
+ // No specs directory in change
52
+ }
53
+ return updates;
54
+ }
55
+ /**
56
+ * Build an updated spec by applying delta operations.
57
+ * Returns the rebuilt content and counts of operations.
58
+ */
59
+ export async function buildUpdatedSpec(update, changeName) {
60
+ // Read change spec content (delta-format expected)
61
+ const changeContent = await fs.readFile(update.source, 'utf-8');
62
+ // Parse deltas from the change spec file
63
+ const plan = parseDeltaSpec(changeContent);
64
+ const specName = path.basename(path.dirname(update.target));
65
+ // Pre-validate duplicates within sections
66
+ const addedNames = new Set();
67
+ for (const add of plan.added) {
68
+ const name = normalizeRequirementName(add.name);
69
+ if (addedNames.has(name)) {
70
+ throw new Error(`${specName} validation failed - duplicate requirement in ADDED for header "### Requirement: ${add.name}"`);
71
+ }
72
+ addedNames.add(name);
73
+ }
74
+ const modifiedNames = new Set();
75
+ for (const mod of plan.modified) {
76
+ const name = normalizeRequirementName(mod.name);
77
+ if (modifiedNames.has(name)) {
78
+ throw new Error(`${specName} validation failed - duplicate requirement in MODIFIED for header "### Requirement: ${mod.name}"`);
79
+ }
80
+ modifiedNames.add(name);
81
+ }
82
+ const removedNamesSet = new Set();
83
+ for (const rem of plan.removed) {
84
+ const name = normalizeRequirementName(rem);
85
+ if (removedNamesSet.has(name)) {
86
+ throw new Error(`${specName} validation failed - duplicate requirement in REMOVED for header "### Requirement: ${rem}"`);
87
+ }
88
+ removedNamesSet.add(name);
89
+ }
90
+ const renamedFromSet = new Set();
91
+ const renamedToSet = new Set();
92
+ for (const { from, to } of plan.renamed) {
93
+ const fromNorm = normalizeRequirementName(from);
94
+ const toNorm = normalizeRequirementName(to);
95
+ if (renamedFromSet.has(fromNorm)) {
96
+ throw new Error(`${specName} validation failed - duplicate FROM in RENAMED for header "### Requirement: ${from}"`);
97
+ }
98
+ if (renamedToSet.has(toNorm)) {
99
+ throw new Error(`${specName} validation failed - duplicate TO in RENAMED for header "### Requirement: ${to}"`);
100
+ }
101
+ renamedFromSet.add(fromNorm);
102
+ renamedToSet.add(toNorm);
103
+ }
104
+ // Pre-validate cross-section conflicts
105
+ const conflicts = [];
106
+ for (const n of modifiedNames) {
107
+ if (removedNamesSet.has(n))
108
+ conflicts.push({ name: n, a: 'MODIFIED', b: 'REMOVED' });
109
+ if (addedNames.has(n))
110
+ conflicts.push({ name: n, a: 'MODIFIED', b: 'ADDED' });
111
+ }
112
+ for (const n of addedNames) {
113
+ if (removedNamesSet.has(n))
114
+ conflicts.push({ name: n, a: 'ADDED', b: 'REMOVED' });
115
+ }
116
+ // Renamed interplay: MODIFIED must reference the NEW header, not FROM
117
+ for (const { from, to } of plan.renamed) {
118
+ const fromNorm = normalizeRequirementName(from);
119
+ const toNorm = normalizeRequirementName(to);
120
+ if (modifiedNames.has(fromNorm)) {
121
+ throw new Error(`${specName} validation failed - when a rename exists, MODIFIED must reference the NEW header "### Requirement: ${to}"`);
122
+ }
123
+ // Detect ADDED colliding with a RENAMED TO
124
+ if (addedNames.has(toNorm)) {
125
+ throw new Error(`${specName} validation failed - RENAMED TO header collides with ADDED for "### Requirement: ${to}"`);
126
+ }
127
+ }
128
+ if (conflicts.length > 0) {
129
+ const c = conflicts[0];
130
+ throw new Error(`${specName} validation failed - requirement present in multiple sections (${c.a} and ${c.b}) for header "### Requirement: ${c.name}"`);
131
+ }
132
+ const hasAnyDelta = plan.added.length + plan.modified.length + plan.removed.length + plan.renamed.length > 0;
133
+ if (!hasAnyDelta) {
134
+ throw new Error(`Delta parsing found no operations for ${path.basename(path.dirname(update.source))}. ` +
135
+ `Provide ADDED/MODIFIED/REMOVED/RENAMED sections in change spec.`);
136
+ }
137
+ // Load or create base target content
138
+ let targetContent;
139
+ let isNewSpec = false;
140
+ try {
141
+ targetContent = await fs.readFile(update.target, 'utf-8');
142
+ }
143
+ catch {
144
+ // Target spec does not exist; MODIFIED and RENAMED are not allowed for new specs
145
+ // REMOVED will be ignored with a warning since there's nothing to remove
146
+ if (plan.modified.length > 0 || plan.renamed.length > 0) {
147
+ throw new Error(`${specName}: target spec does not exist; only ADDED requirements are allowed for new specs. MODIFIED and RENAMED operations require an existing spec.`);
148
+ }
149
+ // Warn about REMOVED requirements being ignored for new specs
150
+ if (plan.removed.length > 0) {
151
+ console.log(chalk.yellow(`⚠️ Warning: ${specName} - ${plan.removed.length} REMOVED requirement(s) ignored for new spec (nothing to remove).`));
152
+ }
153
+ isNewSpec = true;
154
+ targetContent = buildSpecSkeleton(specName, changeName);
155
+ }
156
+ // Extract requirements section and build name->block map
157
+ const parts = extractRequirementsSection(targetContent);
158
+ const nameToBlock = new Map();
159
+ for (const block of parts.bodyBlocks) {
160
+ nameToBlock.set(normalizeRequirementName(block.name), block);
161
+ }
162
+ // Apply operations in order: RENAMED → REMOVED → MODIFIED → ADDED
163
+ // RENAMED
164
+ for (const r of plan.renamed) {
165
+ const from = normalizeRequirementName(r.from);
166
+ const to = normalizeRequirementName(r.to);
167
+ if (!nameToBlock.has(from)) {
168
+ throw new Error(`${specName} RENAMED failed for header "### Requirement: ${r.from}" - source not found`);
169
+ }
170
+ if (nameToBlock.has(to)) {
171
+ throw new Error(`${specName} RENAMED failed for header "### Requirement: ${r.to}" - target already exists`);
172
+ }
173
+ const block = nameToBlock.get(from);
174
+ const newHeader = `### Requirement: ${to}`;
175
+ const rawLines = block.raw.split('\n');
176
+ rawLines[0] = newHeader;
177
+ const renamedBlock = {
178
+ headerLine: newHeader,
179
+ name: to,
180
+ raw: rawLines.join('\n'),
181
+ };
182
+ nameToBlock.delete(from);
183
+ nameToBlock.set(to, renamedBlock);
184
+ }
185
+ // REMOVED
186
+ for (const name of plan.removed) {
187
+ const key = normalizeRequirementName(name);
188
+ if (!nameToBlock.has(key)) {
189
+ // For new specs, REMOVED requirements are already warned about and ignored
190
+ // For existing specs, missing requirements are an error
191
+ if (!isNewSpec) {
192
+ throw new Error(`${specName} REMOVED failed for header "### Requirement: ${name}" - not found`);
193
+ }
194
+ // Skip removal for new specs (already warned above)
195
+ continue;
196
+ }
197
+ nameToBlock.delete(key);
198
+ }
199
+ // MODIFIED
200
+ for (const mod of plan.modified) {
201
+ const key = normalizeRequirementName(mod.name);
202
+ if (!nameToBlock.has(key)) {
203
+ throw new Error(`${specName} MODIFIED failed for header "### Requirement: ${mod.name}" - not found`);
204
+ }
205
+ // Replace block with provided raw (ensure header line matches key)
206
+ const modHeaderMatch = mod.raw.split('\n')[0].match(/^###\s*Requirement:\s*(.+)\s*$/);
207
+ if (!modHeaderMatch || normalizeRequirementName(modHeaderMatch[1]) !== key) {
208
+ throw new Error(`${specName} MODIFIED failed for header "### Requirement: ${mod.name}" - header mismatch in content`);
209
+ }
210
+ nameToBlock.set(key, mod);
211
+ }
212
+ // ADDED
213
+ for (const add of plan.added) {
214
+ const key = normalizeRequirementName(add.name);
215
+ if (nameToBlock.has(key)) {
216
+ throw new Error(`${specName} ADDED failed for header "### Requirement: ${add.name}" - already exists`);
217
+ }
218
+ nameToBlock.set(key, add);
219
+ }
220
+ // Duplicates within resulting map are implicitly prevented by key uniqueness.
221
+ // Recompose requirements section preserving original ordering where possible
222
+ const keptOrder = [];
223
+ const seen = new Set();
224
+ for (const block of parts.bodyBlocks) {
225
+ const key = normalizeRequirementName(block.name);
226
+ const replacement = nameToBlock.get(key);
227
+ if (replacement) {
228
+ keptOrder.push(replacement);
229
+ seen.add(key);
230
+ }
231
+ }
232
+ // Append any newly added that were not in original order
233
+ for (const [key, block] of nameToBlock.entries()) {
234
+ if (!seen.has(key)) {
235
+ keptOrder.push(block);
236
+ }
237
+ }
238
+ const reqBody = [parts.preamble && parts.preamble.trim() ? parts.preamble.trimEnd() : '']
239
+ .filter(Boolean)
240
+ .concat(keptOrder.map((b) => b.raw))
241
+ .join('\n\n')
242
+ .trimEnd();
243
+ const rebuilt = [parts.before.trimEnd(), parts.headerLine, reqBody, parts.after]
244
+ .filter((s, idx) => !(idx === 0 && s === ''))
245
+ .join('\n')
246
+ .replace(/\n{3,}/g, '\n\n');
247
+ return {
248
+ rebuilt,
249
+ counts: {
250
+ added: plan.added.length,
251
+ modified: plan.modified.length,
252
+ removed: plan.removed.length,
253
+ renamed: plan.renamed.length,
254
+ },
255
+ };
256
+ }
257
+ /**
258
+ * Write an updated spec to disk.
259
+ */
260
+ export async function writeUpdatedSpec(update, rebuilt, counts) {
261
+ // Create target directory if needed
262
+ const targetDir = path.dirname(update.target);
263
+ await fs.mkdir(targetDir, { recursive: true });
264
+ await fs.writeFile(update.target, rebuilt);
265
+ const specName = path.basename(path.dirname(update.target));
266
+ console.log(`Applying changes to openspec/specs/${specName}/spec.md:`);
267
+ if (counts.added)
268
+ console.log(` + ${counts.added} added`);
269
+ if (counts.modified)
270
+ console.log(` ~ ${counts.modified} modified`);
271
+ if (counts.removed)
272
+ console.log(` - ${counts.removed} removed`);
273
+ if (counts.renamed)
274
+ console.log(` → ${counts.renamed} renamed`);
275
+ }
276
+ /**
277
+ * Build a skeleton spec for new capabilities.
278
+ */
279
+ export function buildSpecSkeleton(specFolderName, changeName) {
280
+ const titleBase = specFolderName;
281
+ return `# ${titleBase} Specification\n\n## Purpose\nTBD - created by archiving change ${changeName}. Update Purpose after archive.\n\n## Requirements\n`;
282
+ }
283
+ /**
284
+ * Apply all delta specs from a change to main specs.
285
+ *
286
+ * @param projectRoot - The project root directory
287
+ * @param changeName - The name of the change to apply
288
+ * @param options - Options for the operation
289
+ * @returns Result of the operation with counts
290
+ */
291
+ export async function applySpecs(projectRoot, changeName, options = {}) {
292
+ const changeDir = path.join(projectRoot, 'openspec', 'changes', changeName);
293
+ const mainSpecsDir = path.join(projectRoot, 'openspec', 'specs');
294
+ // Verify change exists
295
+ try {
296
+ const stat = await fs.stat(changeDir);
297
+ if (!stat.isDirectory()) {
298
+ throw new Error(`Change '${changeName}' not found.`);
299
+ }
300
+ }
301
+ catch {
302
+ throw new Error(`Change '${changeName}' not found.`);
303
+ }
304
+ // Find specs to update
305
+ const specUpdates = await findSpecUpdates(changeDir, mainSpecsDir);
306
+ if (specUpdates.length === 0) {
307
+ return {
308
+ changeName,
309
+ capabilities: [],
310
+ totals: { added: 0, modified: 0, removed: 0, renamed: 0 },
311
+ noChanges: true,
312
+ };
313
+ }
314
+ // Prepare all updates first (validation pass, no writes)
315
+ const prepared = [];
316
+ for (const update of specUpdates) {
317
+ const built = await buildUpdatedSpec(update, changeName);
318
+ prepared.push({ update, rebuilt: built.rebuilt, counts: built.counts });
319
+ }
320
+ // Validate rebuilt specs unless validation is skipped
321
+ if (!options.skipValidation) {
322
+ const validator = new Validator();
323
+ for (const p of prepared) {
324
+ const specName = path.basename(path.dirname(p.update.target));
325
+ const report = await validator.validateSpecContent(specName, p.rebuilt);
326
+ if (!report.valid) {
327
+ const errors = report.issues
328
+ .filter((i) => i.level === 'ERROR')
329
+ .map((i) => ` ✗ ${i.message}`)
330
+ .join('\n');
331
+ throw new Error(`Validation errors in rebuilt spec for ${specName}:\n${errors}`);
332
+ }
333
+ }
334
+ }
335
+ // Build results
336
+ const capabilities = [];
337
+ const totals = { added: 0, modified: 0, removed: 0, renamed: 0 };
338
+ for (const p of prepared) {
339
+ const capability = path.basename(path.dirname(p.update.target));
340
+ if (!options.dryRun) {
341
+ // Write the updated spec
342
+ const targetDir = path.dirname(p.update.target);
343
+ await fs.mkdir(targetDir, { recursive: true });
344
+ await fs.writeFile(p.update.target, p.rebuilt);
345
+ if (!options.silent) {
346
+ console.log(`Applying changes to openspec/specs/${capability}/spec.md:`);
347
+ if (p.counts.added)
348
+ console.log(` + ${p.counts.added} added`);
349
+ if (p.counts.modified)
350
+ console.log(` ~ ${p.counts.modified} modified`);
351
+ if (p.counts.removed)
352
+ console.log(` - ${p.counts.removed} removed`);
353
+ if (p.counts.renamed)
354
+ console.log(` → ${p.counts.renamed} renamed`);
355
+ }
356
+ }
357
+ else if (!options.silent) {
358
+ console.log(`Would apply changes to openspec/specs/${capability}/spec.md:`);
359
+ if (p.counts.added)
360
+ console.log(` + ${p.counts.added} added`);
361
+ if (p.counts.modified)
362
+ console.log(` ~ ${p.counts.modified} modified`);
363
+ if (p.counts.removed)
364
+ console.log(` - ${p.counts.removed} removed`);
365
+ if (p.counts.renamed)
366
+ console.log(` → ${p.counts.renamed} renamed`);
367
+ }
368
+ capabilities.push({
369
+ capability,
370
+ ...p.counts,
371
+ });
372
+ totals.added += p.counts.added;
373
+ totals.modified += p.counts.modified;
374
+ totals.removed += p.counts.removed;
375
+ totals.renamed += p.counts.renamed;
376
+ }
377
+ return {
378
+ changeName,
379
+ capabilities,
380
+ totals,
381
+ noChanges: false,
382
+ };
383
+ }
384
+ //# sourceMappingURL=specs-apply.js.map