@fission-ai/openspec 0.1.0 → 0.3.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 (36) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +285 -77
  3. package/dist/cli/index.js +14 -14
  4. package/dist/core/config.d.ts +7 -5
  5. package/dist/core/config.js +3 -4
  6. package/dist/core/configurators/agents.d.ts +8 -0
  7. package/dist/core/configurators/agents.js +15 -0
  8. package/dist/core/configurators/registry.js +3 -0
  9. package/dist/core/configurators/slash/base.d.ts +17 -0
  10. package/dist/core/configurators/slash/base.js +61 -0
  11. package/dist/core/configurators/slash/claude.d.ts +9 -0
  12. package/dist/core/configurators/slash/claude.js +37 -0
  13. package/dist/core/configurators/slash/cursor.d.ts +9 -0
  14. package/dist/core/configurators/slash/cursor.js +37 -0
  15. package/dist/core/configurators/slash/registry.d.ts +8 -0
  16. package/dist/core/configurators/slash/registry.js +21 -0
  17. package/dist/core/init.d.ts +28 -0
  18. package/dist/core/init.js +387 -47
  19. package/dist/core/templates/agents-template.d.ts +2 -0
  20. package/dist/core/templates/agents-template.js +455 -0
  21. package/dist/core/templates/claude-template.d.ts +1 -1
  22. package/dist/core/templates/claude-template.js +1 -95
  23. package/dist/core/templates/index.d.ts +4 -0
  24. package/dist/core/templates/index.js +10 -3
  25. package/dist/core/templates/slash-command-templates.d.ts +4 -0
  26. package/dist/core/templates/slash-command-templates.js +40 -0
  27. package/dist/core/update.js +39 -6
  28. package/dist/core/view.d.ts +8 -0
  29. package/dist/core/view.js +148 -0
  30. package/dist/utils/file-system.d.ts +1 -0
  31. package/dist/utils/file-system.js +16 -0
  32. package/package.json +2 -2
  33. package/dist/core/diff.d.ts +0 -11
  34. package/dist/core/diff.js +0 -193
  35. package/dist/core/templates/readme-template.d.ts +0 -2
  36. package/dist/core/templates/readme-template.js +0 -519
@@ -0,0 +1,37 @@
1
+ import { SlashCommandConfigurator } from './base.js';
2
+ const FILE_PATHS = {
3
+ proposal: '.claude/commands/openspec/proposal.md',
4
+ apply: '.claude/commands/openspec/apply.md',
5
+ archive: '.claude/commands/openspec/archive.md'
6
+ };
7
+ const FRONTMATTER = {
8
+ proposal: `---
9
+ name: OpenSpec: Proposal
10
+ description: Scaffold a new OpenSpec change and validate strictly.
11
+ category: OpenSpec
12
+ tags: [openspec, change]
13
+ ---`,
14
+ apply: `---
15
+ name: OpenSpec: Apply
16
+ description: Implement an approved OpenSpec change and keep tasks in sync.
17
+ category: OpenSpec
18
+ tags: [openspec, apply]
19
+ ---`,
20
+ archive: `---
21
+ name: OpenSpec: Archive
22
+ description: Archive a deployed OpenSpec change and update specs.
23
+ category: OpenSpec
24
+ tags: [openspec, archive]
25
+ ---`
26
+ };
27
+ export class ClaudeSlashCommandConfigurator extends SlashCommandConfigurator {
28
+ toolId = 'claude';
29
+ isAvailable = true;
30
+ getRelativePath(id) {
31
+ return FILE_PATHS[id];
32
+ }
33
+ getFrontmatter(id) {
34
+ return FRONTMATTER[id];
35
+ }
36
+ }
37
+ //# sourceMappingURL=claude.js.map
@@ -0,0 +1,9 @@
1
+ import { SlashCommandConfigurator } from './base.js';
2
+ import { SlashCommandId } from '../../templates/index.js';
3
+ export declare class CursorSlashCommandConfigurator extends SlashCommandConfigurator {
4
+ readonly toolId = "cursor";
5
+ readonly isAvailable = true;
6
+ protected getRelativePath(id: SlashCommandId): string;
7
+ protected getFrontmatter(id: SlashCommandId): string;
8
+ }
9
+ //# sourceMappingURL=cursor.d.ts.map
@@ -0,0 +1,37 @@
1
+ import { SlashCommandConfigurator } from './base.js';
2
+ const FILE_PATHS = {
3
+ proposal: '.cursor/commands/openspec-proposal.md',
4
+ apply: '.cursor/commands/openspec-apply.md',
5
+ archive: '.cursor/commands/openspec-archive.md'
6
+ };
7
+ const FRONTMATTER = {
8
+ proposal: `---
9
+ name: /openspec-proposal
10
+ id: openspec-proposal
11
+ category: OpenSpec
12
+ description: Scaffold a new OpenSpec change and validate strictly.
13
+ ---`,
14
+ apply: `---
15
+ name: /openspec-apply
16
+ id: openspec-apply
17
+ category: OpenSpec
18
+ description: Implement an approved OpenSpec change and keep tasks in sync.
19
+ ---`,
20
+ archive: `---
21
+ name: /openspec-archive
22
+ id: openspec-archive
23
+ category: OpenSpec
24
+ description: Archive a deployed OpenSpec change and update specs.
25
+ ---`
26
+ };
27
+ export class CursorSlashCommandConfigurator extends SlashCommandConfigurator {
28
+ toolId = 'cursor';
29
+ isAvailable = true;
30
+ getRelativePath(id) {
31
+ return FILE_PATHS[id];
32
+ }
33
+ getFrontmatter(id) {
34
+ return FRONTMATTER[id];
35
+ }
36
+ }
37
+ //# sourceMappingURL=cursor.js.map
@@ -0,0 +1,8 @@
1
+ import { SlashCommandConfigurator } from './base.js';
2
+ export declare class SlashCommandRegistry {
3
+ private static configurators;
4
+ static register(configurator: SlashCommandConfigurator): void;
5
+ static get(toolId: string): SlashCommandConfigurator | undefined;
6
+ static getAll(): SlashCommandConfigurator[];
7
+ }
8
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1,21 @@
1
+ import { ClaudeSlashCommandConfigurator } from './claude.js';
2
+ import { CursorSlashCommandConfigurator } from './cursor.js';
3
+ export class SlashCommandRegistry {
4
+ static configurators = new Map();
5
+ static {
6
+ const claude = new ClaudeSlashCommandConfigurator();
7
+ const cursor = new CursorSlashCommandConfigurator();
8
+ this.configurators.set(claude.toolId, claude);
9
+ this.configurators.set(cursor.toolId, cursor);
10
+ }
11
+ static register(configurator) {
12
+ this.configurators.set(configurator.toolId, configurator);
13
+ }
14
+ static get(toolId) {
15
+ return this.configurators.get(toolId);
16
+ }
17
+ static getAll() {
18
+ return Array.from(this.configurators.values());
19
+ }
20
+ }
21
+ //# sourceMappingURL=registry.js.map
@@ -1,10 +1,38 @@
1
+ type ToolLabel = {
2
+ primary: string;
3
+ annotation?: string;
4
+ };
5
+ type ToolWizardChoice = {
6
+ value: string;
7
+ label: ToolLabel;
8
+ configured: boolean;
9
+ };
10
+ type ToolWizardConfig = {
11
+ extendMode: boolean;
12
+ baseMessage: string;
13
+ choices: ToolWizardChoice[];
14
+ initialSelected?: string[];
15
+ };
16
+ type ToolSelectionPrompt = (config: ToolWizardConfig) => Promise<string[]>;
17
+ type InitCommandOptions = {
18
+ prompt?: ToolSelectionPrompt;
19
+ };
1
20
  export declare class InitCommand {
21
+ private readonly prompt;
22
+ constructor(options?: InitCommandOptions);
2
23
  execute(targetPath: string): Promise<void>;
3
24
  private validate;
4
25
  private getConfiguration;
26
+ private promptForAITools;
27
+ private getExistingToolStates;
28
+ private isToolConfigured;
5
29
  private createDirectoryStructure;
6
30
  private generateFiles;
7
31
  private configureAITools;
8
32
  private displaySuccessMessage;
33
+ private formatToolNames;
34
+ private renderBanner;
35
+ private startSpinner;
9
36
  }
