@exodus/openspec 1.2.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 (272) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +203 -0
  3. package/bin/openspec.js +3 -0
  4. package/dist/cli/index.d.ts +2 -0
  5. package/dist/cli/index.js +482 -0
  6. package/dist/commands/change.d.ts +35 -0
  7. package/dist/commands/change.js +277 -0
  8. package/dist/commands/completion.d.ts +72 -0
  9. package/dist/commands/completion.js +257 -0
  10. package/dist/commands/config.d.ts +36 -0
  11. package/dist/commands/config.js +552 -0
  12. package/dist/commands/feedback.d.ts +9 -0
  13. package/dist/commands/feedback.js +183 -0
  14. package/dist/commands/schema.d.ts +6 -0
  15. package/dist/commands/schema.js +869 -0
  16. package/dist/commands/show.d.ts +14 -0
  17. package/dist/commands/show.js +132 -0
  18. package/dist/commands/spec.d.ts +15 -0
  19. package/dist/commands/spec.js +225 -0
  20. package/dist/commands/validate.d.ts +24 -0
  21. package/dist/commands/validate.js +294 -0
  22. package/dist/commands/workflow/index.d.ts +17 -0
  23. package/dist/commands/workflow/index.js +12 -0
  24. package/dist/commands/workflow/instructions.d.ts +29 -0
  25. package/dist/commands/workflow/instructions.js +381 -0
  26. package/dist/commands/workflow/new-change.d.ts +11 -0
  27. package/dist/commands/workflow/new-change.js +44 -0
  28. package/dist/commands/workflow/schemas.d.ts +10 -0
  29. package/dist/commands/workflow/schemas.js +34 -0
  30. package/dist/commands/workflow/shared.d.ts +57 -0
  31. package/dist/commands/workflow/shared.js +116 -0
  32. package/dist/commands/workflow/status.d.ts +14 -0
  33. package/dist/commands/workflow/status.js +75 -0
  34. package/dist/commands/workflow/templates.d.ts +16 -0
  35. package/dist/commands/workflow/templates.js +68 -0
  36. package/dist/core/archive.d.ts +11 -0
  37. package/dist/core/archive.js +318 -0
  38. package/dist/core/artifact-graph/graph.d.ts +56 -0
  39. package/dist/core/artifact-graph/graph.js +141 -0
  40. package/dist/core/artifact-graph/index.d.ts +7 -0
  41. package/dist/core/artifact-graph/index.js +13 -0
  42. package/dist/core/artifact-graph/instruction-loader.d.ts +143 -0
  43. package/dist/core/artifact-graph/instruction-loader.js +214 -0
  44. package/dist/core/artifact-graph/resolver.d.ts +81 -0
  45. package/dist/core/artifact-graph/resolver.js +257 -0
  46. package/dist/core/artifact-graph/schema.d.ts +13 -0
  47. package/dist/core/artifact-graph/schema.js +108 -0
  48. package/dist/core/artifact-graph/state.d.ts +12 -0
  49. package/dist/core/artifact-graph/state.js +54 -0
  50. package/dist/core/artifact-graph/types.d.ts +45 -0
  51. package/dist/core/artifact-graph/types.js +43 -0
  52. package/dist/core/available-tools.d.ts +16 -0
  53. package/dist/core/available-tools.js +30 -0
  54. package/dist/core/command-generation/adapters/amazon-q.d.ts +13 -0
  55. package/dist/core/command-generation/adapters/amazon-q.js +26 -0
  56. package/dist/core/command-generation/adapters/antigravity.d.ts +13 -0
  57. package/dist/core/command-generation/adapters/antigravity.js +26 -0
  58. package/dist/core/command-generation/adapters/auggie.d.ts +13 -0
  59. package/dist/core/command-generation/adapters/auggie.js +27 -0
  60. package/dist/core/command-generation/adapters/claude.d.ts +13 -0
  61. package/dist/core/command-generation/adapters/claude.js +50 -0
  62. package/dist/core/command-generation/adapters/cline.d.ts +14 -0
  63. package/dist/core/command-generation/adapters/cline.js +27 -0
  64. package/dist/core/command-generation/adapters/codebuddy.d.ts +13 -0
  65. package/dist/core/command-generation/adapters/codebuddy.js +28 -0
  66. package/dist/core/command-generation/adapters/codex.d.ts +16 -0
  67. package/dist/core/command-generation/adapters/codex.js +39 -0
  68. package/dist/core/command-generation/adapters/continue.d.ts +13 -0
  69. package/dist/core/command-generation/adapters/continue.js +28 -0
  70. package/dist/core/command-generation/adapters/costrict.d.ts +13 -0
  71. package/dist/core/command-generation/adapters/costrict.js +27 -0
  72. package/dist/core/command-generation/adapters/crush.d.ts +13 -0
  73. package/dist/core/command-generation/adapters/crush.js +30 -0
  74. package/dist/core/command-generation/adapters/cursor.d.ts +14 -0
  75. package/dist/core/command-generation/adapters/cursor.js +44 -0
  76. package/dist/core/command-generation/adapters/factory.d.ts +13 -0
  77. package/dist/core/command-generation/adapters/factory.js +27 -0
  78. package/dist/core/command-generation/adapters/gemini.d.ts +13 -0
  79. package/dist/core/command-generation/adapters/gemini.js +26 -0
  80. package/dist/core/command-generation/adapters/github-copilot.d.ts +13 -0
  81. package/dist/core/command-generation/adapters/github-copilot.js +26 -0
  82. package/dist/core/command-generation/adapters/iflow.d.ts +13 -0
  83. package/dist/core/command-generation/adapters/iflow.js +29 -0
  84. package/dist/core/command-generation/adapters/index.d.ts +29 -0
  85. package/dist/core/command-generation/adapters/index.js +29 -0
  86. package/dist/core/command-generation/adapters/kilocode.d.ts +14 -0
  87. package/dist/core/command-generation/adapters/kilocode.js +23 -0
  88. package/dist/core/command-generation/adapters/kiro.d.ts +13 -0
  89. package/dist/core/command-generation/adapters/kiro.js +26 -0
  90. package/dist/core/command-generation/adapters/opencode.d.ts +13 -0
  91. package/dist/core/command-generation/adapters/opencode.js +29 -0
  92. package/dist/core/command-generation/adapters/pi.d.ts +14 -0
  93. package/dist/core/command-generation/adapters/pi.js +41 -0
  94. package/dist/core/command-generation/adapters/qoder.d.ts +13 -0
  95. package/dist/core/command-generation/adapters/qoder.js +30 -0
  96. package/dist/core/command-generation/adapters/qwen.d.ts +13 -0
  97. package/dist/core/command-generation/adapters/qwen.js +26 -0
  98. package/dist/core/command-generation/adapters/roocode.d.ts +14 -0
  99. package/dist/core/command-generation/adapters/roocode.js +27 -0
  100. package/dist/core/command-generation/adapters/windsurf.d.ts +14 -0
  101. package/dist/core/command-generation/adapters/windsurf.js +51 -0
  102. package/dist/core/command-generation/generator.d.ts +21 -0
  103. package/dist/core/command-generation/generator.js +27 -0
  104. package/dist/core/command-generation/index.d.ts +22 -0
  105. package/dist/core/command-generation/index.js +24 -0
  106. package/dist/core/command-generation/registry.d.ts +36 -0
  107. package/dist/core/command-generation/registry.js +92 -0
  108. package/dist/core/command-generation/types.d.ts +56 -0
  109. package/dist/core/command-generation/types.js +8 -0
  110. package/dist/core/completions/command-registry.d.ts +7 -0
  111. package/dist/core/completions/command-registry.js +461 -0
  112. package/dist/core/completions/completion-provider.d.ts +60 -0
  113. package/dist/core/completions/completion-provider.js +102 -0
  114. package/dist/core/completions/factory.d.ts +64 -0
  115. package/dist/core/completions/factory.js +75 -0
  116. package/dist/core/completions/generators/bash-generator.d.ts +32 -0
  117. package/dist/core/completions/generators/bash-generator.js +174 -0
  118. package/dist/core/completions/generators/fish-generator.d.ts +32 -0
  119. package/dist/core/completions/generators/fish-generator.js +157 -0
  120. package/dist/core/completions/generators/powershell-generator.d.ts +33 -0
  121. package/dist/core/completions/generators/powershell-generator.js +207 -0
  122. package/dist/core/completions/generators/zsh-generator.d.ts +44 -0
  123. package/dist/core/completions/generators/zsh-generator.js +250 -0
  124. package/dist/core/completions/installers/bash-installer.d.ts +87 -0
  125. package/dist/core/completions/installers/bash-installer.js +318 -0
  126. package/dist/core/completions/installers/fish-installer.d.ts +43 -0
  127. package/dist/core/completions/installers/fish-installer.js +143 -0
  128. package/dist/core/completions/installers/powershell-installer.d.ts +88 -0
  129. package/dist/core/completions/installers/powershell-installer.js +327 -0
  130. package/dist/core/completions/installers/zsh-installer.d.ts +125 -0
  131. package/dist/core/completions/installers/zsh-installer.js +449 -0
  132. package/dist/core/completions/templates/bash-templates.d.ts +6 -0
  133. package/dist/core/completions/templates/bash-templates.js +24 -0
  134. package/dist/core/completions/templates/fish-templates.d.ts +7 -0
  135. package/dist/core/completions/templates/fish-templates.js +39 -0
  136. package/dist/core/completions/templates/powershell-templates.d.ts +6 -0
  137. package/dist/core/completions/templates/powershell-templates.js +25 -0
  138. package/dist/core/completions/templates/zsh-templates.d.ts +6 -0
  139. package/dist/core/completions/templates/zsh-templates.js +36 -0
  140. package/dist/core/completions/types.d.ts +79 -0
  141. package/dist/core/completions/types.js +2 -0
  142. package/dist/core/config-prompts.d.ts +9 -0
  143. package/dist/core/config-prompts.js +34 -0
  144. package/dist/core/config-schema.d.ts +86 -0
  145. package/dist/core/config-schema.js +213 -0
  146. package/dist/core/config.d.ts +17 -0
  147. package/dist/core/config.js +33 -0
  148. package/dist/core/converters/json-converter.d.ts +6 -0
  149. package/dist/core/converters/json-converter.js +51 -0
  150. package/dist/core/global-config.d.ts +44 -0
  151. package/dist/core/global-config.js +125 -0
  152. package/dist/core/index.d.ts +2 -0
  153. package/dist/core/index.js +3 -0
  154. package/dist/core/init.d.ts +38 -0
  155. package/dist/core/init.js +625 -0
  156. package/dist/core/legacy-cleanup.d.ts +162 -0
  157. package/dist/core/legacy-cleanup.js +512 -0
  158. package/dist/core/list.d.ts +9 -0
  159. package/dist/core/list.js +171 -0
  160. package/dist/core/migration.d.ts +23 -0
  161. package/dist/core/migration.js +108 -0
  162. package/dist/core/parsers/change-parser.d.ts +13 -0
  163. package/dist/core/parsers/change-parser.js +193 -0
  164. package/dist/core/parsers/markdown-parser.d.ts +22 -0
  165. package/dist/core/parsers/markdown-parser.js +187 -0
  166. package/dist/core/parsers/requirement-blocks.d.ts +37 -0
  167. package/dist/core/parsers/requirement-blocks.js +201 -0
  168. package/dist/core/profile-sync-drift.d.ts +38 -0
  169. package/dist/core/profile-sync-drift.js +200 -0
  170. package/dist/core/profiles.d.ts +26 -0
  171. package/dist/core/profiles.js +40 -0
  172. package/dist/core/project-config.d.ts +64 -0
  173. package/dist/core/project-config.js +223 -0
  174. package/dist/core/schemas/base.schema.d.ts +13 -0
  175. package/dist/core/schemas/base.schema.js +13 -0
  176. package/dist/core/schemas/change.schema.d.ts +73 -0
  177. package/dist/core/schemas/change.schema.js +31 -0
  178. package/dist/core/schemas/index.d.ts +4 -0
  179. package/dist/core/schemas/index.js +4 -0
  180. package/dist/core/schemas/spec.schema.d.ts +18 -0
  181. package/dist/core/schemas/spec.schema.js +15 -0
  182. package/dist/core/shared/index.d.ts +8 -0
  183. package/dist/core/shared/index.js +8 -0
  184. package/dist/core/shared/skill-generation.d.ts +49 -0
  185. package/dist/core/shared/skill-generation.js +96 -0
  186. package/dist/core/shared/tool-detection.d.ts +71 -0
  187. package/dist/core/shared/tool-detection.js +158 -0
  188. package/dist/core/specs-apply.d.ts +73 -0
  189. package/dist/core/specs-apply.js +384 -0
  190. package/dist/core/styles/palette.d.ts +7 -0
  191. package/dist/core/styles/palette.js +8 -0
  192. package/dist/core/templates/index.d.ts +8 -0
  193. package/dist/core/templates/index.js +9 -0
  194. package/dist/core/templates/skill-templates.d.ts +19 -0
  195. package/dist/core/templates/skill-templates.js +18 -0
  196. package/dist/core/templates/types.d.ts +19 -0
  197. package/dist/core/templates/types.js +5 -0
  198. package/dist/core/templates/workflows/apply-change.d.ts +10 -0
  199. package/dist/core/templates/workflows/apply-change.js +362 -0
  200. package/dist/core/templates/workflows/archive-change.d.ts +10 -0
  201. package/dist/core/templates/workflows/archive-change.js +331 -0
  202. package/dist/core/templates/workflows/bulk-archive-change.d.ts +10 -0
  203. package/dist/core/templates/workflows/bulk-archive-change.js +488 -0
  204. package/dist/core/templates/workflows/continue-change.d.ts +10 -0
  205. package/dist/core/templates/workflows/continue-change.js +232 -0
  206. package/dist/core/templates/workflows/explore.d.ts +10 -0
  207. package/dist/core/templates/workflows/explore.js +527 -0
  208. package/dist/core/templates/workflows/feedback.d.ts +9 -0
  209. package/dist/core/templates/workflows/feedback.js +108 -0
  210. package/dist/core/templates/workflows/ff-change.d.ts +10 -0
  211. package/dist/core/templates/workflows/ff-change.js +198 -0
  212. package/dist/core/templates/workflows/new-change.d.ts +10 -0
  213. package/dist/core/templates/workflows/new-change.js +143 -0
  214. package/dist/core/templates/workflows/onboard.d.ts +10 -0
  215. package/dist/core/templates/workflows/onboard.js +565 -0
  216. package/dist/core/templates/workflows/propose.d.ts +10 -0
  217. package/dist/core/templates/workflows/propose.js +306 -0
  218. package/dist/core/templates/workflows/sync-specs.d.ts +10 -0
  219. package/dist/core/templates/workflows/sync-specs.js +272 -0
  220. package/dist/core/templates/workflows/verify-change.d.ts +10 -0
  221. package/dist/core/templates/workflows/verify-change.js +332 -0
  222. package/dist/core/update.d.ts +77 -0
  223. package/dist/core/update.js +537 -0
  224. package/dist/core/validation/constants.d.ts +34 -0
  225. package/dist/core/validation/constants.js +40 -0
  226. package/dist/core/validation/types.d.ts +18 -0
  227. package/dist/core/validation/types.js +2 -0
  228. package/dist/core/validation/validator.d.ts +33 -0
  229. package/dist/core/validation/validator.js +409 -0
  230. package/dist/core/view.d.ts +8 -0
  231. package/dist/core/view.js +168 -0
  232. package/dist/core/workspace.d.ts +18 -0
  233. package/dist/core/workspace.js +103 -0
  234. package/dist/index.d.ts +3 -0
  235. package/dist/index.js +3 -0
  236. package/dist/prompts/searchable-multi-select.d.ts +28 -0
  237. package/dist/prompts/searchable-multi-select.js +159 -0
  238. package/dist/telemetry/config.d.ts +32 -0
  239. package/dist/telemetry/config.js +68 -0
  240. package/dist/telemetry/index.d.ts +31 -0
  241. package/dist/telemetry/index.js +145 -0
  242. package/dist/ui/ascii-patterns.d.ts +16 -0
  243. package/dist/ui/ascii-patterns.js +133 -0
  244. package/dist/ui/welcome-screen.d.ts +10 -0
  245. package/dist/ui/welcome-screen.js +146 -0
  246. package/dist/utils/change-metadata.d.ts +51 -0
  247. package/dist/utils/change-metadata.js +147 -0
  248. package/dist/utils/change-utils.d.ts +62 -0
  249. package/dist/utils/change-utils.js +121 -0
  250. package/dist/utils/command-references.d.ts +18 -0
  251. package/dist/utils/command-references.js +20 -0
  252. package/dist/utils/file-system.d.ts +36 -0
  253. package/dist/utils/file-system.js +281 -0
  254. package/dist/utils/index.d.ts +6 -0
  255. package/dist/utils/index.js +9 -0
  256. package/dist/utils/interactive.d.ts +18 -0
  257. package/dist/utils/interactive.js +21 -0
  258. package/dist/utils/item-discovery.d.ts +4 -0
  259. package/dist/utils/item-discovery.js +72 -0
  260. package/dist/utils/match.d.ts +3 -0
  261. package/dist/utils/match.js +22 -0
  262. package/dist/utils/shell-detection.d.ts +20 -0
  263. package/dist/utils/shell-detection.js +41 -0
  264. package/dist/utils/task-progress.d.ts +8 -0
  265. package/dist/utils/task-progress.js +36 -0
  266. package/package.json +83 -0
  267. package/schemas/spec-driven/schema.yaml +153 -0
  268. package/schemas/spec-driven/templates/design.md +19 -0
  269. package/schemas/spec-driven/templates/proposal.md +23 -0
  270. package/schemas/spec-driven/templates/spec.md +8 -0
  271. package/schemas/spec-driven/templates/tasks.md +9 -0
  272. package/scripts/postinstall.js +147 -0
