-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathconfig.ts
More file actions
648 lines (578 loc) · 20.5 KB
/
Copy pathconfig.ts
File metadata and controls
648 lines (578 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
import { Command } from 'commander';
import { spawn, execSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import {
getGlobalConfigPath,
getGlobalConfig,
saveGlobalConfig,
GlobalConfig,
} from '../core/global-config.js';
import type { Profile, Delivery } from '../core/global-config.js';
import {
getNestedValue,
setNestedValue,
deleteNestedValue,
coerceValue,
formatValueYaml,
validateConfigKeyPath,
validateConfig,
DEFAULT_CONFIG,
} from '../core/config-schema.js';
import { CORE_WORKFLOWS, ALL_WORKFLOWS, getProfileWorkflows } from '../core/profiles.js';
import { OPENSPEC_DIR_NAME } from '../core/config.js';
import { hasProjectConfigDrift } from '../core/profile-sync-drift.js';
import { isPromptCancellationError } from './shared-output.js';
type ProfileAction = 'both' | 'delivery' | 'workflows' | 'keep';
interface ProfileState {
profile: Profile;
delivery: Delivery;
workflows: string[];
}
interface ProfileStateDiff {
hasChanges: boolean;
lines: string[];
}
interface WorkflowPromptMeta {
name: string;
description: string;
}
const WORKFLOW_PROMPT_META: Record<string, WorkflowPromptMeta> = {
propose: {
name: 'Propose change',
description: 'Create proposal, design, and tasks from a request',
},
explore: {
name: 'Explore ideas',
description: 'Investigate a problem before implementation',
},
new: {
name: 'New change',
description: 'Create a new change scaffold quickly',
},
continue: {
name: 'Continue change',
description: 'Resume work on an existing change',
},
apply: {
name: 'Apply tasks',
description: 'Implement tasks from the current change',
},
ff: {
name: 'Fast-forward',
description: 'Run a faster implementation workflow',
},
sync: {
name: 'Sync specs',
description: 'Sync change artifacts with specs',
},
archive: {
name: 'Archive change',
description: 'Finalize and archive a completed change',
},
'bulk-archive': {
name: 'Bulk archive',
description: 'Archive multiple completed changes together',
},
verify: {
name: 'Verify change',
description: 'Run verification checks against a change',
},
review: {
name: 'Review implementation',
description: 'Read-only review of code against the change plan',
},
onboard: {
name: 'Onboard',
description: 'Guided onboarding flow for OpenSpec',
},
};
/**
* Resolve the effective current profile state from global config defaults.
*/
export function resolveCurrentProfileState(config: GlobalConfig): ProfileState {
const profile = config.profile || 'core';
const delivery = config.delivery || 'both';
const workflows = [
...getProfileWorkflows(profile, config.workflows ? [...config.workflows] : undefined),
];
return { profile, delivery, workflows };
}
/**
* Derive profile type from selected workflows.
*/
export function deriveProfileFromWorkflowSelection(selectedWorkflows: string[]): Profile {
const isCoreMatch =
selectedWorkflows.length === CORE_WORKFLOWS.length &&
CORE_WORKFLOWS.every((w) => selectedWorkflows.includes(w));
return isCoreMatch ? 'core' : 'custom';
}
/**
* Format a compact workflow summary for the profile header.
*/
export function formatWorkflowSummary(workflows: readonly string[], profile: Profile): string {
return `${workflows.length} selected (${profile})`;
}
function stableWorkflowOrder(workflows: readonly string[]): string[] {
const seen = new Set<string>();
const ordered: string[] = [];
for (const workflow of ALL_WORKFLOWS) {
if (workflows.includes(workflow) && !seen.has(workflow)) {
ordered.push(workflow);
seen.add(workflow);
}
}
const extras = workflows.filter((w) => !ALL_WORKFLOWS.includes(w as (typeof ALL_WORKFLOWS)[number]));
extras.sort();
for (const extra of extras) {
if (!seen.has(extra)) {
ordered.push(extra);
seen.add(extra);
}
}
return ordered;
}
/**
* Build a user-facing diff summary between two profile states.
*/
export function diffProfileState(before: ProfileState, after: ProfileState): ProfileStateDiff {
const lines: string[] = [];
if (before.delivery !== after.delivery) {
lines.push(`delivery: ${before.delivery} -> ${after.delivery}`);
}
if (before.profile !== after.profile) {
lines.push(`profile: ${before.profile} -> ${after.profile}`);
}
const beforeOrdered = stableWorkflowOrder(before.workflows);
const afterOrdered = stableWorkflowOrder(after.workflows);
const beforeSet = new Set(beforeOrdered);
const afterSet = new Set(afterOrdered);
const added = afterOrdered.filter((w) => !beforeSet.has(w));
const removed = beforeOrdered.filter((w) => !afterSet.has(w));
if (added.length > 0 || removed.length > 0) {
const tokens: string[] = [];
if (added.length > 0) {
tokens.push(`added ${added.join(', ')}`);
}
if (removed.length > 0) {
tokens.push(`removed ${removed.join(', ')}`);
}
lines.push(`workflows: ${tokens.join('; ')}`);
}
return {
hasChanges: lines.length > 0,
lines,
};
}
function maybeWarnProjectConfigDrift(
projectDir: string,
state: ProfileState,
colorize: (message: string) => string
): void {
const openspecDir = path.join(projectDir, OPENSPEC_DIR_NAME);
if (!fs.existsSync(openspecDir)) {
return;
}
if (!hasProjectConfigDrift(projectDir, state.workflows, state.delivery)) {
return;
}
console.log(colorize('Warning: Global config is not applied to this project. Run `openspec update` to sync.'));
}
function printConfigProfileApplyGuidance(): void {
console.log('Config updated. Run `openspec update` in your projects to apply.');
}
/**
* Register the config command and all its subcommands.
*
* @param program - The Commander program instance
*/
export function registerConfigCommand(program: Command): void {
const configCmd = program
.command('config')
.description('View and modify global OpenSpec configuration')
.option('--scope <scope>', 'Config scope (only "global" supported currently)')
.hook('preAction', (thisCommand) => {
const opts = thisCommand.opts();
if (opts.scope && opts.scope !== 'global') {
console.error('Error: Project-local config is not yet implemented');
process.exit(1);
}
});
// config path
configCmd
.command('path')
.description('Show config file location')
.action(() => {
console.log(getGlobalConfigPath());
});
// config list
configCmd
.command('list')
.description('Show all current settings')
.option('--json', 'Output as JSON')
.action((options: { json?: boolean }) => {
const config = getGlobalConfig();
if (options.json) {
console.log(JSON.stringify(config, null, 2));
} else {
// Read raw config to determine which values are explicit vs defaults
const configPath = getGlobalConfigPath();
let rawConfig: Record<string, unknown> = {};
try {
if (fs.existsSync(configPath)) {
rawConfig = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
}
} catch {
// If reading fails, treat all as defaults
}
console.log(formatValueYaml(config));
// Annotate profile settings
const profileSource = rawConfig.profile !== undefined ? '(explicit)' : '(default)';
const deliverySource = rawConfig.delivery !== undefined ? '(explicit)' : '(default)';
console.log(`\nProfile settings:`);
console.log(` profile: ${config.profile} ${profileSource}`);
console.log(` delivery: ${config.delivery} ${deliverySource}`);
if (config.profile === 'core') {
console.log(` workflows: ${CORE_WORKFLOWS.join(', ')} (from core profile)`);
} else if (config.workflows && config.workflows.length > 0) {
console.log(` workflows: ${config.workflows.join(', ')} (explicit)`);
} else {
console.log(` workflows: (none)`);
}
}
});
// config get
configCmd
.command('get <key>')
.description('Get a specific value (raw, scriptable)')
.action((key: string) => {
const config = getGlobalConfig();
const value = getNestedValue(config as Record<string, unknown>, key);
if (value === undefined) {
process.exitCode = 1;
return;
}
if (typeof value === 'object' && value !== null) {
console.log(JSON.stringify(value));
} else {
console.log(String(value));
}
});
// config set
configCmd
.command('set <key> <value>')
.description('Set a value (auto-coerce types)')
.option('--string', 'Force value to be stored as string')
.option('--allow-unknown', 'Allow setting unknown keys')
.action((key: string, value: string, options: { string?: boolean; allowUnknown?: boolean }) => {
const allowUnknown = Boolean(options.allowUnknown);
const keyValidation = validateConfigKeyPath(key);
if (!keyValidation.valid && !allowUnknown) {
const reason = keyValidation.reason ? ` ${keyValidation.reason}.` : '';
console.error(`Error: Invalid configuration key "${key}".${reason}`);
console.error('Use "openspec config list" to see available keys.');
console.error('Pass --allow-unknown to bypass this check.');
process.exitCode = 1;
return;
}
const config = getGlobalConfig() as Record<string, unknown>;
const coercedValue = coerceValue(value, options.string || false);
// Create a copy to validate before saving
const newConfig = JSON.parse(JSON.stringify(config));
setNestedValue(newConfig, key, coercedValue);
// Validate the new config
const validation = validateConfig(newConfig);
if (!validation.success) {
console.error(`Error: Invalid configuration - ${validation.error}`);
process.exitCode = 1;
return;
}
// Apply changes and save
setNestedValue(config, key, coercedValue);
saveGlobalConfig(config as GlobalConfig);
const displayValue =
typeof coercedValue === 'string' ? `"${coercedValue}"` : String(coercedValue);
console.log(`Set ${key} = ${displayValue}`);
});
// config unset
configCmd
.command('unset <key>')
.description('Remove a key (revert to default)')
.action((key: string) => {
const config = getGlobalConfig() as Record<string, unknown>;
const existed = deleteNestedValue(config, key);
if (existed) {
saveGlobalConfig(config as GlobalConfig);
console.log(`Unset ${key} (reverted to default)`);
} else {
console.log(`Key "${key}" was not set`);
}
});
// config reset
configCmd
.command('reset')
.description('Reset configuration to defaults')
.option('--all', 'Reset all configuration (required)')
.option('-y, --yes', 'Skip confirmation prompts')
.action(async (options: { all?: boolean; yes?: boolean }) => {
if (!options.all) {
console.error('Error: --all flag is required for reset');
console.error('Usage: openspec config reset --all [-y]');
process.exitCode = 1;
return;
}
if (!options.yes) {
const { confirm } = await import('@inquirer/prompts');
let confirmed: boolean;
try {
confirmed = await confirm({
message: 'Reset all configuration to defaults?',
default: false,
});
} catch (error) {
if (isPromptCancellationError(error)) {
console.log('Reset cancelled.');
process.exitCode = 130;
return;
}
throw error;
}
if (!confirmed) {
console.log('Reset cancelled.');
return;
}
}
saveGlobalConfig({ ...DEFAULT_CONFIG });
console.log('Configuration reset to defaults');
});
// config edit
configCmd
.command('edit')
.description('Open config in $EDITOR')
.action(async () => {
const editor = process.env.EDITOR || process.env.VISUAL;
if (!editor) {
console.error('Error: No editor configured');
console.error('Set the EDITOR or VISUAL environment variable to your preferred editor');
console.error('Example: export EDITOR=vim');
process.exitCode = 1;
return;
}
const configPath = getGlobalConfigPath();
// Ensure config file exists with defaults
if (!fs.existsSync(configPath)) {
saveGlobalConfig({ ...DEFAULT_CONFIG });
}
// Spawn editor and wait for it to close
// Avoid shell parsing to correctly handle paths with spaces in both
// the editor path and config path
const child = spawn(editor, [configPath], {
stdio: 'inherit',
shell: false,
});
await new Promise<void>((resolve, reject) => {
child.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Editor exited with code ${code}`));
}
});
child.on('error', reject);
});
try {
const rawConfig = fs.readFileSync(configPath, 'utf-8');
const parsedConfig = JSON.parse(rawConfig);
const validation = validateConfig(parsedConfig);
if (!validation.success) {
console.error(`Error: Invalid configuration - ${validation.error}`);
process.exitCode = 1;
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
console.error(`Error: Config file not found at ${configPath}`);
} else if (error instanceof SyntaxError) {
console.error(`Error: Invalid JSON in ${configPath}`);
console.error(error.message);
} else {
console.error(`Error: Unable to validate configuration - ${error instanceof Error ? error.message : String(error)}`);
}
process.exitCode = 1;
}
});
// config profile [preset]
configCmd
.command('profile [preset]')
.description('Configure workflow profile (interactive picker or preset shortcut)')
.action(async (preset?: string) => {
// Preset shortcut: `openspec config profile core`
if (preset === 'core') {
const config = getGlobalConfig();
config.profile = 'core';
config.workflows = [...CORE_WORKFLOWS];
// Preserve delivery setting
saveGlobalConfig(config);
printConfigProfileApplyGuidance();
return;
}
if (preset) {
console.error(`Error: Unknown profile preset "${preset}". Available presets: core`);
process.exitCode = 1;
return;
}
// Non-interactive check
if (!process.stdout.isTTY) {
console.error('Interactive mode required. Use `openspec config profile core` or set config via environment/flags.');
process.exitCode = 1;
return;
}
// Interactive picker
const { select, checkbox, confirm } = await import('@inquirer/prompts');
const chalk = (await import('chalk')).default;
try {
const config = getGlobalConfig();
const currentState = resolveCurrentProfileState(config);
console.log(chalk.bold('\nCurrent profile settings'));
console.log(` Delivery: ${currentState.delivery}`);
console.log(` Workflows: ${formatWorkflowSummary(currentState.workflows, currentState.profile)}`);
console.log(chalk.dim(' Delivery = where workflows are installed (skills, commands, or both)'));
console.log(chalk.dim(' Workflows = which actions are available (propose, explore, apply, etc.)'));
console.log();
const action = await select<ProfileAction>({
message: 'What do you want to configure?',
choices: [
{
value: 'both',
name: 'Delivery and workflows',
description: 'Update install mode and available actions together',
},
{
value: 'delivery',
name: 'Delivery only',
description: 'Change where workflows are installed',
},
{
value: 'workflows',
name: 'Workflows only',
description: 'Change which workflow actions are available',
},
{
value: 'keep',
name: 'Keep current settings (exit)',
description: 'Leave configuration unchanged and exit',
},
],
});
if (action === 'keep') {
console.log('No config changes.');
maybeWarnProjectConfigDrift(process.cwd(), currentState, chalk.yellow);
return;
}
const nextState: ProfileState = {
profile: currentState.profile,
delivery: currentState.delivery,
workflows: [...currentState.workflows],
};
if (action === 'both' || action === 'delivery') {
const deliveryChoices: { value: Delivery; name: string; description: string }[] = [
{
value: 'both' as Delivery,
name: 'Both (skills + commands)',
description: 'Install workflows as both skills and slash commands',
},
{
value: 'skills' as Delivery,
name: 'Skills only',
description: 'Install workflows only as skills',
},
{
value: 'commands' as Delivery,
name: 'Commands only',
description: 'Install workflows only as slash commands',
},
];
for (const choice of deliveryChoices) {
if (choice.value === currentState.delivery) {
choice.name += ' [current]';
}
}
nextState.delivery = await select<Delivery>({
message: 'Delivery mode (how workflows are installed):',
choices: deliveryChoices,
default: currentState.delivery,
});
}
if (action === 'both' || action === 'workflows') {
const formatWorkflowChoice = (workflow: string) => {
const metadata = WORKFLOW_PROMPT_META[workflow] ?? {
name: workflow,
description: `Workflow: ${workflow}`,
};
return {
value: workflow,
name: metadata.name,
description: metadata.description,
short: metadata.name,
checked: currentState.workflows.includes(workflow),
};
};
const selectedWorkflows = await checkbox<string>({
message: 'Select workflows to make available:',
instructions: 'Space to toggle, Enter to confirm',
pageSize: ALL_WORKFLOWS.length,
theme: {
icon: {
checked: '[x]',
unchecked: '[ ]',
},
},
choices: ALL_WORKFLOWS.map(formatWorkflowChoice),
});
nextState.workflows = selectedWorkflows;
nextState.profile = deriveProfileFromWorkflowSelection(selectedWorkflows);
}
const diff = diffProfileState(currentState, nextState);
if (!diff.hasChanges) {
console.log('No config changes.');
maybeWarnProjectConfigDrift(process.cwd(), nextState, chalk.yellow);
return;
}
console.log(chalk.bold('\nConfig changes:'));
for (const line of diff.lines) {
console.log(` ${line}`);
}
console.log();
config.profile = nextState.profile;
config.delivery = nextState.delivery;
config.workflows = nextState.workflows;
saveGlobalConfig(config);
// Check if inside an OpenSpec project
const projectDir = process.cwd();
const openspecDir = path.join(projectDir, OPENSPEC_DIR_NAME);
if (fs.existsSync(openspecDir)) {
const applyNow = await confirm({
message: 'Apply changes to this project now?',
default: true,
});
if (applyNow) {
try {
execSync('npx openspec update', { stdio: 'inherit', cwd: projectDir });
console.log('Run `openspec update` in your other projects to apply.');
} catch {
console.error('`openspec update` failed. Please run it manually to apply the profile changes.');
process.exitCode = 1;
}
return;
}
}
printConfigProfileApplyGuidance();
} catch (error) {
if (isPromptCancellationError(error)) {
console.log('Config profile cancelled.');
process.exitCode = 130;
return;
}
throw error;
}
});
}