-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathdoctor.ts
More file actions
1631 lines (1544 loc) · 55.4 KB
/
Copy pathdoctor.ts
File metadata and controls
1631 lines (1544 loc) · 55.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 path from 'path';
import os from 'os';
import { promises as fs } from 'fs';
import type { BigIntStats, Dirent } from 'fs';
import { copyFile, fileExists, readDir } from '../../platform/fs/file-system.js';
import { sameFileObject, type FileObjectIdentity } from '../../platform/fs/file-identity.js';
import {
getOpenSpecVersion,
isCommandAvailable,
isOpenSpecVersionCompatible,
MINIMUM_OPENSPEC_VERSION,
} from '../../domains/integrations/openspec.js';
import {
inspectCodegraphIndex,
repairCodegraphIndex,
resolveCodegraphCommand,
type CodegraphIndexDiagnostic,
} from '../../domains/integrations/codegraph.js';
import {
copyCometRulesForPlatform,
readManifest,
getAssetsDir,
getManagedSkillPaths,
getManagedSkillPathsForSelection,
} from '../../domains/skill/platform-install.js';
import {
reconcileCometHooksForPlatform,
reconcileProjectCometHooksForPlatform,
} from '../../domains/skill/hook-lifecycle.js';
import {
getPlatformRuleDestinations,
getLegacyPlatformRuleDestinations,
inspectCometHooksForPlatform,
} from '../../domains/skill/platform-inspect.js';
import {
PLATFORMS,
getPlatformSkillsDir,
getPlatformSkillsDirs,
type Platform,
} from '../../platform/install/platforms.js';
import { resolveCanonicalSkillRootOwners } from '../../platform/install/skill-root-owner.js';
import type { InstallScope } from '../../platform/install/types.js';
import { inspectClassicChangeReadOnly } from '../../domains/comet-classic/classic-diagnostics.js';
import {
inspectClassicLayout,
resolveClassicLayout,
} from '../../domains/comet-classic/classic-layout.js';
import { assertClassicOpenSpecRootHealthy } from '../../domains/comet-classic/classic-openspec-root.js';
import {
inspectClassicRootMove,
repairClassicRootMove,
} from '../../domains/comet-classic/classic-root-move.js';
import {
inspectClassicLayoutInitialization,
repairClassicLayoutInitialization,
} from '../../domains/comet-classic/classic-layout-initialization.js';
import { getCurrentVersion } from '../../platform/version/version.js';
import { repairCometCurrentSelection } from '../../domains/comet-entry/current-selection-repair.js';
import { readWorkflowProjectConfig } from '../../domains/workflow-contract/project-config-reader.js';
import { inspectProtectedProjectPath } from '../../domains/workflow-contract/protected-project-path.js';
import {
inspectWorkflowProjectConfigTransaction,
repairWorkflowProjectConfigTransaction,
} from '../../domains/workflow-contract/project-config-transaction.js';
import type { WorkflowProjectConfig } from '../../domains/workflow-contract/types.js';
import { resolveHookWorkflowOwner } from '../../domains/comet-entry/hook-router.js';
import type { InitWorkflowSelection } from '../../domains/comet-entry/types.js';
import { inspectGitWorktree } from '../../platform/paths/git-worktree.js';
import { projectCometHooksFromInstalledScope } from '../../domains/skill/project-hook-projection.js';
interface CheckResult {
check: string;
status: 'pass' | 'warn' | 'fail';
message: string;
}
type DoctorScope = InstallScope | 'auto';
interface DoctorContext {
homeDir: string;
}
type ManagedInstallAvailability = 'ready' | 'partial' | 'missing';
interface DoctorRuntimeDiagnostic {
isSecondaryWorktree: boolean;
currentWorktreeRoot: string | null;
primaryWorktreeRoot: string | null;
currentProjectInstall: ManagedInstallAvailability;
primaryProjectInstall: ManagedInstallAvailability;
globalFallbackReady: boolean;
effectiveScope: 'project' | 'global' | 'none';
remediation: string | null;
}
interface DoctorReport {
results: CheckResult[];
runtime: DoctorRuntimeDiagnostic;
codegraph: CodegraphIndexDiagnostic | null;
}
const SUPERPOWERS_SENTINELS = [
'using-superpowers/SKILL.md',
'test-driven-development/SKILL.md',
'writing-plans/SKILL.md',
] as const;
const HOOK_ROUTER_RUNTIME = 'comet/scripts/comet-hook-router.mjs';
const CLASSIC_PLATFORM_TOOL_SCAN_MAX_ENTRIES = 4096;
const CLASSIC_PLATFORM_TOOL_SCAN_MAX_DEPTH = 8;
const CLASSIC_PLATFORM_TOOL_SCAN_MAX_FINDINGS = 128;
const CLASSIC_PLATFORM_TOOL_ROOTS = [
...new Set([
...PLATFORMS.flatMap((platform) => getPlatformSkillsDirs(platform, 'project')),
// OpenSpec commands for these platforms live outside their Skill roots.
'.agent',
'.clinerules',
]),
].sort();
const OPEN_SPEC_COMMAND_CONTAINER_NAMES = new Set(['command', 'commands', 'prompts', 'workflows']);
function configuredWorkflows(config: WorkflowProjectConfig | null): Array<'native' | 'classic'> {
return config?.workflows ?? (config ? [config.default_workflow] : ['classic']);
}
function configuredSkillLanguage(
config: WorkflowProjectConfig | null,
workflows: Array<'native' | 'classic'>,
): 'zh' | 'en' {
if (!config) return 'en';
const ordered = [
config.default_workflow,
...workflows.filter((workflow) => workflow !== config.default_workflow),
];
for (const workflow of ordered) {
if (!workflows.includes(workflow)) continue;
const language = workflow === 'native' ? config.native?.language : config.classic?.language;
if (language) return language === 'zh-CN' ? 'zh' : 'en';
}
return 'en';
}
function hookRouterRuntimePaths(
baseDir: string,
platform: Platform,
scope: InstallScope,
): { source: string; destination: string } {
return {
source: path.join(getAssetsDir(), 'skills', ...HOOK_ROUTER_RUNTIME.split('/')),
destination: path.join(
baseDir,
getPlatformSkillsDir(platform, scope),
'skills',
...HOOK_ROUTER_RUNTIME.split('/'),
),
};
}
function checkCometCli(): CheckResult {
return {
check: 'Comet CLI',
status: 'pass',
message: `installed (${getCurrentVersion()})`,
};
}
async function checkOpenSpecCli(): Promise<CheckResult> {
if (!isCommandAvailable('openspec')) {
return {
check: 'openspec CLI',
status: 'warn',
message: 'not installed — install with: npm install -g @fission-ai/openspec@latest',
};
}
const version = getOpenSpecVersion();
if (!version || !isOpenSpecVersionCompatible(version)) {
return {
check: 'openspec CLI',
status: 'warn',
message: `installed (${version || 'version unknown'}), but Comet requires >= ${MINIMUM_OPENSPEC_VERSION} — run: npm install -g @fission-ai/openspec@latest`,
};
}
return { check: 'openspec CLI', status: 'pass', message: `installed (${version})` };
}
function checkEnvironment(projectPath: string, context: DoctorContext): CheckResult {
return {
check: 'Environment',
status: 'pass',
message: `node ${process.version}; platform ${process.platform}/${process.arch}; project ${projectPath}; global ${context.homeDir}`,
};
}
function checkScopeMode(
projectPath: string,
scope: DoctorScope,
context: DoctorContext,
): CheckResult | null {
if (scope !== 'auto') return null;
const includesGlobal = path.resolve(projectPath) !== path.resolve(context.homeDir);
return {
check: 'Scope',
status: 'pass',
message: includesGlobal
? 'auto checks project scope first, then global scope when it is different'
: 'auto checks project scope only because project path is the global home directory',
};
}
async function checkWorkingDirs(projectPath: string): Promise<CheckResult> {
let layout;
try {
layout = await resolveClassicLayout(projectPath);
} catch (error) {
return {
check: 'working directories',
status: 'fail',
message: error instanceof Error ? error.message : String(error),
};
}
const expected = [
layout.changesDir,
layout.archiveDir,
layout.specsDir,
layout.superpowersSpecsDir,
layout.superpowersPlansDir,
layout.superpowersReportsDir,
];
let presence: boolean[];
try {
const inspections = await Promise.all(
expected.map((directory) =>
inspectProtectedProjectPath(
projectPath,
path.relative(projectPath, directory).replaceAll('\\', '/'),
{
label: `Classic working directory ${path
.relative(projectPath, directory)
.replaceAll('\\', '/')}`,
expected: 'directory',
},
),
),
);
presence = inspections.map((inspection) => inspection.exists);
} catch (error) {
return {
check: 'working directories',
status: 'fail',
message: error instanceof Error ? error.message : String(error),
};
}
const missing = expected
.filter((_, index) => !presence[index])
.map((directory) => path.relative(projectPath, directory).replaceAll('\\', '/'));
if (missing.length === 0) {
return {
check: 'working directories',
status: 'pass',
message: `present (${layout.artifactLayout})`,
};
}
if (missing.length === expected.length) {
return {
check: 'working directories',
status: 'warn',
message:
'project not initialized for Comet — run: comet init --scope project if this project should use Comet workflows',
};
}
return {
check: 'working directories',
status: 'warn',
message: `partial (missing: ${missing.join(', ')})`,
};
}
async function checkClassicLayout(projectPath: string): Promise<CheckResult> {
let transaction;
try {
transaction = await inspectClassicRootMove(projectPath);
} catch (error) {
return {
check: 'Classic artifact layout',
status: 'fail',
message: `invalid root move journal; allowed strategies: none (${
error instanceof Error ? error.message : String(error)
})`,
};
}
if (transaction) {
const allowed =
transaction.allowedStrategies.length > 0 ? transaction.allowedStrategies.join(', ') : 'none';
return {
check: 'Classic artifact layout',
status: 'fail',
message: `root move ${transaction.id} is incomplete at ${transaction.stage}; source ${transaction.source}; target ${transaction.target}; staging ${transaction.staging}; plan ${transaction.planId}; allowed strategies: ${allowed}${
transaction.reason ? ` (${transaction.reason})` : ''
}; run comet doctor --repair --strategy <strategy>`,
};
}
let inspection;
try {
inspection = await inspectClassicLayout(projectPath);
} catch (error) {
return {
check: 'Classic artifact layout',
status: 'fail',
message: error instanceof Error ? error.message : String(error),
};
}
if (inspection.dualRoots) {
return {
check: 'Classic artifact layout',
status: 'fail',
message: `both ${path.relative(projectPath, inspection.paths.openSpecRoot).replaceAll('\\', '/')}/ and ${path.relative(projectPath, inspection.alternateRoot).replaceAll('\\', '/')}/ exist; Classic writes are blocked until the conflict is resolved — run comet classic root show, then comet classic root move docs --dry-run to inspect a safe migration; do not delete either root automatically`,
};
}
const configuredRoot = path
.relative(projectPath, inspection.paths.openSpecRoot)
.replaceAll('\\', '/');
const alternateRoot = path.relative(projectPath, inspection.alternateRoot).replaceAll('\\', '/');
if (!inspection.configuredRootExists) {
return {
check: 'Classic artifact layout',
status: 'fail',
message: `${inspection.paths.artifactLayout}: configured ${configuredRoot}/ missing; alternate ${alternateRoot}/ ${
inspection.alternateRootExists ? 'present' : 'missing'
} — run: comet classic root show, then restore the configured root or use comet classic root move`,
};
}
return {
check: 'Classic artifact layout',
status: 'pass',
message: `${inspection.paths.artifactLayout}: configured ${configuredRoot}/ present; alternate ${alternateRoot}/ ${
inspection.alternateRootExists ? 'present' : 'missing'
}`,
};
}
async function checkClassicInitialization(projectPath: string): Promise<CheckResult | null> {
try {
const initialization = await inspectClassicLayoutInitialization(projectPath);
if (!initialization) return null;
const location = initialization.quarantine ? `; preserved at ${initialization.quarantine}` : '';
return {
check: 'Classic initialization',
status: 'warn',
message: `${initialization.id} at ${initialization.stage}${location}; allowed strategies: ${initialization.allowedStrategies.join(', ')}`,
};
} catch (error) {
return {
check: 'Classic initialization',
status: 'fail',
message: error instanceof Error ? error.message : String(error),
};
}
}
async function checkProjectConfigWriteTransaction(
projectPath: string,
): Promise<CheckResult | null> {
try {
const transaction = await inspectWorkflowProjectConfigTransaction(projectPath);
if (!transaction) return null;
return {
check: 'project config write transaction',
status: 'warn',
message: `${transaction.id} at ${transaction.stage}; repair with: comet doctor --repair`,
};
} catch (error) {
return {
check: 'project config write transaction',
status: 'fail',
message: error instanceof Error ? error.message : String(error),
};
}
}
async function checkClassicOpenSpecRoot(projectPath: string): Promise<CheckResult> {
try {
const health = await assertClassicOpenSpecRootHealthy(projectPath);
return {
check: 'Classic OpenSpec root',
status: 'pass',
message: `${health.configPath} is valid (${health.schema})`,
};
} catch (error) {
return {
check: 'Classic OpenSpec root',
status: 'fail',
message: error instanceof Error ? error.message : String(error),
};
}
}
interface DoctorDirectoryIdentity {
object: FileObjectIdentity;
ctimeNs: bigint;
mtimeNs: bigint;
size: bigint;
}
function doctorDirectoryIdentity(stat: BigIntStats): DoctorDirectoryIdentity {
return {
object: {
dev: stat.dev,
ino: stat.ino,
birthtime: stat.birthtimeNs,
},
ctimeNs: stat.ctimeNs,
mtimeNs: stat.mtimeNs,
size: stat.size,
};
}
function sameDoctorDirectory(
left: DoctorDirectoryIdentity,
right: DoctorDirectoryIdentity,
): boolean {
return (
sameFileObject(left.object, right.object) &&
left.ctimeNs === right.ctimeNs &&
left.mtimeNs === right.mtimeNs &&
left.size === right.size
);
}
async function readDoctorPlatformDirectory(
projectPath: string,
relativeDirectory: string,
maxEntries: number,
): Promise<Dirent[] | null> {
const label = `Classic platform tool directory ${relativeDirectory}`;
const inspection = await inspectProtectedProjectPath(projectPath, relativeDirectory, {
label,
expected: 'directory',
});
if (!inspection.exists) return null;
const beforeStat = await fs.lstat(inspection.target, { bigint: true });
if (!beforeStat.isDirectory() || beforeStat.isSymbolicLink()) {
throw new Error(`${label} must be a real directory`);
}
const before = doctorDirectoryIdentity(beforeStat);
const entries: Dirent[] = [];
let readError: unknown;
const directory = await fs.opendir(inspection.target);
try {
for await (const entry of directory) {
entries.push(entry);
if (entries.length > maxEntries) {
throw new Error(
`Classic platform tool scan exceeds ${CLASSIC_PLATFORM_TOOL_SCAN_MAX_ENTRIES} entries`,
);
}
}
} catch (error) {
readError = error;
} finally {
await directory.close().catch((error: unknown) => {
if ((error as NodeJS.ErrnoException).code !== 'ERR_DIR_CLOSED' && !readError) {
readError = error;
}
});
}
const afterInspection = await inspectProtectedProjectPath(projectPath, relativeDirectory, {
label,
expected: 'directory',
});
if (!afterInspection.exists) {
throw new Error(`${label} changed while being inspected`);
}
const afterStat = await fs.lstat(afterInspection.target, { bigint: true });
if (
!afterStat.isDirectory() ||
afterStat.isSymbolicLink() ||
!sameDoctorDirectory(before, doctorDirectoryIdentity(afterStat))
) {
throw new Error(`${label} changed while being inspected`);
}
if (readError) throw readError;
return entries;
}
function isOpenSpecPlatformToolSentinel(relativePath: string, kind: 'file' | 'directory'): boolean {
const segments = relativePath.split('/');
const name = segments.at(-1) ?? '';
const parent = segments.at(-2) ?? '';
if (kind === 'directory' && parent === 'skills' && /^openspec-[a-z0-9-]+$/iu.test(name)) {
return true;
}
if (kind !== 'file') return false;
const insideCommandContainer = segments.some((segment) =>
OPEN_SPEC_COMMAND_CONTAINER_NAMES.has(segment),
);
if (!insideCommandContainer) return false;
return /^(?:opsx|openspec)-[a-z0-9-]+\.[a-z0-9.]+$/iu.test(name) || segments.includes('opsx');
}
async function findClassicArtifactPlatformTools(
projectPath: string,
artifactBaseRelative: string,
): Promise<string[]> {
const findings = new Set<string>();
const queue = CLASSIC_PLATFORM_TOOL_ROOTS.map((platformRoot) => ({
relative: path.posix.join(artifactBaseRelative, platformRoot.replaceAll('\\', '/')),
depth: 0,
}));
let inspectedEntries = 0;
while (queue.length > 0) {
const current = queue.shift()!;
const entries = await readDoctorPlatformDirectory(
projectPath,
current.relative,
CLASSIC_PLATFORM_TOOL_SCAN_MAX_ENTRIES - inspectedEntries,
);
if (!entries) continue;
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
inspectedEntries += 1;
if (inspectedEntries > CLASSIC_PLATFORM_TOOL_SCAN_MAX_ENTRIES) {
throw new Error(
`Classic platform tool scan exceeds ${CLASSIC_PLATFORM_TOOL_SCAN_MAX_ENTRIES} entries`,
);
}
const relative = path.posix.join(current.relative, entry.name);
const inspection = await inspectProtectedProjectPath(projectPath, relative, {
label: `Classic platform tool candidate ${relative}`,
expected: 'any',
});
if (!inspection.exists) {
throw new Error(
`Classic platform tool candidate ${relative} changed while being inspected`,
);
}
const kind = inspection.kind === 'directory' ? 'directory' : 'file';
if (isOpenSpecPlatformToolSentinel(relative, kind)) {
findings.add(relative);
if (findings.size > CLASSIC_PLATFORM_TOOL_SCAN_MAX_FINDINGS) {
throw new Error(
`Classic platform tool scan exceeds ${CLASSIC_PLATFORM_TOOL_SCAN_MAX_FINDINGS} findings`,
);
}
continue;
}
if (kind === 'directory') {
if (current.depth >= CLASSIC_PLATFORM_TOOL_SCAN_MAX_DEPTH) {
throw new Error(
`Classic platform tool scan exceeds depth ${CLASSIC_PLATFORM_TOOL_SCAN_MAX_DEPTH} at ${relative}`,
);
}
queue.push({ relative, depth: current.depth + 1 });
}
}
}
return [...findings].sort();
}
async function checkClassicPlatformToolAssets(projectPath: string): Promise<CheckResult | null> {
let layout;
try {
layout = await resolveClassicLayout(projectPath);
} catch {
// The dedicated layout check already reports why the configured layout
// cannot be trusted. Do not guess whether the docs-only check applies.
return null;
}
if (layout.artifactLayout !== 'docs') return null;
const artifactBaseRelative = path
.relative(projectPath, layout.openSpecBase)
.replaceAll('\\', '/');
try {
const findings = await findClassicArtifactPlatformTools(projectPath, artifactBaseRelative);
if (findings.length === 0) {
return {
check: 'Classic platform tool assets',
status: 'pass',
message: 'no OpenSpec platform tool assets under docs/',
};
}
return {
check: 'Classic platform tool assets',
status: 'fail',
message: `found OpenSpec platform tool assets under the docs artifact root: ${findings.join(
', ',
)}; these assets belong in platform directories at the project root — run comet update to repair the platform installation. Doctor did not move any files.`,
};
} catch (error) {
return {
check: 'Classic platform tool assets',
status: 'fail',
message: `could not safely inspect platform tool assets under docs/: ${
error instanceof Error ? error.message : String(error)
}; platform tool assets belong in platform directories at the project root — run comet update to repair the platform installation. Doctor did not move any files.`,
};
}
}
async function checkSuperpowers(
projectPath: string,
scope: DoctorScope,
context: DoctorContext,
): Promise<CheckResult> {
const detected: string[] = [];
for (const base of getScopeBases(projectPath, scope, context)) {
for (const platform of PLATFORMS) {
for (const skillsDir of getPlatformSkillsDirs(platform, base.scope)) {
for (const sentinel of SUPERPOWERS_SENTINELS) {
if (await fileExists(path.join(base.baseDir, skillsDir, 'skills', sentinel))) {
detected.push(`${platform.name} ${base.scope}`);
break;
}
}
}
}
}
const uniqueDetected = [...new Set(detected)];
if (uniqueDetected.length > 0) {
return {
check: 'Superpowers',
status: 'pass',
message: `detected (${uniqueDetected.join(', ')}; version not recorded by skills installer)`,
};
}
return {
check: 'Superpowers',
status: 'warn',
message: 'not detected — install with: npx skills add obra/superpowers -y --agent <platform>',
};
}
function getScopeBases(
projectPath: string,
scope: DoctorScope,
context: DoctorContext,
): Array<{
scope: InstallScope;
baseDir: string;
}> {
if (scope === 'project') return [{ scope, baseDir: projectPath }];
if (scope === 'global') return [{ scope, baseDir: context.homeDir }];
const bases: Array<{ scope: InstallScope; baseDir: string }> = [
{ scope: 'project', baseDir: projectPath },
];
if (path.resolve(projectPath) !== path.resolve(context.homeDir)) {
bases.push({ scope: 'global', baseDir: context.homeDir });
}
return bases;
}
function globalHookCheckResult(
platform: Platform,
scope: InstallScope,
inspection: Awaited<ReturnType<typeof inspectCometHooksForPlatform>>,
): CheckResult {
const globalHookPresent =
inspection.present || inspection.managedPresent === true || inspection.legacyPresent === true;
return {
check: `hooks: ${platform.name} (${scope})`,
status: globalHookPresent || inspection.error ? 'warn' : 'pass',
message: inspection.error
? `${inspection.error} — run: comet doctor --repair --scope global`
: globalHookPresent
? 'global blocking Hook remains — run: comet doctor --repair --scope global'
: 'no global blocking Hook present',
};
}
async function checkPlatformComponents(
baseDir: string,
platform: (typeof PLATFORMS)[number],
scope: InstallScope,
workflowSelection: InitWorkflowSelection,
): Promise<CheckResult[]> {
const results: CheckResult[] = [];
const ruleDestinations = await getPlatformRuleDestinations(
baseDir,
platform,
scope,
workflowSelection,
);
if (ruleDestinations.length > 0) {
let present = 0;
const inspectionErrors: string[] = [];
for (const destination of ruleDestinations) {
try {
if (await fileExists(destination)) present++;
} catch (error) {
inspectionErrors.push(`${destination}: ${(error as Error).message}`);
}
}
results.push({
check: `rules: ${platform.name} (${scope})`,
status:
inspectionErrors.length === 0 && present === ruleDestinations.length ? 'pass' : 'warn',
message:
inspectionErrors.length > 0
? `unable to inspect managed Rule (${inspectionErrors.join('; ')}) — run: comet update --scope ${scope}`
: present === ruleDestinations.length
? `complete (${present} files)`
: `partial (${present}/${ruleDestinations.length} files) — run: comet update --scope ${scope}`,
});
const legacyRuleDestinations = getLegacyPlatformRuleDestinations(baseDir, platform, scope);
let legacyRules = 0;
const legacyInspectionErrors: string[] = [];
for (const destination of legacyRuleDestinations) {
try {
if (await fileExists(destination)) legacyRules++;
} catch (error) {
legacyInspectionErrors.push(`${destination}: ${(error as Error).message}`);
}
}
if (legacyInspectionErrors.length > 0) {
results.push({
check: `legacy rules: ${platform.name} (${scope})`,
status: 'warn',
message: `unable to inspect legacy managed Rule (${legacyInspectionErrors.join('; ')})`,
});
}
if (legacyRules > 0) {
results.push({
check: `legacy rules: ${platform.name} (${scope})`,
status: 'warn',
message: `${legacyRules} legacy managed Rule file(s) remain — run: comet doctor --repair --scope ${scope}`,
});
}
}
results.push(...(await checkHookComponents(baseDir, platform, scope, workflowSelection)));
return results;
}
async function checkHookComponents(
baseDir: string,
platform: Platform,
scope: InstallScope,
workflowSelection: InitWorkflowSelection,
): Promise<CheckResult[]> {
if (!platform.supportsHooks || !platform.hookFormat) return [];
const results: CheckResult[] = [];
const runtime = hookRouterRuntimePaths(baseDir, platform, scope);
try {
const [expected, installed] = await Promise.all([
fs.readFile(runtime.source),
fs.readFile(runtime.destination),
]);
results.push({
check: `hook runtime: ${platform.name} (${scope})`,
status: expected.equals(installed) ? 'pass' : 'warn',
message: expected.equals(installed)
? 'current'
: `outdated — run: comet doctor --repair --scope ${scope}`,
});
} catch (error) {
results.push({
check: `hook runtime: ${platform.name} (${scope})`,
status: 'warn',
message: `unable to verify current Router runtime (${(error as Error).message}) — run: comet doctor --repair --scope ${scope}`,
});
}
const inspection = await inspectCometHooksForPlatform(
baseDir,
platform,
scope,
workflowSelection,
);
if (scope === 'global') {
results.push(globalHookCheckResult(platform, scope, inspection));
return results;
}
results.push({
check: `hooks: ${platform.name} (${scope})`,
status:
inspection.present &&
!inspection.error &&
!inspection.legacyPresent &&
!inspection.duplicatePresent
? 'pass'
: 'warn',
message:
inspection.present &&
!inspection.error &&
!inspection.legacyPresent &&
!inspection.duplicatePresent
? 'exactly one managed Router Hook present'
: inspection.present && inspection.duplicatePresent
? `duplicate managed Router Hooks remain — run: comet doctor --repair --scope ${scope}`
: inspection.present && inspection.legacyPresent
? `Router Hook and legacy managed Hook coexist — run: comet doctor --repair --scope ${scope}`
: `${inspection.error ?? 'managed Hook missing'} — run: comet update --scope ${scope}`,
});
return results;
}
async function getPlatformsForSkillInspection(
baseDir: string,
scope: InstallScope,
doctorScope: DoctorScope,
): Promise<Array<{ platform: Platform; inspectComponents: boolean }>> {
return (
await resolveCanonicalSkillRootOwners(baseDir, scope, {
respectDetectionPaths: doctorScope === 'auto',
})
).map(({ platform, hasOwnershipEvidence, sharedCanonicalRoot }) => ({
platform,
inspectComponents: !sharedCanonicalRoot || hasOwnershipEvidence,
}));
}
async function getHookOnlyInspections(
baseDir: string,
scope: InstallScope,
knownPlatformIds: ReadonlySet<string>,
): Promise<
Array<{
platform: Platform;
inspection: Awaited<ReturnType<typeof inspectCometHooksForPlatform>>;
}>
> {
const results: Array<{
platform: Platform;
inspection: Awaited<ReturnType<typeof inspectCometHooksForPlatform>>;
}> = [];
for (const platform of PLATFORMS) {
if (knownPlatformIds.has(platform.id) || !platform.supportsHooks || !platform.hookFormat) {
continue;
}
const inspection = await inspectCometHooksForPlatform(baseDir, platform, scope);
if (
inspection.present ||
inspection.managedPresent ||
inspection.legacyPresent ||
inspection.error
) {
results.push({ platform, inspection });
}
}
return results;
}
async function checkSkillCompleteness(
projectPath: string,
scope: DoctorScope,
context: DoctorContext,
workflowSelection: InitWorkflowSelection,
): Promise<CheckResult[]> {
const results: CheckResult[] = [];
const manifest = await readManifest();
let anyCometInstall = false;
const scopeState: Record<InstallScope, { hasInstall: boolean; hasComplete: boolean }> = {
project: { hasInstall: false, hasComplete: false },
global: { hasInstall: false, hasComplete: false },
};
for (const base of getScopeBases(projectPath, scope, context)) {
const managedSkills = getManagedSkillPathsForSelection(
manifest,
base.scope === 'global' ? 'classic' : workflowSelection,
);
const total = managedSkills.length;
const platforms = await getPlatformsForSkillInspection(base.baseDir, base.scope, scope);
const detectedPlatformIds = new Set<string>();
for (const { platform, inspectComponents } of platforms) {
const skillsDirs = getPlatformSkillsDirs(platform, base.scope);
const canonicalSkillsDir = skillsDirs[0];
let detectedSkillsDir: string | undefined;
let present: string[] = [];
let missing: string[] = [];
for (const skillsDir of skillsDirs) {
const candidatePresent: string[] = [];
const candidateMissing: string[] = [];
for (const relPath of managedSkills) {
const fullPath = path.join(base.baseDir, skillsDir, 'skills', relPath);
if (await fileExists(fullPath)) candidatePresent.push(relPath);
else candidateMissing.push(relPath);
}
if (candidatePresent.length === 0) continue;
detectedSkillsDir = skillsDir;
present = candidatePresent;
missing = candidateMissing;
break;
}
if (!detectedSkillsDir) continue;
detectedPlatformIds.add(platform.id);
anyCometInstall = true;
scopeState[base.scope].hasInstall = true;
const isLegacy = detectedSkillsDir !== canonicalSkillsDir;
if (missing.length === 0 && !isLegacy) {
scopeState[base.scope].hasComplete = true;
}
results.push(
isLegacy
? {
check: `skills: ${platform.name} (${base.scope})`,
status: 'warn' as const,
message: `legacy installation (${present.length}/${total} files) — run: comet update --scope ${base.scope}`,
}
: missing.length === 0
? {
check: `skills: ${platform.name} (${base.scope})`,
status: 'pass' as const,
message: `complete (${total} files)`,
}
: {
check: `skills: ${platform.name} (${base.scope})`,
status: 'warn' as const,
message: `partial (${present.length}/${total} files; missing ${missing.length}) — run: comet update --scope ${base.scope}`,
},
);
if (inspectComponents) {
results.push(
...(await checkPlatformComponents(
base.baseDir,
platform,
base.scope,
base.scope === 'global' ? 'classic' : workflowSelection,
)),
);
}
}
for (const { platform } of await getHookOnlyInspections(
base.baseDir,
base.scope,
detectedPlatformIds,
)) {
results.push(
...(await checkHookComponents(
base.baseDir,
platform,
base.scope,
base.scope === 'global' ? 'classic' : workflowSelection,
)),
);
}
}
if (scope === 'auto' && !scopeState.project.hasInstall && scopeState.global.hasComplete) {
results.push({
check: 'Project scope',
status: 'pass',
message:
'no project-local Comet skills installed; global scope is available — run: comet init --scope project only if this project needs its own copy',
});
}
if (!anyCometInstall) {
results.push({
check: 'Comet skills',
status: 'warn',
message:
scope === 'auto'
? 'not installed in project or global scope — run: comet init'
: `not installed in ${scope} scope — run: comet init --scope ${scope}`,
});
}
return results;
}
async function checkScriptsPresent(): Promise<CheckResult> {
const assetsDir = getAssetsDir();
const scriptsDir = path.join(assetsDir, 'skills', 'comet', 'scripts');
if (!(await fileExists(scriptsDir))) {
return { check: 'scripts present', status: 'warn', message: 'scripts directory not found' };
}
const entries = await readDir(scriptsDir);
const scriptFiles = entries.filter((e) => e.endsWith('.mjs'));
return {
check: 'scripts present',
status: 'pass',
message: `OK (${scriptFiles.length} scripts)`,
};
}
function formatMissingEvidence(missingEvidence: readonly string[]): string {
return missingEvidence.join(', ');
}
function formatRuntimeEvalRecovery(
nextCommand: string | null,
missingEvidence: readonly string[],
): string {
const missing = formatMissingEvidence(missingEvidence);
if (nextCommand) {
return `run ${nextCommand} or restore missing evidence (${missing}), then rerun comet doctor`;
}