-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathdoctor.test.ts
More file actions
1900 lines (1733 loc) · 71.3 KB
/
Copy pathdoctor.test.ts
File metadata and controls
1900 lines (1733 loc) · 71.3 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createHash } from 'crypto';
import { spawnSync } from 'child_process';
import { promises as fs } from 'fs';
import os from 'os';
import path from 'path';
import { doctorCommand } from '../../app/commands/doctor.js';
import {
copyCometSkillsForPlatform,
copyCometRulesForPlatform,
installCometHooksForPlatform,
} from '../../domains/skill/platform-install.js';
import { PLATFORMS } from '../../platform/install/platforms.js';
import {
readCometCurrentSelection,
writeCometCurrentSelection,
} from '../../domains/comet-entry/current-selection.js';
import {
defaultProjectConfig,
writeProjectConfig,
} from '../../domains/comet-native/native-config.js';
import { writeWorkflowProjectConfig } from '../../domains/workflow-contract/project-config-writer.js';
import { planClassicRootMove } from '../../domains/comet-classic/classic-root-move.js';
import {
assertClassicLayoutInitializationSafe,
beginClassicLayoutInitialization,
checkpointClassicLayoutInitialization,
} from '../../domains/comet-classic/classic-layout-initialization.js';
const stateScript = path.resolve('assets', 'skills', 'comet', 'scripts', 'comet-state.mjs');
async function installManagedCometSkills(baseDir: string, platformDir = '.claude'): Promise<void> {
const manifest = JSON.parse(
await fs.readFile(path.resolve('assets', 'manifest.json'), 'utf8'),
) as {
skills: string[];
internalSkills?: string[];
};
const managedPaths = [...new Set([...manifest.skills, ...(manifest.internalSkills ?? [])])];
for (const relPath of managedPaths) {
const target = path.join(baseDir, platformDir, 'skills', ...relPath.split('/'));
await fs.mkdir(path.dirname(target), { recursive: true });
await fs.writeFile(target, `${relPath}\n`);
}
}
interface DoctorPayload {
scope: 'project' | 'global' | 'auto';
status: 'passed' | 'failed';
healthy: boolean;
repaired: string[];
codegraph?: {
status: string;
repairable: boolean;
remediation: string | null;
};
runtime?: {
isSecondaryWorktree: boolean;
currentProjectInstall: string;
primaryProjectInstall: string;
globalFallbackReady: boolean;
effectiveScope: string;
remediation: string | null;
};
results: Array<{ check: string; status: string; message: string }>;
}
async function collectDoctorPayload(
targetPath: string,
scope: 'project' | 'global' | 'auto' = 'project',
homeDir = targetPath,
): Promise<DoctorPayload> {
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
try {
await doctorCommand(targetPath, { json: true, scope, homeDir });
const output = log.mock.calls.map((call) => call.join(' ')).join('\n');
return JSON.parse(output) as DoctorPayload;
} finally {
log.mockRestore();
}
}
async function collectDoctorResults(
targetPath: string,
scope: 'project' | 'global' | 'auto' = 'project',
): Promise<DoctorPayload['results']> {
return (await collectDoctorPayload(targetPath, scope)).results;
}
function sha256(value: string): string {
return createHash('sha256').update(value).digest('hex');
}
async function writeReadyClassicRootMove(projectRoot: string): Promise<void> {
const transactionId = '22222222-2222-4222-8222-222222222222';
const config = defaultProjectConfig('docs', 'en');
config.default_workflow = 'classic';
config.workflows = ['classic'];
config.classic = {
artifact_layout: 'legacy',
language: 'en',
context_compression: 'off',
review_mode: 'standard',
auto_transition: true,
};
await writeProjectConfig(projectRoot, config);
const source = path.join(projectRoot, 'openspec');
await fs.mkdir(path.join(source, 'changes', 'archive'), { recursive: true });
await fs.mkdir(path.join(source, 'specs'), { recursive: true });
const directories = ['changes', 'changes/archive', 'specs'];
const manifestSource = { directories, files: [], totalBytes: 0 };
const manifest = { ...manifestSource, hash: sha256(JSON.stringify(manifestSource)) };
const plan = await planClassicRootMove(projectRoot);
const legacyPlanId = sha256(
JSON.stringify({
source: 'openspec',
target: 'docs/openspec',
staging: '.comet/transactions/classic-root-move/<transaction-id>/openspec',
targetInitialState: 'missing',
fileCount: manifest.files.length,
directoryCount: manifest.directories.length,
totalBytes: manifest.totalBytes,
manifestHash: manifest.hash,
configPath: plan.configPath,
originalConfigHash: plan.originalConfigHash,
expectedConfigHash: plan.expectedConfigHash,
}),
);
const staging = path.join(
projectRoot,
'.comet',
'transactions',
'classic-root-move',
transactionId,
'openspec',
);
await fs.mkdir(path.dirname(staging), { recursive: true });
await fs.cp(source, staging, { recursive: true });
await fs.writeFile(
path.join(projectRoot, '.comet', 'classic-root-move.json'),
`${JSON.stringify(
{
schema: 'comet.classic-root-move.v1',
id: transactionId,
stage: 'ready',
source: 'openspec',
target: 'docs/openspec',
staging: `.comet/transactions/classic-root-move/${transactionId}/openspec`,
configPath: plan.configPath,
originalConfigHash: plan.originalConfigHash,
expectedConfigHash: plan.expectedConfigHash,
planId: legacyPlanId,
targetInitialState: 'missing',
manifest,
},
null,
2,
)}\n`,
);
}
async function writeHealthyDocsClassicProject(projectRoot: string): Promise<void> {
const config = defaultProjectConfig('docs', 'en');
config.default_workflow = 'classic';
config.workflows = ['classic'];
config.classic = {
artifact_layout: 'docs',
language: 'en',
context_compression: 'off',
review_mode: 'standard',
auto_transition: true,
};
await writeProjectConfig(projectRoot, config);
await Promise.all([
fs.mkdir(path.join(projectRoot, 'docs', 'openspec', 'changes', 'archive'), {
recursive: true,
}),
fs.mkdir(path.join(projectRoot, 'docs', 'openspec', 'specs'), { recursive: true }),
fs.mkdir(path.join(projectRoot, 'docs', 'superpowers', 'specs'), { recursive: true }),
fs.mkdir(path.join(projectRoot, 'docs', 'superpowers', 'plans'), { recursive: true }),
fs.mkdir(path.join(projectRoot, 'docs', 'superpowers', 'reports'), { recursive: true }),
]);
await fs.writeFile(
path.join(projectRoot, 'docs', 'openspec', 'config.yaml'),
'schema: spec-driven\n',
'utf8',
);
}
async function state(cwd: string, ...args: string[]) {
const configPath = path.join(cwd, '.comet', 'config.yaml');
try {
await fs.access(configPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
await fs.mkdir(path.join(cwd, '.comet'), { recursive: true });
await fs.writeFile(
configPath,
[
'schema: comet.project.v1',
'default_workflow: classic',
'workflows: [classic]',
'classic:',
' artifact_layout: legacy',
' language: en',
'',
].join('\n'),
'utf8',
);
await fs.mkdir(path.join(cwd, 'openspec'), { recursive: true });
}
const env: NodeJS.ProcessEnv = { ...process.env };
if (args[0] === 'set' && args[2] === 'phase') {
// Direct phase writes are normally blocked; the force hatch is the
// documented way for tooling/tests to seed a change into a specific phase.
env.COMET_FORCE_PHASE = '1';
}
return spawnSync(process.execPath, [stateScript, ...args], {
cwd,
encoding: 'utf8',
env,
});
}
describe('doctor command', () => {
let tmpDir: string;
beforeEach(async () => {
tmpDir = path.join(
os.tmpdir(),
`comet-doctor-${Date.now()}-${Math.random().toString(36).slice(2)}`,
);
await fs.mkdir(tmpDir, { recursive: true });
});
it('reports a secondary worktree using a complete global fallback without calling it broken', async () => {
const secondary = path.join(
os.tmpdir(),
`comet-doctor-secondary-${Date.now()}-${Math.random().toString(36).slice(2)}`,
);
const fakeHome = path.join(tmpDir, 'fake-home');
const git = (...args: string[]) =>
spawnSync('git', ['-C', tmpDir, ...args], { encoding: 'utf8', timeout: 20_000 });
try {
expect(git('init', '-b', 'master').status).toBe(0);
expect(git('config', 'user.email', 'doctor@example.com').status).toBe(0);
expect(git('config', 'user.name', 'Doctor Test').status).toBe(0);
await fs.writeFile(path.join(tmpDir, 'README.md'), '# test\n');
expect(git('add', 'README.md').status).toBe(0);
expect(git('commit', '-m', 'test').status).toBe(0);
await installManagedCometSkills(tmpDir);
await installManagedCometSkills(fakeHome);
expect(git('worktree', 'add', secondary, '-b', 'feature/doctor-secondary').status).toBe(0);
const payload = await collectDoctorPayload(secondary, 'project', fakeHome);
expect(payload.runtime).toMatchObject({
isSecondaryWorktree: true,
currentProjectInstall: 'missing',
primaryProjectInstall: 'ready',
globalFallbackReady: true,
effectiveScope: 'global',
remediation: null,
});
expect(payload.results.find((result) => result.check === 'Worktree runtime')).toMatchObject({
status: 'pass',
message: expect.stringContaining('global fallback'),
});
expect(payload.results.find((result) => result.check === 'Comet skills')).toMatchObject({
status: 'pass',
message: expect.stringContaining('secondary worktree'),
});
expect(JSON.stringify(payload.results)).not.toContain(
'not installed in project scope — run: comet init --scope project',
);
await fs.rm(fakeHome, { recursive: true, force: true });
const unavailable = await collectDoctorPayload(secondary, 'project', fakeHome);
expect(unavailable.runtime).toMatchObject({
isSecondaryWorktree: true,
primaryProjectInstall: 'ready',
globalFallbackReady: false,
effectiveScope: 'none',
remediation: expect.stringContaining('this worktree'),
});
expect(
unavailable.results.find((result) => result.check === 'Worktree runtime'),
).toMatchObject({
status: 'fail',
message: expect.stringContaining('not executed here'),
});
expect(unavailable).toMatchObject({ status: 'failed', healthy: false });
const manifest = JSON.parse(
await fs.readFile(path.resolve('assets', 'manifest.json'), 'utf8'),
) as { skills: string[] };
await fs.rm(path.join(tmpDir, '.claude', 'skills', ...manifest.skills[0]!.split('/')));
const stalePrimary = await collectDoctorPayload(secondary, 'project', fakeHome);
expect(stalePrimary.runtime).toMatchObject({
currentProjectInstall: 'missing',
primaryProjectInstall: 'partial',
effectiveScope: 'none',
});
await installManagedCometSkills(secondary);
const projectReady = await collectDoctorPayload(secondary, 'project', fakeHome);
expect(projectReady.runtime).toMatchObject({
currentProjectInstall: 'ready',
primaryProjectInstall: 'partial',
effectiveScope: 'project',
remediation: null,
});
} finally {
git('worktree', 'remove', '--force', secondary);
await fs.rm(secondary, { recursive: true, force: true });
}
});
it('projects the primary worktree Router into a secondary worktree during project repair', async () => {
const secondary = path.join(
os.tmpdir(),
`comet-doctor-hook-secondary-${Date.now()}-${Math.random().toString(36).slice(2)}`,
);
const fakeHome = path.join(tmpDir, 'fake-home');
const git = (...args: string[]) =>
spawnSync('git', ['-C', tmpDir, ...args], { encoding: 'utf8', timeout: 20_000 });
try {
expect(git('init', '-b', 'master').status).toBe(0);
expect(git('config', 'user.email', 'doctor@example.com').status).toBe(0);
expect(git('config', 'user.name', 'Doctor Test').status).toBe(0);
await fs.writeFile(path.join(tmpDir, 'README.md'), '# test\n');
await writeProjectConfig(tmpDir, defaultProjectConfig('docs'));
expect(git('add', 'README.md', '.comet/config.yaml').status).toBe(0);
expect(git('commit', '-m', 'test').status).toBe(0);
expect(git('worktree', 'add', secondary, '-b', 'feature/doctor-hook-secondary').status).toBe(
0,
);
const primaryRouter = path.join(
tmpDir,
'.agents',
'skills',
'comet',
'scripts',
'comet-hook-router.mjs',
);
await fs.mkdir(path.dirname(primaryRouter), { recursive: true });
await fs.mkdir(path.join(tmpDir, '.codex'), { recursive: true });
await fs.writeFile(primaryRouter, '// primary Router\n', 'utf8');
await fs.writeFile(
path.join(tmpDir, '.comet', 'current-change.json'),
'{"schema":"comet.selection.v2","workflow":"native","change":"primary"}',
'utf8',
);
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
let payload: DoctorPayload;
try {
await doctorCommand(secondary, {
json: true,
repair: true,
scope: 'project',
homeDir: fakeHome,
});
payload = JSON.parse(log.mock.calls.map((call) => call.join(' ')).join('\n'));
} finally {
log.mockRestore();
}
const hooks = await fs.readFile(path.join(secondary, '.codex', 'hooks.json'), 'utf8');
expect(hooks.replaceAll('\\', '/')).toContain(
`${secondary.replaceAll('\\', '/')}/.agents/skills/comet/scripts/comet-hook-router.mjs`,
);
await expect(
fs.access(
path.join(secondary, '.agents', 'skills', 'comet', 'scripts', 'comet-hook-router.mjs'),
),
).resolves.toBeUndefined();
await expect(
fs.access(path.join(secondary, '.comet', 'current-change.json')),
).rejects.toMatchObject({ code: 'ENOENT' });
expect(payload!.results).toContainEqual(
expect.objectContaining({ check: 'hooks: Codex (project)', status: 'pass' }),
);
} finally {
git('worktree', 'remove', '--force', secondary);
await fs.rm(secondary, { recursive: true, force: true });
}
});
it('falls back to a global Router source when the primary worktree has none', async () => {
const secondary = path.join(
os.tmpdir(),
`comet-doctor-global-hook-secondary-${Date.now()}-${Math.random().toString(36).slice(2)}`,
);
const fakeHome = path.join(tmpDir, 'global-hook-home');
const git = (...args: string[]) =>
spawnSync('git', ['-C', tmpDir, ...args], { encoding: 'utf8', timeout: 20_000 });
try {
expect(git('init', '-b', 'master').status).toBe(0);
expect(git('config', 'user.email', 'doctor@example.com').status).toBe(0);
expect(git('config', 'user.name', 'Doctor Test').status).toBe(0);
await fs.writeFile(path.join(tmpDir, 'README.md'), '# test\n');
await writeProjectConfig(tmpDir, defaultProjectConfig('docs'));
expect(git('add', 'README.md', '.comet/config.yaml').status).toBe(0);
expect(git('commit', '-m', 'test').status).toBe(0);
expect(git('worktree', 'add', secondary, '-b', 'feature/doctor-global-hook').status).toBe(0);
const globalRouter = path.join(
fakeHome,
'.agents',
'skills',
'comet',
'scripts',
'comet-hook-router.mjs',
);
await fs.mkdir(path.dirname(globalRouter), { recursive: true });
await fs.mkdir(path.join(fakeHome, '.codex'), { recursive: true });
await fs.writeFile(globalRouter, '// global Router\n', 'utf8');
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
try {
await doctorCommand(secondary, {
json: true,
repair: true,
scope: 'project',
homeDir: fakeHome,
});
} finally {
log.mockRestore();
}
const hooks = await fs.readFile(path.join(secondary, '.codex', 'hooks.json'), 'utf8');
expect(hooks.replaceAll('\\', '/')).toContain(
`${secondary.replaceAll('\\', '/')}/.agents/skills/comet/scripts/comet-hook-router.mjs`,
);
} finally {
git('worktree', 'remove', '--force', secondary);
await fs.rm(secondary, { recursive: true, force: true });
}
});
it('repairs a missing CodeGraph index only with explicit --yes authorization', async () => {
const binDir = path.join(tmpDir, 'bin');
const logFile = path.join(tmpDir, 'codegraph.log');
await fs.mkdir(binDir, { recursive: true });
const executable =
process.platform === 'win32'
? path.join(binDir, 'codegraph.cmd')
: path.join(binDir, 'codegraph');
const script =
process.platform === 'win32'
? [
'@echo off',
`echo %1>>"${logFile}"`,
'if "%1"=="init" (',
' if not exist ".codegraph" mkdir ".codegraph"',
' type nul > ".codegraph\\codegraph.db"',
')',
'if "%1"=="status" echo {"initialized":true,"pendingChanges":{"added":0,"modified":0,"removed":0},"index":{"state":"complete","reindexRecommended":false,"pendingRefs":0}}',
'',
].join('\r\n')
: [
'#!/bin/sh',
`printf '%s\\n' "$1" >> '${logFile.replaceAll("'", "'\\''")}'`,
'if [ "$1" = "init" ]; then mkdir -p .codegraph; : > .codegraph/codegraph.db; fi',
'if [ "$1" = "status" ]; then printf \'%s\\n\' \'{"initialized":true,"pendingChanges":{"added":0,"modified":0,"removed":0},"index":{"state":"complete","reindexRecommended":false,"pendingRefs":0}}\'; fi',
'',
].join('\n');
await fs.writeFile(executable, script);
if (process.platform !== 'win32') await fs.chmod(executable, 0o755);
const previousPath = process.env.PATH;
process.env.PATH = `${binDir}${path.delimiter}${previousPath ?? ''}`;
try {
const config = defaultProjectConfig('openspec');
config.default_workflow = 'classic';
config.workflows = ['classic'];
config.classic = {
artifact_layout: 'docs',
language: 'en',
context_compression: 'off',
review_mode: 'standard',
auto_transition: true,
};
await writeProjectConfig(tmpDir, config);
const before = await collectDoctorPayload(tmpDir);
expect(before.codegraph).toMatchObject({
status: 'project_not_initialized',
repairable: true,
});
await expect(fs.access(logFile)).rejects.toMatchObject({ code: 'ENOENT' });
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
let repaired: DoctorPayload;
try {
await doctorCommand(tmpDir, {
json: true,
repair: true,
yes: true,
scope: 'project',
homeDir: tmpDir,
});
repaired = JSON.parse(
log.mock.calls.map((call) => call.join(' ')).join('\n'),
) as DoctorPayload;
} finally {
log.mockRestore();
}
expect(repaired!).toMatchObject({
repaired: expect.arrayContaining(['CodeGraph project index']),
codegraph: { status: 'index_ready', repairable: false },
});
await expect(fs.readFile(logFile, 'utf8')).resolves.toContain('init');
await expect(
fs.access(path.join(tmpDir, '.codegraph', 'codegraph.db')),
).resolves.toBeUndefined();
} finally {
process.env.PATH = previousPath;
}
});
it('reports allowed Classic recovery strategies and never chooses one implicitly', async () => {
await fs.mkdir(path.join(tmpDir, '.git'));
await writeReadyClassicRootMove(tmpDir);
const before = await collectDoctorPayload(tmpDir);
expect(
before.results.find((result) => result.check === 'Classic artifact layout'),
).toMatchObject({
status: 'fail',
message: expect.stringContaining('allowed strategies: continue, rollback'),
});
expect(
before.results.find((result) => result.check === 'Classic artifact layout')?.message,
).toContain(
'staging .comet/transactions/classic-root-move/22222222-2222-4222-8222-222222222222/openspec',
);
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
try {
await doctorCommand(tmpDir, {
json: true,
repair: true,
scope: 'project',
homeDir: tmpDir,
});
} finally {
log.mockRestore();
}
await expect(
fs.stat(path.join(tmpDir, '.comet', 'classic-root-move.json')),
).resolves.toBeDefined();
const repairLog = vi.spyOn(console, 'log').mockImplementation(() => undefined);
try {
await doctorCommand(tmpDir, {
json: true,
repair: true,
strategy: 'rollback',
scope: 'project',
homeDir: tmpDir,
});
} finally {
repairLog.mockRestore();
}
await expect(
fs.stat(path.join(tmpDir, '.comet', 'classic-root-move.json')),
).rejects.toMatchObject({ code: 'ENOENT' });
});
it('reports and repairs a project config write interrupted after quarantine', async () => {
await writeProjectConfig(tmpDir, defaultProjectConfig('before-crash'));
const configPath = path.join(tmpDir, '.comet', 'config.yaml');
const previous = await fs.readFile(configPath, 'utf8');
const worker = path.resolve('test/helpers/project-config-crash-worker.mjs');
const crashed = spawnSync(process.execPath, [worker, tmpDir], {
cwd: path.resolve('.'),
encoding: 'utf8',
timeout: 30_000,
});
expect(crashed.status, crashed.stderr).toBe(73);
const before = await collectDoctorPayload(tmpDir);
expect(
before.results.find((result) => result.check === 'project config write transaction'),
).toMatchObject({
status: 'warn',
message: expect.stringContaining('config-quarantined'),
});
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
let repaired: DoctorPayload;
try {
await doctorCommand(tmpDir, {
json: true,
repair: true,
scope: 'project',
homeDir: tmpDir,
});
repaired = JSON.parse(log.mock.calls.map((call) => call.join(' ')).join('\n'));
} finally {
log.mockRestore();
}
expect(repaired!.repaired).toContain('project config write transaction');
await expect(fs.readFile(configPath, 'utf8')).resolves.toBe(previous);
const after = await collectDoctorPayload(tmpDir);
expect(
after.results.find((result) => result.check === 'project config write transaction'),
).toBeUndefined();
});
it('does not repair a project config transaction while its writer is still active', async () => {
await writeProjectConfig(tmpDir, defaultProjectConfig('before-live-write'));
let enterPublish!: () => void;
const publishEntered = new Promise<void>((resolve) => {
enterPublish = resolve;
});
let releasePublish!: () => void;
const publishRelease = new Promise<void>((resolve) => {
releasePublish = resolve;
});
const writer = writeWorkflowProjectConfig(tmpDir, defaultProjectConfig('after-live-write'), {
beforePublish: async () => {
enterPublish();
await publishRelease;
},
});
await publishEntered;
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
try {
await expect(
doctorCommand(tmpDir, {
json: true,
repair: true,
scope: 'project',
homeDir: tmpDir,
}),
).rejects.toThrow(/transaction .* still active/iu);
} finally {
log.mockRestore();
releasePublish();
}
await writer;
await expect(
fs.readFile(path.join(tmpDir, '.comet', 'config.yaml'), 'utf8'),
).resolves.toContain('artifact_root: after-live-write');
expect(
(await fs.readdir(path.join(tmpDir, '.comet'))).filter(
(entry) =>
entry.includes('config-write-transaction') ||
entry.endsWith('.next') ||
entry.endsWith('.quarantine'),
),
).toEqual([]);
});
it('reports an owned Classic initialization and atomically quarantines it on rollback', async () => {
const initialization = await assertClassicLayoutInitializationSafe(tmpDir, 'docs');
const owned = await beginClassicLayoutInitialization(tmpDir, initialization);
await fs.mkdir(path.join(owned.openSpecRoot, 'changes', 'archive'), {
recursive: true,
});
await fs.mkdir(path.join(owned.openSpecRoot, 'specs'), { recursive: true });
await fs.writeFile(path.join(owned.openSpecRoot, 'config.yaml'), 'schema: spec-driven\n');
await checkpointClassicLayoutInitialization(tmpDir, owned.initializationPermit);
const before = await collectDoctorPayload(tmpDir);
expect(
before.results.find((result) => result.check === 'Classic initialization'),
).toMatchObject({
status: 'warn',
message: expect.stringMatching(/initializing.*continue, rollback/iu),
});
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
let repaired: DoctorPayload;
try {
await doctorCommand(tmpDir, {
json: true,
repair: true,
strategy: 'rollback',
scope: 'project',
homeDir: tmpDir,
});
repaired = JSON.parse(log.mock.calls.map((call) => call.join(' ')).join('\n'));
} finally {
log.mockRestore();
}
expect(repaired!.repaired).toContain('Classic initialization');
await expect(fs.access(owned.openSpecRoot)).rejects.toMatchObject({ code: 'ENOENT' });
const journal = JSON.parse(
await fs.readFile(path.join(tmpDir, '.comet', 'classic-init-ownership.json'), 'utf8'),
) as { stage: string; quarantine: string };
expect(journal.stage).toBe('quarantined');
await expect(
fs.readFile(path.join(tmpDir, ...journal.quarantine.split('/'), 'config.yaml'), 'utf8'),
).resolves.toBe('schema: spec-driven\n');
});
it('reports an invalid project config without guessing Classic working directories', async () => {
await fs.mkdir(path.join(tmpDir, '.comet'), { recursive: true });
await fs.writeFile(path.join(tmpDir, '.comet', 'config.yaml'), 'schema: [broken\n');
await fs.mkdir(path.join(tmpDir, 'openspec', 'changes', 'must-not-be-scanned'), {
recursive: true,
});
const results = await collectDoctorResults(tmpDir);
expect(results.find((result) => result.check === 'Classic artifact layout')).toMatchObject({
status: 'fail',
message: expect.stringContaining('Invalid .comet/config.yaml'),
});
expect(results.find((result) => result.check === 'working directories')).toMatchObject({
status: 'fail',
message: expect.stringContaining('Invalid .comet/config.yaml'),
});
});
it('reports both Classic root states and a repair command when the configured root is missing', async () => {
await fs.mkdir(path.join(tmpDir, '.comet'), { recursive: true });
await fs.writeFile(
path.join(tmpDir, '.comet', 'config.yaml'),
[
'schema: comet.project.v1',
'default_workflow: classic',
'workflows: [classic]',
'classic:',
' artifact_layout: docs',
'',
].join('\n'),
'utf8',
);
await fs.mkdir(path.join(tmpDir, 'openspec'), { recursive: true });
const results = await collectDoctorResults(tmpDir);
expect(results.find((result) => result.check === 'Classic artifact layout')).toMatchObject({
status: 'fail',
message: expect.stringMatching(
/configured docs\/openspec\/ missing; alternate openspec\/ present.*comet classic root show/iu,
),
});
});
it('reports an uninitialized or corrupt configured OpenSpec root as unhealthy', async () => {
await fs.mkdir(path.join(tmpDir, '.comet'), { recursive: true });
await fs.writeFile(
path.join(tmpDir, '.comet', 'config.yaml'),
[
'schema: comet.project.v1',
'default_workflow: classic',
'workflows: [classic]',
'classic:',
' artifact_layout: docs',
'',
].join('\n'),
'utf8',
);
await fs.mkdir(path.join(tmpDir, 'docs', 'openspec', 'changes', 'archive'), {
recursive: true,
});
await fs.mkdir(path.join(tmpDir, 'docs', 'openspec', 'specs'), { recursive: true });
await fs.mkdir(path.join(tmpDir, 'docs', 'superpowers', 'specs'), { recursive: true });
await fs.mkdir(path.join(tmpDir, 'docs', 'superpowers', 'plans'), { recursive: true });
await fs.mkdir(path.join(tmpDir, 'docs', 'superpowers', 'reports'), { recursive: true });
let results = await collectDoctorResults(tmpDir);
expect(results.find((result) => result.check === 'Classic OpenSpec root')).toMatchObject({
status: 'fail',
message: expect.stringContaining('config.yaml is missing'),
});
await fs.writeFile(
path.join(tmpDir, 'docs', 'openspec', 'config.yaml'),
'schema: [broken\n',
'utf8',
);
results = await collectDoctorResults(tmpDir);
expect(results.find((result) => result.check === 'Classic OpenSpec root')).toMatchObject({
status: 'fail',
message: expect.stringContaining('invalid YAML'),
});
});
it('does not confuse normal docs artifacts or project-level OpenSpec tools with coupled assets', async () => {
await writeHealthyDocsClassicProject(tmpDir);
await fs.mkdir(path.join(tmpDir, 'docs', 'openspec', 'specs', 'openspec-notes'), {
recursive: true,
});
await fs.mkdir(path.join(tmpDir, '.claude', 'skills', 'openspec-propose'), {
recursive: true,
});
await fs.writeFile(
path.join(tmpDir, '.claude', 'skills', 'openspec-propose', 'SKILL.md'),
'project-level OpenSpec skill\n',
'utf8',
);
const results = await collectDoctorResults(tmpDir);
expect(results.find((result) => result.check === 'Classic platform tool assets')).toMatchObject(
{
status: 'pass',
message: expect.stringContaining('no OpenSpec platform tool assets under docs/'),
},
);
});
it('does not run the docs coupling check for a legacy Classic layout', async () => {
const config = defaultProjectConfig('docs', 'en');
config.default_workflow = 'classic';
config.workflows = ['classic'];
config.classic = {
artifact_layout: 'legacy',
language: 'en',
context_compression: 'off',
review_mode: 'standard',
auto_transition: true,
};
await writeProjectConfig(tmpDir, config);
await fs.mkdir(path.join(tmpDir, 'openspec', 'changes', 'archive'), { recursive: true });
await fs.mkdir(path.join(tmpDir, 'openspec', 'specs'), { recursive: true });
await fs.writeFile(path.join(tmpDir, 'openspec', 'config.yaml'), 'schema: spec-driven\n');
const nestedSkill = path.join(
tmpDir,
'docs',
'.claude',
'skills',
'openspec-propose',
'SKILL.md',
);
await fs.mkdir(path.dirname(nestedSkill), { recursive: true });
await fs.writeFile(nestedSkill, 'legacy layout leaves docs coupling out of scope\n');
const results = await collectDoctorResults(tmpDir);
expect(
results.find((result) => result.check === 'Classic platform tool assets'),
).toBeUndefined();
});
it('reports OpenSpec skills and command files nested under docs for every registered platform root', async () => {
await writeHealthyDocsClassicProject(tmpDir);
const platformRoots = [
...new Set(
PLATFORMS.flatMap((platform) => [platform.skillsDir, ...(platform.legacySkillsDirs ?? [])]),
),
];
for (const platformRoot of platformRoots) {
const skillDir = path.join(tmpDir, 'docs', platformRoot, 'skills', 'openspec-propose');
await fs.mkdir(skillDir, { recursive: true });
await fs.writeFile(path.join(skillDir, 'SKILL.md'), `${platformRoot} misplaced skill\n`);
}
await fs.mkdir(path.join(tmpDir, 'docs', '.cursor', 'commands'), { recursive: true });
await fs.writeFile(
path.join(tmpDir, 'docs', '.cursor', 'commands', 'opsx-propose.md'),
'misplaced Cursor command\n',
);
await fs.mkdir(path.join(tmpDir, 'docs', '.codex', 'prompts'), { recursive: true });
await fs.writeFile(
path.join(tmpDir, 'docs', '.codex', 'prompts', 'opsx-propose.md'),
'misplaced Codex command\n',
);
await fs.mkdir(path.join(tmpDir, 'docs', '.clinerules', 'workflows'), {
recursive: true,
});
await fs.writeFile(
path.join(tmpDir, 'docs', '.clinerules', 'workflows', 'opsx-propose.md'),
'misplaced Cline command\n',
);
await fs.mkdir(path.join(tmpDir, 'docs', '.agent', 'workflows'), {
recursive: true,
});
await fs.writeFile(
path.join(tmpDir, 'docs', '.agent', 'workflows', 'opsx-propose.md'),
'misplaced Antigravity command\n',
);
const results = await collectDoctorResults(tmpDir);
const platformAssets = results.find(
(result) => result.check === 'Classic platform tool assets',
);
expect(platformAssets).toMatchObject({
status: 'fail',
message: expect.stringMatching(
/platform directories at the project root.*comet update.*Doctor did not move/iu,
),
});
for (const platformRoot of platformRoots) {
expect(platformAssets?.message).toContain(
path.posix.join('docs', platformRoot, 'skills', 'openspec-propose'),
);
}
expect(platformAssets?.message).toContain('docs/.cursor/commands/opsx-propose.md');
expect(platformAssets?.message).toContain('docs/.codex/prompts/opsx-propose.md');
expect(platformAssets?.message).toContain('docs/.clinerules/workflows/opsx-propose.md');
expect(platformAssets?.message).toContain('docs/.agent/workflows/opsx-propose.md');
const repairLog = vi.spyOn(console, 'log').mockImplementation(() => undefined);
try {
await doctorCommand(tmpDir, {
json: true,
repair: true,
scope: 'project',
homeDir: tmpDir,
});
} finally {
repairLog.mockRestore();
}
await expect(
fs.readFile(
path.join(tmpDir, 'docs', '.claude', 'skills', 'openspec-propose', 'SKILL.md'),
'utf8',
),
).resolves.toBe('.claude misplaced skill\n');
});
it('fails closed without following a linked platform directory under docs', async () => {
await writeHealthyDocsClassicProject(tmpDir);
const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'comet-doctor-tools-link-'));
const outsideMarker = path.join(outsideRoot, 'skills', 'openspec-propose', 'SKILL.md');
try {
await fs.mkdir(path.dirname(outsideMarker), { recursive: true });
await fs.writeFile(outsideMarker, 'outside-platform-marker\n', 'utf8');
try {
await fs.symlink(
outsideRoot,
path.join(tmpDir, 'docs', '.claude'),
process.platform === 'win32' ? 'junction' : 'dir',
);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'EPERM') return;
throw error;
}
const results = await collectDoctorResults(tmpDir);
const platformAssets = results.find(
(result) => result.check === 'Classic platform tool assets',
);
expect(platformAssets).toMatchObject({
status: 'fail',
message: expect.stringMatching(/symbolic link or junction.*comet update/iu),
});
expect(JSON.stringify(results)).not.toContain('outside-platform-marker');
await expect(fs.readFile(outsideMarker, 'utf8')).resolves.toBe('outside-platform-marker\n');
} finally {
await fs.rm(outsideRoot, { recursive: true, force: true });
}
});
it.each(['configured', 'alternate'] as const)(
'fails the Classic layout check when the %s root is a directory link',
async (kind) => {
const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'comet-doctor-root-link-'));
try {
await fs.mkdir(path.join(outsideRoot, 'changes', 'external-marker'), {
recursive: true,
});
await fs.writeFile(
path.join(outsideRoot, 'changes', 'external-marker', '.comet.yaml'),
'phase: open\n',
'utf8',
);
await fs.mkdir(path.join(tmpDir, '.comet'), { recursive: true });
await fs.writeFile(
path.join(tmpDir, '.comet', 'config.yaml'),
[
'schema: comet.project.v1',
'default_workflow: classic',
'workflows: [classic]',
'classic:',
' artifact_layout: docs',
'',
].join('\n'),
'utf8',
);
if (kind === 'configured') {
await fs.mkdir(path.join(tmpDir, 'docs'), { recursive: true });
try {
await fs.symlink(
outsideRoot,
path.join(tmpDir, 'docs', 'openspec'),
process.platform === 'win32' ? 'junction' : 'dir',
);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'EPERM') return;
throw error;
}
} else {
await fs.mkdir(path.join(tmpDir, 'docs', 'openspec'), { recursive: true });
try {
await fs.symlink(
outsideRoot,
path.join(tmpDir, 'openspec'),
process.platform === 'win32' ? 'junction' : 'dir',
);