-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Expand file tree
/
Copy pathinit.test.ts
More file actions
1247 lines (994 loc) · 52.4 KB
/
Copy pathinit.test.ts
File metadata and controls
1247 lines (994 loc) · 52.4 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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { promises as fs } from 'fs';
import { randomUUID } from 'crypto';
import path from 'path';
import os from 'os';
import { InitCommand } from '../../src/core/init.js';
import { saveGlobalConfig, getGlobalConfig } from '../../src/core/global-config.js';
const { confirmMock, showWelcomeScreenMock, searchableMultiSelectMock } = vi.hoisted(() => ({
confirmMock: vi.fn(),
showWelcomeScreenMock: vi.fn().mockResolvedValue(undefined),
searchableMultiSelectMock: vi.fn(),
}));
vi.mock('@inquirer/prompts', () => ({
confirm: confirmMock,
}));
vi.mock('../../src/ui/welcome-screen.js', () => ({
showWelcomeScreen: showWelcomeScreenMock,
}));
vi.mock('../../src/prompts/searchable-multi-select.js', () => ({
searchableMultiSelect: searchableMultiSelectMock,
}));
describe('InitCommand', () => {
let testDir: string;
let configTempDir: string;
let originalEnv: NodeJS.ProcessEnv;
beforeEach(async () => {
testDir = path.join(os.tmpdir(), `openspec-init-test-${randomUUID()}`);
await fs.mkdir(testDir, { recursive: true });
originalEnv = { ...process.env };
// Use a temp dir for global config to avoid reading real config
configTempDir = path.join(os.tmpdir(), `openspec-config-init-${randomUUID()}`);
await fs.mkdir(configTempDir, { recursive: true });
process.env.XDG_CONFIG_HOME = configTempDir;
process.env.CODEX_HOME = path.join(testDir, 'codex-home');
// Mock console.log to suppress output during tests
vi.spyOn(console, 'log').mockImplementation(() => { });
confirmMock.mockReset();
confirmMock.mockResolvedValue(true);
showWelcomeScreenMock.mockClear();
searchableMultiSelectMock.mockReset();
});
afterEach(async () => {
process.env = originalEnv;
await fs.rm(testDir, { recursive: true, force: true });
await fs.rm(configTempDir, { recursive: true, force: true });
vi.restoreAllMocks();
});
describe('execute with --tools flag', () => {
it('should create OpenSpec directory structure', async () => {
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const openspecPath = path.join(testDir, 'openspec');
expect(await directoryExists(openspecPath)).toBe(true);
expect(await directoryExists(path.join(openspecPath, 'specs'))).toBe(true);
expect(await directoryExists(path.join(openspecPath, 'changes'))).toBe(true);
expect(await directoryExists(path.join(openspecPath, 'changes', 'archive'))).toBe(true);
});
it('should create config.yaml with default schema', async () => {
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const configPath = path.join(testDir, 'openspec', 'config.yaml');
expect(await fileExists(configPath)).toBe(true);
const content = await fs.readFile(configPath, 'utf-8');
expect(content).toContain('schema: spec-driven');
});
it('should create core profile skills for Claude Code by default', async () => {
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
// Core profile: propose, explore, apply, update, sync, archive
const coreSkillNames = [
'openspec-propose',
'openspec-explore',
'openspec-apply-change',
'openspec-update-change',
'openspec-sync-specs',
'openspec-archive-change',
];
for (const skillName of coreSkillNames) {
const skillFile = path.join(testDir, '.claude', 'skills', skillName, 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
const content = await fs.readFile(skillFile, 'utf-8');
expect(content).toContain('---');
expect(content).toContain('name:');
expect(content).toContain('description:');
}
// Non-core skills should NOT be created
const nonCoreSkillNames = [
'openspec-new-change',
'openspec-continue-change',
'openspec-ff-change',
'openspec-bulk-archive-change',
'openspec-verify-change',
];
for (const skillName of nonCoreSkillNames) {
const skillFile = path.join(testDir, '.claude', 'skills', skillName, 'SKILL.md');
expect(await fileExists(skillFile)).toBe(false);
}
});
it('should create core profile commands for Claude Code by default', async () => {
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
// Core profile: propose, explore, apply, update, sync, archive
const coreCommandNames = [
'opsx/propose.md',
'opsx/explore.md',
'opsx/apply.md',
'opsx/update.md',
'opsx/sync.md',
'opsx/archive.md',
];
for (const cmdName of coreCommandNames) {
const cmdFile = path.join(testDir, '.claude', 'commands', cmdName);
expect(await fileExists(cmdFile)).toBe(true);
}
// Non-core commands should NOT be created
const nonCoreCommandNames = [
'opsx/new.md',
'opsx/continue.md',
'opsx/ff.md',
'opsx/bulk-archive.md',
'opsx/verify.md',
];
for (const cmdName of nonCoreCommandNames) {
const cmdFile = path.join(testDir, '.claude', 'commands', cmdName);
expect(await fileExists(cmdFile)).toBe(false);
}
});
it('should create skills in Cursor skills directory', async () => {
const initCommand = new InitCommand({ tools: 'cursor', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.cursor', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
});
it('should create skills in Windsurf skills directory', async () => {
const initCommand = new InitCommand({ tools: 'windsurf', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.windsurf', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
});
it('should generate ZCode skills and commands under .zcode without creating .agents', async () => {
const initCommand = new InitCommand({ tools: 'zcode', force: true });
await initCommand.execute(testDir);
// Core profile skills land under .zcode/skills
const exploreSkill = path.join(testDir, '.zcode', 'skills', 'openspec-explore', 'SKILL.md');
const proposeSkill = path.join(testDir, '.zcode', 'skills', 'openspec-propose', 'SKILL.md');
expect(await fileExists(exploreSkill)).toBe(true);
expect(await fileExists(proposeSkill)).toBe(true);
// Core profile commands land under .zcode/commands/opsx
const exploreCmd = path.join(testDir, '.zcode', 'commands', 'opsx', 'explore.md');
const proposeCmd = path.join(testDir, '.zcode', 'commands', 'opsx', 'propose.md');
expect(await fileExists(exploreCmd)).toBe(true);
expect(await fileExists(proposeCmd)).toBe(true);
const cmdContent = await fs.readFile(exploreCmd, 'utf-8');
expect(cmdContent).toContain('---');
expect(cmdContent).toContain('name:');
expect(cmdContent).toContain('description:');
expect(cmdContent).toContain('category:');
expect(cmdContent).toContain('tags:');
// .agents is a detection-only root and must never be created during generation
expect(await directoryExists(path.join(testDir, '.agents'))).toBe(false);
});
it('should support Kimi Code as an adapterless skills-only tool', async () => {
saveGlobalConfig({
featureFlags: {},
profile: 'core',
delivery: 'both',
});
const initCommand = new InitCommand({ tools: 'kimi', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.kimi-code', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
const commandsDir = path.join(testDir, '.kimi-code', 'commands');
expect(await directoryExists(commandsDir)).toBe(false);
const logCalls = (console.log as unknown as { mock: { calls: unknown[][] } }).mock.calls.flat().map(String);
expect(
logCalls.some(
(entry) => entry.includes('Commands skipped for: kimi') && entry.includes('(no adapter)'),
),
).toBe(true);
});
it('should support CodeArts as an adapterless skills-only tool', async () => {
saveGlobalConfig({
featureFlags: {},
profile: 'core',
delivery: 'both',
});
const initCommand = new InitCommand({ tools: 'codeartsagent', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.codeartsdoer', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
const commandsDir = path.join(testDir, '.codeartsdoer', 'commands');
expect(await directoryExists(commandsDir)).toBe(false);
const codeArtsLogCalls = (console.log as unknown as { mock: { calls: unknown[][] } }).mock.calls.flat().map(String);
expect(codeArtsLogCalls.some((entry) => entry.includes('Created: CodeArts'))).toBe(true);
expect(
codeArtsLogCalls.some(
(entry) => entry.includes('Commands skipped for: codeartsagent') && entry.includes('(no adapter)'),
),
).toBe(true);
});
it('should support Hermes Agent as an adapterless skills-only tool with a setup note', async () => {
saveGlobalConfig({
featureFlags: {},
profile: 'core',
delivery: 'both',
});
const initCommand = new InitCommand({ tools: 'hermes', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.hermes', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
const commandsDir = path.join(testDir, '.hermes', 'commands');
expect(await directoryExists(commandsDir)).toBe(false);
const logCalls = (console.log as unknown as { mock: { calls: unknown[][] } }).mock.calls.flat().map(String);
expect(
logCalls.some(
(entry) => entry.includes('Commands skipped for: hermes') && entry.includes('(no adapter)'),
),
).toBe(true);
expect(
logCalls.some(
(entry) => entry.includes('Setup required for Hermes Agent') && entry.includes('skills.external_dirs'),
),
).toBe(true);
});
it('should migrate OpenSpec skills from legacy .kimi to .kimi-code during init', async () => {
const legacySkillDir = path.join(testDir, '.kimi', 'skills', 'openspec-explore');
await fs.mkdir(legacySkillDir, { recursive: true });
await fs.writeFile(
path.join(legacySkillDir, 'SKILL.md'),
`---\nname: openspec-explore\nmetadata:\n author: openspec\n version: "0.9"\n---\n\nOld instructions content\n`
);
await fs.writeFile(path.join(testDir, '.kimi', 'config.toml'), 'user config');
const initCommand = new InitCommand({ tools: 'kimi', force: true });
await initCommand.execute(testDir);
// Regenerated in the new location, legacy managed skill removed
const newSkill = path.join(testDir, '.kimi-code', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(newSkill)).toBe(true);
expect(await directoryExists(legacySkillDir)).toBe(false);
// User files under .kimi are preserved
expect(await fileExists(path.join(testDir, '.kimi', 'config.toml'))).toBe(true);
});
it('should create both skills and commands for Trae with adapter', async () => {
saveGlobalConfig({
featureFlags: {},
profile: 'core',
delivery: 'both',
});
const initCommand = new InitCommand({ tools: 'trae', force: true });
await initCommand.execute(testDir);
// Skills should be created
const skillFile = path.join(testDir, '.trae', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
// Commands should also be created (Trae has an adapter)
const commandFile = path.join(testDir, '.trae', 'commands', 'opsx-explore.md');
expect(await fileExists(commandFile)).toBe(true);
const commandContent = await fs.readFile(commandFile, 'utf-8');
expect(commandContent).toContain('---');
expect(commandContent).toContain('name:');
expect(commandContent).toContain('description:');
});
it.each(['both', 'skills', 'commands'] as const)(
'should create Codex skills and no global prompts when delivery=%s',
async (delivery) => {
saveGlobalConfig({
featureFlags: {},
profile: 'core',
delivery,
});
const initCommand = new InitCommand({ tools: 'codex', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.codex', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
const promptFile = path.join(process.env.CODEX_HOME!, 'prompts', 'opsx-explore.md');
expect(await fileExists(promptFile)).toBe(false);
}
);
it('should create skills for multiple tools at once', async () => {
const initCommand = new InitCommand({ tools: 'claude,cursor', force: true });
await initCommand.execute(testDir);
const claudeSkill = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const cursorSkill = path.join(testDir, '.cursor', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(claudeSkill)).toBe(true);
expect(await fileExists(cursorSkill)).toBe(true);
});
it('should select all tools with --tools all option', async () => {
const initCommand = new InitCommand({ tools: 'all', force: true });
await initCommand.execute(testDir);
// Check a few representative tools
const claudeSkill = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const codeArtsSkill = path.join(testDir, '.codeartsdoer', 'skills', 'openspec-explore', 'SKILL.md');
const cursorSkill = path.join(testDir, '.cursor', 'skills', 'openspec-explore', 'SKILL.md');
const windsurfSkill = path.join(testDir, '.windsurf', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(claudeSkill)).toBe(true);
expect(await fileExists(codeArtsSkill)).toBe(true);
expect(await fileExists(cursorSkill)).toBe(true);
expect(await fileExists(windsurfSkill)).toBe(true);
});
it('should skip tool configuration with --tools none option', async () => {
const initCommand = new InitCommand({ tools: 'none', force: true });
await initCommand.execute(testDir);
// Should create OpenSpec structure but no skills
const openspecPath = path.join(testDir, 'openspec');
expect(await directoryExists(openspecPath)).toBe(true);
// No tool-specific directories should be created
const claudeSkillsDir = path.join(testDir, '.claude', 'skills');
expect(await directoryExists(claudeSkillsDir)).toBe(false);
});
it('should throw error for invalid tool names', async () => {
const initCommand = new InitCommand({ tools: 'invalid-tool', force: true });
await expect(initCommand.execute(testDir)).rejects.toThrow(/Invalid tool\(s\): invalid-tool/);
});
it('should handle comma-separated tool names with spaces', async () => {
const initCommand = new InitCommand({ tools: 'claude, cursor', force: true });
await initCommand.execute(testDir);
const claudeSkill = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const cursorSkill = path.join(testDir, '.cursor', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(claudeSkill)).toBe(true);
expect(await fileExists(cursorSkill)).toBe(true);
});
it('should reject combining reserved keywords with explicit tool ids', async () => {
const initCommand = new InitCommand({ tools: 'all,claude', force: true });
await expect(initCommand.execute(testDir)).rejects.toThrow(
/Cannot combine reserved values "all" or "none" with specific tool IDs/
);
});
it('should not create config.yaml if it already exists', async () => {
// Pre-create config.yaml
const openspecDir = path.join(testDir, 'openspec');
await fs.mkdir(openspecDir, { recursive: true });
const configPath = path.join(openspecDir, 'config.yaml');
const existingContent = 'schema: custom-schema\n';
await fs.writeFile(configPath, existingContent);
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const content = await fs.readFile(configPath, 'utf-8');
expect(content).toBe(existingContent);
});
it('should handle non-existent target directory', async () => {
const newDir = path.join(testDir, 'new-project');
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(newDir);
const openspecPath = path.join(newDir, 'openspec');
expect(await directoryExists(openspecPath)).toBe(true);
});
it('should work in extend mode (re-running init)', async () => {
const initCommand1 = new InitCommand({ tools: 'claude', force: true });
await initCommand1.execute(testDir);
// Run init again with a different tool
const initCommand2 = new InitCommand({ tools: 'cursor', force: true });
await initCommand2.execute(testDir);
// Both tools should have skills
const claudeSkill = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const cursorSkill = path.join(testDir, '.cursor', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(claudeSkill)).toBe(true);
expect(await fileExists(cursorSkill)).toBe(true);
});
it('should refresh skills on re-run for the same tool', async () => {
const initCommand1 = new InitCommand({ tools: 'claude', force: true });
await initCommand1.execute(testDir);
const skillFile = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const originalContent = await fs.readFile(skillFile, 'utf-8');
// Modify the file
await fs.writeFile(skillFile, '# Modified content\n');
// Run init again
const initCommand2 = new InitCommand({ tools: 'claude', force: true });
await initCommand2.execute(testDir);
const newContent = await fs.readFile(skillFile, 'utf-8');
expect(newContent).toBe(originalContent);
});
});
describe('skill content validation', () => {
it('should generate valid SKILL.md with YAML frontmatter', async () => {
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const content = await fs.readFile(skillFile, 'utf-8');
// Should have YAML frontmatter
expect(content).toMatch(/^---\n/);
expect(content).toContain('name: openspec-explore');
expect(content).toContain('description:');
expect(content).toContain('license:');
expect(content).toContain('compatibility:');
expect(content).toContain('metadata:');
expect(content).toMatch(/---\n\n/); // End of frontmatter
});
it('should include explore mode instructions', async () => {
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const content = await fs.readFile(skillFile, 'utf-8');
expect(content).toContain('Enter explore mode');
expect(content).toContain('thinking partner');
});
it('should include propose skill instructions', async () => {
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.claude', 'skills', 'openspec-propose', 'SKILL.md');
const content = await fs.readFile(skillFile, 'utf-8');
expect(content).toContain('name: openspec-propose');
});
it('should include apply-change skill instructions', async () => {
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.claude', 'skills', 'openspec-apply-change', 'SKILL.md');
const content = await fs.readFile(skillFile, 'utf-8');
expect(content).toContain('name: openspec-apply-change');
});
it('should embed generatedBy version in skill files', async () => {
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const content = await fs.readFile(skillFile, 'utf-8');
// Should contain generatedBy field with a version string
expect(content).toMatch(/generatedBy:\s*["']?\d+\.\d+\.\d+["']?/);
});
});
describe('command generation', () => {
it('should generate Claude Code commands with correct format', async () => {
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const cmdFile = path.join(testDir, '.claude', 'commands', 'opsx', 'explore.md');
const content = await fs.readFile(cmdFile, 'utf-8');
// Claude commands use YAML frontmatter
expect(content).toMatch(/^---\n/);
expect(content).toContain('name:');
expect(content).toContain('description:');
});
it('should generate Cursor commands with correct format', async () => {
const initCommand = new InitCommand({ tools: 'cursor', force: true });
await initCommand.execute(testDir);
const cmdFile = path.join(testDir, '.cursor', 'commands', 'opsx-explore.md');
expect(await fileExists(cmdFile)).toBe(true);
const content = await fs.readFile(cmdFile, 'utf-8');
expect(content).toMatch(/^---\n/);
});
});
describe('error handling', () => {
it('should provide helpful error for insufficient permissions', async () => {
// Mock the permission check to fail
const readOnlyDir = path.join(testDir, 'readonly');
await fs.mkdir(readOnlyDir);
const originalWriteFile = fs.writeFile;
vi.spyOn(fs, 'writeFile').mockImplementation(
async (filePath: any, ...args: any[]) => {
if (
typeof filePath === 'string' &&
filePath.includes('.openspec-test-')
) {
throw new Error('EACCES: permission denied');
}
return (originalWriteFile as any)(filePath, ...args);
}
);
const initCommand = new InitCommand({ tools: 'claude', force: true });
await expect(initCommand.execute(readOnlyDir)).rejects.toThrow(/Insufficient permissions/);
});
it('should throw error in non-interactive mode without --tools flag and no detected tools', async () => {
const initCommand = new InitCommand({ interactive: false });
await expect(initCommand.execute(testDir)).rejects.toThrow(/No tools detected and no --tools flag/);
});
});
describe('tool-specific adapters', () => {
it('should generate Gemini CLI commands as TOML files', async () => {
const initCommand = new InitCommand({ tools: 'gemini', force: true });
await initCommand.execute(testDir);
const cmdFile = path.join(testDir, '.gemini', 'commands', 'opsx', 'explore.toml');
expect(await fileExists(cmdFile)).toBe(true);
const content = await fs.readFile(cmdFile, 'utf-8');
expect(content).toContain('description =');
expect(content).toContain('prompt =');
});
it('should generate Windsurf commands', async () => {
const initCommand = new InitCommand({ tools: 'windsurf', force: true });
await initCommand.execute(testDir);
const cmdFile = path.join(testDir, '.windsurf', 'workflows', 'opsx-explore.md');
expect(await fileExists(cmdFile)).toBe(true);
});
it('should generate Continue prompt files', async () => {
const initCommand = new InitCommand({ tools: 'continue', force: true });
await initCommand.execute(testDir);
const cmdFile = path.join(testDir, '.continue', 'prompts', 'opsx-explore.prompt');
expect(await fileExists(cmdFile)).toBe(true);
const content = await fs.readFile(cmdFile, 'utf-8');
expect(content).toContain('name: opsx-explore');
expect(content).toContain('invokable: true');
});
it('should generate Cline workflow files', async () => {
const initCommand = new InitCommand({ tools: 'cline', force: true });
await initCommand.execute(testDir);
const cmdFile = path.join(testDir, '.clinerules', 'workflows', 'opsx-explore.md');
expect(await fileExists(cmdFile)).toBe(true);
});
it('should generate GitHub Copilot prompt files', async () => {
const initCommand = new InitCommand({ tools: 'github-copilot', force: true });
await initCommand.execute(testDir);
const cmdFile = path.join(testDir, '.github', 'prompts', 'opsx-explore.prompt.md');
expect(await fileExists(cmdFile)).toBe(true);
});
});
});
describe('InitCommand - profile and detection features', () => {
let testDir: string;
let configTempDir: string;
let originalEnv: NodeJS.ProcessEnv;
beforeEach(async () => {
testDir = path.join(os.tmpdir(), `openspec-init-profile-test-${randomUUID()}`);
await fs.mkdir(testDir, { recursive: true });
originalEnv = { ...process.env };
// Use a temp dir for global config to avoid polluting real config
configTempDir = path.join(os.tmpdir(), `openspec-config-test-${randomUUID()}`);
await fs.mkdir(configTempDir, { recursive: true });
process.env.XDG_CONFIG_HOME = configTempDir;
process.env.CODEX_HOME = path.join(testDir, 'codex-home');
vi.spyOn(console, 'log').mockImplementation(() => {});
confirmMock.mockReset();
confirmMock.mockResolvedValue(true);
showWelcomeScreenMock.mockClear();
searchableMultiSelectMock.mockReset();
});
afterEach(async () => {
process.env = originalEnv;
await fs.rm(testDir, { recursive: true, force: true });
await fs.rm(configTempDir, { recursive: true, force: true });
vi.restoreAllMocks();
});
it('should use --profile flag to override global config', async () => {
// Set global config to custom profile
saveGlobalConfig({
featureFlags: {},
profile: 'custom',
delivery: 'both',
workflows: ['explore', 'new', 'apply'],
});
// Override with --profile core
const initCommand = new InitCommand({ tools: 'claude', force: true, profile: 'core' });
await initCommand.execute(testDir);
// Core profile skills should be created
const proposeSkill = path.join(testDir, '.claude', 'skills', 'openspec-propose', 'SKILL.md');
expect(await fileExists(proposeSkill)).toBe(true);
// Non-core skills (from the custom profile) should NOT be created
const newChangeSkill = path.join(testDir, '.claude', 'skills', 'openspec-new-change', 'SKILL.md');
expect(await fileExists(newChangeSkill)).toBe(false);
});
it('should reject invalid --profile values', async () => {
const initCommand = new InitCommand({
tools: 'claude',
force: true,
profile: 'invalid-profile',
});
await expect(initCommand.execute(testDir)).rejects.toThrow(
/Invalid profile "invalid-profile"/
);
});
it('should use detected tools in non-interactive mode when no --tools flag', async () => {
// Create a .claude directory to simulate detected tool
await fs.mkdir(path.join(testDir, '.claude'), { recursive: true });
const initCommand = new InitCommand({ interactive: false, force: true });
await initCommand.execute(testDir);
// Should have used claude (detected)
const skillFile = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
});
it('should auto-cleanup legacy artifacts in non-interactive mode without --force', async () => {
// Create legacy OpenCode command files (singular 'command' path)
const legacyDir = path.join(testDir, '.opencode', 'command');
await fs.mkdir(legacyDir, { recursive: true });
await fs.writeFile(path.join(legacyDir, 'opsx-propose.md'), 'legacy content');
// Run init in non-interactive mode without --force
const initCommand = new InitCommand({ tools: 'opencode' });
await initCommand.execute(testDir);
// Legacy files should be cleaned up automatically
expect(await fileExists(path.join(legacyDir, 'opsx-propose.md'))).toBe(false);
// New commands should be at the correct plural path
const newCommandsDir = path.join(testDir, '.opencode', 'commands');
expect(await directoryExists(newCommandsDir)).toBe(true);
});
it('should remove managed global Codex prompts in non-interactive mode', async () => {
const promptDir = path.join(process.env.CODEX_HOME!, 'prompts');
const legacyPrompt = path.join(promptDir, 'opsx-apply.md');
await fs.mkdir(promptDir, { recursive: true });
await fs.writeFile(legacyPrompt, 'legacy apply prompt');
const initCommand = new InitCommand({ tools: 'codex' });
await initCommand.execute(testDir);
expect(await fileExists(legacyPrompt)).toBe(false);
expect(await fileExists(
path.join(testDir, '.codex', 'skills', 'openspec-apply-change', 'SKILL.md')
)).toBe(true);
});
it('should preserve legacy Codex prompts without replacement skills during non-interactive init', async () => {
const promptDir = path.join(process.env.CODEX_HOME!, 'prompts');
const legacyPrompt = path.join(promptDir, 'opsx-onboard.md');
await fs.mkdir(promptDir, { recursive: true });
await fs.writeFile(legacyPrompt, 'legacy onboard prompt');
const initCommand = new InitCommand({ tools: 'codex' });
await initCommand.execute(testDir);
expect(await fileExists(legacyPrompt)).toBe(true);
expect(await fileExists(
path.join(testDir, '.codex', 'skills', 'openspec-explore', 'SKILL.md')
)).toBe(true);
expect(await fileExists(
path.join(testDir, '.codex', 'skills', 'openspec-onboard', 'SKILL.md')
)).toBe(false);
});
it('should defer global Codex prompt removal messaging until after interactive tool selection', async () => {
const promptDir = path.join(process.env.CODEX_HOME!, 'prompts');
const legacyPrompt = path.join(promptDir, 'opsx-apply.md');
await fs.mkdir(promptDir, { recursive: true });
await fs.writeFile(legacyPrompt, 'legacy apply prompt');
searchableMultiSelectMock.mockResolvedValue(['codex']);
const initCommand = new InitCommand({ force: true });
vi.spyOn(initCommand as any, 'canPromptInteractively').mockReturnValue(true);
await initCommand.execute(testDir);
const toolSelectionOrder = searchableMultiSelectMock.mock.invocationCallOrder[0];
const consoleLogMock = console.log as ReturnType<typeof vi.fn>;
const logsBeforeSelection = consoleLogMock.mock.calls
.filter((_, index) => consoleLogMock.mock.invocationCallOrder[index] < toolSelectionOrder)
.flat()
.join('\n');
expect(logsBeforeSelection).toContain('Deferred global prompts cleanup');
expect(logsBeforeSelection).toContain('will only be removed after matching replacement skills are installed');
expect(logsBeforeSelection).toContain(`codex: ${legacyPrompt}`);
expect(await fileExists(legacyPrompt)).toBe(false);
});
it('should preselect configured tools but not directory-detected tools in extend mode', async () => {
// Simulate existing OpenSpec project (extend mode).
await fs.mkdir(path.join(testDir, 'openspec'), { recursive: true });
// Configured with OpenSpec
const claudeSkillDir = path.join(testDir, '.claude', 'skills', 'openspec-explore');
await fs.mkdir(claudeSkillDir, { recursive: true });
await fs.writeFile(path.join(claudeSkillDir, 'SKILL.md'), 'configured');
// Directory detected only (not configured with OpenSpec)
await fs.mkdir(path.join(testDir, '.github'), { recursive: true });
await fs.writeFile(path.join(testDir, '.github', 'copilot-instructions.md'), '');
searchableMultiSelectMock.mockResolvedValue(['claude']);
const initCommand = new InitCommand({ force: true });
vi.spyOn(initCommand as any, 'canPromptInteractively').mockReturnValue(true);
await initCommand.execute(testDir);
expect(searchableMultiSelectMock).toHaveBeenCalledTimes(1);
const [{ choices }] = searchableMultiSelectMock.mock.calls[0] as [{ choices: Array<{ value: string; preSelected?: boolean; detected?: boolean }> }];
const claude = choices.find((choice) => choice.value === 'claude');
const githubCopilot = choices.find((choice) => choice.value === 'github-copilot');
expect(claude?.preSelected).toBe(true);
expect(githubCopilot?.preSelected).toBe(false);
expect(githubCopilot?.detected).toBe(true);
});
it('should preselect detected tools for first-time interactive setup', async () => {
// First-time init: no openspec/ directory and no configured OpenSpec skills.
await fs.mkdir(path.join(testDir, '.github'), { recursive: true });
await fs.writeFile(path.join(testDir, '.github', 'copilot-instructions.md'), '');
searchableMultiSelectMock.mockResolvedValue(['github-copilot']);
const initCommand = new InitCommand({ force: true });
vi.spyOn(initCommand as any, 'canPromptInteractively').mockReturnValue(true);
await initCommand.execute(testDir);
expect(searchableMultiSelectMock).toHaveBeenCalledTimes(1);
const [{ choices }] = searchableMultiSelectMock.mock.calls[0] as [{ choices: Array<{ value: string; preSelected?: boolean }> }];
const githubCopilot = choices.find((choice) => choice.value === 'github-copilot');
expect(githubCopilot?.preSelected).toBe(true);
});
it('should respect custom profile from global config', async () => {
saveGlobalConfig({
featureFlags: {},
profile: 'custom',
delivery: 'both',
workflows: ['explore', 'new'],
});
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
// Custom profile skills should be created
const exploreSkill = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const newChangeSkill = path.join(testDir, '.claude', 'skills', 'openspec-new-change', 'SKILL.md');
expect(await fileExists(exploreSkill)).toBe(true);
expect(await fileExists(newChangeSkill)).toBe(true);
// Non-selected skills should NOT be created
const proposeSkill = path.join(testDir, '.claude', 'skills', 'openspec-propose', 'SKILL.md');
expect(await fileExists(proposeSkill)).toBe(false);
});
it('should migrate commands-only extend mode to custom profile without injecting propose', async () => {
await fs.mkdir(path.join(testDir, 'openspec'), { recursive: true });
await fs.mkdir(path.join(testDir, '.claude', 'commands', 'opsx'), { recursive: true });
await fs.writeFile(path.join(testDir, '.claude', 'commands', 'opsx', 'explore.md'), '# explore\n');
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const config = getGlobalConfig();
expect(config.profile).toBe('custom');
expect(config.delivery).toBe('commands');
expect(config.workflows).toEqual(['explore']);
const exploreCommand = path.join(testDir, '.claude', 'commands', 'opsx', 'explore.md');
const proposeCommand = path.join(testDir, '.claude', 'commands', 'opsx', 'propose.md');
expect(await fileExists(exploreCommand)).toBe(true);
expect(await fileExists(proposeCommand)).toBe(false);
const exploreSkill = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const proposeSkill = path.join(testDir, '.claude', 'skills', 'openspec-propose', 'SKILL.md');
expect(await fileExists(exploreSkill)).toBe(false);
expect(await fileExists(proposeSkill)).toBe(false);
});
it('should not prompt for confirmation when applying custom profile in interactive init', async () => {
saveGlobalConfig({
featureFlags: {},
profile: 'custom',
delivery: 'both',
workflows: ['explore', 'new'],
});
const initCommand = new InitCommand({ force: true });
vi.spyOn(initCommand as any, 'canPromptInteractively').mockReturnValue(true);
vi.spyOn(initCommand as any, 'getSelectedTools').mockResolvedValue(['claude']);
await initCommand.execute(testDir);
expect(showWelcomeScreenMock).toHaveBeenCalled();
// The welcome screen must be handed the profile's workflows, otherwise it
// advertises commands this profile never installs.
expect(showWelcomeScreenMock).toHaveBeenCalledWith(['explore', 'new']);
expect(confirmMock).not.toHaveBeenCalled();
const exploreSkill = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
const newChangeSkill = path.join(testDir, '.claude', 'skills', 'openspec-new-change', 'SKILL.md');
expect(await fileExists(exploreSkill)).toBe(true);
expect(await fileExists(newChangeSkill)).toBe(true);
const logCalls = (console.log as unknown as { mock: { calls: unknown[][] } }).mock.calls.flat().map(String);
expect(logCalls.some((entry) => entry.includes('Applying custom profile'))).toBe(false);
});
it('should respect delivery=skills setting (no commands)', async () => {
saveGlobalConfig({
featureFlags: {},
profile: 'core',
delivery: 'skills',
});
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
// Skills should exist
const skillFile = path.join(testDir, '.claude', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
// Commands should NOT exist
const cmdFile = path.join(testDir, '.claude', 'commands', 'opsx', 'explore.md');
expect(await fileExists(cmdFile)).toBe(false);
// Skill content should reference skills, not commands that were never generated
const skillContent = await fs.readFile(skillFile, 'utf-8');
expect(skillContent).not.toContain('/opsx:');
expect(skillContent).not.toContain('/opsx-');
expect(skillContent).toContain('/openspec-');
// update-change references several other workflows; a command missing
// from the reference map would leave a raw /opsx: reference behind
const updateSkillContent = await fs.readFile(
path.join(testDir, '.claude', 'skills', 'openspec-update-change', 'SKILL.md'),
'utf-8'
);
expect(updateSkillContent).not.toContain('/opsx:');
expect(updateSkillContent).not.toContain('/opsx-');
expect(updateSkillContent).toContain('/openspec-');
});
it('should use skill references for adapterless tools under default delivery (#1155)', async () => {
// Kimi Code has no command adapter: commands are skipped even when
// delivery is 'both', so generated skills must not reference /opsx:*
const initCommand = new InitCommand({ tools: 'kimi', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.kimi-code', 'skills', 'openspec-apply-change', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
const skillContent = await fs.readFile(skillFile, 'utf-8');
expect(skillContent).not.toContain('/opsx:');
expect(skillContent).not.toContain('/opsx-');
// Kimi Code documents /skill:<name> invocations (docs/supported-tools.md)
expect(skillContent).toContain('/skill:openspec-');
// The getting-started hint must point at the skill, not a missing command
const logCalls = (console.log as unknown as { mock: { calls: unknown[][] } }).mock.calls.flat().map(String);
const startHint = logCalls.find((entry) => entry.includes('Start your first change'));
expect(startHint).toContain('/skill:openspec-propose');
expect(startHint).not.toContain('/opsx:propose');
});
it('should print a configuration correction, not a dead hint, when delivery=commands generates nothing (adapterless tool)', async () => {
saveGlobalConfig({
featureFlags: {},
profile: 'core',
delivery: 'commands',
});
const initCommand = new InitCommand({ tools: 'kimi', force: true });
await initCommand.execute(testDir);
// Kimi has no command adapter and delivery excludes skills: nothing is generated
expect(await fileExists(path.join(testDir, '.kimi-code', 'skills', 'openspec-explore', 'SKILL.md'))).toBe(false);
expect(await fileExists(path.join(testDir, '.kimi-code', 'commands'))).toBe(false);
const logCalls = (console.log as unknown as { mock: { calls: unknown[][] } }).mock.calls.flat().map(String);
// No invocation hint may be shown — neither /opsx:* nor a skill reference exists
expect(logCalls.some((entry) => entry.includes('Start your first change'))).toBe(false);
const correction = logCalls.find((entry) => entry.includes('No skills or commands were generated'));
expect(correction).toBeTruthy();
expect(correction).toContain("openspec config set delivery both");
// Nothing was generated, so there is nothing an IDE restart would pick up
expect(logCalls.some((entry) => entry.includes('Restart your IDE'))).toBe(false);
});
it('should print one usable hint per invocation syntax when adapterless tools disagree', async () => {