forked from rpamis/comet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplatform-install.ts
More file actions
2094 lines (1884 loc) · 68.9 KB
/
Copy pathplatform-install.ts
File metadata and controls
2094 lines (1884 loc) · 68.9 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 { existsSync } from 'fs';
import { readFile, writeFile, lstat, unlink, symlink, rm, readdir } from 'fs/promises';
import { fileURLToPath } from 'url';
import { fileExists, readJson, copyFile, ensureDir } from '../../platform/fs/file-system.js';
import {
getPlatformConfigDir,
getPlatformSkillsDir,
type Platform,
} from '../../platform/install/platforms.js';
import type { InstallScope, InstallMode } from '../../platform/install/types.js';
import { resolveArtifactLanguage } from './languages.js';
import type { LanguageConfig, SkillLanguageId } from './languages.js';
import { installCometProjectInstructions } from './project-instructions.js';
import { readJsonObjectFile } from './json-object.js';
import type { InitWorkflowSelection } from '../comet-entry/types.js';
import {
assertClassicLayoutInitializationSafe,
checkpointClassicLayoutInitialization,
type ClassicLayoutInitializationPermit,
} from '../comet-classic/classic-layout-initialization.js';
import {
DEFAULT_WORKFLOW_NATIVE_SNAPSHOT_CONFIG,
parseWorkflowProjectConfigDocument,
projectConfigComment,
renderStructuredProjectConfig,
} from '../workflow-contract/project-config.js';
import { readWorkflowProjectConfigSnapshot } from '../workflow-contract/project-config-reader.js';
import { writeWorkflowProjectConfigSource } from '../workflow-contract/project-config-writer.js';
import { ensureProtectedProjectDirectory } from '../workflow-contract/protected-project-path.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
type HookConfig = {
matcher: string;
description: string;
};
type Manifest = {
version: string;
skills: string[];
internalSkills?: string[];
rules?: string[];
nativeRules?: string[];
hooks?: Record<string, HookConfig>;
nativeHooks?: Record<string, HookConfig>;
languages?: LanguageConfig[];
};
const HOOK_ROUTER_SCRIPT = 'comet/scripts/comet-hook-router.mjs';
const LEGACY_HOOK_SCRIPTS = [
'comet/scripts/comet-hook-guard.mjs',
'comet-native/scripts/comet-native-hook-guard.mjs',
] as const;
const LEGACY_RULE_FILES = ['comet-phase-guard.md', 'comet-native-phase-guard.md'] as const;
const NATIVE_SHARED_SKILL_PATHS = new Set([
'comet/SKILL.md',
'comet/scripts/comet-entry-runtime.mjs',
'comet/scripts/comet-hook-router.mjs',
]);
interface HookCommandContext {
platformId: string;
scope: InstallScope;
}
type HookInstallStatus = 'installed' | 'skipped' | 'failed';
export interface HookInstallResult {
status: HookInstallStatus;
reason?: string;
cleanupFailed?: number;
}
interface PlannedSkillSourceFile {
relativePath: string;
source: string;
}
interface PlannedSkillFile {
source: string;
destination: string;
}
function planSkillDirectoryCopy(
files: readonly PlannedSkillSourceFile[],
destinationRoot: string,
): PlannedSkillFile[] {
return files
.map((file) => ({
source: file.source,
destination: path.join(destinationRoot, ...file.relativePath.split('/')),
}))
.sort((left, right) =>
left.destination < right.destination ? -1 : left.destination > right.destination ? 1 : 0,
);
}
function getManagedSkillPaths(manifest: Manifest): string[] {
return [...new Set([...manifest.skills, ...(manifest.internalSkills ?? [])])];
}
function isManagedSkillPathForSelection(
skillPath: string,
workflowSelection: InitWorkflowSelection,
): boolean {
if (workflowSelection === 'both') return true;
if (workflowSelection === 'classic') return !skillPath.startsWith('comet-native/');
return (
NATIVE_SHARED_SKILL_PATHS.has(skillPath) ||
skillPath.startsWith('comet-native/') ||
skillPath.startsWith('comet-any/')
);
}
/**
* Derive the workflow selection from the Skills already on disk by checking
* the two workflow markers (comet-native/SKILL.md and comet-classic/SKILL.md).
* This lets `comet update` keep already-installed workflows in sync without
* expanding the range the user chose at install time:
* neither / classic only -> 'classic' (no Native added)
* native only -> 'native' (no Classic added)
* both -> 'both'
* The caller is responsible for computing `skillsRoot` (e.g. base dir +
* platform skills dir + 'skills'); this function only performs the marker
* check and mapping.
*/
export async function detectInstalledWorkflowSelection(
skillsRoot: string,
): Promise<InitWorkflowSelection> {
const [hasNative, hasClassic] = await Promise.all([
fileExists(path.join(skillsRoot, 'comet-native', 'SKILL.md')),
fileExists(path.join(skillsRoot, 'comet-classic', 'SKILL.md')),
]);
if (hasNative && hasClassic) return 'both';
if (hasNative) return 'native';
return 'classic';
}
function getManagedSkillPathsForSelection(
manifest: Manifest,
workflowSelection: InitWorkflowSelection,
): string[] {
return getManagedSkillPaths(manifest).filter((skillPath) =>
isManagedSkillPathForSelection(skillPath, workflowSelection),
);
}
function getUserFacingSkillPathsForSelection(
manifest: Manifest,
workflowSelection: InitWorkflowSelection,
): string[] {
return manifest.skills.filter((skillPath) =>
isManagedSkillPathForSelection(skillPath, workflowSelection),
);
}
function getUserFacingSkillNames(manifest: Manifest): string[] {
return getTopLevelSkillNames(manifest.skills);
}
function getManagedSkillReplacementPaths(
manifest: Manifest,
workflowSelection: InitWorkflowSelection = 'both',
): Set<string> {
const allowed = new Set<string>();
for (const skillPath of getManagedSkillPathsForSelection(manifest, workflowSelection)) {
const parts = skillPath.split('/').filter(Boolean);
for (let depth = 1; depth <= parts.length; depth++) {
allowed.add(parts.slice(0, depth).join('/'));
}
}
return allowed;
}
function getManagedSkillTopLevelEntries(
manifest: Manifest,
workflowSelection: InitWorkflowSelection = 'both',
): string[] {
const entries = new Set<string>();
for (const skillPath of getManagedSkillPathsForSelection(manifest, workflowSelection)) {
const [topLevel] = skillPath.split('/').filter(Boolean);
if (topLevel) entries.add(topLevel);
}
return [...entries].sort();
}
function getManagedEntriesForTopLevel(
managedEntries: Set<string>,
topLevelEntry: string,
): Set<string> {
const scopedEntries = new Set<string>();
const prefix = `${topLevelEntry}/`;
for (const entry of managedEntries) {
if (entry.startsWith(prefix)) {
scopedEntries.add(entry.slice(prefix.length));
}
}
return scopedEntries;
}
async function collectDirectoryEntryPaths(root: string, current = root): Promise<string[]> {
const entries = await readdir(current, { withFileTypes: true });
const paths: string[] = [];
for (const entry of entries) {
const fullPath = path.join(current, entry.name);
const relativePath = path.relative(root, fullPath).split(path.sep).join('/');
paths.push(relativePath);
if (entry.isDirectory() && !entry.isSymbolicLink()) {
paths.push(...(await collectDirectoryEntryPaths(root, fullPath)));
}
}
return paths;
}
async function assertDirectoryContainsOnlyManagedEntries(
dirPath: string,
managedEntries: Set<string>,
): Promise<void> {
const entries = await collectDirectoryEntryPaths(dirPath);
const unmanagedEntries = entries.filter((entry) => !managedEntries.has(entry));
if (unmanagedEntries.length === 0) return;
const preview = unmanagedEntries.slice(0, 5).join(', ');
const suffix = unmanagedEntries.length > 5 ? `, and ${unmanagedEntries.length - 5} more` : '';
throw new Error(
`Refusing to replace ${dirPath} with a symlink because it contains unmanaged entries: ${preview}${suffix}. Move them aside or use copy install mode.`,
);
}
const OPENCODE_COMMAND_HEADER = `---
description: Run the {skillName} Comet workflow
---
`;
const PI_COMMAND_EXTENSION_FILE = 'comet-commands.ts';
const OPENCODE_STYLE_PLATFORM_IDS = new Set(['opencode', 'mimocode']);
function getAssetsDir(): string {
const directAssets = path.resolve(__dirname, '..', '..', 'assets');
if (existsSync(path.join(directAssets, 'manifest.json'))) {
return directAssets;
}
const packageRootAssets = path.resolve(__dirname, '..', '..', '..', 'assets');
if (existsSync(path.join(packageRootAssets, 'manifest.json'))) {
return packageRootAssets;
}
return directAssets;
}
/**
* Get the central skills directory for symlink mode.
* Project scope: <project>/.comet/skills/
* Global scope: ~/.comet/skills/
*/
function getCentralSkillsDir(baseDir: string, _scope: InstallScope): string {
return path.join(baseDir, '.comet', 'skills');
}
/**
* Create a symlink from linkPath pointing to target.
* On Windows, uses 'junction' type for directory symlinks (no admin required).
*/
async function createSymlink(
target: string,
linkPath: string,
managedEntries: Set<string>,
): Promise<void> {
await ensureDir(path.dirname(linkPath));
// Remove existing link/directory if present
let stat: Awaited<ReturnType<typeof lstat>> | null = null;
try {
stat = await lstat(linkPath);
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
throw err;
}
}
if (stat?.isSymbolicLink()) {
await unlink(linkPath);
} else if (stat?.isDirectory()) {
// For directories, try unlink first (handles Windows junctions)
try {
await unlink(linkPath);
} catch {
await assertDirectoryContainsOnlyManagedEntries(linkPath, managedEntries);
await rm(linkPath, { recursive: true, force: true });
}
}
// Windows uses 'junction' for directory symlinks (no admin privileges required)
const type = process.platform === 'win32' ? 'junction' : 'dir';
await symlink(target, linkPath, type);
}
async function lstatOrNull(filePath: string): Promise<Awaited<ReturnType<typeof lstat>> | null> {
try {
return await lstat(filePath);
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code === 'ENOENT' || code === 'ENOTDIR') return null;
throw err;
}
}
async function prepareManagedSkillCopyTarget(
baseDir: string,
platform: Platform,
scope: InstallScope = 'project',
workflowSelection: InitWorkflowSelection = 'both',
): Promise<void> {
const manifest = await readManifest();
const managedEntries = new Set(getManagedSkillTopLevelEntries(manifest, workflowSelection));
const skillsRoot = path.join(baseDir, getPlatformSkillsDir(platform, scope), 'skills');
const rootStat = await lstatOrNull(skillsRoot);
if (!rootStat) return;
if (rootStat.isSymbolicLink()) {
let linkedEntries: string[] = [];
try {
linkedEntries = await readdir(skillsRoot);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
const unmanagedEntries = linkedEntries.filter((entry) => !managedEntries.has(entry));
if (unmanagedEntries.length > 0) {
throw new Error(
`Refusing to replace ${skillsRoot} with managed copies because the linked directory contains unmanaged entries: ${unmanagedEntries.join(', ')}`,
);
}
await unlink(skillsRoot);
await ensureDir(skillsRoot);
return;
}
if (!rootStat.isDirectory()) return;
for (const entry of managedEntries) {
const entryPath = path.join(skillsRoot, entry);
const entryStat = await lstatOrNull(entryPath);
if (entryStat?.isSymbolicLink()) {
await unlink(entryPath);
}
}
}
async function prepareNativeSkillInstallTarget(
baseDir: string,
platform: Platform,
scope: InstallScope,
languageSkillsDir: string,
action: 'overwrite' | 'fill' | 'skip',
): Promise<void> {
if (action !== 'skip') {
await prepareManagedSkillCopyTarget(baseDir, platform, scope, 'native');
}
if (action === 'overwrite') return;
const skillsRoot = path.join(baseDir, getPlatformSkillsDir(platform, scope), 'skills');
const assetsDir = getAssetsDir();
const manifest = await readManifest();
const requiredFiles = getManagedSkillPaths(manifest)
.filter(
(relativePath) =>
relativePath === 'comet/SKILL.md' ||
relativePath === 'comet/scripts/comet-entry-runtime.mjs' ||
relativePath === 'comet/scripts/comet-hook-router.mjs' ||
relativePath.startsWith('comet-any/') ||
relativePath.startsWith('comet-native/'),
)
.map((relativePath) => {
const pathParts = relativePath.split('/');
const sourceDir = relativePath.includes('/scripts/') ? 'skills' : languageSkillsDir;
return {
label: `the required Native asset ${relativePath}`,
destination: path.join(skillsRoot, ...pathParts),
source: path.join(assetsDir, sourceDir, ...pathParts),
};
});
for (const required of requiredFiles) {
const destinationStat = await lstatOrNull(required.destination);
if (!destinationStat) {
if (action === 'fill') continue;
throw new Error(
`Cannot activate Native while skipping existing Comet files because ${required.label} is missing at ${required.destination}`,
);
}
if (!destinationStat.isFile()) {
throw new Error(
`Cannot activate Native because ${required.label} is not a regular file at ${required.destination}; rerun with --overwrite after preserving any custom content`,
);
}
const [installed, bundled] = await Promise.all([
readFile(required.destination),
readFile(required.source),
]);
if (!installed.equals(bundled)) {
throw new Error(
`Cannot activate Native because ${required.label} differs from the bundled routing contract at ${required.destination}; rerun with --overwrite after preserving any custom content`,
);
}
}
}
async function createSkillsSymlinks(
targetRoot: string,
linkRoot: string,
managedEntries: Set<string>,
topLevelEntries: string[],
): Promise<number> {
const rootStat = await lstatOrNull(linkRoot);
if (!rootStat || rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
await createSymlink(targetRoot, linkRoot, managedEntries);
return 0;
}
let failed = 0;
for (const topLevelEntry of topLevelEntries) {
const targetEntry = path.join(targetRoot, topLevelEntry);
const linkEntry = path.join(linkRoot, topLevelEntry);
const managedEntryScope = getManagedEntriesForTopLevel(managedEntries, topLevelEntry);
try {
await createSymlink(targetEntry, linkEntry, managedEntryScope);
} catch (err) {
failed++;
console.error(
` Failed to create symlink ${linkEntry} -> ${targetEntry}: ${(err as Error).message}`,
);
}
}
return failed;
}
/**
* Install skills using symlink mode:
* 1. Copy skills to central store (.comet/skills/)
* 2. Create symlinks from the platform skills dir to central store
*/
async function installSkillsAsSymlink(
baseDir: string,
platform: Platform,
overwrite: boolean,
languageSkillsDir: string = 'skills',
scope: InstallScope = 'project',
workflowSelection: InitWorkflowSelection = 'both',
): Promise<{ copied: number; skipped: number; failed: number }> {
const centralDir = getCentralSkillsDir(baseDir, scope);
const assetsDir = getAssetsDir();
const manifestPath = path.join(assetsDir, 'manifest.json');
if (!(await fileExists(manifestPath))) {
throw new Error(`Manifest not found at ${manifestPath}`);
}
const manifest = await readJson<Manifest>(manifestPath);
if (!manifest || !Array.isArray(manifest.skills)) {
throw new Error(`Invalid manifest at ${manifestPath}: "skills" must be an array`);
}
const managedSkillPaths = getManagedSkillPathsForSelection(manifest, workflowSelection);
const userFacingSkillPaths = getUserFacingSkillPathsForSelection(manifest, workflowSelection);
const managedSkillReplacementPaths = getManagedSkillReplacementPaths(manifest, workflowSelection);
const managedSkillTopLevelEntries = getManagedSkillTopLevelEntries(manifest, workflowSelection);
// Step 1: Copy skills to central store
let copied = 0;
let skippedCount = 0;
let failedCount = 0;
// Count manifest entries filtered out by the workflow selection so the
// symlink path reports skipped files consistently with copy mode.
skippedCount += getManagedSkillPaths(manifest).length - managedSkillPaths.length;
for (const skillRelPath of managedSkillPaths) {
const isScript = skillRelPath.includes('/scripts/');
const sourceDir = isScript ? 'skills' : languageSkillsDir;
const src = path.join(assetsDir, sourceDir, skillRelPath);
const centralDest = path.join(centralDir, 'skills', skillRelPath);
try {
if (!overwrite && (await fileExists(centralDest))) {
skippedCount++;
continue;
}
await copyFile(src, centralDest);
copied++;
} catch (err) {
failedCount++;
console.error(
` Failed to copy ${skillRelPath} to central store: ${(err as Error).message}`,
);
}
}
// Step 2: Create symlinks from platform dir to central store
const platformSkillsDir = path.join(baseDir, getPlatformSkillsDir(platform, scope), 'skills');
const centralSkillsDir = path.join(centralDir, 'skills');
try {
failedCount += await createSkillsSymlinks(
centralSkillsDir,
platformSkillsDir,
managedSkillReplacementPaths,
managedSkillTopLevelEntries,
);
} catch (err) {
failedCount++;
console.error(
` Failed to create symlink ${platformSkillsDir} -> ${centralSkillsDir}: ${(err as Error).message}`,
);
}
// Handle OpenCode-style platform commands (still need copy, as command content may differ)
if (OPENCODE_STYLE_PLATFORM_IDS.has(platform.id)) {
const result = await createOpenCodeCommands(
baseDir,
platform,
userFacingSkillPaths,
overwrite,
scope,
languageSkillsDir,
);
copied += result.copied;
skippedCount += result.skipped;
failedCount += result.failed;
}
// Handle Pi platform command extension
if (platform.id === 'pi') {
const result = await createPiCommandExtension(
baseDir,
platform,
userFacingSkillPaths,
overwrite,
scope,
);
copied += result.copied;
skippedCount += result.skipped;
failedCount += result.failed;
}
return { copied, skipped: skippedCount, failed: failedCount };
}
async function copyCometSkillsForPlatform(
baseDir: string,
platform: Platform,
overwrite: boolean,
languageSkillsDir: string = 'skills',
scope: InstallScope = 'project',
installMode: InstallMode = 'copy',
workflowSelection: InitWorkflowSelection = 'both',
): Promise<{ copied: number; skipped: number; failed: number }> {
if (installMode === 'symlink') {
return installSkillsAsSymlink(
baseDir,
platform,
overwrite,
languageSkillsDir,
scope,
workflowSelection,
);
}
const assetsDir = getAssetsDir();
const manifestPath = path.join(assetsDir, 'manifest.json');
if (!(await fileExists(manifestPath))) {
throw new Error(`Manifest not found at ${manifestPath}`);
}
const manifest = await readJson<Manifest>(manifestPath);
if (!manifest || !Array.isArray(manifest.skills)) {
throw new Error(`Invalid manifest at ${manifestPath}: "skills" must be an array`);
}
let copied = 0;
let skippedCount = 0;
let failedCount = 0;
const managedSkillPaths = getManagedSkillPathsForSelection(manifest, workflowSelection);
const userFacingSkillPaths = getUserFacingSkillPathsForSelection(manifest, workflowSelection);
// Count manifest entries that the workflow selection filters out so the
// update summary stays honest: a Classic-only update reports the Native
// files it intentionally skips instead of pretending they do not exist.
const filteredCount = getManagedSkillPaths(manifest).length - managedSkillPaths.length;
skippedCount += filteredCount;
for (const skillRelPath of managedSkillPaths) {
const isScript = skillRelPath.includes('/scripts/');
const sourceDir = isScript ? 'skills' : languageSkillsDir;
const src = path.join(assetsDir, sourceDir, skillRelPath);
const dest = path.join(baseDir, getPlatformSkillsDir(platform, scope), 'skills', skillRelPath);
try {
if (!overwrite && (await fileExists(dest))) {
skippedCount++;
continue;
}
await copyFile(src, dest);
copied++;
} catch (err) {
// Surface the failure via the returned `failed` count instead of
// swallowing it, so a half-installed state (e.g. a missing
// comet-hook-guard.mjs) is visible in the summary rather than silently
// breaking phase guard downstream.
failedCount++;
console.error(` Failed to copy ${skillRelPath}: ${(err as Error).message}`);
}
}
if (OPENCODE_STYLE_PLATFORM_IDS.has(platform.id)) {
const result = await createOpenCodeCommands(
baseDir,
platform,
userFacingSkillPaths,
overwrite,
scope,
languageSkillsDir,
);
copied += result.copied;
skippedCount += result.skipped;
failedCount += result.failed;
}
if (platform.id === 'pi') {
const result = await createPiCommandExtension(
baseDir,
platform,
userFacingSkillPaths,
overwrite,
scope,
);
copied += result.copied;
skippedCount += result.skipped;
failedCount += result.failed;
}
return { copied, skipped: skippedCount, failed: failedCount };
}
function getTopLevelSkillNames(skillPaths: string[]): string[] {
return skillPaths.flatMap((skillPath) => {
const parts = skillPath.split('/');
return parts.length === 2 && parts[1] === 'SKILL.md' ? [parts[0]] : [];
});
}
function renderPiCommandExtension(skillNames: string[]): string {
return `import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
const commands = ${JSON.stringify(skillNames, null, 2)} as const;
export default function registerCometCommands(pi: ExtensionAPI) {
for (const name of commands) {
pi.registerCommand(name, {
description: \`Comet: /\${name}\`,
handler: async (args) => {
pi.sendUserMessage(args ? \`/skill:\${name} \${args}\` : \`/skill:\${name}\`);
},
});
}
}
`;
}
async function createPiCommandExtension(
baseDir: string,
platform: Platform,
skillPaths: string[],
overwrite: boolean,
scope: InstallScope,
): Promise<{ copied: number; skipped: number; failed: number }> {
const platformBase = path.join(baseDir, getPlatformSkillsDir(platform, scope));
const settingsPath = path.join(platformBase, 'settings.json');
const extensionPath = path.join(platformBase, 'extensions', PI_COMMAND_EXTENSION_FILE);
let copied = 0;
let skipped = 0;
let failed = 0;
try {
let settings: Record<string, unknown> = {};
if (await fileExists(settingsPath)) {
const parsed = JSON.parse(await readFile(settingsPath, 'utf-8')) as unknown;
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('expected a JSON object');
}
settings = parsed as Record<string, unknown>;
}
if (settings.enableSkillCommands !== true) {
settings.enableSkillCommands = true;
await ensureDir(path.dirname(settingsPath));
await writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
copied++;
}
} catch (err) {
failed++;
console.error(` Failed to update Pi settings at ${settingsPath}: ${(err as Error).message}`);
}
if (failed > 0) return { copied, skipped, failed };
try {
if (!overwrite && (await fileExists(extensionPath))) {
skipped++;
} else {
await ensureDir(path.dirname(extensionPath));
await writeFile(
extensionPath,
renderPiCommandExtension(getTopLevelSkillNames(skillPaths)),
'utf-8',
);
copied++;
}
} catch (err) {
failed++;
console.error(
` Failed to write Pi command extension at ${extensionPath}: ${(err as Error).message}`,
);
}
return { copied, skipped, failed };
}
function stripFrontmatter(content: string): string {
if (!content.startsWith('---\n') && !content.startsWith('---\r\n')) {
return content.trimStart();
}
const normalized = content.replace(/\r\n/g, '\n');
const end = normalized.indexOf('\n---\n', 4);
if (end === -1) return content.trimStart();
return normalized.slice(end + '\n---\n'.length).trimStart();
}
async function createOpenCodeCommands(
baseDir: string,
platform: Platform,
skillPaths: string[],
overwrite: boolean,
scope: InstallScope,
languageSkillsDir: string,
): Promise<{ copied: number; skipped: number; failed: number }> {
let copied = 0;
let skipped = 0;
let failed = 0;
const assetsDir = getAssetsDir();
const commandsDir = path.join(baseDir, getPlatformSkillsDir(platform, scope), 'commands');
for (const skillPath of skillPaths) {
const parts = skillPath.split('/');
if (parts.length !== 2 || parts[1] !== 'SKILL.md') continue;
const skillName = parts[0];
const dest = path.join(commandsDir, `${skillName}.md`);
try {
if (!overwrite && (await fileExists(dest))) {
skipped++;
continue;
}
await ensureDir(path.dirname(dest));
let skillSourcePath = path.join(assetsDir, languageSkillsDir, skillPath);
if (!(await fileExists(skillSourcePath))) {
skillSourcePath = path.join(assetsDir, 'skills', skillPath);
}
const skillBody = stripFrontmatter(await readFile(skillSourcePath, 'utf-8'));
const content = `${OPENCODE_COMMAND_HEADER.replace('{skillName}', skillName)}
Equivalent Comet skill: \`${skillName}\`
Command name: \`/${skillName}\`
Use the invocation arguments below as the user input for this workflow:
\`\`\`text
$ARGUMENTS
\`\`\`
${skillBody}
`;
await writeFile(dest, content, 'utf-8');
copied++;
} catch (err) {
failed++;
console.error(` Failed to create OpenCode command ${dest}: ${(err as Error).message}`);
}
}
return { copied, skipped, failed };
}
async function readManifest(): Promise<Manifest> {
const assetsDir = getAssetsDir();
const manifestPath = path.join(assetsDir, 'manifest.json');
return readJson<Manifest>(manifestPath);
}
async function getManifestSkills(
workflowSelection: InitWorkflowSelection = 'both',
): Promise<string[]> {
const manifest = await readManifest();
return getManagedSkillPathsForSelection(manifest, workflowSelection);
}
/**
* Copy Comet rule files to a platform's rules directory.
* Formats:
* 'md' = plain markdown copy
* 'mdc' = Cursor MDC with frontmatter
* 'copilot' = GitHub Copilot .instructions.md with applyTo frontmatter
* Skips platforms without rulesDir.
*/
// Rule variants share a base name and differ only by a `.en.md` suffix
// (e.g. `comet-phase-guard.md` = zh default, `comet-phase-guard.en.md` = en).
// Centralized here so the naming convention only needs to change in one place.
const EN_RULE_SUFFIX = /\.en\.md$/;
function isEnglishRuleVariant(ruleRelPath: string): boolean {
return EN_RULE_SUFFIX.test(ruleRelPath);
}
function toRuleBaseName(ruleRelPath: string): string {
return ruleRelPath.replace(EN_RULE_SUFFIX, '.md');
}
// Pick exactly one variant per base name for the requested language, falling
// back to whichever variant exists if there's no per-language pair.
function selectRulePathsForLanguage(rulePaths: string[], languageId: SkillLanguageId): string[] {
const wantEnglish = languageId === 'en';
const selected = new Map<string, { rulePath: string; matched: boolean }>();
for (const rulePath of rulePaths) {
const isEnglishVariant = isEnglishRuleVariant(rulePath);
const baseKey = toRuleBaseName(rulePath);
const matched = isEnglishVariant === wantEnglish;
const existing = selected.get(baseKey);
if (!existing || (matched && !existing.matched)) {
selected.set(baseKey, { rulePath, matched });
}
}
return [...selected.values()].map((entry) => entry.rulePath);
}
function managedRulesForSelection(manifest: Manifest, _selection: InitWorkflowSelection): string[] {
return manifest.rules ?? [];
}
function managedHooksForSelection(
manifest: Manifest,
_selection: InitWorkflowSelection,
): Record<string, HookConfig> {
return manifest.hooks ?? {};
}
function managedHookScriptPaths(hooksConfig: Record<string, HookConfig>): string[] {
return [...new Set([...Object.keys(hooksConfig), ...LEGACY_HOOK_SCRIPTS])];
}
async function copyCometRulesForPlatform(
baseDir: string,
platform: Platform,
overwrite: boolean,
languageId: SkillLanguageId,
scope: InstallScope = 'project',
workflowSelection: InitWorkflowSelection = 'classic',
): Promise<{ copied: number; skipped: number; failed: number }> {
if (!platform.rulesDir || !platform.rulesFormat) {
return { copied: 0, skipped: 0, failed: 0 };
}
const manifest = await readManifest();
const rulePaths = selectRulePathsForLanguage(
managedRulesForSelection(manifest, workflowSelection),
languageId,
);
if (!rulePaths || rulePaths.length === 0) {
return { copied: 0, skipped: 0, failed: 0 };
}
const assetsDir = getAssetsDir();
// Support platforms whose rules live outside the skills config dir
// (e.g., Cline: rules go to .clinerules/ at project root, not .cline/rules/)
const rulesBase =
platform.rulesBaseDir !== undefined
? platform.rulesBaseDir === ''
? baseDir
: path.join(baseDir, platform.rulesBaseDir)
: path.join(baseDir, getPlatformSkillsDir(platform, scope));
let copied = 0;
let skippedCount = 0;
let failed = 0;
for (const ruleRelPath of rulePaths) {
const src = path.join(assetsDir, 'skills', ruleRelPath);
try {
if (!(await fileExists(src))) {
console.error(` Rule source not found: ${ruleRelPath}`);
failed++;
continue;
}
// Normalize the `.en` infix away so the installed file name is the same
// regardless of which language variant was selected.
const ruleFileName = toRuleBaseName(path.basename(ruleRelPath));
const rulesDestDir = path.join(rulesBase, platform.rulesDir);
const dest = computeRuleDestPath(rulesDestDir, ruleFileName, platform.rulesFormat);
if (!overwrite && (await fileExists(dest))) {
skippedCount++;
continue;
}
const content = await readFile(src, 'utf-8');
await ensureDir(path.dirname(dest));
const formatted = formatRuleContent(content, ruleFileName, platform.rulesFormat);
await writeFile(dest, formatted, 'utf-8');
copied++;
} catch (err) {
console.error(` Failed to copy rule ${ruleRelPath}: ${(err as Error).message}`);
failed++;
}
}
const rulesDestDir = path.join(rulesBase, platform.rulesDir);
for (const legacyFile of LEGACY_RULE_FILES) {
const legacyPath = computeRuleDestPath(rulesDestDir, legacyFile, platform.rulesFormat);
try {
await rm(legacyPath, { force: true });
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === 'ENOENT' || code === 'ENOTDIR') continue;
console.error(` Failed to remove legacy Rule ${legacyPath}: ${(error as Error).message}`);
failed++;
}
}
return { copied, skipped: skippedCount, failed };
}
function computeRuleDestPath(
rulesDestDir: string,
ruleFileName: string,
rulesFormat: string,
): string {
if (rulesFormat === 'mdc') {
return path.join(rulesDestDir, ruleFileName.replace(/\.md$/, '.mdc'));
}
if (rulesFormat === 'copilot') {
// GitHub Copilot: comet-phase-guard.md → comet-phase-guard.instructions.md
return path.join(rulesDestDir, ruleFileName.replace(/\.md$/, '.instructions.md'));
}
return path.join(rulesDestDir, ruleFileName);
}
function formatRuleContent(content: string, ruleFileName: string, rulesFormat: string): string {
if (rulesFormat === 'mdc') {
// Cursor MDC: wrap in YAML frontmatter
return `---
description: ${ruleFileName.replace(/\.md$/, '').replace(/-/g, ' ')}
globs:
alwaysApply: true
---
${content}`;
}
if (rulesFormat === 'copilot') {
// GitHub Copilot: wrap in applyTo frontmatter (apply to all files)
return `---
applyTo: "**"
---
${content}`;
}
// Plain markdown — no transformation
return content;
}
/**
* Install Comet hooks for platforms that support them.
* Supports multiple hook formats:
* 'claude-code' — Claude-shaped JSON with PreToolUse array; defaults to settings.local.json,