crysk 0.0.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +609 -3
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +81 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,1084 @@
1
+ import crypto from "node:crypto";
2
+ import {
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ renameSync,
8
+ rmdirSync,
9
+ unlinkSync,
10
+ writeFileSync,
11
+ } from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import {
15
+ type EngineAssets,
16
+ isNpxCacheInvocation,
17
+ NPX_REGISTRATION_REFUSED,
18
+ } from "./assets";
19
+ import {
20
+ LEGACY_MCP_SERVER_KEY,
21
+ LEGACY_SKILL_NAMES,
22
+ MCP_SERVER_KEY,
23
+ SKILL_NAMES,
24
+ } from "./brand";
25
+
26
+ export type AgentEnvId =
27
+ | "claude"
28
+ | "cursor"
29
+ | "windsurf"
30
+ | "codex"
31
+ | "antigravity"
32
+ | "opencode";
33
+
34
+ export type AgentEnvStatus = "active" | "detected_inactive" | "coming_soon";
35
+
36
+ export interface AgentEnvCapabilities {
37
+ skills: boolean;
38
+ mcp: boolean;
39
+ }
40
+
41
+ export interface AgentEnvAuthStatus {
42
+ authenticated: boolean;
43
+ message: string;
44
+ tokenSource?: "env" | "file" | "session";
45
+ }
46
+
47
+ export interface AgentEnvDetection {
48
+ id: AgentEnvId;
49
+ displayName: string;
50
+ status: AgentEnvStatus;
51
+ binaryFound: boolean;
52
+ binaryPath?: string;
53
+ version?: string;
54
+ auth: AgentEnvAuthStatus;
55
+ skillsDir?: string;
56
+ mcpConfigFile?: string;
57
+ }
58
+
59
+ export interface McpRegistration {
60
+ command: string;
61
+ args: string[];
62
+ }
63
+
64
+ export interface DetectAgentEnvironmentsOptions {
65
+ home?: string;
66
+ which?: (binary: string) => string | null | Promise<string | null>;
67
+ exists?: (path: string) => boolean;
68
+ }
69
+
70
+ export interface SyncSkillsOptions {
71
+ force?: boolean;
72
+ readFile?: (path: string) => string | undefined;
73
+ writeFile?: (path: string, content: string) => Promise<void> | void;
74
+ exists?: (path: string) => boolean;
75
+ // The legacy cleanup's deletes, so a faked filesystem fakes them too.
76
+ unlink?: (path: string) => void;
77
+ rmdir?: (path: string) => void;
78
+ }
79
+
80
+ export type SkillSyncStatus =
81
+ | "installed"
82
+ | "updated"
83
+ | "current"
84
+ | "drift-kept";
85
+
86
+ export interface SkillSyncOutcome {
87
+ skill: string;
88
+ status: SkillSyncStatus;
89
+ // Set for drift-kept: why the local copy was left alone.
90
+ reason?: string;
91
+ }
92
+
93
+ // What sync did with a pre-rename skill dir once its replacement was installed.
94
+ export interface LegacySkillOutcome {
95
+ skill: string;
96
+ // removed: the dir is gone. kept: a file the user edited, or one sync never
97
+ // recorded, is still there, so the dir stays and the user is told.
98
+ status: "removed" | "kept";
99
+ reason?: string;
100
+ }
101
+
102
+ export interface SyncSkillsResult {
103
+ synced: string[];
104
+ // One outcome per bundled skill, in sync order, for this agent environment.
105
+ skills: SkillSyncOutcome[];
106
+ // Present only when an old-name dir was found.
107
+ legacy?: LegacySkillOutcome[];
108
+ upToDate?: boolean;
109
+ driftDetected?: boolean;
110
+ errors: string[];
111
+ }
112
+
113
+ const NO_DIGEST_DRIFT_REASON =
114
+ "local copy differs and has no recorded digest; not overwritten — run `crysk upgrade` to replace it with the bundled copy";
115
+
116
+ export interface RegisterMcpOptions {
117
+ readFile?: (path: string) => string | undefined;
118
+ writeFile?: (path: string, content: string) => Promise<void> | void;
119
+ exists?: (path: string) => boolean;
120
+ }
121
+
122
+ export interface RegisterMcpResult {
123
+ registered: boolean;
124
+ alreadyRegistered?: boolean;
125
+ configFile: string;
126
+ error?: string;
127
+ }
128
+
129
+ function sha256(content: string): string {
130
+ return crypto.createHash("sha256").update(content).digest("hex");
131
+ }
132
+
133
+ export async function detectAgentEnvironments(
134
+ options: DetectAgentEnvironmentsOptions = {},
135
+ ): Promise<AgentEnvDetection[]> {
136
+ const home = options.home ?? os.homedir();
137
+ const which = options.which ?? ((bin: string) => Bun.which(bin));
138
+ const exists = options.exists ?? existsSync;
139
+
140
+ const results: AgentEnvDetection[] = [];
141
+
142
+ // 1. Claude Code
143
+ const claudeBin = await which("claude");
144
+ const claudeDirExists =
145
+ exists(path.join(home, ".claude")) ||
146
+ exists(path.join(home, ".claude.json"));
147
+ if (claudeBin || claudeDirExists) {
148
+ results.push({
149
+ id: "claude",
150
+ displayName: "Claude Code",
151
+ status: "active",
152
+ binaryFound: Boolean(claudeBin),
153
+ binaryPath: claudeBin ?? undefined,
154
+ auth: { authenticated: true, message: "Detected" },
155
+ skillsDir: path.join(home, ".claude", "skills"),
156
+ mcpConfigFile: path.join(home, ".claude", "mcp.json"),
157
+ });
158
+ }
159
+
160
+ // 2. Cursor
161
+ const cursorBin = await which("cursor");
162
+ const cursorDirExists =
163
+ exists(path.join(home, ".cursor")) ||
164
+ exists(path.join(home, ".config", "cursor"));
165
+ if (cursorBin || cursorDirExists) {
166
+ results.push({
167
+ id: "cursor",
168
+ displayName: "Cursor",
169
+ status: "active",
170
+ binaryFound: Boolean(cursorBin),
171
+ binaryPath: cursorBin ?? undefined,
172
+ auth: { authenticated: true, message: "Detected" },
173
+ skillsDir: path.join(home, ".cursor", "skills"),
174
+ mcpConfigFile: path.join(home, ".cursor", "mcp.json"),
175
+ });
176
+ }
177
+
178
+ // 3. Windsurf
179
+ const windsurfBin = await which("windsurf");
180
+ const windsurfDirExists =
181
+ exists(path.join(home, ".windsurf")) ||
182
+ exists(path.join(home, ".codeium", "windsurf"));
183
+ if (windsurfBin || windsurfDirExists) {
184
+ results.push({
185
+ id: "windsurf",
186
+ displayName: "Windsurf",
187
+ status: "active",
188
+ binaryFound: Boolean(windsurfBin),
189
+ binaryPath: windsurfBin ?? undefined,
190
+ auth: { authenticated: true, message: "Detected" },
191
+ skillsDir: path.join(home, ".windsurf", "skills"),
192
+ mcpConfigFile: path.join(home, ".windsurf", "mcp.json"),
193
+ });
194
+ }
195
+
196
+ // 4. Codex
197
+ const codexBin = await which("codex");
198
+ const codexDirExists =
199
+ exists(path.join(home, ".codex")) ||
200
+ exists(path.join(home, ".config", "codex"));
201
+ if (codexBin || codexDirExists) {
202
+ results.push({
203
+ id: "codex",
204
+ displayName: "OpenAI Codex CLI",
205
+ status: "active",
206
+ binaryFound: Boolean(codexBin),
207
+ binaryPath: codexBin ?? undefined,
208
+ auth: { authenticated: true, message: "Detected" },
209
+ skillsDir: path.join(home, ".codex", "skills"),
210
+ mcpConfigFile: path.join(home, ".codex", "mcp.json"),
211
+ });
212
+ }
213
+
214
+ // 5. Antigravity / Gemini
215
+ const agyBin = (await which("antigravity")) || (await which("agy"));
216
+ const agyDirExists =
217
+ exists(path.join(home, ".gemini")) ||
218
+ exists(path.join(home, ".antigravity"));
219
+ if (agyBin || agyDirExists) {
220
+ results.push({
221
+ id: "antigravity",
222
+ displayName: "Antigravity",
223
+ status: "active",
224
+ binaryFound: Boolean(agyBin),
225
+ binaryPath: agyBin ?? undefined,
226
+ auth: { authenticated: true, message: "Detected" },
227
+ skillsDir: exists(path.join(home, ".gemini", "config", "skills"))
228
+ ? path.join(home, ".gemini", "config", "skills")
229
+ : path.join(home, ".antigravity", "skills"),
230
+ mcpConfigFile: path.join(home, ".antigravity", "mcp.json"),
231
+ });
232
+ }
233
+
234
+ // 6. OpenCode
235
+ const opencodeBin = await which("opencode");
236
+ const opencodeDirExists =
237
+ exists(path.join(home, ".opencode")) ||
238
+ exists(path.join(home, ".config", "opencode"));
239
+ if (opencodeBin || opencodeDirExists) {
240
+ results.push({
241
+ id: "opencode",
242
+ displayName: "OpenCode",
243
+ status: "active",
244
+ binaryFound: Boolean(opencodeBin),
245
+ binaryPath: opencodeBin ?? undefined,
246
+ auth: { authenticated: true, message: "Detected" },
247
+ skillsDir: path.join(home, ".opencode", "skills"),
248
+ mcpConfigFile: path.join(home, ".opencode", "mcp.json"),
249
+ });
250
+ }
251
+
252
+ return results;
253
+ }
254
+
255
+ type SkillRole = keyof typeof SKILL_NAMES;
256
+
257
+ interface BundledSkill {
258
+ role: SkillRole;
259
+ name: string;
260
+ files: Record<string, string>;
261
+ }
262
+
263
+ // The skills this build ships, in sync order, named once for sync and inspect.
264
+ // The triage skill is always shipped; the others only when their asset list is
265
+ // filled, as an engine build without them must not install an empty dir.
266
+ function bundledSkills(assets: EngineAssets): BundledSkill[] {
267
+ const byRole: Record<SkillRole, Record<string, string> | undefined> = {
268
+ triage: assets.triageSkillFiles,
269
+ ciSetup: assets.ciSetupSkillFiles,
270
+ pr: assets.prSkillFiles,
271
+ general: assets.generalSkillFiles,
272
+ };
273
+ const skills: BundledSkill[] = [];
274
+ for (const role of Object.keys(SKILL_NAMES) as SkillRole[]) {
275
+ const files = byRole[role];
276
+ if (!files) continue;
277
+ if (role !== "triage" && Object.keys(files).length === 0) continue;
278
+ skills.push({ role, name: SKILL_NAMES[role], files });
279
+ }
280
+ return skills;
281
+ }
282
+
283
+ interface SkillDirIo {
284
+ exists: (path: string) => boolean;
285
+ readFile: (path: string) => string | undefined;
286
+ unlink?: (path: string) => void;
287
+ rmdir?: (path: string) => void;
288
+ // Delete nothing unless every recorded file still matches its digest. The legacy
289
+ // cleanup needs it: removing the untouched files of an edited skill leaves a
290
+ // SKILL.md that points at files that are gone.
291
+ allOrNothing?: boolean;
292
+ }
293
+
294
+ export interface RemoveSkillDirResult {
295
+ removed: string[];
296
+ skippedModified: string[];
297
+ // Recorded files still on disk because they could not be read or unlinked. Their
298
+ // digest is kept, so a later run can retry them.
299
+ failed: string[];
300
+ errors: string[];
301
+ // False when anything is left in the dir: an edited file, or a copy with no
302
+ // recorded digest. Nothing here ever deletes a dir recursively.
303
+ dirRemoved: boolean;
304
+ }
305
+
306
+ // Removes the files a skill dir's digest.json recorded, but only those still
307
+ // equal to their recorded hash; an edited file is skipped and keeps its dir.
308
+ // The dir itself goes only if that left it empty (a non-recursive rmdir).
309
+ export function removeSkillDir(
310
+ targetDir: string,
311
+ io: SkillDirIo,
312
+ ): RemoveSkillDirResult {
313
+ const unlink = io.unlink ?? unlinkSync;
314
+ const rmdir = io.rmdir ?? rmdirSync;
315
+ const digestFile = path.join(targetDir, "digest.json");
316
+ const removed: string[] = [];
317
+ const skippedModified: string[] = [];
318
+ const errors: string[] = [];
319
+
320
+ let digest: { files?: Record<string, string> } | undefined;
321
+ if (io.exists(digestFile)) {
322
+ try {
323
+ const raw = io.readFile(digestFile);
324
+ if (raw) digest = JSON.parse(raw);
325
+ } catch {
326
+ // Ignored
327
+ }
328
+ }
329
+
330
+ let skillSkippedModified = false;
331
+ // Recorded files still on disk after this pass: unreadable, or their unlink failed.
332
+ const failed: string[] = [];
333
+ const subdirs = new Set<string>();
334
+ if (io.allOrNothing && digest?.files) {
335
+ const edited: string[] = [];
336
+ const unreadable: string[] = [];
337
+ for (const [logicalName, hash] of Object.entries(digest.files)) {
338
+ const filePath = path.join(targetDir, logicalName);
339
+ if (!io.exists(filePath)) continue;
340
+ const content = io.readFile(filePath);
341
+ if (content === undefined) unreadable.push(logicalName);
342
+ else if (sha256(content) !== hash) edited.push(logicalName);
343
+ }
344
+ if (edited.length > 0 || unreadable.length > 0) {
345
+ return {
346
+ removed: [],
347
+ skippedModified: edited,
348
+ failed: unreadable,
349
+ errors: [],
350
+ dirRemoved: false,
351
+ };
352
+ }
353
+ }
354
+ if (digest?.files) {
355
+ for (const [logicalName, expectedHash] of Object.entries(digest.files)) {
356
+ const filePath = path.join(targetDir, logicalName);
357
+ if (!io.exists(filePath)) continue;
358
+
359
+ const content = io.readFile(filePath);
360
+ if (content === undefined) {
361
+ failed.push(logicalName);
362
+ continue;
363
+ }
364
+
365
+ if (sha256(content) === expectedHash) {
366
+ try {
367
+ unlink(filePath);
368
+ removed.push(logicalName);
369
+ for (
370
+ let dir = path.dirname(filePath);
371
+ dir !== targetDir && dir.startsWith(targetDir);
372
+ dir = path.dirname(dir)
373
+ ) {
374
+ subdirs.add(dir);
375
+ }
376
+ } catch (err) {
377
+ failed.push(logicalName);
378
+ errors.push(
379
+ `Failed to remove ${filePath}: ${(err as Error).message}`,
380
+ );
381
+ }
382
+ } else {
383
+ skippedModified.push(logicalName);
384
+ skillSkippedModified = true;
385
+ }
386
+ }
387
+ }
388
+
389
+ // The digest goes only once every recorded file is gone: it is the only record that
390
+ // makes a leftover provably removable on a later run.
391
+ if (!skillSkippedModified && failed.length === 0 && io.exists(digestFile)) {
392
+ try {
393
+ unlink(digestFile);
394
+ removed.push("digest.json");
395
+ } catch (err) {
396
+ errors.push(`Failed to remove ${digestFile}: ${(err as Error).message}`);
397
+ }
398
+ }
399
+
400
+ // Emptied subdirs (assets/, references/), deepest first, then the skill dir.
401
+ // A non-empty one throws and stays: that is the point of not recursing.
402
+ const dirs = [...subdirs].sort((a, b) => b.length - a.length);
403
+ for (const dir of dirs) {
404
+ try {
405
+ rmdir(dir);
406
+ } catch {
407
+ // Not empty: something the digest did not cover is in there.
408
+ }
409
+ }
410
+ let dirRemoved = false;
411
+ try {
412
+ rmdir(targetDir);
413
+ dirRemoved = true;
414
+ } catch {
415
+ // Not empty, or already gone.
416
+ }
417
+
418
+ return { removed, skippedModified, failed, errors, dirRemoved };
419
+ }
420
+
421
+ // Every dir name a skill may sit under on disk: current names, then old ones.
422
+ // The uninstaller plans from this too, so it cleans both generations.
423
+ export function allSkillDirNames(): string[] {
424
+ return [...Object.values(SKILL_NAMES), ...Object.values(LEGACY_SKILL_NAMES)];
425
+ }
426
+
427
+ function legacyKeptReason(res: RemoveSkillDirResult): string {
428
+ const parts: string[] = [];
429
+ if (res.skippedModified.length > 0) {
430
+ parts.push(`edited ${res.skippedModified.join(", ")} kept`);
431
+ }
432
+ if (res.failed.length > 0) {
433
+ parts.push(
434
+ `${res.failed.join(", ")} could not be read or removed (digest kept for a retry)`,
435
+ );
436
+ }
437
+ return parts.length > 0
438
+ ? parts.join("; ")
439
+ : "files with no recorded digest kept";
440
+ }
441
+
442
+ // Decision table for each bundled skill in an agent's skills dir. The disk and
443
+ // the digest.json recorded by the last sync decide, file by file:
444
+ //
445
+ // file on disk | recorded digest for the file | action
446
+ // ---------------------+------------------------------+------------------------------------
447
+ // missing | (any) | write it
448
+ // equals the bundle | (any) | nothing to write
449
+ // differs from bundle | none (no digest recorded) | keep it: drift-kept unless force
450
+ // differs from bundle | == disk hash (untouched) | overwrite it: updated
451
+ // differs from bundle | != disk hash (user edited) | keep it: drift-kept unless force
452
+ //
453
+ // `force` overwrites every differing file. A skill with any kept file is
454
+ // drift-kept as a whole and nothing of it is written, so one skill never ends up
455
+ // half one version and half another. A skill whose files all match the bundle
456
+ // and that has no digest records one (writing only digest.json) and reports
457
+ // current; that is how a pre-digest install becomes protected. A kept file never
458
+ // gets a digest recorded over it: that would make the user's bytes look like the
459
+ // product of a sync, and the next sync would overwrite them.
460
+ export async function syncSkills(
461
+ env: AgentEnvDetection,
462
+ assets: EngineAssets,
463
+ options: SyncSkillsOptions = {},
464
+ ): Promise<SyncSkillsResult> {
465
+ if (!env.skillsDir) {
466
+ return {
467
+ synced: [],
468
+ skills: [],
469
+ errors: ["No skills directory resolved for environment"],
470
+ };
471
+ }
472
+
473
+ const exists = options.exists ?? existsSync;
474
+ const readFile =
475
+ options.readFile ??
476
+ ((p: string) => {
477
+ try {
478
+ return readFileSync(p, "utf-8");
479
+ } catch {
480
+ return undefined;
481
+ }
482
+ });
483
+ const writeFile =
484
+ options.writeFile ??
485
+ ((p: string, c: string) => {
486
+ mkdirSync(path.dirname(p), { recursive: true });
487
+ writeFileSync(p, c, "utf-8");
488
+ });
489
+
490
+ const skillsToSync = bundledSkills(assets);
491
+ const allSynced: string[] = [];
492
+ const allErrors: string[] = [];
493
+ const outcomes: SkillSyncOutcome[] = [];
494
+ let driftDetected = false;
495
+
496
+ for (const skill of skillsToSync) {
497
+ const targetDir = path.join(env.skillsDir, skill.name);
498
+ const digestFile = path.join(targetDir, "digest.json");
499
+
500
+ // 1. Read existing digest
501
+ let existingDigest:
502
+ | { files?: Record<string, string>; engine_version?: string }
503
+ | undefined;
504
+ if (exists(digestFile)) {
505
+ try {
506
+ const raw = readFile(digestFile);
507
+ if (raw) existingDigest = JSON.parse(raw);
508
+ } catch {
509
+ // Ignored
510
+ }
511
+ }
512
+
513
+ // 2. Read upstream assets and check hashes
514
+ const upstreamContents: Record<string, string> = {};
515
+ const upstreamHashes: Record<string, string> = {};
516
+
517
+ for (const [logicalName, srcPath] of Object.entries(skill.files)) {
518
+ const content = readFile(srcPath);
519
+ if (content === undefined) {
520
+ return {
521
+ synced: [],
522
+ skills: outcomes,
523
+ errors: [`Missing upstream asset for ${logicalName} at ${srcPath}`],
524
+ };
525
+ }
526
+ upstreamContents[logicalName] = content;
527
+ upstreamHashes[logicalName] = sha256(content);
528
+ }
529
+
530
+ // 3. Classify each file by the decision table above
531
+ let toWrite: string[] = [];
532
+ const keptReasons: string[] = [];
533
+ const existed = new Set<string>();
534
+ let fullyCurrent = true;
535
+ for (const [logicalName, upstreamHash] of Object.entries(upstreamHashes)) {
536
+ const destFile = path.join(targetDir, logicalName);
537
+ if (!exists(destFile)) {
538
+ toWrite.push(logicalName);
539
+ fullyCurrent = false;
540
+ continue;
541
+ }
542
+
543
+ const diskContent = readFile(destFile);
544
+ if (diskContent === undefined) {
545
+ toWrite.push(logicalName);
546
+ fullyCurrent = false;
547
+ continue;
548
+ }
549
+ existed.add(logicalName);
550
+
551
+ const diskHash = sha256(diskContent);
552
+ if (diskHash === upstreamHash) continue;
553
+ fullyCurrent = false;
554
+
555
+ // The recorded hash is the disk hash of the last sync: equal means the
556
+ // file was never edited since, so upstream may replace it safely.
557
+ const recordedHash = existingDigest?.files?.[logicalName];
558
+ if (options.force || recordedHash === diskHash) {
559
+ toWrite.push(logicalName);
560
+ continue;
561
+ }
562
+
563
+ // A user edit since the last sync, or a copy that was never recorded.
564
+ const reason = existingDigest
565
+ ? `Local edits detected in ${destFile}. Pass force to overwrite.`
566
+ : NO_DIGEST_DRIFT_REASON;
567
+ keptReasons.push(reason);
568
+ allErrors.push(existingDigest ? reason : `${destFile}: ${reason}`);
569
+ }
570
+
571
+ // force overwrites everything: a skill that is not already fully current
572
+ // is rewritten whole, the same as before the decision table existed.
573
+ if (options.force && !(fullyCurrent && existingDigest)) {
574
+ toWrite = Object.keys(upstreamHashes);
575
+ }
576
+
577
+ if (keptReasons.length > 0) {
578
+ driftDetected = true;
579
+ outcomes.push({
580
+ skill: skill.name,
581
+ status: "drift-kept",
582
+ reason: keptReasons[0],
583
+ });
584
+ continue;
585
+ }
586
+
587
+ // 4. Nothing to write: record the digest of a copy that already matches
588
+ if (toWrite.length === 0) {
589
+ if (!existingDigest) {
590
+ const digest = {
591
+ files: upstreamHashes,
592
+ synced_at: new Date().toISOString(),
593
+ engine_version: assets.version,
594
+ };
595
+ await writeFile(digestFile, `${JSON.stringify(digest, null, 2)}\n`);
596
+ }
597
+ outcomes.push({ skill: skill.name, status: "current" });
598
+ continue;
599
+ }
600
+
601
+ // 5. Write the files that need it, then the digest
602
+ for (const logicalName of toWrite) {
603
+ await writeFile(
604
+ path.join(targetDir, logicalName),
605
+ upstreamContents[logicalName],
606
+ );
607
+ allSynced.push(logicalName);
608
+ }
609
+
610
+ const newDigest = {
611
+ files: upstreamHashes,
612
+ synced_at: new Date().toISOString(),
613
+ engine_version: assets.version,
614
+ };
615
+ await writeFile(digestFile, `${JSON.stringify(newDigest, null, 2)}\n`);
616
+ outcomes.push({
617
+ skill: skill.name,
618
+ status: existed.size === 0 ? "installed" : "updated",
619
+ });
620
+ }
621
+
622
+ const upToDate =
623
+ !driftDetected &&
624
+ allSynced.length === 0 &&
625
+ outcomes.every((o) => o.status === "current");
626
+
627
+ // An old-name dir goes only once the skill of the same role stands under the
628
+ // new name; while the new copy is kept for the user's edits, the old one
629
+ // keeps serving. Removal is digest-gated, so an edited file survives.
630
+ const standing = new Set(
631
+ outcomes.filter((o) => o.status !== "drift-kept").map((o) => o.skill),
632
+ );
633
+ const legacy: LegacySkillOutcome[] = [];
634
+ for (const skill of skillsToSync) {
635
+ if (!standing.has(skill.name)) continue;
636
+ const legacyName = LEGACY_SKILL_NAMES[skill.role];
637
+ const legacyDir = path.join(env.skillsDir, legacyName);
638
+ if (!exists(legacyDir)) continue;
639
+ const res = removeSkillDir(legacyDir, {
640
+ exists,
641
+ readFile,
642
+ allOrNothing: true,
643
+ ...(options.unlink ? { unlink: options.unlink } : {}),
644
+ ...(options.rmdir ? { rmdir: options.rmdir } : {}),
645
+ });
646
+ allErrors.push(...res.errors);
647
+ legacy.push({
648
+ skill: legacyName,
649
+ status: res.dirRemoved ? "removed" : "kept",
650
+ ...(res.dirRemoved ? {} : { reason: legacyKeptReason(res) }),
651
+ });
652
+ }
653
+
654
+ return {
655
+ synced: allSynced,
656
+ skills: outcomes,
657
+ ...(legacy.length > 0 ? { legacy } : {}),
658
+ ...(upToDate ? { upToDate: true } : {}),
659
+ ...(driftDetected ? { driftDetected: true } : {}),
660
+ errors: allErrors,
661
+ };
662
+ }
663
+
664
+ // Reports whether the skills read as synced. A copy without a recorded digest is
665
+ // not synced yet (the next sync records it), and a differing copy that is not
666
+ // the untouched recorded one is drift: the same rule syncSkills applies.
667
+ //
668
+ // `legacy` names each pre-rename dir still on disk (sync keeps one the user
669
+ // edited), so a leftover is visible; it never changes `synced`.
670
+ export function inspectSkillsSync(
671
+ env: AgentEnvDetection,
672
+ assets: EngineAssets,
673
+ options: {
674
+ exists?: (p: string) => boolean;
675
+ readFile?: (p: string) => string | undefined;
676
+ } = {},
677
+ ): { synced: boolean; drift: boolean; legacy: string[] } {
678
+ const skillsDir = env.skillsDir;
679
+ if (!skillsDir) return { synced: false, drift: false, legacy: [] };
680
+ const exists = options.exists ?? existsSync;
681
+ const legacy = Object.values(LEGACY_SKILL_NAMES).filter((name) =>
682
+ exists(path.join(skillsDir, name)),
683
+ );
684
+ return { ...inspectBundledSkills(env, assets, options), legacy };
685
+ }
686
+
687
+ function inspectBundledSkills(
688
+ env: AgentEnvDetection,
689
+ assets: EngineAssets,
690
+ options: {
691
+ exists?: (p: string) => boolean;
692
+ readFile?: (p: string) => string | undefined;
693
+ },
694
+ ): { synced: boolean; drift: boolean } {
695
+ if (!env.skillsDir) return { synced: false, drift: false };
696
+ const exists = options.exists ?? existsSync;
697
+ const readFile =
698
+ options.readFile ??
699
+ ((p: string) => {
700
+ try {
701
+ return readFileSync(p, "utf-8");
702
+ } catch {
703
+ return undefined;
704
+ }
705
+ });
706
+
707
+ const skillsToCheck = bundledSkills(assets);
708
+ let everyDigestRecorded = true;
709
+ for (const skill of skillsToCheck) {
710
+ const targetDir = path.join(env.skillsDir, skill.name);
711
+ const digestFile = path.join(targetDir, "digest.json");
712
+
713
+ let existingDigest: { files?: Record<string, string> } | undefined;
714
+ if (exists(digestFile)) {
715
+ try {
716
+ const raw = readFile(digestFile);
717
+ if (raw) existingDigest = JSON.parse(raw);
718
+ } catch {
719
+ return { synced: false, drift: false };
720
+ }
721
+ } else {
722
+ everyDigestRecorded = false;
723
+ }
724
+
725
+ for (const [logicalName, srcPath] of Object.entries(skill.files)) {
726
+ const destFile = path.join(targetDir, logicalName);
727
+ if (!exists(destFile)) return { synced: false, drift: false };
728
+
729
+ const srcContent = readFile(srcPath);
730
+ const destContent = readFile(destFile);
731
+ if (!srcContent || !destContent) return { synced: false, drift: false };
732
+
733
+ const diskHash = sha256(destContent);
734
+ const upstreamHash = sha256(srcContent);
735
+ if (diskHash === upstreamHash) continue;
736
+
737
+ const recordedHash = existingDigest?.files?.[logicalName];
738
+ if (diskHash !== recordedHash) {
739
+ return { synced: false, drift: true };
740
+ }
741
+ return { synced: false, drift: false };
742
+ }
743
+ }
744
+
745
+ return { synced: everyDigestRecorded, drift: false };
746
+ }
747
+
748
+ export async function registerMcpServer(
749
+ env: AgentEnvDetection,
750
+ reg: McpRegistration,
751
+ options: RegisterMcpOptions = {},
752
+ ): Promise<RegisterMcpResult> {
753
+ if (!env.mcpConfigFile) {
754
+ return {
755
+ registered: false,
756
+ configFile: "",
757
+ error: "No MCP configuration file path resolved for environment",
758
+ };
759
+ }
760
+ if (isNpxCacheInvocation({ command: reg.command, args: reg.args })) {
761
+ return {
762
+ registered: false,
763
+ configFile: env.mcpConfigFile,
764
+ error: NPX_REGISTRATION_REFUSED,
765
+ };
766
+ }
767
+
768
+ const configFile = env.mcpConfigFile;
769
+ const exists = options.exists ?? existsSync;
770
+ const readFile =
771
+ options.readFile ??
772
+ ((p: string) => {
773
+ try {
774
+ return readFileSync(p, "utf-8");
775
+ } catch {
776
+ return undefined;
777
+ }
778
+ });
779
+ const writeFile =
780
+ options.writeFile ??
781
+ ((p: string, c: string) => {
782
+ mkdirSync(path.dirname(p), { recursive: true });
783
+ const tmpPath = `${p}.tmp.${Date.now()}`;
784
+ writeFileSync(tmpPath, c, "utf-8");
785
+ try {
786
+ renameSync(tmpPath, p);
787
+ } catch (err) {
788
+ try {
789
+ if (existsSync(tmpPath)) {
790
+ unlinkSync(tmpPath);
791
+ }
792
+ } catch {
793
+ // ignore cleanup error
794
+ }
795
+ throw err;
796
+ }
797
+ });
798
+
799
+ if (exists(configFile)) {
800
+ try {
801
+ const stat = lstatSync(configFile);
802
+ if (stat.isSymbolicLink()) {
803
+ return {
804
+ registered: false,
805
+ configFile,
806
+ error: `Refusing to edit symlinked MCP config file: ${configFile}`,
807
+ };
808
+ }
809
+ } catch {
810
+ // ignore
811
+ }
812
+ }
813
+
814
+ let config: {
815
+ mcpServers?: Record<string, Record<string, unknown>>;
816
+ } = {};
817
+
818
+ if (exists(configFile)) {
819
+ const raw = readFile(configFile);
820
+ if (raw && raw.trim().length > 0) {
821
+ try {
822
+ config = JSON.parse(raw);
823
+ } catch (err) {
824
+ return {
825
+ registered: false,
826
+ configFile,
827
+ error: `Failed to parse existing MCP config at ${configFile}: ${(err as Error).message}`,
828
+ };
829
+ }
830
+ }
831
+ }
832
+
833
+ if (!config.mcpServers) {
834
+ config.mcpServers = {};
835
+ }
836
+
837
+ const current = config.mcpServers[MCP_SERVER_KEY];
838
+ const legacy = config.mcpServers[LEGACY_MCP_SERVER_KEY];
839
+ // A leftover legacy entry is not "already registered": it still has to go.
840
+ if (matchesRegistration(current, reg) && legacy === undefined) {
841
+ return {
842
+ registered: true,
843
+ alreadyRegistered: true,
844
+ configFile,
845
+ };
846
+ }
847
+
848
+ // Backup original config if it existed
849
+ if (exists(configFile)) {
850
+ const raw = readFile(configFile);
851
+ if (raw) {
852
+ await writeFile(`${configFile}.bak`, raw);
853
+ }
854
+ }
855
+
856
+ // The legacy entry moves to the new key in this one write. Its fields the
857
+ // registration does not own (env, timeout, disabled...) are the user's
858
+ // edits, so they carry over; command and args come from the registration.
859
+ config.mcpServers[MCP_SERVER_KEY] = {
860
+ ...asRecord(legacy),
861
+ ...asRecord(current),
862
+ command: reg.command,
863
+ args: reg.args,
864
+ };
865
+ delete config.mcpServers[LEGACY_MCP_SERVER_KEY];
866
+
867
+ await writeFile(configFile, `${JSON.stringify(config, null, 2)}\n`);
868
+
869
+ return {
870
+ registered: true,
871
+ configFile,
872
+ };
873
+ }
874
+
875
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
876
+ return typeof value === "object" && value !== null && !Array.isArray(value)
877
+ ? (value as Record<string, unknown>)
878
+ : undefined;
879
+ }
880
+
881
+ function matchesRegistration(entry: unknown, reg: McpRegistration): boolean {
882
+ const server = asRecord(entry);
883
+ return (
884
+ server !== undefined &&
885
+ server.command === reg.command &&
886
+ JSON.stringify(server.args) === JSON.stringify(reg.args)
887
+ );
888
+ }
889
+
890
+ // "legacy" is registered and working, but under the pre-rename key; setup
891
+ // moves it.
892
+ export function inspectMcpRegistration(
893
+ env: AgentEnvDetection,
894
+ reg: McpRegistration,
895
+ options: {
896
+ exists?: (p: string) => boolean;
897
+ readFile?: (p: string) => string | undefined;
898
+ } = {},
899
+ ): "current" | "legacy" | "missing" {
900
+ if (!env.mcpConfigFile) return "missing";
901
+ const exists = options.exists ?? existsSync;
902
+ const readFile =
903
+ options.readFile ??
904
+ ((p: string) => {
905
+ try {
906
+ return readFileSync(p, "utf-8");
907
+ } catch {
908
+ return undefined;
909
+ }
910
+ });
911
+
912
+ if (!exists(env.mcpConfigFile)) return "missing";
913
+ try {
914
+ const raw = readFile(env.mcpConfigFile);
915
+ if (!raw) return "missing";
916
+ const servers = asRecord(JSON.parse(raw)?.mcpServers);
917
+ // A leftover legacy key next to a matching new one is still a migration to do,
918
+ // exactly as registerMcpServer sees it.
919
+ if (matchesRegistration(servers?.[MCP_SERVER_KEY], reg)) {
920
+ return servers?.[LEGACY_MCP_SERVER_KEY] === undefined
921
+ ? "current"
922
+ : "legacy";
923
+ }
924
+ if (matchesRegistration(servers?.[LEGACY_MCP_SERVER_KEY], reg)) {
925
+ return "legacy";
926
+ }
927
+ return "missing";
928
+ } catch {
929
+ return "missing";
930
+ }
931
+ }
932
+
933
+ // Deletes the one entry a caller named (another server's). True when it was there.
934
+ function removeOneMcpServer(config: unknown, key: string): boolean {
935
+ const servers = asRecord(asRecord(config)?.mcpServers);
936
+ if (!servers || !(key in servers)) return false;
937
+ delete servers[key];
938
+ return true;
939
+ }
940
+
941
+ // Deletes this product's entry under both its keys, so an unregister or an
942
+ // uninstall leaves nothing of either generation. True when something was removed.
943
+ export function removeMcpServerEntries(config: unknown): boolean {
944
+ const servers = asRecord(asRecord(config)?.mcpServers);
945
+ if (!servers) return false;
946
+ let removed = false;
947
+ for (const key of [MCP_SERVER_KEY, LEGACY_MCP_SERVER_KEY]) {
948
+ if (key in servers) {
949
+ delete servers[key];
950
+ removed = true;
951
+ }
952
+ }
953
+ return removed;
954
+ }
955
+
956
+ export interface UnregisterMcpOptions {
957
+ readFile?: (path: string) => string | undefined;
958
+ writeFile?: (path: string, content: string) => Promise<void> | void;
959
+ exists?: (path: string) => boolean;
960
+ }
961
+
962
+ export interface UnregisterMcpResult {
963
+ unregistered: boolean;
964
+ configFile?: string;
965
+ error?: string;
966
+ }
967
+
968
+ // With no name, removes this product's entry under both keys. A caller naming
969
+ // another server removes only that one.
970
+ export async function unregisterMcpServer(
971
+ env: AgentEnvDetection,
972
+ serverName?: string,
973
+ options: UnregisterMcpOptions = {},
974
+ ): Promise<UnregisterMcpResult> {
975
+ if (!env.mcpConfigFile) {
976
+ return {
977
+ unregistered: false,
978
+ error: "No MCP config file resolved for environment",
979
+ };
980
+ }
981
+
982
+ const exists = options.exists ?? existsSync;
983
+ const readFile =
984
+ options.readFile ??
985
+ ((p: string) => {
986
+ try {
987
+ return readFileSync(p, "utf-8");
988
+ } catch {
989
+ return undefined;
990
+ }
991
+ });
992
+ const writeFile =
993
+ options.writeFile ??
994
+ ((p: string, c: string) => {
995
+ writeFileSync(p, c, "utf-8");
996
+ });
997
+
998
+ if (!exists(env.mcpConfigFile)) {
999
+ return { unregistered: true, configFile: env.mcpConfigFile };
1000
+ }
1001
+
1002
+ try {
1003
+ const raw = readFile(env.mcpConfigFile);
1004
+ if (!raw) return { unregistered: true, configFile: env.mcpConfigFile };
1005
+ const config = JSON.parse(raw);
1006
+ const removed =
1007
+ serverName === undefined ||
1008
+ serverName === MCP_SERVER_KEY ||
1009
+ serverName === LEGACY_MCP_SERVER_KEY
1010
+ ? removeMcpServerEntries(config)
1011
+ : removeOneMcpServer(config, serverName);
1012
+ if (removed) {
1013
+ await writeFile(
1014
+ env.mcpConfigFile,
1015
+ `${JSON.stringify(config, null, 2)}\n`,
1016
+ );
1017
+ }
1018
+ return { unregistered: true, configFile: env.mcpConfigFile };
1019
+ } catch (error) {
1020
+ return {
1021
+ unregistered: false,
1022
+ configFile: env.mcpConfigFile,
1023
+ error: `Failed to update MCP config: ${(error as Error).message}`,
1024
+ };
1025
+ }
1026
+ }
1027
+
1028
+ export interface RemoveSkillsOptions {
1029
+ exists?: (path: string) => boolean;
1030
+ readFile?: (path: string) => string | undefined;
1031
+ unlink?: (path: string) => void;
1032
+ rmdir?: (path: string) => void;
1033
+ }
1034
+
1035
+ export interface RemoveSkillsResult {
1036
+ removed: string[];
1037
+ skippedModified: string[];
1038
+ errors: string[];
1039
+ }
1040
+
1041
+ // Removes every bundled skill under its current and its pre-rename name.
1042
+ export async function removeSkills(
1043
+ env: AgentEnvDetection,
1044
+ options: RemoveSkillsOptions = {},
1045
+ ): Promise<RemoveSkillsResult> {
1046
+ if (!env.skillsDir) {
1047
+ return {
1048
+ removed: [],
1049
+ skippedModified: [],
1050
+ errors: ["No skills directory resolved for environment"],
1051
+ };
1052
+ }
1053
+
1054
+ const exists = options.exists ?? existsSync;
1055
+ const io: SkillDirIo = {
1056
+ exists,
1057
+ readFile:
1058
+ options.readFile ??
1059
+ ((p: string) => {
1060
+ try {
1061
+ return readFileSync(p, "utf-8");
1062
+ } catch {
1063
+ return undefined;
1064
+ }
1065
+ }),
1066
+ unlink: options.unlink,
1067
+ rmdir: options.rmdir,
1068
+ };
1069
+
1070
+ const result: RemoveSkillsResult = {
1071
+ removed: [],
1072
+ skippedModified: [],
1073
+ errors: [],
1074
+ };
1075
+ for (const name of allSkillDirNames()) {
1076
+ const targetDir = path.join(env.skillsDir, name);
1077
+ if (!exists(targetDir)) continue;
1078
+ const res = removeSkillDir(targetDir, io);
1079
+ result.removed.push(...res.removed);
1080
+ result.skippedModified.push(...res.skippedModified);
1081
+ result.errors.push(...res.errors);
1082
+ }
1083
+ return result;
1084
+ }