forked from rpamis/comet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuninstall.ts
More file actions
1583 lines (1458 loc) · 51.7 KB
/
Copy pathuninstall.ts
File metadata and controls
1583 lines (1458 loc) · 51.7 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 { randomUUID } from 'crypto';
import { execFileSync } from 'child_process';
import type { BigIntStats } from 'fs';
import { homedir } from 'os';
import {
hasComparableFileObject,
sameFileObject,
type FileObjectIdentity,
} from '../../platform/fs/file-identity.js';
import { classicLayoutPaths } from '../comet-classic/classic-layout.js';
import { nativeProjectPaths } from '../comet-native/native-paths.js';
import {
readWorkflowProjectConfigIdentity,
readWorkflowProjectConfigSnapshot,
workflowProjectConfigIdentityEquals,
type WorkflowProjectConfigIdentity,
} from '../workflow-contract/project-config-reader.js';
import { lstat, realpath, rename, rmdir, unlink, writeFile } from 'fs/promises';
import {
fileExists,
readDir,
removeFile,
removeDir,
isDirEmpty,
} from '../../platform/fs/file-system.js';
import {
getPlatformConfigDir,
getPlatformSkillsDir,
getPlatformSkillsDirs,
type Platform,
} from '../../platform/install/platforms.js';
import type { InstallScope } from '../../platform/install/types.js';
import {
readManifest,
getManagedSkillPaths,
getManagedSkillPathsForSelection,
computeRuleDestPath,
isManagedHookCommand,
removeManagedCopilotHookEntries,
removeManagedHooksFromJsonFile,
} from './platform-install.js';
import type { CometWorkflow, InitWorkflowSelection } from '../comet-entry/types.js';
import { removeCometProjectInstructions } from './project-instructions.js';
import { readJsonObjectFile } from './json-object.js';
import { SKILLS_AGENT_MAP } from '../integrations/superpowers.js';
interface RemovalResult {
removed: number;
failed: number;
preserved?: string[];
reason?: string;
}
const OPENCODE_STYLE_PLATFORM_IDS = new Set(['opencode', 'mimocode']);
const LEGACY_RULE_PATHS = [
'comet/rules/comet-phase-guard.md',
'comet-native/rules/comet-native-phase-guard.md',
] as const;
const LEGACY_HOOK_SCRIPT_PATHS = [
'comet/scripts/comet-hook-guard.mjs',
'comet-native/scripts/comet-native-hook-guard.mjs',
] as const;
type ManagedWorkingTree = {
readonly [entry: string]: 'file' | ManagedWorkingTree;
};
function managedWorkingTreeEntry(
tree: ManagedWorkingTree,
entry: string,
): 'file' | ManagedWorkingTree | undefined {
return Object.prototype.hasOwnProperty.call(tree, entry) ? tree[entry] : undefined;
}
function setManagedWorkingTreeEntry(
tree: ManagedWorkingTree,
entry: string,
value: 'file' | ManagedWorkingTree,
): void {
Object.defineProperty(tree, entry, {
value,
enumerable: true,
configurable: true,
writable: true,
});
}
const EMPTY_MANAGED_WORKING_TREE: ManagedWorkingTree = {};
const OPENSPEC_WORKING_TREE: ManagedWorkingTree = {
changes: {
archive: EMPTY_MANAGED_WORKING_TREE,
},
specs: EMPTY_MANAGED_WORKING_TREE,
};
const SUPERPOWERS_WORKING_TREE: ManagedWorkingTree = {
specs: EMPTY_MANAGED_WORKING_TREE,
plans: EMPTY_MANAGED_WORKING_TREE,
reports: EMPTY_MANAGED_WORKING_TREE,
};
const COMET_WORKING_TREE: ManagedWorkingTree = {
'config.yaml': 'file',
};
const NATIVE_WORKING_TREE: ManagedWorkingTree = {
specs: EMPTY_MANAGED_WORKING_TREE,
changes: EMPTY_MANAGED_WORKING_TREE,
archive: EMPTY_MANAGED_WORKING_TREE,
runtime: {
locks: EMPTY_MANAGED_WORKING_TREE,
transactions: EMPTY_MANAGED_WORKING_TREE,
},
};
interface WorkingObjectIdentity {
kind: 'file' | 'directory';
fileObject: FileObjectIdentity;
size: bigint;
}
interface InspectedWorkingNode {
identity: WorkingObjectIdentity;
children: Map<string, InspectedWorkingNode> | null;
}
interface ManagedWorkingTreePlan {
directory: string;
managedTree: ManagedWorkingTree;
root: InspectedWorkingNode;
ancestorIdentities: Map<string, WorkingObjectIdentity>;
countRemoval: boolean;
}
interface QuarantinedWorkingTree {
plan: ManagedWorkingTreePlan;
quarantine: string;
}
interface RemoveWorkingDirsOptions {
workflows?: readonly CometWorkflow[];
testHooks?: {
afterPlanInspection?: () => void | Promise<void>;
};
}
function birthtimeOf(stat: BigIntStats): bigint {
return stat.birthtimeNs;
}
function workingIdentity(stat: BigIntStats): WorkingObjectIdentity {
return {
kind: stat.isFile() ? 'file' : 'directory',
fileObject: { dev: stat.dev, ino: stat.ino, birthtime: birthtimeOf(stat) },
size: stat.size,
};
}
function sameWorkingIdentity(
expected: WorkingObjectIdentity,
actual: WorkingObjectIdentity,
): boolean {
if (expected.kind !== actual.kind) return false;
if (
hasComparableFileObject(expected.fileObject, actual.fileObject) &&
!sameFileObject(expected.fileObject, actual.fileObject)
) {
return false;
}
if (
!hasComparableFileObject(expected.fileObject, actual.fileObject) &&
!sameFileObject(expected.fileObject, actual.fileObject)
) {
return false;
}
return expected.kind === 'directory' || expected.size === actual.size;
}
function isInsideDirectory(parent: string, target: string): boolean {
const relative = path.relative(parent, target);
return (
relative === '' ||
(!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${path.sep}`))
);
}
async function readWorkingObjectIdentity(
target: string,
expected: 'file' | 'directory',
): Promise<WorkingObjectIdentity> {
const stat = await lstat(target, { bigint: true });
if (stat.isSymbolicLink() || (expected === 'file' ? !stat.isFile() : !stat.isDirectory())) {
throw new Error(`Refusing to remove non-${expected} working object: ${target}`);
}
return workingIdentity(stat);
}
async function captureAncestorIdentities(
projectRoot: string,
directory: string,
): Promise<Map<string, WorkingObjectIdentity>> {
if (!isInsideDirectory(projectRoot, directory)) {
throw new Error(`Working directory is outside the project root: ${directory}`);
}
const identities = new Map<string, WorkingObjectIdentity>();
let cursor = projectRoot;
identities.set(path.resolve(cursor), await readWorkingObjectIdentity(cursor, 'directory'));
const relative = path.relative(projectRoot, directory);
for (const segment of relative.split(path.sep).filter(Boolean)) {
cursor = path.join(cursor, segment);
identities.set(path.resolve(cursor), await readWorkingObjectIdentity(cursor, 'directory'));
}
return identities;
}
async function assertIdentityChain(
projectRoot: string,
target: string,
identities: ReadonlyMap<string, WorkingObjectIdentity>,
): Promise<void> {
if (!isInsideDirectory(projectRoot, target)) {
throw new Error(`Working directory is outside the project root: ${target}`);
}
let cursor = projectRoot;
const paths = [cursor];
const relative = path.relative(projectRoot, target);
for (const segment of relative.split(path.sep).filter(Boolean)) {
cursor = path.join(cursor, segment);
paths.push(cursor);
}
for (const current of paths) {
const expected = identities.get(path.resolve(current));
if (!expected) {
throw new Error(`Working-directory identity is not bound: ${current}`);
}
const actual = await readWorkingObjectIdentity(current, expected.kind);
if (!sameWorkingIdentity(expected, actual)) {
throw new Error(`Working-directory object changed after inspection: ${current}`);
}
}
}
async function inspectManagedNode(
projectRoot: string,
directory: string,
managedTree: ManagedWorkingTree,
identities: Map<string, WorkingObjectIdentity>,
): Promise<InspectedWorkingNode> {
const identity = identities.get(path.resolve(directory));
if (!identity) throw new Error(`Working-directory identity is not bound: ${directory}`);
const entries = (await readDir(directory)).sort();
await assertIdentityChain(projectRoot, directory, identities);
const children = new Map<string, InspectedWorkingNode>();
for (const entry of entries) {
if (!Object.prototype.hasOwnProperty.call(managedTree, entry)) {
throw new Error(
`Refusing to remove unknown working-directory content: ${path.join(directory, entry)}`,
);
}
const expected = managedTree[entry];
const entryPath = path.join(directory, entry);
if (expected === 'file') {
const childIdentity = await readWorkingObjectIdentity(entryPath, 'file');
identities.set(path.resolve(entryPath), childIdentity);
children.set(entry, { identity: childIdentity, children: null });
continue;
}
const childIdentity = await readWorkingObjectIdentity(entryPath, 'directory');
identities.set(path.resolve(entryPath), childIdentity);
children.set(entry, await inspectManagedNode(projectRoot, entryPath, expected, identities));
}
const entriesAfter = (await readDir(directory)).sort();
await assertIdentityChain(projectRoot, directory, identities);
if (JSON.stringify(entriesAfter) !== JSON.stringify(entries)) {
throw new Error(`Working directory changed during inspection: ${directory}`);
}
return { identity, children };
}
async function inspectManagedWorkingTree(
projectRoot: string,
directory: string,
managedTree: ManagedWorkingTree,
countRemoval = false,
): Promise<ManagedWorkingTreePlan | null> {
try {
const ancestorIdentities = await captureAncestorIdentities(projectRoot, directory);
return {
directory,
managedTree,
root: await inspectManagedNode(projectRoot, directory, managedTree, ancestorIdentities),
ancestorIdentities,
countRemoval,
};
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
throw error;
}
}
async function validateManagedNode(
projectRoot: string,
directory: string,
node: InspectedWorkingNode,
identities: ReadonlyMap<string, WorkingObjectIdentity>,
): Promise<void> {
await assertIdentityChain(projectRoot, directory, identities);
const actualIdentity = await readWorkingObjectIdentity(directory, node.identity.kind);
if (!sameWorkingIdentity(node.identity, actualIdentity)) {
throw new Error(`Working-directory object changed after inspection: ${directory}`);
}
if (!node.children) return;
const entries = (await readDir(directory)).sort();
await assertIdentityChain(projectRoot, directory, identities);
const expectedEntries = [...node.children.keys()].sort();
if (JSON.stringify(entries) !== JSON.stringify(expectedEntries)) {
throw new Error(`Working directory changed after inspection: ${directory}`);
}
for (const entry of expectedEntries) {
await validateManagedNode(
projectRoot,
path.join(directory, entry),
node.children.get(entry)!,
identities,
);
}
const entriesAfter = (await readDir(directory)).sort();
await assertIdentityChain(projectRoot, directory, identities);
if (JSON.stringify(entriesAfter) !== JSON.stringify(expectedEntries)) {
throw new Error(`Working directory changed after inspection: ${directory}`);
}
}
async function validateManagedWorkingTree(
projectRoot: string,
plan: ManagedWorkingTreePlan,
): Promise<void> {
await validateManagedNode(projectRoot, plan.directory, plan.root, plan.ancestorIdentities);
}
function mergeManagedWorkingTree(
target: ManagedWorkingTree,
segments: readonly string[],
managedTree: ManagedWorkingTree,
): void {
if (segments.length === 0) {
for (const [entry, expected] of Object.entries(managedTree)) {
const current = managedWorkingTreeEntry(target, entry);
if (current === 'file' || expected === 'file') {
if (current !== undefined && current !== expected) {
throw new Error(`Conflicting managed working-tree entry: ${entry}`);
}
setManagedWorkingTreeEntry(target, entry, expected);
} else if (current === undefined) {
setManagedWorkingTreeEntry(target, entry, expected);
} else {
mergeManagedWorkingTree(current, [], expected);
}
}
return;
}
const [head, ...tail] = segments;
const current = managedWorkingTreeEntry(target, head);
if (current === 'file') throw new Error(`Conflicting managed working-tree entry: ${head}`);
const child = current ?? Object.create(null);
setManagedWorkingTreeEntry(target, head, child);
mergeManagedWorkingTree(child, tail, managedTree);
}
function cloneManagedWorkingTree(managedTree: ManagedWorkingTree): ManagedWorkingTree {
return Object.fromEntries(
Object.entries(managedTree).map(([entry, expected]) => [
entry,
expected === 'file' ? expected : cloneManagedWorkingTree(expected),
]),
);
}
async function assertWorkingTreeAbsentOrRealDirectory(
projectRoot: string,
directory: string,
): Promise<boolean> {
try {
await captureAncestorIdentities(projectRoot, directory);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
throw error;
}
}
async function realWorkingFileExists(file: string): Promise<boolean> {
try {
await readWorkingObjectIdentity(file, 'file');
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
throw error;
}
}
async function validateQuarantinedNode(
directory: string,
node: InspectedWorkingNode,
ancestors: readonly { path: string; identity: WorkingObjectIdentity }[],
): Promise<void> {
await assertQuarantineAncestorIdentities(ancestors);
const actual = await readWorkingObjectIdentity(directory, node.identity.kind);
if (!sameWorkingIdentity(node.identity, actual)) {
throw new Error(`Quarantined working object changed: ${directory}`);
}
if (!node.children) return;
const entries = (await readDir(directory)).sort();
await assertQuarantineAncestorIdentities(ancestors);
const expectedEntries = [...node.children.keys()].sort();
const after = await readWorkingObjectIdentity(directory, 'directory');
if (
!sameWorkingIdentity(node.identity, after) ||
JSON.stringify(entries) !== JSON.stringify(expectedEntries)
) {
throw new Error(`Quarantined working directory changed: ${directory}`);
}
for (const entry of expectedEntries) {
await validateQuarantinedNode(path.join(directory, entry), node.children.get(entry)!, [
...ancestors,
{ path: directory, identity: node.identity },
]);
}
const entriesAfter = (await readDir(directory)).sort();
await assertQuarantineAncestorIdentities(ancestors);
const finalIdentity = await readWorkingObjectIdentity(directory, 'directory');
if (
!sameWorkingIdentity(node.identity, finalIdentity) ||
JSON.stringify(entriesAfter) !== JSON.stringify(expectedEntries)
) {
throw new Error(`Quarantined working directory changed: ${directory}`);
}
}
async function assertQuarantineAncestorIdentities(
ancestors: readonly { path: string; identity: WorkingObjectIdentity }[],
): Promise<void> {
for (const ancestor of ancestors) {
const actual = await readWorkingObjectIdentity(ancestor.path, 'directory');
if (!sameWorkingIdentity(ancestor.identity, actual)) {
throw new Error(`Quarantine ancestor changed: ${ancestor.path}`);
}
}
}
async function removeQuarantinedNode(
directory: string,
node: InspectedWorkingNode,
ancestors: readonly { path: string; identity: WorkingObjectIdentity }[],
): Promise<void> {
await assertQuarantineAncestorIdentities(ancestors);
const actual = await readWorkingObjectIdentity(directory, node.identity.kind);
if (!sameWorkingIdentity(node.identity, actual)) {
throw new Error(`Quarantined working object changed: ${directory}`);
}
if (!node.children) {
await unlink(directory);
return;
}
for (const [entry, child] of node.children) {
await removeQuarantinedNode(path.join(directory, entry), child, [
...ancestors,
{ path: directory, identity: node.identity },
]);
}
const entries = await readDir(directory);
await assertQuarantineAncestorIdentities(ancestors);
const after = await readWorkingObjectIdentity(directory, 'directory');
if (!sameWorkingIdentity(node.identity, after) || entries.length !== 0) {
throw new Error(`Quarantined working directory changed before removal: ${directory}`);
}
await assertQuarantineAncestorIdentities(ancestors);
const beforeRemove = await readWorkingObjectIdentity(directory, 'directory');
if (!sameWorkingIdentity(node.identity, beforeRemove)) {
throw new Error(`Quarantined working directory changed before removal: ${directory}`);
}
await rmdir(directory);
}
function quarantineAncestorChain(
plan: ManagedWorkingTreePlan,
): Array<{ path: string; identity: WorkingObjectIdentity }> {
const parent = path.dirname(plan.directory);
return [...plan.ancestorIdentities.entries()]
.filter(([candidate]) => candidate !== path.resolve(plan.directory))
.filter(([candidate]) => isInsideDirectory(candidate, parent))
.sort(([left], [right]) => left.split(path.sep).length - right.split(path.sep).length)
.map(([ancestorPath, identity]) => ({ path: ancestorPath, identity }));
}
async function rollbackQuarantinedTrees(
quarantined: readonly QuarantinedWorkingTree[],
): Promise<void> {
for (const item of [...quarantined].reverse()) {
try {
await rename(item.quarantine, item.plan.directory);
} catch {
// Preserve the original failure. A conflicting replacement remains
// visible for explicit repair instead of being overwritten.
}
}
}
async function removeManagedWorkingTree(
projectRoot: string,
plans: readonly ManagedWorkingTreePlan[],
): Promise<RemovalResult> {
for (const plan of plans) {
await validateManagedWorkingTree(projectRoot, plan);
}
// Preserve the existing retry contract for a config directory whose final
// rmdir is denied, while ensuring this probe happens before any tree moves.
const configPlan = plans.find((plan) => plan.countRemoval);
if (configPlan?.root.children && configPlan.root.children.size > 0) {
try {
await rmdir(configPlan.directory);
throw new Error('Managed config directory changed after inspection');
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error;
}
}
const quarantined: QuarantinedWorkingTree[] = [];
try {
for (const plan of plans) {
await validateManagedWorkingTree(projectRoot, plan);
const ancestors = quarantineAncestorChain(plan);
await assertQuarantineAncestorIdentities(ancestors);
const quarantine = path.join(
path.dirname(plan.directory),
`.${path.basename(plan.directory)}.comet-uninstall-${randomUUID()}`,
);
try {
await lstat(quarantine);
throw new Error(`Uninstall quarantine already exists: ${quarantine}`);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
await rename(plan.directory, quarantine);
const item = { plan, quarantine };
quarantined.push(item);
await assertQuarantineAncestorIdentities(ancestors);
await validateQuarantinedNode(quarantine, plan.root, ancestors);
}
} catch (error) {
await rollbackQuarantinedTrees(quarantined);
throw error;
}
let removed = 0;
try {
for (const item of quarantined) {
await removeQuarantinedNode(
item.quarantine,
item.plan.root,
quarantineAncestorChain(item.plan),
);
if (item.plan.countRemoval) removed++;
}
} catch {
const remaining: QuarantinedWorkingTree[] = [];
for (const item of quarantined) {
try {
await lstat(item.quarantine);
remaining.push(item);
} catch {
// A fully removed quarantine has nothing left to restore.
}
}
await rollbackQuarantinedTrees(remaining);
return { removed, failed: 1 };
}
return { removed, failed: 0 };
}
async function removeManagedProjectConfigAfterFailedCleanup(
projectRoot: string,
expectedIdentity: WorkflowProjectConfigIdentity,
): Promise<RemovalResult> {
if (!expectedIdentity.exists) return { removed: 0, failed: 0 };
try {
const currentIdentity = await readWorkflowProjectConfigIdentity(projectRoot);
if (!workflowProjectConfigIdentityEquals(expectedIdentity, currentIdentity)) {
return { removed: 0, failed: 1 };
}
const configPath = path.join(projectRoot, '.comet', 'config.yaml');
if (!(await removeFile(configPath))) return { removed: 0, failed: 1 };
try {
await rmdir(path.dirname(configPath));
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error;
}
return { removed: 1, failed: 0 };
} catch (error) {
return {
removed: 0,
failed: 1,
reason: error instanceof Error ? error.message : String(error),
};
}
}
function retainedWorkingDirectoryContent(error: unknown, cometDir: string): string | null {
const prefix = 'Refusing to remove unknown working-directory content: ';
const message = (error as Error).message;
if (!message.startsWith(prefix)) return null;
const contentPath = message.slice(prefix.length);
return isInsideDirectory(cometDir, contentPath) ? null : contentPath;
}
async function removeManagedSkillsFromDirs(
baseDir: string,
skillsDirs: string[],
managedSkills: string[],
): Promise<RemovalResult> {
let removed = 0;
let failed = 0;
const parentDirs = new Set<string>();
for (const skillsDir of skillsDirs) {
const platformRoot = path.join(baseDir, skillsDir);
const skillsRoot = path.join(baseDir, skillsDir, 'skills');
let sharedBoundary = false;
for (const boundary of [platformRoot, skillsRoot]) {
try {
if ((await lstat(boundary)).isSymbolicLink()) {
failed++;
sharedBoundary = true;
break;
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
failed++;
sharedBoundary = true;
break;
}
}
}
if (sharedBoundary) continue;
for (const skillRelPath of managedSkills) {
try {
const parts = skillRelPath.split('/');
let current = baseDir;
let linkedAncestor = false;
const ancestorParts = [
...skillsDir.split(/[\\/]/u).filter(Boolean),
'skills',
...parts.slice(0, -1),
];
for (const part of ancestorParts) {
current = path.join(current, part);
if ((await lstat(current)).isSymbolicLink()) {
if (await removeFile(current)) removed++;
linkedAncestor = true;
break;
}
}
if (linkedAncestor) continue;
if (await removeFile(path.join(skillsRoot, ...parts))) removed++;
current = skillsRoot;
for (const part of parts.slice(0, -1)) {
current = path.join(current, part);
parentDirs.add(current);
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') failed++;
}
}
}
for (const dir of [...parentDirs].sort(
(left, right) => right.split(path.sep).length - left.split(path.sep).length,
)) {
try {
if (await isDirEmpty(dir)) await removeDir(dir);
} catch {
failed++;
}
}
return { removed, failed };
}
export async function removeLegacyCometSkillsForPlatform(
baseDir: string,
platform: Platform,
scope: InstallScope = 'project',
): Promise<RemovalResult> {
const canonicalDir = getPlatformSkillsDir(platform, scope);
const legacyDirs = getPlatformSkillsDirs(platform, scope).filter((dir) => dir !== canonicalDir);
if (legacyDirs.length === 0) return { removed: 0, failed: 0 };
const managedSkills = getManagedSkillPaths(await readManifest());
return removeManagedSkillsFromDirs(baseDir, legacyDirs, managedSkills);
}
async function removeCometSkillsForPlatform(
baseDir: string,
platform: Platform,
scope: InstallScope = 'project',
workflowsToRemove: readonly CometWorkflow[] = ['native', 'classic'],
workflowsToKeep: readonly CometWorkflow[] = [],
): Promise<RemovalResult> {
const manifest = await readManifest();
const selectionFor = (workflows: readonly CometWorkflow[]): InitWorkflowSelection =>
workflows.length === 2 ? 'both' : workflows[0]!;
const removablePaths = new Set(
getManagedSkillPathsForSelection(manifest, selectionFor(workflowsToRemove)),
);
for (const retainedPath of getManagedSkillPathsForSelection(
manifest,
workflowsToKeep.length === 0 ? 'both' : selectionFor(workflowsToKeep),
)) {
if (workflowsToKeep.length > 0) removablePaths.delete(retainedPath);
}
const managedSkills = [...removablePaths];
const skillsDir = getPlatformSkillsDir(platform, scope);
const uniqueSkillsDirs = [
...new Set([
...getPlatformSkillsDirs(platform, scope),
...(scope === 'global' && platform.id === 'pi' ? [platform.skillsDir] : []),
]),
];
const skillsRemoval = await removeManagedSkillsFromDirs(baseDir, uniqueSkillsDirs, managedSkills);
let removed = skillsRemoval.removed;
let failed = skillsRemoval.failed;
if (OPENCODE_STYLE_PLATFORM_IDS.has(platform.id)) {
const commandsDir = path.join(baseDir, skillsDir, 'commands');
for (const skillRelPath of manifest.skills.filter((path) => removablePaths.has(path))) {
const parts = skillRelPath.split('/');
if (parts.length !== 2 || parts[1] !== 'SKILL.md') continue;
const skillName = parts[0];
const commandFile = path.join(commandsDir, `${skillName}.md`);
try {
const result = await removeFile(commandFile);
if (result) {
removed++;
}
} catch {
failed++;
}
}
}
if (platform.id === 'pi') {
if (workflowsToKeep.length > 0) {
return { removed, failed };
}
const extensionsDir = path.join(baseDir, skillsDir, 'extensions');
try {
if (await removeFile(path.join(extensionsDir, 'comet-commands.ts'))) {
removed++;
}
} catch {
failed++;
}
try {
if (await isDirEmpty(extensionsDir)) {
await removeDir(extensionsDir);
}
} catch {
failed++;
}
}
return { removed, failed };
}
async function removeCometRulesForPlatform(
baseDir: string,
platform: Platform,
scope: InstallScope = 'project',
): Promise<RemovalResult> {
if (!platform.rulesDir || !platform.rulesFormat) {
return { removed: 0, failed: 0 };
}
const manifest = await readManifest();
const rulePaths = [
...(manifest.rules ?? []),
...(manifest.nativeRules ?? []),
...LEGACY_RULE_PATHS,
];
if (!rulePaths || rulePaths.length === 0) {
return { removed: 0, failed: 0 };
}
const skillsDir = getPlatformSkillsDir(platform, scope);
const rulesBase =
platform.rulesBaseDir !== undefined
? platform.rulesBaseDir === ''
? baseDir
: path.join(baseDir, platform.rulesBaseDir)
: path.join(baseDir, skillsDir);
let removed = 0;
let failed = 0;
for (const ruleRelPath of rulePaths) {
const ruleFileName = path.basename(ruleRelPath);
const rulesDestDir = path.join(rulesBase, platform.rulesDir);
const dest = computeRuleDestPath(rulesDestDir, ruleFileName, platform.rulesFormat);
try {
const result = await removeFile(dest);
if (result) {
removed++;
}
} catch {
failed++;
}
}
const rulesDestDir = path.join(rulesBase, platform.rulesDir);
try {
if (await isDirEmpty(rulesDestDir)) {
await removeDir(rulesDestDir);
}
} catch {
failed++;
}
return { removed, failed };
}
async function removeOpenSpecSkillsForPlatform(
baseDir: string,
platform: Platform,
scope: InstallScope = 'project',
): Promise<RemovalResult> {
let removed = 0;
let failed = 0;
for (const skillsDir of getPlatformSkillsDirs(platform, scope)) {
const skillsRoot = path.join(baseDir, skillsDir, 'skills');
try {
for (const entry of await readDir(skillsRoot)) {
if (!/^openspec-[a-z0-9-]+$/iu.test(entry)) continue;
if (await removeDir(path.join(skillsRoot, entry))) removed++;
}
} catch {
failed++;
}
const commandsRoot = path.join(baseDir, skillsDir, 'commands');
try {
for (const entry of await readDir(commandsRoot)) {
if (!/^(?:opsx|openspec)-[a-z0-9-]+\.[a-z0-9.]+$/iu.test(entry)) continue;
if (await removeFile(path.join(commandsRoot, entry))) removed++;
}
} catch {
failed++;
}
}
return { removed, failed };
}
async function readLockedSuperpowersSkillNames(projectPath: string): Promise<string[]> {
const lock = await readJsonObjectFile(path.join(projectPath, 'skills-lock.json'));
if (lock.status !== 'present') return [];
const skills = lock.value.skills;
if (!skills || typeof skills !== 'object' || Array.isArray(skills)) return [];
return Object.entries(skills).flatMap(([name, entry]) =>
entry &&
typeof entry === 'object' &&
!Array.isArray(entry) &&
(entry as Record<string, unknown>).source === 'obra/superpowers'
? [name]
: [],
);
}
async function removeSuperpowersSkillDirs(
baseDir: string,
platforms: readonly Platform[],
scope: InstallScope,
names: readonly string[],
): Promise<RemovalResult> {
let removed = 0;
let failed = 0;
const skillsDirs = [
...new Set(platforms.flatMap((platform) => getPlatformSkillsDirs(platform, scope))),
];
for (const skillsDir of skillsDirs) {
const platformRoot = path.join(baseDir, skillsDir);
const skillsRoot = path.join(platformRoot, 'skills');
try {
if (
(await lstat(platformRoot)).isSymbolicLink() ||
(await lstat(skillsRoot)).isSymbolicLink()
) {
failed++;
continue;
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') failed++;
continue;
}
for (const name of names) {
try {
if (await removeDir(path.join(skillsRoot, name))) removed++;
} catch {
failed++;
}
}
}
return { removed, failed };
}
async function removeSuperpowersSkillsForPlatforms(
projectPath: string,
platforms: readonly Platform[],
scope: InstallScope = 'project',
options: { removeSharedStorage?: boolean } = {},
): Promise<RemovalResult> {
const agents = [
...new Set(
platforms
.map((platform) => SKILLS_AGENT_MAP[platform.id])
.filter((agent): agent is string => Boolean(agent)),
),
];
if (agents.length === 0) return { removed: 0, failed: 0 };
const command = process.platform === 'win32' ? 'npx.cmd' : 'npx';
const scopeArgs = scope === 'global' ? ['--global'] : [];
try {
const output = execFileSync(command, ['skills', 'list', '--json', ...scopeArgs], {
cwd: projectPath,
encoding: 'utf8',
timeout: 30_000,
shell: process.platform === 'win32',
});
const listed = JSON.parse(output) as Array<{
name?: unknown;
source?: unknown;
}>;
const names = new Set([
...listed.flatMap((skill) =>
skill.source === 'obra/superpowers' && typeof skill.name === 'string' ? [skill.name] : [],
),
...(await readLockedSuperpowersSkillNames(projectPath)),
]);
let failed = 0;
for (const name of names) {
try {
execFileSync(
command,
['skills', 'remove', name, '--agent', ...agents, '--yes', ...scopeArgs],
{
cwd: projectPath,
stdio: 'ignore',
timeout: 60_000,
shell: process.platform === 'win32',
},
);
} catch {
failed++;
}
}
const baseDir = scope === 'global' ? homedir() : projectPath;
if (options.removeSharedStorage) {
const fallbackResult = await removeSuperpowersSkillDirs(baseDir, platforms, scope, [
...names,
]);
failed += fallbackResult.failed;
}
const remaining = (
await Promise.all(
[...names].map(async (name) => {
for (const platform of platforms) {
for (const skillsDir of getPlatformSkillsDirs(platform, scope)) {
if (await fileExists(path.join(baseDir, skillsDir, 'skills', name))) return true;
}
}
return false;
}),
)
).filter(Boolean).length;
if (remaining > 0) failed++;
return { removed: names.size - remaining, failed };
} catch {
return { removed: 0, failed: 1 };
}
}
async function removeCometHooksForPlatform(