@@ -0,0 +1,625 @@
1
+ /**
2
+ * Init Command
3
+ *
4
+ * Sets up OpenSpec with Agent Skills and /opsx:* slash commands.
5
+ * This is the unified setup command that replaces both the old init and experimental commands.
6
+ */
7
+ import path from 'path';
8
+ import chalk from 'chalk';
9
+ import ora from 'ora';
10
+ import * as fs from 'fs';
11
+ import { createRequire } from 'module';
12
+ import { FileSystemUtils } from '../utils/file-system.js';
13
+ import { transformToHyphenCommands } from '../utils/command-references.js';
14
+ import { AI_TOOLS, OPENSPEC_DIR_NAME, } from './config.js';
15
+ import { PALETTE } from './styles/palette.js';
16
+ import { isInteractive } from '../utils/interactive.js';
17
+ import { serializeConfig } from './config-prompts.js';
18
+ import { generateCommands, CommandAdapterRegistry, } from './command-generation/index.js';
19
+ import { detectLegacyArtifacts, cleanupLegacyArtifacts, formatCleanupSummary, formatDetectionSummary, } from './legacy-cleanup.js';
20
+ import { getToolsWithSkillsDir, getToolStates, getSkillTemplates, getCommandContents, generateSkillContent, } from './shared/index.js';
21
+ import { getGlobalConfig } from './global-config.js';
22
+ import { getProfileWorkflows, ALL_WORKFLOWS } from './profiles.js';
23
+ import { getAvailableTools } from './available-tools.js';
24
+ import { migrateIfNeeded } from './migration.js';
25
+ import { detectMonorepoScopes, writeWorkspaceConfig, isWorkspace } from './workspace.js';
26
+ const require = createRequire(import.meta.url);
27
+ const { version: OPENSPEC_VERSION } = require('../../package.json');
28
+ // -----------------------------------------------------------------------------
29
+ // Constants
30
+ // -----------------------------------------------------------------------------
31
+ const DEFAULT_SCHEMA = 'spec-driven';
32
+ const PROGRESS_SPINNER = {
33
+ interval: 80,
34
+ frames: ['░░░', '▒░░', '▒▒░', '▒▒▒', '▓▒▒', '▓▓▒', '▓▓▓', '▒▓▓', '░▒▓'],
35
+ };
36
+ const WORKFLOW_TO_SKILL_DIR = {
37
+ 'explore': 'openspec-explore',
38
+ 'new': 'openspec-new-change',
39
+ 'continue': 'openspec-continue-change',
40
+ 'apply': 'openspec-apply-change',
41
+ 'ff': 'openspec-ff-change',
42
+ 'sync': 'openspec-sync-specs',
43
+ 'archive': 'openspec-archive-change',
44
+ 'bulk-archive': 'openspec-bulk-archive-change',
45
+ 'verify': 'openspec-verify-change',
46
+ 'onboard': 'openspec-onboard',
47
+ 'propose': 'openspec-propose',
48
+ };
49
+ // -----------------------------------------------------------------------------
50
+ // Init Command Class
51
+ // -----------------------------------------------------------------------------
52
+ export class InitCommand {
53
+ toolsArg;
54
+ force;
55
+ interactiveOption;
56
+ profileOverride;
57
+ constructor(options = {}) {
58
+ this.toolsArg = options.tools;
59
+ this.force = options.force ?? false;
60
+ this.interactiveOption = options.interactive;
61
+ this.profileOverride = options.profile;
62
+ }
63
+ async execute(targetPath) {
64
+ const projectPath = path.resolve(targetPath);
65
+ const openspecDir = OPENSPEC_DIR_NAME;
66
+ const openspecPath = path.join(projectPath, openspecDir);
67
+ // Validation happens silently in the background
68
+ const extendMode = await this.validate(projectPath, openspecPath);
69
+ // Check for legacy artifacts and handle cleanup
70
+ await this.handleLegacyCleanup(projectPath, extendMode);
71
+ // Detect available tools in the project (task 7.1)
72
+ const detectedTools = getAvailableTools(projectPath);
73
+ // Migration check: migrate existing projects to profile system (task 7.3)
74
+ if (extendMode) {
75
+ migrateIfNeeded(projectPath, detectedTools);
76
+ }
77
+ // Show animated welcome screen (interactive mode only)
78
+ const canPrompt = this.canPromptInteractively();
79
+ if (canPrompt) {
80
+ const { showWelcomeScreen } = await import('../ui/welcome-screen.js');
81
+ await showWelcomeScreen();
82
+ }
83
+ // Validate profile override early so invalid values fail before tool setup.
84
+ // The resolved value is consumed later when generation reads effective config.
85
+ this.resolveProfileOverride();
86
+ // Get tool states before processing
87
+ const toolStates = getToolStates(projectPath);
88
+ // Get tool selection (pass detected tools for pre-selection)
89
+ const selectedToolIds = await this.getSelectedTools(toolStates, extendMode, detectedTools, projectPath);
90
+ // Validate selected tools
91
+ const validatedTools = this.validateTools(selectedToolIds, toolStates);
92
+ // Create directory structure and config
93
+ await this.createDirectoryStructure(openspecPath, extendMode);
94
+ // Detect monorepo and offer workspace setup
95
+ await this.handleWorkspaceDetection(projectPath, extendMode);
96
+ // Generate skills and commands for each tool
97
+ const results = await this.generateSkillsAndCommands(projectPath, validatedTools);
98
+ // Create config.yaml if needed
99
+ const configStatus = await this.createConfig(openspecPath, extendMode);
100
+ // Display success message
101
+ this.displaySuccessMessage(projectPath, validatedTools, results, configStatus);
102
+ }
103
+ // ═══════════════════════════════════════════════════════════
104
+ // VALIDATION & SETUP
105
+ // ═══════════════════════════════════════════════════════════
106
+ async validate(projectPath, openspecPath) {
107
+ const extendMode = await FileSystemUtils.directoryExists(openspecPath);
108
+ // Check write permissions
109
+ if (!(await FileSystemUtils.ensureWritePermissions(projectPath))) {
110
+ throw new Error(`Insufficient permissions to write to ${projectPath}`);
111
+ }
112
+ return extendMode;
113
+ }
114
+ canPromptInteractively() {
115
+ if (this.interactiveOption === false)
116
+ return false;
117
+ if (this.toolsArg !== undefined)
118
+ return false;
119
+ return isInteractive({ interactive: this.interactiveOption });
120
+ }
121
+ resolveProfileOverride() {
122
+ if (this.profileOverride === undefined) {
123
+ return undefined;
124
+ }
125
+ if (this.profileOverride === 'core' || this.profileOverride === 'custom') {
126
+ return this.profileOverride;
127
+ }
128
+ throw new Error(`Invalid profile "${this.profileOverride}". Available profiles: core, custom`);
129
+ }
130
+ // ═══════════════════════════════════════════════════════════
131
+ // LEGACY CLEANUP
132
+ // ═══════════════════════════════════════════════════════════
133
+ async handleLegacyCleanup(projectPath, extendMode) {
134
+ // Detect legacy artifacts
135
+ const detection = await detectLegacyArtifacts(projectPath);
136
+ if (!detection.hasLegacyArtifacts) {
137
+ return; // No legacy artifacts found
138
+ }
139
+ // Show what was detected
140
+ console.log();
141
+ console.log(formatDetectionSummary(detection));
142
+ console.log();
143
+ const canPrompt = this.canPromptInteractively();
144
+ if (this.force || !canPrompt) {
145
+ // --force flag or non-interactive mode: proceed with cleanup automatically.
146
+ // Legacy slash commands are 100% OpenSpec-managed, and config file cleanup
147
+ // only removes markers (never deletes files), so auto-cleanup is safe.
148
+ await this.performLegacyCleanup(projectPath, detection);
149
+ return;
150
+ }
151
+ // Interactive mode: prompt for confirmation
152
+ const { confirm } = await import('@inquirer/prompts');
153
+ const shouldCleanup = await confirm({
154
+ message: 'Upgrade and clean up legacy files?',
155
+ default: true,
156
+ });
157
+ if (!shouldCleanup) {
158
+ console.log(chalk.dim('Initialization cancelled.'));
159
+ console.log(chalk.dim('Run with --force to skip this prompt, or manually remove legacy files.'));
160
+ process.exit(0);
161
+ }
162
+ await this.performLegacyCleanup(projectPath, detection);
163
+ }
164
+ async performLegacyCleanup(projectPath, detection) {
165
+ const spinner = ora('Cleaning up legacy files...').start();
166
+ const result = await cleanupLegacyArtifacts(projectPath, detection);
167
+ spinner.succeed('Legacy files cleaned up');
168
+ const summary = formatCleanupSummary(result);
169
+ if (summary) {
170
+ console.log();
171
+ console.log(summary);
172
+ }
173
+ console.log();
174
+ }
175
+ // ═══════════════════════════════════════════════════════════
176
+ // TOOL SELECTION
177
+ // ═══════════════════════════════════════════════════════════
178
+ async getSelectedTools(toolStates, extendMode, detectedTools, projectPath) {
179
+ // Check for --tools flag first
180
+ const nonInteractiveSelection = this.resolveToolsArg();
181
+ if (nonInteractiveSelection !== null) {
182
+ return nonInteractiveSelection;
183
+ }
184
+ const validTools = getToolsWithSkillsDir();
185
+ const detectedToolIds = new Set(detectedTools.map((t) => t.value));
186
+ const configuredToolIds = new Set([...toolStates.entries()]
187
+ .filter(([, status]) => status.configured)
188
+ .map(([toolId]) => toolId));
189
+ const shouldPreselectDetected = !extendMode && configuredToolIds.size === 0;
190
+ const canPrompt = this.canPromptInteractively();
191
+ // Non-interactive mode: use detected tools as fallback (task 7.8)
192
+ if (!canPrompt) {
193
+ if (detectedToolIds.size > 0) {
194
+ return [...detectedToolIds];
195
+ }
196
+ throw new Error(`No tools detected and no --tools flag provided. Valid tools:\n ${validTools.join('\n ')}\n\nUse --tools all, --tools none, or --tools claude,cursor,...`);
197
+ }
198
+ if (validTools.length === 0) {
199
+ throw new Error(`No tools available for skill generation.`);
200
+ }
201
+ // Interactive mode: show searchable multi-select
202
+ const { searchableMultiSelect } = await import('../prompts/searchable-multi-select.js');
203
+ // Build choices: pre-select configured tools; keep detected tools visible but unselected.
204
+ const sortedChoices = validTools
205
+ .map((toolId) => {
206
+ const tool = AI_TOOLS.find((t) => t.value === toolId);
207
+ const status = toolStates.get(toolId);
208
+ const configured = status?.configured ?? false;
209
+ const detected = detectedToolIds.has(toolId);
210
+ return {
211
+ name: tool?.name || toolId,
212
+ value: toolId,
213
+ configured,
214
+ detected: detected && !configured,
215
+ preSelected: configured || (shouldPreselectDetected && detected && !configured),
216
+ };
217
+ })
218
+ .sort((a, b) => {
219
+ // Configured tools first, then detected (not configured), then everything else.
220
+ if (a.configured && !b.configured)
221
+ return -1;
222
+ if (!a.configured && b.configured)
223
+ return 1;
224
+ if (a.detected && !b.detected)
225
+ return -1;
226
+ if (!a.detected && b.detected)
227
+ return 1;
228
+ return 0;
229
+ });
230
+ const configuredNames = validTools
231
+ .filter((toolId) => configuredToolIds.has(toolId))
232
+ .map((toolId) => AI_TOOLS.find((t) => t.value === toolId)?.name || toolId);
233
+ if (configuredNames.length > 0) {
234
+ console.log(`OpenSpec configured: ${configuredNames.join(', ')} (pre-selected)`);
235
+ }
236
+ const detectedOnlyNames = detectedTools
237
+ .filter((tool) => !configuredToolIds.has(tool.value))
238
+ .map((tool) => tool.name);
239
+ if (detectedOnlyNames.length > 0) {
240
+ const detectionLabel = shouldPreselectDetected
241
+ ? 'pre-selected for first-time setup'
242
+ : 'not pre-selected';
243
+ console.log(`Detected tool directories: ${detectedOnlyNames.join(', ')} (${detectionLabel})`);
244
+ }
245
+ const selectedTools = await searchableMultiSelect({
246
+ message: `Select tools to set up (${validTools.length} available)`,
247
+ pageSize: 15,
248
+ choices: sortedChoices,
249
+ validate: (selected) => selected.length > 0 || 'Select at least one tool',
250
+ });
251
+ if (selectedTools.length === 0) {
252
+ throw new Error('At least one tool must be selected');
253
+ }
254
+ return selectedTools;
255
+ }
256
+ resolveToolsArg() {
257
+ if (typeof this.toolsArg === 'undefined') {
258
+ return null;
259
+ }
260
+ const raw = this.toolsArg.trim();
261
+ if (raw.length === 0) {
262
+ throw new Error('The --tools option requires a value. Use "all", "none", or a comma-separated list of tool IDs.');
263
+ }
264
+ const availableTools = getToolsWithSkillsDir();
265
+ const availableSet = new Set(availableTools);
266
+ const availableList = ['all', 'none', ...availableTools].join(', ');
267
+ const lowerRaw = raw.toLowerCase();
268
+ if (lowerRaw === 'all') {
269
+ return availableTools;
270
+ }
271
+ if (lowerRaw === 'none') {
272
+ return [];
273
+ }
274
+ const tokens = raw
275
+ .split(',')
276
+ .map((token) => token.trim())
277
+ .filter((token) => token.length > 0);
278
+ if (tokens.length === 0) {
279
+ throw new Error('The --tools option requires at least one tool ID when not using "all" or "none".');
280
+ }
281
+ const normalizedTokens = tokens.map((token) => token.toLowerCase());
282
+ if (normalizedTokens.some((token) => token === 'all' || token === 'none')) {
283
+ throw new Error('Cannot combine reserved values "all" or "none" with specific tool IDs.');
284
+ }
285
+ const invalidTokens = tokens.filter((_token, index) => !availableSet.has(normalizedTokens[index]));
286
+ if (invalidTokens.length > 0) {
287
+ throw new Error(`Invalid tool(s): ${invalidTokens.join(', ')}. Available values: ${availableList}`);
288
+ }
289
+ // Deduplicate while preserving order
290
+ const deduped = [];
291
+ for (const token of normalizedTokens) {
292
+ if (!deduped.includes(token)) {
293
+ deduped.push(token);
294
+ }
295
+ }
296
+ return deduped;
297
+ }
298
+ validateTools(toolIds, toolStates) {
299
+ const validatedTools = [];
300
+ for (const toolId of toolIds) {
301
+ const tool = AI_TOOLS.find((t) => t.value === toolId);
302
+ if (!tool) {
303
+ const validToolIds = getToolsWithSkillsDir();
304
+ throw new Error(`Unknown tool '${toolId}'. Valid tools:\n ${validToolIds.join('\n ')}`);
305
+ }
306
+ if (!tool.skillsDir) {
307
+ const validToolsWithSkills = getToolsWithSkillsDir();
308
+ throw new Error(`Tool '${toolId}' does not support skill generation.\nTools with skill generation support:\n ${validToolsWithSkills.join('\n ')}`);
309
+ }
310
+ const preState = toolStates.get(tool.value);
311
+ validatedTools.push({
312
+ value: tool.value,
313
+ name: tool.name,
314
+ skillsDir: tool.skillsDir,
315
+ wasConfigured: preState?.configured ?? false,
316
+ });
317
+ }
318
+ return validatedTools;
319
+ }
320
+ // ═══════════════════════════════════════════════════════════
321
+ // DIRECTORY STRUCTURE
322
+ // ═══════════════════════════════════════════════════════════
323
+ async createDirectoryStructure(openspecPath, extendMode) {
324
+ if (extendMode) {
325
+ // In extend mode, just ensure directories exist without spinner
326
+ const directories = [
327
+ openspecPath,
328
+ path.join(openspecPath, 'specs'),
329
+ path.join(openspecPath, 'changes'),
330
+ path.join(openspecPath, 'changes', 'archive'),
331
+ ];
332
+ for (const dir of directories) {
333
+ await FileSystemUtils.createDirectory(dir);
334
+ }
335
+ return;
336
+ }
337
+ const spinner = this.startSpinner('Creating OpenSpec structure...');
338
+ const directories = [
339
+ openspecPath,
340
+ path.join(openspecPath, 'specs'),
341
+ path.join(openspecPath, 'changes'),
342
+ path.join(openspecPath, 'changes', 'archive'),
343
+ ];
344
+ for (const dir of directories) {
345
+ await FileSystemUtils.createDirectory(dir);
346
+ }
347
+ spinner.stopAndPersist({
348
+ symbol: PALETTE.white('▌'),
349
+ text: PALETTE.white('OpenSpec structure created'),
350
+ });
351
+ }
352
+ // ═══════════════════════════════════════════════════════════
353
+ // SKILL & COMMAND GENERATION
354
+ // ═══════════════════════════════════════════════════════════
355
+ async generateSkillsAndCommands(projectPath, tools) {
356
+ const createdTools = [];
357
+ const refreshedTools = [];
358
+ const failedTools = [];
359
+ const commandsSkipped = [];
360
+ let removedCommandCount = 0;
361
+ let removedSkillCount = 0;
362
+ // Read global config for profile and delivery settings (use --profile override if set)
363
+ const globalConfig = getGlobalConfig();
364
+ const profile = this.resolveProfileOverride() ?? globalConfig.profile ?? 'core';
365
+ const delivery = globalConfig.delivery ?? 'both';
366
+ const workflows = getProfileWorkflows(profile, globalConfig.workflows);
367
+ // Get skill and command templates filtered by profile workflows
368
+ const shouldGenerateSkills = delivery !== 'commands';
369
+ const shouldGenerateCommands = delivery !== 'skills';
370
+ const skillTemplates = shouldGenerateSkills ? getSkillTemplates(workflows) : [];
371
+ const commandContents = shouldGenerateCommands ? getCommandContents(workflows) : [];
372
+ // Process each tool
373
+ for (const tool of tools) {
374
+ const spinner = ora(`Setting up ${tool.name}...`).start();
375
+ try {
376
+ // Generate skill files if delivery includes skills
377
+ if (shouldGenerateSkills) {
378
+ // Use tool-specific skillsDir
379
+ const skillsDir = path.join(projectPath, tool.skillsDir, 'skills');
380
+ // Create skill directories and SKILL.md files
381
+ for (const { template, dirName } of skillTemplates) {
382
+ const skillDir = path.join(skillsDir, dirName);
383
+ const skillFile = path.join(skillDir, 'SKILL.md');
384
+ // Generate SKILL.md content with YAML frontmatter including generatedBy
385
+ // Use hyphen-based command references for OpenCode
386
+ const transformer = tool.value === 'opencode' ? transformToHyphenCommands : undefined;
387
+ const skillContent = generateSkillContent(template, OPENSPEC_VERSION, transformer);
388
+ // Write the skill file
389
+ await FileSystemUtils.writeFile(skillFile, skillContent);
390
+ }
391
+ }
392
+ if (!shouldGenerateSkills) {
393
+ const skillsDir = path.join(projectPath, tool.skillsDir, 'skills');
394
+ removedSkillCount += await this.removeSkillDirs(skillsDir);
395
+ }
396
+ // Generate commands if delivery includes commands
397
+ if (shouldGenerateCommands) {
398
+ const adapter = CommandAdapterRegistry.get(tool.value);
399
+ if (adapter) {
400
+ const generatedCommands = generateCommands(commandContents, adapter);
401
+ for (const cmd of generatedCommands) {
402
+ const commandFile = path.isAbsolute(cmd.path) ? cmd.path : path.join(projectPath, cmd.path);
403
+ await FileSystemUtils.writeFile(commandFile, cmd.fileContent);
404
+ }
405
+ }
406
+ else {
407
+ commandsSkipped.push(tool.value);
408
+ }
409
+ }
410
+ if (!shouldGenerateCommands) {
411
+ removedCommandCount += await this.removeCommandFiles(projectPath, tool.value);
412
+ }
413
+ spinner.succeed(`Setup complete for ${tool.name}`);
414
+ if (tool.wasConfigured) {
415
+ refreshedTools.push(tool);
416
+ }
417
+ else {
418
+ createdTools.push(tool);
419
+ }
420
+ }
421
+ catch (error) {
422
+ spinner.fail(`Failed for ${tool.name}`);
423
+ failedTools.push({ name: tool.name, error: error });
424
+ }
425
+ }
426
+ return {
427
+ createdTools,
428
+ refreshedTools,
429
+ failedTools,
430
+ commandsSkipped,
431
+ removedCommandCount,
432
+ removedSkillCount,
433
+ };
434
+ }
435
+ // ═══════════════════════════════════════════════════════════
436
+ // WORKSPACE DETECTION
437
+ // ═══════════════════════════════════════════════════════════
438
+ async handleWorkspaceDetection(projectPath, extendMode) {
439
+ if (isWorkspace(projectPath)) {
440
+ return;
441
+ }
442
+ const scopes = detectMonorepoScopes(projectPath);
443
+ if (scopes.length === 0) {
444
+ return;
445
+ }
446
+ const canPrompt = this.canPromptInteractively();
447
+ if (!canPrompt) {
448
+ return;
449
+ }
450
+ const { confirm } = await import('@inquirer/prompts');
451
+ const shouldCreate = await confirm({
452
+ message: 'This looks like a monorepo. Create a workspace.yaml to enable multi-scope support? (recommended)',
453
+ default: true,
454
+ });
455
+ if (!shouldCreate) {
456
+ return;
457
+ }
458
+ writeWorkspaceConfig(projectPath, { scopes });
459
+ const openspecChangesDir = path.join(projectPath, OPENSPEC_DIR_NAME, 'changes');
460
+ await FileSystemUtils.createDirectory(openspecChangesDir);
461
+ const scopeNames = scopes.map((s) => s.name).join(', ');
462
+ console.log(chalk.dim(`Workspace created with scopes: ${scopeNames}`));
463
+ }
464
+ // ═══════════════════════════════════════════════════════════
465
+ // CONFIG FILE
466
+ // ═══════════════════════════════════════════════════════════
467
+ async createConfig(openspecPath, extendMode) {
468
+ const configPath = path.join(openspecPath, 'config.yaml');
469
+ const configYmlPath = path.join(openspecPath, 'config.yml');
470
+ const configYamlExists = fs.existsSync(configPath);
471
+ const configYmlExists = fs.existsSync(configYmlPath);
472
+ if (configYamlExists || configYmlExists) {
473
+ return 'exists';
474
+ }
475
+ // In non-interactive mode without --force, skip config creation
476
+ if (!this.canPromptInteractively() && !this.force) {
477
+ return 'skipped';
478
+ }
479
+ try {
480
+ const yamlContent = serializeConfig({ schema: DEFAULT_SCHEMA });
481
+ await FileSystemUtils.writeFile(configPath, yamlContent);
482
+ return 'created';
483
+ }
484
+ catch {
485
+ return 'skipped';
486
+ }
487
+ }
488
+ // ═══════════════════════════════════════════════════════════
489
+ // UI & OUTPUT
490
+ // ═══════════════════════════════════════════════════════════
491
+ displaySuccessMessage(projectPath, tools, results, configStatus) {
492
+ console.log();
493
+ console.log(chalk.bold('OpenSpec Setup Complete'));
494
+ console.log();
495
+ // Show created vs refreshed tools
496
+ if (results.createdTools.length > 0) {
497
+ console.log(`Created: ${results.createdTools.map((t) => t.name).join(', ')}`);
498
+ }
499
+ if (results.refreshedTools.length > 0) {
500
+ console.log(`Refreshed: ${results.refreshedTools.map((t) => t.name).join(', ')}`);
501
+ }
502
+ // Show counts (respecting profile filter)
503
+ const successfulTools = [...results.createdTools, ...results.refreshedTools];
504
+ if (successfulTools.length > 0) {
505
+ const globalConfig = getGlobalConfig();
506
+ const profile = this.profileOverride ?? globalConfig.profile ?? 'core';
507
+ const delivery = globalConfig.delivery ?? 'both';
508
+ const workflows = getProfileWorkflows(profile, globalConfig.workflows);
509
+ const toolDirs = [...new Set(successfulTools.map((t) => t.skillsDir))].join(', ');
510
+ const skillCount = delivery !== 'commands' ? getSkillTemplates(workflows).length : 0;
511
+ const commandCount = delivery !== 'skills' ? getCommandContents(workflows).length : 0;
512
+ if (skillCount > 0 && commandCount > 0) {
513
+ console.log(`${skillCount} skills and ${commandCount} commands in ${toolDirs}/`);
514
+ }
515
+ else if (skillCount > 0) {
516
+ console.log(`${skillCount} skills in ${toolDirs}/`);
517
+ }
518
+ else if (commandCount > 0) {
519
+ console.log(`${commandCount} commands in ${toolDirs}/`);
520
+ }
521
+ }
522
+ // Show failures
523
+ if (results.failedTools.length > 0) {
524
+ console.log(chalk.red(`Failed: ${results.failedTools.map((f) => `${f.name} (${f.error.message})`).join(', ')}`));
525
+ }
526
+ // Show skipped commands
527
+ if (results.commandsSkipped.length > 0) {
528
+ console.log(chalk.dim(`Commands skipped for: ${results.commandsSkipped.join(', ')} (no adapter)`));
529
+ }
530
+ if (results.removedCommandCount > 0) {
531
+ console.log(chalk.dim(`Removed: ${results.removedCommandCount} command files (delivery: skills)`));
532
+ }
533
+ if (results.removedSkillCount > 0) {
534
+ console.log(chalk.dim(`Removed: ${results.removedSkillCount} skill directories (delivery: commands)`));
535
+ }
536
+ // Config status
537
+ if (configStatus === 'created') {
538
+ console.log(`Config: openspec/config.yaml (schema: ${DEFAULT_SCHEMA})`);
539
+ }
540
+ else if (configStatus === 'exists') {
541
+ // Show actual filename (config.yaml or config.yml)
542
+ const configYaml = path.join(projectPath, OPENSPEC_DIR_NAME, 'config.yaml');
543
+ const configYml = path.join(projectPath, OPENSPEC_DIR_NAME, 'config.yml');
544
+ const configName = fs.existsSync(configYaml) ? 'config.yaml' : fs.existsSync(configYml) ? 'config.yml' : 'config.yaml';
545
+ console.log(`Config: openspec/${configName} (exists)`);
546
+ }
547
+ else {
548
+ console.log(chalk.dim(`Config: skipped (non-interactive mode)`));
549
+ }
550
+ // Getting started (task 7.6: show propose if in profile)
551
+ const globalCfg = getGlobalConfig();
552
+ const activeProfile = this.profileOverride ?? globalCfg.profile ?? 'core';
553
+ const activeWorkflows = [...getProfileWorkflows(activeProfile, globalCfg.workflows)];
554
+ console.log();
555
+ if (activeWorkflows.includes('propose')) {
556
+ console.log(chalk.bold('Getting started:'));
557
+ console.log(' Start your first change: /opsx:propose "your idea"');
558
+ }
559
+ else if (activeWorkflows.includes('new')) {
560
+ console.log(chalk.bold('Getting started:'));
561
+ console.log(' Start your first change: /opsx:new "your idea"');
562
+ }
563
+ else {
564
+ console.log("Done. Run 'openspec config profile' to configure your workflows.");
565
+ }
566
+ // Links
567
+ console.log();
568
+ console.log(`Learn more: ${chalk.cyan('https://github.com/Fission-AI/OpenSpec')}`);
569
+ console.log(`Feedback: ${chalk.cyan('https://github.com/Fission-AI/OpenSpec/issues')}`);
570
+ // Restart instruction if any tools were configured
571
+ if (results.createdTools.length > 0 || results.refreshedTools.length > 0) {
572
+ console.log();
573
+ console.log(chalk.white('Restart your IDE for slash commands to take effect.'));
574
+ }
575
+ console.log();
576
+ }
577
+ startSpinner(text) {
578
+ return ora({
579
+ text,
580
+ stream: process.stdout,
581
+ color: 'gray',
582
+ spinner: PROGRESS_SPINNER,
583
+ }).start();
584
+ }
585
+ async removeSkillDirs(skillsDir) {
586
+ let removed = 0;
587
+ for (const workflow of ALL_WORKFLOWS) {
588
+ const dirName = WORKFLOW_TO_SKILL_DIR[workflow];
589
+ if (!dirName)
590
+ continue;
591
+ const skillDir = path.join(skillsDir, dirName);
592
+ try {
593
+ if (fs.existsSync(skillDir)) {
594
+ await fs.promises.rm(skillDir, { recursive: true, force: true });
595
+ removed++;
596
+ }
597
+ }
598
+ catch {
599
+ // Ignore errors
600
+ }
601
+ }
602
+ return removed;
603
+ }
604
+ async removeCommandFiles(projectPath, toolId) {
605
+ let removed = 0;
606
+ const adapter = CommandAdapterRegistry.get(toolId);
607
+ if (!adapter)
608
+ return 0;
609
+ for (const workflow of ALL_WORKFLOWS) {
610
+ const cmdPath = adapter.getFilePath(workflow);
611
+ const fullPath = path.isAbsolute(cmdPath) ? cmdPath : path.join(projectPath, cmdPath);
612
+ try {
613
+ if (fs.existsSync(fullPath)) {
614
+ await fs.promises.unlink(fullPath);
615
+ removed++;
616
+ }
617
+ }
618
+ catch {
619
+ // Ignore errors
620
+ }
621
+ }
622
+ return removed;
623
+ }
624
+ }
625
+ //# sourceMappingURL=init.js.map