37
+ export {};
10
38
  //# sourceMappingURL=init.d.ts.map
package/dist/core/init.js CHANGED
@@ -1,57 +1,335 @@
1
1
  import path from 'path';
2
- import { select } from '@inquirer/prompts';
2
+ import { createPrompt, isBackspaceKey, isDownKey, isEnterKey, isSpaceKey, isUpKey, useKeypress, usePagination, useState } from '@inquirer/core';
3
+ import chalk from 'chalk';
3
4
  import ora from 'ora';
4
5
  import { FileSystemUtils } from '../utils/file-system.js';
5
6
  import { TemplateManager } from './templates/index.js';
6
7
  import { ToolRegistry } from './configurators/registry.js';
8
+ import { SlashCommandRegistry } from './configurators/slash/registry.js';
7
9
  import { AI_TOOLS, OPENSPEC_DIR_NAME } from './config.js';
10
+ const PROGRESS_SPINNER = {
11
+ interval: 80,
12
+ frames: ['░░░', '▒░░', '▒▒░', '▒▒▒', '▓▒▒', '▓▓▒', '▓▓▓', '▒▓▓', '░▒▓']
13
+ };
14
+ const PALETTE = {
15
+ white: chalk.hex('#f4f4f4'),
16
+ lightGray: chalk.hex('#c8c8c8'),
17
+ midGray: chalk.hex('#8a8a8a'),
18
+ darkGray: chalk.hex('#4a4a4a')
19
+ };
20
+ const LETTER_MAP = {
21
+ O: [
22
+ ' ████ ',
23
+ '██ ██',
24
+ '██ ██',
25
+ '██ ██',
26
+ ' ████ '
27
+ ],
28
+ P: [
29
+ '█████ ',
30
+ '██ ██',
31
+ '█████ ',
32
+ '██ ',
33
+ '██ '
34
+ ],
35
+ E: [
36
+ '██████',
37
+ '██ ',
38
+ '█████ ',
39
+ '██ ',
40
+ '██████'
41
+ ],
42
+ N: [
43
+ '██ ██',
44
+ '███ ██',
45
+ '██ ███',
46
+ '██ ██',
47
+ '██ ██'
48
+ ],
49
+ S: [
50
+ ' █████',
51
+ '██ ',
52
+ ' ████ ',
53
+ ' ██',
54
+ '█████ '
55
+ ],
56
+ C: [
57
+ ' █████',
58
+ '██ ',
59
+ '██ ',
60
+ '██ ',
61
+ ' █████'
62
+ ],
63
+ ' ': [
64
+ ' ',
65
+ ' ',
66
+ ' ',
67
+ ' ',
68
+ ' '
69
+ ]
70
+ };
71
+ const sanitizeToolLabel = (raw) => raw.replace(/✅/gu, '✔').trim();
72
+ const parseToolLabel = (raw) => {
73
+ const sanitized = sanitizeToolLabel(raw);
74
+ const match = sanitized.match(/^(.*?)\s*\((.+)\)$/u);
75
+ if (!match) {
76
+ return { primary: sanitized };
77
+ }
78
+ return {
79
+ primary: match[1].trim(),
80
+ annotation: match[2].trim()
81
+ };
82
+ };
83
+ const toolSelectionWizard = createPrompt((config, done) => {
84
+ const totalSteps = 3;
85
+ const [step, setStep] = useState('intro');
86
+ const [cursor, setCursor] = useState(0);
87
+ const [selected, setSelected] = useState(() => config.initialSelected ?? []);
88
+ const [error, setError] = useState(null);
89
+ const selectedSet = new Set(selected);
90
+ const pageSize = Math.max(Math.min(config.choices.length, 7), 1);
91
+ const updateSelected = (next) => {
92
+ const ordered = config.choices
93
+ .map((choice) => choice.value)
94
+ .filter((value) => next.has(value));
95
+ setSelected(ordered);
96
+ };
97
+ const page = usePagination({
98
+ items: config.choices,
99
+ active: cursor,
100
+ pageSize,
101
+ loop: config.choices.length > 1,
102
+ renderItem: ({ item, isActive }) => {
103
+ const isSelected = selectedSet.has(item.value);
104
+ const cursorSymbol = isActive ? PALETTE.white('›') : PALETTE.midGray(' ');
105
+ const indicator = isSelected ? PALETTE.white('◉') : PALETTE.midGray('○');
106
+ const nameColor = isActive ? PALETTE.white : PALETTE.midGray;
107
+ const label = `${nameColor(item.label.primary)}${item.configured ? PALETTE.midGray(' (already configured)') : ''}`;
108
+ return `${cursorSymbol} ${indicator} ${label}`;
109
+ }
110
+ });
111
+ useKeypress((key) => {
112
+ if (step === 'intro') {
113
+ if (isEnterKey(key)) {
114
+ setStep('select');
115
+ }
116
+ return;
117
+ }
118
+ if (step === 'select') {
119
+ if (isUpKey(key)) {
120
+ const previousIndex = cursor <= 0 ? config.choices.length - 1 : cursor - 1;
121
+ setCursor(previousIndex);
122
+ setError(null);
123
+ return;
124
+ }
125
+ if (isDownKey(key)) {
126
+ const nextIndex = cursor >= config.choices.length - 1 ? 0 : cursor + 1;
127
+ setCursor(nextIndex);
128
+ setError(null);
129
+ return;
130
+ }
131
+ if (isSpaceKey(key)) {
132
+ const current = config.choices[cursor];
133
+ if (!current)
134
+ return;
135
+ const next = new Set(selected);
136
+ if (next.has(current.value)) {
137
+ next.delete(current.value);
138
+ }
139
+ else {
140
+ next.add(current.value);
141
+ }
142
+ updateSelected(next);
143
+ setError(null);
144
+ return;
145
+ }
146
+ if (isEnterKey(key)) {
147
+ if (selected.length === 0) {
148
+ setError('Select at least one AI tool to continue.');
149
+ return;
150
+ }
151
+ setStep('review');
152
+ setError(null);
153
+ return;
154
+ }
155
+ if (key.name === 'escape') {
156
+ setSelected([]);
157
+ setError(null);
158
+ }
159
+ return;
160
+ }
161
+ if (step === 'review') {
162
+ if (isEnterKey(key)) {
163
+ const finalSelection = config.choices
164
+ .map((choice) => choice.value)
165
+ .filter((value) => selectedSet.has(value));
166
+ done(finalSelection);
167
+ return;
168
+ }
169
+ if (isBackspaceKey(key) || key.name === 'escape') {
170
+ setStep('select');
171
+ setError(null);
172
+ }
173
+ }
174
+ });
175
+ const selectedNames = config.choices
176
+ .filter((choice) => selectedSet.has(choice.value))
177
+ .map((choice) => choice.label.primary);
178
+ const stepIndex = step === 'intro' ? 1 : step === 'select' ? 2 : 3;
179
+ const lines = [];
180
+ lines.push(PALETTE.midGray(`Step ${stepIndex}/${totalSteps}`));
181
+ lines.push('');
182
+ if (step === 'intro') {
183
+ const introHeadline = config.extendMode
184
+ ? 'Extend your OpenSpec tooling'
185
+ : 'Configure your OpenSpec tooling';
186
+ const introBody = config.extendMode
187
+ ? 'We detected an existing setup. We will help you refresh or add integrations.'
188
+ : "Let's get your AI assistants connected so they understand OpenSpec.";
189
+ lines.push(PALETTE.white(introHeadline));
190
+ lines.push(PALETTE.midGray(introBody));
191
+ lines.push('');
192
+ lines.push(PALETTE.midGray('Press Enter to continue.'));
193
+ }
194
+ else if (step === 'select') {
195
+ lines.push(PALETTE.white(config.baseMessage));
196
+ lines.push(PALETTE.midGray('Use ↑/↓ to move · Space to toggle · Enter to review selections.'));
197
+ lines.push('');
198
+ lines.push(page);
199
+ lines.push('');
200
+ if (selectedNames.length === 0) {
201
+ lines.push(`${PALETTE.midGray('Selected')}: ${PALETTE.midGray('None selected yet')}`);
202
+ }
203
+ else {
204
+ lines.push(PALETTE.midGray('Selected:'));
205
+ selectedNames.forEach((name) => {
206
+ lines.push(` ${PALETTE.white('-')} ${PALETTE.white(name)}`);
207
+ });
208
+ }
209
+ }
210
+ else {
211
+ lines.push(PALETTE.white('Review selections'));
212
+ lines.push(PALETTE.midGray('Press Enter to confirm or Backspace to adjust.'));
213
+ lines.push('');
214
+ if (selectedNames.length === 0) {
215
+ lines.push(PALETTE.midGray('No tools selected. Press Backspace to return.'));
216
+ }
217
+ else {
218
+ selectedNames.forEach((name) => {
219
+ lines.push(`${PALETTE.white('▌')} ${PALETTE.white(name)}`);
220
+ });
221
+ }
222
+ }
223
+ if (error) {
224
+ return [lines.join('\n'), chalk.red(error)];
225
+ }
226
+ return lines.join('\n');
227
+ });
8
228
  export class InitCommand {
229
+ prompt;
230
+ constructor(options = {}) {
231
+ this.prompt = options.prompt ?? ((config) => toolSelectionWizard(config));
232
+ }
9
233
  async execute(targetPath) {
10
234
  const projectPath = path.resolve(targetPath);
11
235
  const openspecDir = OPENSPEC_DIR_NAME;
12
236
  const openspecPath = path.join(projectPath, openspecDir);
13
237
  // Validation happens silently in the background
14
- await this.validate(projectPath, openspecPath);
238
+ const extendMode = await this.validate(projectPath, openspecPath);
239
+ const existingToolStates = await this.getExistingToolStates(projectPath);
240
+ this.renderBanner(extendMode);
15
241
  // Get configuration (after validation to avoid prompts if validation fails)
16
- const config = await this.getConfiguration();
242
+ const config = await this.getConfiguration(existingToolStates, extendMode);
243
+ if (config.aiTools.length === 0) {
244
+ if (extendMode) {
245
+ throw new Error(`OpenSpec seems to already be initialized at ${openspecPath}.\n` +
246
+ `Use 'openspec update' to update the structure.`);
247
+ }
248
+ throw new Error('You must select at least one AI tool to configure.');
249
+ }
250
+ const availableTools = AI_TOOLS.filter(tool => tool.available);
251
+ const selectedIds = new Set(config.aiTools);
252
+ const selectedTools = availableTools.filter(tool => selectedIds.has(tool.value));
253
+ const created = selectedTools.filter(tool => !existingToolStates[tool.value]);
254
+ const refreshed = selectedTools.filter(tool => existingToolStates[tool.value]);
255
+ const skippedExisting = availableTools.filter(tool => !selectedIds.has(tool.value) && existingToolStates[tool.value]);
256
+ const skipped = availableTools.filter(tool => !selectedIds.has(tool.value) && !existingToolStates[tool.value]);
17
257
  // Step 1: Create directory structure
18
- const structureSpinner = ora({ text: 'Creating OpenSpec structure...', stream: process.stdout }).start();
19
- await this.createDirectoryStructure(openspecPath);
20
- await this.generateFiles(openspecPath, config);
21
- structureSpinner.succeed('OpenSpec structure created');
258
+ if (!extendMode) {
259
+ const structureSpinner = this.startSpinner('Creating OpenSpec structure...');
260
+ await this.createDirectoryStructure(openspecPath);
261
+ await this.generateFiles(openspecPath, config);
262
+ structureSpinner.stopAndPersist({
263
+ symbol: PALETTE.white('▌'),
264
+ text: PALETTE.white('OpenSpec structure created')
265
+ });
266
+ }
267
+ else {
268
+ ora({ stream: process.stdout }).info(PALETTE.midGray('ℹ OpenSpec already initialized. Skipping base scaffolding.'));
269
+ }
22
270
  // Step 2: Configure AI tools
23
- const toolSpinner = ora({ text: 'Configuring AI tools...', stream: process.stdout }).start();
271
+ const toolSpinner = this.startSpinner('Configuring AI tools...');
24
272
  await this.configureAITools(projectPath, openspecDir, config.aiTools);
25
- toolSpinner.succeed('AI tools configured');
273
+ toolSpinner.stopAndPersist({
274
+ symbol: PALETTE.white('▌'),
275
+ text: PALETTE.white('AI tools configured')
276
+ });
26
277
  // Success message
27
- this.displaySuccessMessage(openspecDir, config);
278
+ this.displaySuccessMessage(selectedTools, created, refreshed, skippedExisting, skipped, extendMode);
28
279
  }
29
- async validate(projectPath, openspecPath) {
30
- // Check if OpenSpec already exists
31
- if (await FileSystemUtils.directoryExists(openspecPath)) {
32
- throw new Error(`OpenSpec seems to already be initialized at ${openspecPath}.\n` +
33
- `Use 'openspec update' to update the structure.`);
34
- }
280
+ async validate(projectPath, _openspecPath) {
281
+ const extendMode = await FileSystemUtils.directoryExists(_openspecPath);
35
282
  // Check write permissions
36
283
  if (!await FileSystemUtils.ensureWritePermissions(projectPath)) {
37
284
  throw new Error(`Insufficient permissions to write to ${projectPath}`);
38
285
  }
286
+ return extendMode;
39
287
  }
40
- async getConfiguration() {
41
- const config = {
42
- aiTools: []
43
- };
44
- // Single-select for better UX
45
- const selectedTool = await select({
46
- message: 'Which AI tool do you use?',
47
- choices: AI_TOOLS.map(tool => ({
48
- name: tool.available ? tool.name : `${tool.name} (coming soon)`,
288
+ async getConfiguration(existingTools, extendMode) {
289
+ const selectedTools = await this.promptForAITools(existingTools, extendMode);
290
+ return { aiTools: selectedTools };
291
+ }
292
+ async promptForAITools(existingTools, extendMode) {
293
+ const availableTools = AI_TOOLS.filter(tool => tool.available);
294
+ if (availableTools.length === 0) {
295
+ return [];
296
+ }
297
+ const baseMessage = extendMode
298
+ ? 'Which AI tools would you like to add or refresh?'
299
+ : 'Which AI tools do you use?';
300
+ const initialSelected = extendMode
301
+ ? availableTools.filter(tool => existingTools[tool.value]).map(tool => tool.value)
302
+ : [];
303
+ return this.prompt({
304
+ extendMode,
305
+ baseMessage,
306
+ choices: availableTools.map((tool) => ({
49
307
  value: tool.value,
50
- disabled: !tool.available
51
- }))
308
+ label: parseToolLabel(tool.name),
309
+ configured: Boolean(existingTools[tool.value])
310
+ })),
311
+ initialSelected
52
312
  });
53
- config.aiTools = [selectedTool];
54
- return config;
313
+ }
314
+ async getExistingToolStates(projectPath) {
315
+ const states = {};
316
+ for (const tool of AI_TOOLS) {
317
+ states[tool.value] = await this.isToolConfigured(projectPath, tool.value);
318
+ }
319
+ return states;
320
+ }
321
+ async isToolConfigured(projectPath, toolId) {
322
+ const configFile = ToolRegistry.get(toolId)?.configFileName;
323
+ if (configFile && await FileSystemUtils.fileExists(path.join(projectPath, configFile)))
324
+ return true;
325
+ const slashConfigurator = SlashCommandRegistry.get(toolId);
326
+ if (!slashConfigurator)
327
+ return false;
328
+ for (const target of slashConfigurator.getTargets()) {
329
+ if (await FileSystemUtils.fileExists(path.join(projectPath, target.path)))
330
+ return true;
331
+ }
332
+ return false;
55
333
  }
56
334
  async createDirectoryStructure(openspecPath) {
57
335
  const directories = [
@@ -83,27 +361,89 @@ export class InitCommand {
83
361
  if (configurator && configurator.isAvailable) {
84
362
  await configurator.configure(projectPath, openspecDir);
85
363
  }
364
+ const slashConfigurator = SlashCommandRegistry.get(toolId);
365
+ if (slashConfigurator && slashConfigurator.isAvailable) {
366
+ await slashConfigurator.generateAll(projectPath, openspecDir);
367
+ }
86
368
  }
87
369
  }
88
- displaySuccessMessage(openspecDir, config) {
370
+ displaySuccessMessage(selectedTools, created, refreshed, skippedExisting, skipped, extendMode) {
89
371
  console.log(); // Empty line for spacing
90
- ora().succeed('OpenSpec initialized successfully!');
91
- // Get the selected tool name for display
92
- const selectedToolId = config.aiTools[0];
93
- const selectedTool = AI_TOOLS.find(t => t.value === selectedToolId);
94
- const toolName = selectedTool ? selectedTool.name : 'your AI assistant';
95
- console.log(`\nNext steps - Copy these prompts to ${toolName}:\n`);
96
- console.log('────────────────────────────────────────────────────────────');
97
- console.log('1. Populate your project context:');
98
- console.log(' "Please read openspec/project.md and help me fill it out');
99
- console.log(' with details about my project, tech stack, and conventions"\n');
100
- console.log('2. Create your first change proposal:');
101
- console.log(' "I want to add [YOUR FEATURE HERE]. Please create an');
102
- console.log(' OpenSpec change proposal for this feature"\n');
103
- console.log('3. Learn the OpenSpec workflow:');
104
- console.log(' "Please explain the OpenSpec workflow from openspec/README.md');
105
- console.log(' and how I should work with you on this project"');
106
- console.log('────────────────────────────────────────────────────────────\n');
372
+ const successHeadline = extendMode
373
+ ? 'OpenSpec tool configuration updated!'
374
+ : 'OpenSpec initialized successfully!';
375
+ ora().succeed(PALETTE.white(successHeadline));
376
+ console.log();
377
+ console.log(PALETTE.lightGray('Tool summary:'));
378
+ const summaryLines = [
379
+ created.length ? `${PALETTE.white('▌')} ${PALETTE.white('Created:')} ${this.formatToolNames(created)}` : null,
380
+ refreshed.length ? `${PALETTE.lightGray('▌')} ${PALETTE.lightGray('Refreshed:')} ${this.formatToolNames(refreshed)}` : null,
381
+ skippedExisting.length ? `${PALETTE.midGray('▌')} ${PALETTE.midGray('Skipped (already configured):')} ${this.formatToolNames(skippedExisting)}` : null,
382
+ skipped.length ? `${PALETTE.darkGray('▌')} ${PALETTE.darkGray('Skipped:')} ${this.formatToolNames(skipped)}` : null
383
+ ].filter((line) => Boolean(line));
384
+ for (const line of summaryLines) {
385
+ console.log(line);
386
+ }
387
+ console.log();
388
+ console.log(PALETTE.midGray('Use `openspec update` to refresh shared OpenSpec instructions in the future.'));
389
+ // Get the selected tool name(s) for display
390
+ const toolName = this.formatToolNames(selectedTools);
391
+ console.log();
392
+ console.log(`Next steps - Copy these prompts to ${toolName}:`);
393
+ console.log(chalk.gray('────────────────────────────────────────────────────────────'));
394
+ console.log(PALETTE.white('1. Populate your project context:'));
395
+ console.log(PALETTE.lightGray(' "Please read openspec/project.md and help me fill it out'));
396
+ console.log(PALETTE.lightGray(' with details about my project, tech stack, and conventions"\n'));
397
+ console.log(PALETTE.white('2. Create your first change proposal:'));
398
+ console.log(PALETTE.lightGray(' "I want to add [YOUR FEATURE HERE]. Please create an'));
399
+ console.log(PALETTE.lightGray(' OpenSpec change proposal for this feature"\n'));
400
+ console.log(PALETTE.white('3. Learn the OpenSpec workflow:'));
401
+ console.log(PALETTE.lightGray(' "Please explain the OpenSpec workflow from openspec/AGENTS.md'));
402
+ console.log(PALETTE.lightGray(' and how I should work with you on this project"'));
403
+ console.log(PALETTE.darkGray('────────────────────────────────────────────────────────────\n'));
404
+ }
405
+ formatToolNames(tools) {
406
+ const names = tools
407
+ .map((tool) => tool.successLabel ?? tool.name)
408
+ .filter((name) => Boolean(name));
409
+ if (names.length === 0)
410
+ return PALETTE.lightGray('your AI assistant');
411
+ if (names.length === 1)
412
+ return PALETTE.white(names[0]);
413
+ const base = names.slice(0, -1).map((name) => PALETTE.white(name));
414
+ const last = PALETTE.white(names[names.length - 1]);
415
+ return `${base.join(PALETTE.midGray(', '))}${base.length ? PALETTE.midGray(', and ') : ''}${last}`;
416
+ }
417
+ renderBanner(_extendMode) {
418
+ const rows = ['', '', '', '', ''];
419
+ for (const char of 'OPENSPEC') {
420
+ const glyph = LETTER_MAP[char] ?? LETTER_MAP[' '];
421
+ for (let i = 0; i < rows.length; i += 1) {
422
+ rows[i] += `${glyph[i]} `;
423
+ }
424
+ }
425
+ const rowStyles = [
426
+ PALETTE.white,
427
+ PALETTE.lightGray,
428
+ PALETTE.midGray,
429
+ PALETTE.lightGray,
430
+ PALETTE.white
431
+ ];
432
+ console.log();
433
+ rows.forEach((row, index) => {
434
+ console.log(rowStyles[index](row.replace(/\s+$/u, '')));
435
+ });
436
+ console.log();
437
+ console.log(PALETTE.white('Welcome to OpenSpec!'));
438
+ console.log();
439
+ }
440
+ startSpinner(text) {
441
+ return ora({
442
+ text,
443
+ stream: process.stdout,
444
+ color: 'gray',
445
+ spinner: PROGRESS_SPINNER
446
+ }).start();
107
447
  }
108
448
  }
109
449
  //# sourceMappingURL=init.js.map
@@ -0,0 +1,2 @@
1
+ export declare const agentsTemplate = "# OpenSpec Instructions\n\nInstructions for AI coding assistants using OpenSpec for spec-driven development.\n\n## TL;DR Quick Checklist\n\n- Search existing work: `openspec spec list --long`, `openspec list` (use `rg` only for full-text search)\n- Decide scope: new capability vs modify existing capability\n- Pick a unique `change-id`: kebab-case, verb-led (`add-`, `update-`, `remove-`, `refactor-`)\n- Scaffold: `proposal.md`, `tasks.md`, `design.md` (only if needed), and delta specs per affected capability\n- Write deltas: use `## ADDED|MODIFIED|REMOVED|RENAMED Requirements`; include at least one `#### Scenario:` per requirement\n- Validate: `openspec validate [change-id] --strict` and fix issues\n- Request approval: Do not start implementation until proposal is approved\n\n## Three-Stage Workflow\n\n### Stage 1: Creating Changes\nCreate proposal when you need to:\n- Add features or functionality\n- Make breaking changes (API, schema)\n- Change architecture or patterns \n- Optimize performance (changes behavior)\n- Update security patterns\n\nTriggers (examples):\n- \"Help me create a change proposal\"\n- \"Help me plan a change\"\n- \"Help me create a proposal\"\n- \"I want to create a spec proposal\"\n- \"I want to create a spec\"\n\nLoose matching guidance:\n- Contains one of: `proposal`, `change`, `spec`\n- With one of: `create`, `plan`, `make`, `start`, `help`\n\nSkip proposal for:\n- Bug fixes (restore intended behavior)\n- Typos, formatting, comments\n- Dependency updates (non-breaking)\n- Configuration changes\n- Tests for existing behavior\n\n**Workflow**\n1. Review `openspec/project.md`, `openspec list`, and `openspec list --specs` to understand current context.\n2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, optional `design.md`, and spec deltas under `openspec/changes/<id>/`.\n3. Draft spec deltas using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement.\n4. Run `openspec validate <id> --strict` and resolve any issues before sharing the proposal.\n\n### Stage 2: Implementing Changes\n1. **Read proposal.md** - Understand what's being built\n2. **Read design.md** (if exists) - Review technical decisions\n3. **Read tasks.md** - Get implementation checklist\n4. **Implement tasks sequentially** - Complete in order\n5. **Mark complete immediately** - Update `- [x]` after each task\n6. **Approval gate** - Do not start implementation until the proposal is reviewed and approved\n\n### Stage 3: Archiving Changes\nAfter deployment, create separate PR to:\n- Move `changes/[name]/` \u2192 `changes/archive/YYYY-MM-DD-[name]/`\n- Update `specs/` if capabilities changed\n- Use `openspec archive [change] --skip-specs` for tooling-only changes\n- Run `openspec validate --strict` to confirm the archived change passes checks\n\n## Before Any Task\n\n**Context Checklist:**\n- [ ] Read relevant specs in `specs/[capability]/spec.md`\n- [ ] Check pending changes in `changes/` for conflicts\n- [ ] Read `openspec/project.md` for conventions\n- [ ] Run `openspec list` to see active changes\n- [ ] Run `openspec list --specs` to see existing capabilities\n\n**Before Creating Specs:**\n- Always check if capability already exists\n- Prefer modifying existing specs over creating duplicates\n- Use `openspec show [spec]` to review current state\n- If request is ambiguous, ask 1\u20132 clarifying questions before scaffolding\n\n### Search Guidance\n- Enumerate specs: `openspec spec list --long` (or `--json` for scripts)\n- Enumerate changes: `openspec list` (or `openspec change list --json` - deprecated but available)\n- Show details:\n - Spec: `openspec show <spec-id> --type spec` (use `--json` for filters)\n - Change: `openspec show <change-id> --json --deltas-only`\n- Full-text search (use ripgrep): `rg -n \"Requirement:|Scenario:\" openspec/specs`\n\n## Quick Start\n\n### CLI Commands\n\n```bash\n# Essential commands\nopenspec list # List active changes\nopenspec list --specs # List specifications\nopenspec show [item] # Display change or spec\nopenspec diff [change] # Show spec differences\nopenspec validate [item] # Validate changes or specs\nopenspec archive [change] # Archive after deployment\n\n# Project management\nopenspec init [path] # Initialize OpenSpec\nopenspec update [path] # Update instruction files\n\n# Interactive mode\nopenspec show # Prompts for selection\nopenspec validate # Bulk validation mode\n\n# Debugging\nopenspec show [change] --json --deltas-only\nopenspec validate [change] --strict\n```\n\n### Command Flags\n\n- `--json` - Machine-readable output\n- `--type change|spec` - Disambiguate items\n- `--strict` - Comprehensive validation\n- `--no-interactive` - Disable prompts\n- `--skip-specs` - Archive without spec updates\n\n## Directory Structure\n\n```\nopenspec/\n\u251C\u2500\u2500 project.md # Project conventions\n\u251C\u2500\u2500 specs/ # Current truth - what IS built\n\u2502 \u2514\u2500\u2500 [capability]/ # Single focused capability\n\u2502 \u251C\u2500\u2500 spec.md # Requirements and scenarios\n\u2502 \u2514\u2500\u2500 design.md # Technical patterns\n\u251C\u2500\u2500 changes/ # Proposals - what SHOULD change\n\u2502 \u251C\u2500\u2500 [change-name]/\n\u2502 \u2502 \u251C\u2500\u2500 proposal.md # Why, what, impact\n\u2502 \u2502 \u251C\u2500\u2500 tasks.md # Implementation checklist\n\u2502 \u2502 \u251C\u2500\u2500 design.md # Technical decisions (optional; see criteria)\n\u2502 \u2502 \u2514\u2500\u2500 specs/ # Delta changes\n\u2502 \u2502 \u2514\u2500\u2500 [capability]/\n\u2502 \u2502 \u2514\u2500\u2500 spec.md # ADDED/MODIFIED/REMOVED\n\u2502 \u2514\u2500\u2500 archive/ # Completed changes\n```\n\n## Creating Change Proposals\n\n### Decision Tree\n\n```\nNew request?\n\u251C\u2500 Bug fix restoring spec behavior? \u2192 Fix directly\n\u251C\u2500 Typo/format/comment? \u2192 Fix directly \n\u251C\u2500 New feature/capability? \u2192 Create proposal\n\u251C\u2500 Breaking change? \u2192 Create proposal\n\u251C\u2500 Architecture change? \u2192 Create proposal\n\u2514\u2500 Unclear? \u2192 Create proposal (safer)\n```\n\n### Proposal Structure\n\n1. **Create directory:** `changes/[change-id]/` (kebab-case, verb-led, unique)\n\n2. **Write proposal.md:**\n```markdown\n## Why\n[1-2 sentences on problem/opportunity]\n\n## What Changes\n- [Bullet list of changes]\n- [Mark breaking changes with **BREAKING**]\n\n## Impact\n- Affected specs: [list capabilities]\n- Affected code: [key files/systems]\n```\n\n3. **Create spec deltas:** `specs/[capability]/spec.md`\n```markdown\n## ADDED Requirements\n### Requirement: New Feature\nThe system SHALL provide...\n\n#### Scenario: Success case\n- **WHEN** user performs action\n- **THEN** expected result\n\n## MODIFIED Requirements\n### Requirement: Existing Feature\n[Complete modified requirement]\n\n## REMOVED Requirements\n### Requirement: Old Feature\n**Reason**: [Why removing]\n**Migration**: [How to handle]\n```\nIf multiple capabilities are affected, create multiple delta files under `changes/[change-id]/specs/<capability>/spec.md`\u2014one per capability.\n\n4. **Create tasks.md:**\n```markdown\n## 1. Implementation\n- [ ] 1.1 Create database schema\n- [ ] 1.2 Implement API endpoint\n- [ ] 1.3 Add frontend component\n- [ ] 1.4 Write tests\n```\n\n5. **Create design.md when needed:**\nCreate `design.md` if any of the following apply; otherwise omit it:\n- Cross-cutting change (multiple services/modules) or a new architectural pattern\n- New external dependency or significant data model changes\n- Security, performance, or migration complexity\n- Ambiguity that benefits from technical decisions before coding\n\nMinimal `design.md` skeleton:\n```markdown\n## Context\n[Background, constraints, stakeholders]\n\n## Goals / Non-Goals\n- Goals: [...]\n- Non-Goals: [...]\n\n## Decisions\n- Decision: [What and why]\n- Alternatives considered: [Options + rationale]\n\n## Risks / Trade-offs\n- [Risk] \u2192 Mitigation\n\n## Migration Plan\n[Steps, rollback]\n\n## Open Questions\n- [...]\n```\n\n## Spec File Format\n\n### Critical: Scenario Formatting\n\n**CORRECT** (use #### headers):\n```markdown\n#### Scenario: User login success\n- **WHEN** valid credentials provided\n- **THEN** return JWT token\n```\n\n**WRONG** (don't use bullets or bold):\n```markdown\n- **Scenario: User login** \u274C\n**Scenario**: User login \u274C\n### Scenario: User login \u274C\n```\n\nEvery requirement MUST have at least one scenario.\n\n### Requirement Wording\n- Use SHALL/MUST for normative requirements (avoid should/may unless intentionally non-normative)\n\n### Delta Operations\n\n- `## ADDED Requirements` - New capabilities\n- `## MODIFIED Requirements` - Changed behavior\n- `## REMOVED Requirements` - Deprecated features\n- `## RENAMED Requirements` - Name changes\n\nHeaders matched with `trim(header)` - whitespace ignored.\n\n#### When to use ADDED vs MODIFIED\n- ADDED: Introduces a new capability or sub-capability that can stand alone as a requirement. Prefer ADDED when the change is orthogonal (e.g., adding \"Slash Command Configuration\") rather than altering the semantics of an existing requirement.\n- MODIFIED: Changes the behavior, scope, or acceptance criteria of an existing requirement. Always paste the full, updated requirement content (header + all scenarios). The archiver will replace the entire requirement with what you provide here; partial deltas will drop previous details.\n- RENAMED: Use when only the name changes. If you also change behavior, use RENAMED (name) plus MODIFIED (content) referencing the new name.\n\nCommon pitfall: Using MODIFIED to add a new concern without including the previous text. This causes loss of detail at archive time. If you aren\u2019t explicitly changing the existing requirement, add a new requirement under ADDED instead.\n\nAuthoring a MODIFIED requirement correctly:\n1) Locate the existing requirement in `openspec/specs/<capability>/spec.md`.\n2) Copy the entire requirement block (from `### Requirement: ...` through its scenarios).\n3) Paste it under `## MODIFIED Requirements` and edit to reflect the new behavior.\n4) Ensure the header text matches exactly (whitespace-insensitive) and keep at least one `#### Scenario:`.\n\nExample for RENAMED:\n```markdown\n## RENAMED Requirements\n- FROM: `### Requirement: Login`\n- TO: `### Requirement: User Authentication`\n```\n\n## Troubleshooting\n\n### Common Errors\n\n**\"Change must have at least one delta\"**\n- Check `changes/[name]/specs/` exists with .md files\n- Verify files have operation prefixes (## ADDED Requirements)\n\n**\"Requirement must have at least one scenario\"**\n- Check scenarios use `#### Scenario:` format (4 hashtags)\n- Don't use bullet points or bold for scenario headers\n\n**Silent scenario parsing failures**\n- Exact format required: `#### Scenario: Name`\n- Debug with: `openspec show [change] --json --deltas-only`\n\n### Validation Tips\n\n```bash\n# Always use strict mode for comprehensive checks\nopenspec validate [change] --strict\n\n# Debug delta parsing\nopenspec show [change] --json | jq '.deltas'\n\n# Check specific requirement\nopenspec show [spec] --json -r 1\n```\n\n## Happy Path Script\n\n```bash\n# 1) Explore current state\nopenspec spec list --long\nopenspec list\n# Optional full-text search:\n# rg -n \"Requirement:|Scenario:\" openspec/specs\n# rg -n \"^#|Requirement:\" openspec/changes\n\n# 2) Choose change id and scaffold\nCHANGE=add-two-factor-auth\nmkdir -p openspec/changes/$CHANGE/{specs/auth}\nprintf \"## Why\\n...\\n\\n## What Changes\\n- ...\\n\\n## Impact\\n- ...\\n\" > openspec/changes/$CHANGE/proposal.md\nprintf \"## 1. Implementation\\n- [ ] 1.1 ...\\n\" > openspec/changes/$CHANGE/tasks.md\n\n# 3) Add deltas (example)\ncat > openspec/changes/$CHANGE/specs/auth/spec.md << 'EOF'\n## ADDED Requirements\n### Requirement: Two-Factor Authentication\nUsers MUST provide a second factor during login.\n\n#### Scenario: OTP required\n- **WHEN** valid credentials are provided\n- **THEN** an OTP challenge is required\nEOF\n\n# 4) Validate\nopenspec validate $CHANGE --strict\n```\n\n## Multi-Capability Example\n\n```\nopenspec/changes/add-2fa-notify/\n\u251C\u2500\u2500 proposal.md\n\u251C\u2500\u2500 tasks.md\n\u2514\u2500\u2500 specs/\n \u251C\u2500\u2500 auth/\n \u2502 \u2514\u2500\u2500 spec.md # ADDED: Two-Factor Authentication\n \u2514\u2500\u2500 notifications/\n \u2514\u2500\u2500 spec.md # ADDED: OTP email notification\n```\n\nauth/spec.md\n```markdown\n## ADDED Requirements\n### Requirement: Two-Factor Authentication\n...\n```\n\nnotifications/spec.md\n```markdown\n## ADDED Requirements\n### Requirement: OTP Email Notification\n...\n```\n\n## Best Practices\n\n### Simplicity First\n- Default to <100 lines of new code\n- Single-file implementations until proven insufficient\n- Avoid frameworks without clear justification\n- Choose boring, proven patterns\n\n### Complexity Triggers\nOnly add complexity with:\n- Performance data showing current solution too slow\n- Concrete scale requirements (>1000 users, >100MB data)\n- Multiple proven use cases requiring abstraction\n\n### Clear References\n- Use `file.ts:42` format for code locations\n- Reference specs as `specs/auth/spec.md`\n- Link related changes and PRs\n\n### Capability Naming\n- Use verb-noun: `user-auth`, `payment-capture`\n- Single purpose per capability\n- 10-minute understandability rule\n- Split if description needs \"AND\"\n\n### Change ID Naming\n- Use kebab-case, short and descriptive: `add-two-factor-auth`\n- Prefer verb-led prefixes: `add-`, `update-`, `remove-`, `refactor-`\n- Ensure uniqueness; if taken, append `-2`, `-3`, etc.\n\n## Tool Selection Guide\n\n| Task | Tool | Why |\n|------|------|-----|\n| Find files by pattern | Glob | Fast pattern matching |\n| Search code content | Grep | Optimized regex search |\n| Read specific files | Read | Direct file access |\n| Explore unknown scope | Task | Multi-step investigation |\n\n## Error Recovery\n\n### Change Conflicts\n1. Run `openspec list` to see active changes\n2. Check for overlapping specs\n3. Coordinate with change owners\n4. Consider combining proposals\n\n### Validation Failures\n1. Run with `--strict` flag\n2. Check JSON output for details\n3. Verify spec file format\n4. Ensure scenarios properly formatted\n\n### Missing Context\n1. Read project.md first\n2. Check related specs\n3. Review recent archives\n4. Ask for clarification\n\n## Quick Reference\n\n### Stage Indicators\n- `changes/` - Proposed, not yet built\n- `specs/` - Built and deployed\n- `archive/` - Completed changes\n\n### File Purposes\n- `proposal.md` - Why and what\n- `tasks.md` - Implementation steps\n- `design.md` - Technical decisions\n- `spec.md` - Requirements and behavior\n\n### CLI Essentials\n```bash\nopenspec list # What's in progress?\nopenspec show [item] # View details\nopenspec diff [change] # What's changing?\nopenspec validate --strict # Is it correct?\nopenspec archive [change] # Mark complete\n```\n\nRemember: Specs are truth. Changes are proposals. Keep them in sync.\n";
2
+ //# sourceMappingURL=agents-template.d.ts.map