@ai-primitives-hub/app 0.2.0 → 0.2.2-next.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 (325) hide show
  1. package/README.md +5 -1
  2. package/dist/collection/affected-collections.d.ts +11 -0
  3. package/dist/collection/affected-collections.d.ts.map +1 -0
  4. package/dist/collection/affected-collections.js +90 -0
  5. package/dist/collection/affected-collections.js.map +1 -0
  6. package/dist/collection/create-plugin.d.ts +35 -0
  7. package/dist/collection/create-plugin.d.ts.map +1 -0
  8. package/dist/collection/create-plugin.js +118 -0
  9. package/dist/collection/create-plugin.js.map +1 -0
  10. package/dist/collection/index.d.ts +4 -2
  11. package/dist/collection/index.d.ts.map +1 -1
  12. package/dist/collection/index.js +8 -4
  13. package/dist/collection/index.js.map +1 -1
  14. package/dist/collection/kind-route-warning.d.ts +13 -0
  15. package/dist/collection/kind-route-warning.d.ts.map +1 -0
  16. package/dist/collection/kind-route-warning.js +40 -0
  17. package/dist/collection/kind-route-warning.js.map +1 -0
  18. package/dist/collection/plugin-item-issues.d.ts +36 -0
  19. package/dist/collection/plugin-item-issues.d.ts.map +1 -0
  20. package/dist/collection/plugin-item-issues.js +31 -0
  21. package/dist/collection/plugin-item-issues.js.map +1 -0
  22. package/dist/collection/read-collection.d.ts +1 -1
  23. package/dist/collection/read-collection.d.ts.map +1 -1
  24. package/dist/collection/read-collection.js +14 -15
  25. package/dist/collection/read-collection.js.map +1 -1
  26. package/dist/collection-editor/collection-contribution-workflow.d.ts +96 -0
  27. package/dist/collection-editor/collection-contribution-workflow.d.ts.map +1 -0
  28. package/dist/collection-editor/collection-contribution-workflow.js +479 -0
  29. package/dist/collection-editor/collection-contribution-workflow.js.map +1 -0
  30. package/dist/collection-editor/collection-editor-service.d.ts +232 -0
  31. package/dist/collection-editor/collection-editor-service.d.ts.map +1 -0
  32. package/dist/collection-editor/collection-editor-service.js +868 -0
  33. package/dist/collection-editor/collection-editor-service.js.map +1 -0
  34. package/dist/collection-editor/index.d.ts +7 -0
  35. package/dist/collection-editor/index.d.ts.map +1 -0
  36. package/dist/collection-editor/index.js +12 -0
  37. package/dist/collection-editor/index.js.map +1 -0
  38. package/dist/diagnostics/find-ancestor-file.d.ts +13 -0
  39. package/dist/diagnostics/find-ancestor-file.d.ts.map +1 -0
  40. package/dist/diagnostics/find-ancestor-file.js +85 -0
  41. package/dist/diagnostics/find-ancestor-file.js.map +1 -0
  42. package/dist/diagnostics/index.d.ts +10 -0
  43. package/dist/diagnostics/index.d.ts.map +1 -0
  44. package/dist/diagnostics/index.js +26 -0
  45. package/dist/diagnostics/index.js.map +1 -0
  46. package/dist/diagnostics/run-primitive-diagnostics.d.ts +43 -0
  47. package/dist/diagnostics/run-primitive-diagnostics.d.ts.map +1 -0
  48. package/dist/diagnostics/run-primitive-diagnostics.js +413 -0
  49. package/dist/diagnostics/run-primitive-diagnostics.js.map +1 -0
  50. package/dist/diagnostics/sandbox-snapshot.d.ts +20 -0
  51. package/dist/diagnostics/sandbox-snapshot.d.ts.map +1 -0
  52. package/dist/diagnostics/sandbox-snapshot.js +117 -0
  53. package/dist/diagnostics/sandbox-snapshot.js.map +1 -0
  54. package/dist/governance/generate-catalogue.d.ts +16 -0
  55. package/dist/governance/generate-catalogue.d.ts.map +1 -0
  56. package/dist/governance/generate-catalogue.js +67 -0
  57. package/dist/governance/generate-catalogue.js.map +1 -0
  58. package/dist/governance/hub-scoped-governance.d.ts +37 -0
  59. package/dist/governance/hub-scoped-governance.d.ts.map +1 -0
  60. package/dist/governance/hub-scoped-governance.js +110 -0
  61. package/dist/governance/hub-scoped-governance.js.map +1 -0
  62. package/dist/governance/index.d.ts +10 -0
  63. package/dist/governance/index.d.ts.map +1 -0
  64. package/dist/governance/index.js +26 -0
  65. package/dist/governance/index.js.map +1 -0
  66. package/dist/governance/load-config.d.ts +45 -0
  67. package/dist/governance/load-config.d.ts.map +1 -0
  68. package/dist/governance/load-config.js +137 -0
  69. package/dist/governance/load-config.js.map +1 -0
  70. package/dist/governance/pr-scope.d.ts +23 -0
  71. package/dist/governance/pr-scope.d.ts.map +1 -0
  72. package/dist/governance/pr-scope.js +22 -0
  73. package/dist/governance/pr-scope.js.map +1 -0
  74. package/dist/governance/report.d.ts +23 -0
  75. package/dist/governance/report.d.ts.map +1 -0
  76. package/dist/governance/report.js +177 -0
  77. package/dist/governance/report.js.map +1 -0
  78. package/dist/governance/run-governance.d.ts +22 -0
  79. package/dist/governance/run-governance.d.ts.map +1 -0
  80. package/dist/governance/run-governance.js +78 -0
  81. package/dist/governance/run-governance.js.map +1 -0
  82. package/dist/governance/source-checks.d.ts +29 -0
  83. package/dist/governance/source-checks.d.ts.map +1 -0
  84. package/dist/governance/source-checks.js +80 -0
  85. package/dist/governance/source-checks.js.map +1 -0
  86. package/dist/governance/validate-collection-governance.d.ts +46 -0
  87. package/dist/governance/validate-collection-governance.d.ts.map +1 -0
  88. package/dist/governance/validate-collection-governance.js +291 -0
  89. package/dist/governance/validate-collection-governance.js.map +1 -0
  90. package/dist/hub-editor/hub-config-editor-service.d.ts +94 -0
  91. package/dist/hub-editor/hub-config-editor-service.d.ts.map +1 -0
  92. package/dist/hub-editor/hub-config-editor-service.js +289 -0
  93. package/dist/hub-editor/hub-config-editor-service.js.map +1 -0
  94. package/dist/hub-editor/hub-contribution-workflow.d.ts +99 -0
  95. package/dist/hub-editor/hub-contribution-workflow.d.ts.map +1 -0
  96. package/dist/hub-editor/hub-contribution-workflow.js +385 -0
  97. package/dist/hub-editor/hub-contribution-workflow.js.map +1 -0
  98. package/dist/hub-editor/index.d.ts +7 -0
  99. package/dist/hub-editor/index.d.ts.map +1 -0
  100. package/dist/hub-editor/index.js +23 -0
  101. package/dist/hub-editor/index.js.map +1 -0
  102. package/dist/index.d.ts +6 -0
  103. package/dist/index.d.ts.map +1 -1
  104. package/dist/index.js +6 -0
  105. package/dist/index.js.map +1 -1
  106. package/dist/install/index.d.ts +2 -0
  107. package/dist/install/index.d.ts.map +1 -1
  108. package/dist/install/index.js +3 -1
  109. package/dist/install/index.js.map +1 -1
  110. package/dist/install/partial-target-write.d.ts +63 -0
  111. package/dist/install/partial-target-write.d.ts.map +1 -0
  112. package/dist/install/partial-target-write.js +128 -0
  113. package/dist/install/partial-target-write.js.map +1 -0
  114. package/dist/install/pipeline.d.ts +2 -1
  115. package/dist/install/pipeline.d.ts.map +1 -1
  116. package/dist/install/pipeline.js +4 -3
  117. package/dist/install/pipeline.js.map +1 -1
  118. package/dist/install/target-write.d.ts +10 -0
  119. package/dist/install/target-write.d.ts.map +1 -1
  120. package/dist/install/target-write.js +3 -2
  121. package/dist/install/target-write.js.map +1 -1
  122. package/dist/install/uninstall-pipeline.d.ts +11 -10
  123. package/dist/install/uninstall-pipeline.d.ts.map +1 -1
  124. package/dist/install/uninstall-pipeline.js +10 -11
  125. package/dist/install/uninstall-pipeline.js.map +1 -1
  126. package/dist/records/atomic-write.d.ts +11 -0
  127. package/dist/records/atomic-write.d.ts.map +1 -0
  128. package/dist/records/atomic-write.js +66 -0
  129. package/dist/records/atomic-write.js.map +1 -0
  130. package/dist/records/confine-path.d.ts +35 -0
  131. package/dist/records/confine-path.d.ts.map +1 -0
  132. package/dist/records/confine-path.js +140 -0
  133. package/dist/records/confine-path.js.map +1 -0
  134. package/dist/records/git-root.d.ts +66 -0
  135. package/dist/records/git-root.d.ts.map +1 -0
  136. package/dist/records/git-root.js +208 -0
  137. package/dist/records/git-root.js.map +1 -0
  138. package/dist/records/index.d.ts +30 -0
  139. package/dist/records/index.d.ts.map +1 -0
  140. package/dist/records/index.js +46 -0
  141. package/dist/records/index.js.map +1 -0
  142. package/dist/records/install-record-service.d.ts +496 -0
  143. package/dist/records/install-record-service.d.ts.map +1 -0
  144. package/dist/records/install-record-service.js +1365 -0
  145. package/dist/records/install-record-service.js.map +1 -0
  146. package/dist/records/install-record-services.d.ts +29 -0
  147. package/dist/records/install-record-services.d.ts.map +1 -0
  148. package/dist/records/install-record-services.js +17 -0
  149. package/dist/records/install-record-services.js.map +1 -0
  150. package/dist/records/legacy-shapes.d.ts +18 -0
  151. package/dist/records/legacy-shapes.d.ts.map +1 -0
  152. package/dist/records/legacy-shapes.js +30 -0
  153. package/dist/records/legacy-shapes.js.map +1 -0
  154. package/dist/records/map-tool-to-target.d.ts +33 -0
  155. package/dist/records/map-tool-to-target.d.ts.map +1 -0
  156. package/dist/records/map-tool-to-target.js +98 -0
  157. package/dist/records/map-tool-to-target.js.map +1 -0
  158. package/dist/records/mcp-servers.d.ts +116 -0
  159. package/dist/records/mcp-servers.d.ts.map +1 -0
  160. package/dist/records/mcp-servers.js +268 -0
  161. package/dist/records/mcp-servers.js.map +1 -0
  162. package/dist/records/modified-files.d.ts +32 -0
  163. package/dist/records/modified-files.d.ts.map +1 -0
  164. package/dist/records/modified-files.js +146 -0
  165. package/dist/records/modified-files.js.map +1 -0
  166. package/dist/records/plan-record-entries.d.ts +76 -0
  167. package/dist/records/plan-record-entries.d.ts.map +1 -0
  168. package/dist/records/plan-record-entries.js +84 -0
  169. package/dist/records/plan-record-entries.js.map +1 -0
  170. package/dist/records/read-record-text.d.ts +15 -0
  171. package/dist/records/read-record-text.d.ts.map +1 -0
  172. package/dist/records/read-record-text.js +36 -0
  173. package/dist/records/read-record-text.js.map +1 -0
  174. package/dist/records/record-entry.d.ts +31 -0
  175. package/dist/records/record-entry.d.ts.map +1 -0
  176. package/dist/records/record-entry.js +81 -0
  177. package/dist/records/record-entry.js.map +1 -0
  178. package/dist/records/record-file-shape.d.ts +90 -0
  179. package/dist/records/record-file-shape.d.ts.map +1 -0
  180. package/dist/records/record-file-shape.js +288 -0
  181. package/dist/records/record-file-shape.js.map +1 -0
  182. package/dist/records/record-hub.d.ts +42 -0
  183. package/dist/records/record-hub.d.ts.map +1 -0
  184. package/dist/records/record-hub.js +85 -0
  185. package/dist/records/record-hub.js.map +1 -0
  186. package/dist/records/record-identity.d.ts +14 -0
  187. package/dist/records/record-identity.d.ts.map +1 -0
  188. package/dist/records/record-identity.js +41 -0
  189. package/dist/records/record-identity.js.map +1 -0
  190. package/dist/records/record-migration.d.ts +118 -0
  191. package/dist/records/record-migration.d.ts.map +1 -0
  192. package/dist/records/record-migration.js +454 -0
  193. package/dist/records/record-migration.js.map +1 -0
  194. package/dist/records/record-store.d.ts +123 -0
  195. package/dist/records/record-store.d.ts.map +1 -0
  196. package/dist/records/record-store.js +291 -0
  197. package/dist/records/record-store.js.map +1 -0
  198. package/dist/records/resolve-record-source.d.ts +64 -0
  199. package/dist/records/resolve-record-source.d.ts.map +1 -0
  200. package/dist/records/resolve-record-source.js +160 -0
  201. package/dist/records/resolve-record-source.js.map +1 -0
  202. package/dist/records/sanitize-source.d.ts +18 -0
  203. package/dist/records/sanitize-source.d.ts.map +1 -0
  204. package/dist/records/sanitize-source.js +90 -0
  205. package/dist/records/sanitize-source.js.map +1 -0
  206. package/dist/records/select-record.d.ts +54 -0
  207. package/dist/records/select-record.d.ts.map +1 -0
  208. package/dist/records/select-record.js +180 -0
  209. package/dist/records/select-record.js.map +1 -0
  210. package/dist/records/serialize-record.d.ts +20 -0
  211. package/dist/records/serialize-record.d.ts.map +1 -0
  212. package/dist/records/serialize-record.js +100 -0
  213. package/dist/records/serialize-record.js.map +1 -0
  214. package/dist/records/source-fields.d.ts +21 -0
  215. package/dist/records/source-fields.d.ts.map +1 -0
  216. package/dist/records/source-fields.js +28 -0
  217. package/dist/records/source-fields.js.map +1 -0
  218. package/dist/records/to-record-source.d.ts +23 -0
  219. package/dist/records/to-record-source.d.ts.map +1 -0
  220. package/dist/records/to-record-source.js +39 -0
  221. package/dist/records/to-record-source.js.map +1 -0
  222. package/dist/records/user-home.d.ts +16 -0
  223. package/dist/records/user-home.d.ts.map +1 -0
  224. package/dist/records/user-home.js +84 -0
  225. package/dist/records/user-home.js.map +1 -0
  226. package/dist/records/writer-group.d.ts +7 -0
  227. package/dist/records/writer-group.d.ts.map +1 -0
  228. package/dist/records/writer-group.js +31 -0
  229. package/dist/records/writer-group.js.map +1 -0
  230. package/dist/registry/activate-registry-profile.d.ts.map +1 -1
  231. package/dist/registry/activate-registry-profile.js +4 -1
  232. package/dist/registry/activate-registry-profile.js.map +1 -1
  233. package/dist/registry/batch-install-profile.d.ts +76 -0
  234. package/dist/registry/batch-install-profile.d.ts.map +1 -0
  235. package/dist/registry/batch-install-profile.js +67 -0
  236. package/dist/registry/batch-install-profile.js.map +1 -0
  237. package/dist/registry/create-source-adapter.d.ts +16 -1
  238. package/dist/registry/create-source-adapter.d.ts.map +1 -1
  239. package/dist/registry/create-source-adapter.js +76 -3
  240. package/dist/registry/create-source-adapter.js.map +1 -1
  241. package/dist/registry/hub-manager.d.ts +41 -0
  242. package/dist/registry/hub-manager.d.ts.map +1 -1
  243. package/dist/registry/hub-manager.js +82 -4
  244. package/dist/registry/hub-manager.js.map +1 -1
  245. package/dist/registry/index.d.ts +1 -0
  246. package/dist/registry/index.d.ts.map +1 -1
  247. package/dist/registry/index.js +1 -0
  248. package/dist/registry/index.js.map +1 -1
  249. package/dist/registry/install-registry-bundle.js +4 -3
  250. package/dist/registry/install-registry-bundle.js.map +1 -1
  251. package/dist/registry/list-installed-bundles.d.ts +2 -3
  252. package/dist/registry/list-installed-bundles.d.ts.map +1 -1
  253. package/dist/registry/list-installed-bundles.js.map +1 -1
  254. package/dist/registry/load-hub-sources.d.ts +8 -0
  255. package/dist/registry/load-hub-sources.d.ts.map +1 -1
  256. package/dist/registry/load-hub-sources.js +70 -3
  257. package/dist/registry/load-hub-sources.js.map +1 -1
  258. package/dist/registry/profile-lifecycle.d.ts +7 -2
  259. package/dist/registry/profile-lifecycle.d.ts.map +1 -1
  260. package/dist/registry/profile-lifecycle.js +82 -11
  261. package/dist/registry/profile-lifecycle.js.map +1 -1
  262. package/dist/registry/uninstall-installed-bundle.d.ts +2 -3
  263. package/dist/registry/uninstall-installed-bundle.d.ts.map +1 -1
  264. package/dist/registry/uninstall-installed-bundle.js.map +1 -1
  265. package/dist/registry/update-registry-bundle.d.ts +2 -2
  266. package/dist/registry/update-registry-bundle.js +2 -2
  267. package/dist/registry/update-registry-bundle.js.map +1 -1
  268. package/dist/registry/validate-hub-config-file.d.ts +14 -1
  269. package/dist/registry/validate-hub-config-file.d.ts.map +1 -1
  270. package/dist/registry/validate-hub-config-file.js +81 -44
  271. package/dist/registry/validate-hub-config-file.js.map +1 -1
  272. package/dist/release/plan-bundle-release.d.ts +6 -12
  273. package/dist/release/plan-bundle-release.d.ts.map +1 -1
  274. package/dist/release/plan-bundle-release.js +178 -7
  275. package/dist/release/plan-bundle-release.js.map +1 -1
  276. package/dist/replicate/replicate.d.ts +5 -2
  277. package/dist/replicate/replicate.d.ts.map +1 -1
  278. package/dist/replicate/replicate.js +121 -17
  279. package/dist/replicate/replicate.js.map +1 -1
  280. package/dist/security/index.d.ts +4 -0
  281. package/dist/security/index.d.ts.map +1 -0
  282. package/dist/security/index.js +22 -0
  283. package/dist/security/index.js.map +1 -0
  284. package/dist/security/rating/bundle-discovery.d.ts +19 -0
  285. package/dist/security/rating/bundle-discovery.d.ts.map +1 -0
  286. package/dist/security/rating/bundle-discovery.js +244 -0
  287. package/dist/security/rating/bundle-discovery.js.map +1 -0
  288. package/dist/security/rating/index.d.ts +5 -0
  289. package/dist/security/rating/index.d.ts.map +1 -0
  290. package/dist/security/rating/index.js +21 -0
  291. package/dist/security/rating/index.js.map +1 -0
  292. package/dist/security/rating/security-rating-markdown.d.ts +17 -0
  293. package/dist/security/rating/security-rating-markdown.d.ts.map +1 -0
  294. package/dist/security/rating/security-rating-markdown.js +131 -0
  295. package/dist/security/rating/security-rating-markdown.js.map +1 -0
  296. package/dist/security/rating/security-rating-scan.d.ts +23 -0
  297. package/dist/security/rating/security-rating-scan.d.ts.map +1 -0
  298. package/dist/security/rating/security-rating-scan.js +40 -0
  299. package/dist/security/rating/security-rating-scan.js.map +1 -0
  300. package/dist/security/rating/security-rating-templates.d.ts +40 -0
  301. package/dist/security/rating/security-rating-templates.d.ts.map +1 -0
  302. package/dist/security/rating/security-rating-templates.js +83 -0
  303. package/dist/security/rating/security-rating-templates.js.map +1 -0
  304. package/dist/security/rating/security-rating.d.ts +32 -0
  305. package/dist/security/rating/security-rating.d.ts.map +1 -0
  306. package/dist/security/rating/security-rating.js +94 -0
  307. package/dist/security/rating/security-rating.js.map +1 -0
  308. package/dist/security/security-scan-use-case.d.ts +101 -0
  309. package/dist/security/security-scan-use-case.d.ts.map +1 -0
  310. package/dist/security/security-scan-use-case.js +185 -0
  311. package/dist/security/security-scan-use-case.js.map +1 -0
  312. package/dist/stores/json-lockfile-store.d.ts.map +1 -1
  313. package/dist/stores/json-lockfile-store.js +6 -32
  314. package/dist/stores/json-lockfile-store.js.map +1 -1
  315. package/dist/transform/transformer-registry.d.ts.map +1 -1
  316. package/dist/transform/transformer-registry.js +3 -0
  317. package/dist/transform/transformer-registry.js.map +1 -1
  318. package/dist/transform/transformers/windsurf-transformer.d.ts +5 -0
  319. package/dist/transform/transformers/windsurf-transformer.d.ts.map +1 -1
  320. package/dist/transform/transformers/windsurf-transformer.js.map +1 -1
  321. package/dist/writers/file-tree-writer.d.ts +14 -1
  322. package/dist/writers/file-tree-writer.d.ts.map +1 -1
  323. package/dist/writers/file-tree-writer.js +23 -71
  324. package/dist/writers/file-tree-writer.js.map +1 -1
  325. package/package.json +5 -4
@@ -0,0 +1,1365 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.InstallRecordService = exports.listedMcpServers = exports.listedPaths = exports.isLoneUnknown = exports.isMergedMcpConfigPath = exports.RECORD_SOURCE_TYPES = void 0;
37
+ /**
38
+ * Install record service: records a tool's install or uninstall of a bundle in
39
+ * the shared record and keeps sibling tools that share its files in step. It
40
+ * also moves entries between the two repository files and remaps source ids.
41
+ * It deletes nothing itself; superseded files come back in `deletedFiles` for
42
+ * `deleteSuperseded` to remove after the save.
43
+ * @module records/install-record-service
44
+ */
45
+ const node_crypto_1 = require("node:crypto");
46
+ const path = __importStar(require("node:path"));
47
+ const core_1 = require("@ai-primitives-hub/core");
48
+ const infra_1 = require("@ai-primitives-hub/infra");
49
+ const layout_resolver_1 = require("../install/layout-resolver");
50
+ const confine_path_1 = require("./confine-path");
51
+ const git_root_1 = require("./git-root");
52
+ const mcp_servers_1 = require("./mcp-servers");
53
+ const modified_files_1 = require("./modified-files");
54
+ const record_entry_1 = require("./record-entry");
55
+ const record_file_shape_1 = require("./record-file-shape");
56
+ const record_hub_1 = require("./record-hub");
57
+ const record_identity_1 = require("./record-identity");
58
+ const sanitize_source_1 = require("./sanitize-source");
59
+ /** Typed as `Record<SourceType, true>` so the compiler keeps it in step with the union. */
60
+ const SOURCE_TYPE_KEYS = {
61
+ github: true,
62
+ local: true,
63
+ 'awesome-copilot': true,
64
+ 'local-awesome-copilot': true,
65
+ apm: true,
66
+ 'local-apm': true,
67
+ skills: true,
68
+ 'local-skills': true,
69
+ 'azure-devops': true,
70
+ artifactory: true
71
+ };
72
+ /** Every `SourceType` value, the only `sourceType` a new entry may carry. */
73
+ exports.RECORD_SOURCE_TYPES = Object.keys(SOURCE_TYPE_KEYS);
74
+ /** Repository-scope MCP config paths of the built-in layouts; merged, not owned, so never recorded. */
75
+ const mergedMcpConfigPaths = () => {
76
+ const prefix = core_1.WORKSPACE_ROOT_TOKEN;
77
+ const paths = new Set();
78
+ for (const type of core_1.TARGET_TYPES) {
79
+ const config = (0, layout_resolver_1.resolveMcpLayoutConfig)(type, 'repository', [infra_1.defaultLayouts]);
80
+ if (config?.path.startsWith(prefix)) {
81
+ paths.add(config.path.slice(prefix.length).replaceAll('\\', '/').replace(/^\/+/, ''));
82
+ }
83
+ }
84
+ return [...paths];
85
+ };
86
+ const MERGED_MCP_CONFIG_PATHS = mergedMcpConfigPaths();
87
+ /**
88
+ * Whether a git-root-relative path is exactly a merged MCP config file of the
89
+ * install's workspace; a same-named bundle file elsewhere is still recorded.
90
+ * @param relative - Path relative to the git root.
91
+ * @param workspacePrefix - Workspace root relative to the git root; `''` when they are the same.
92
+ */
93
+ const isMergedMcpConfigPath = (relative, workspacePrefix = '') => MERGED_MCP_CONFIG_PATHS.some((mcpPath) => relative === (workspacePrefix === '' ? mcpPath : `${workspacePrefix}/${mcpPath}`));
94
+ exports.isMergedMcpConfigPath = isMergedMcpConfigPath;
95
+ const copyRecordedFile = (file) => {
96
+ const copy = Object.create(null);
97
+ copy.path = file.path;
98
+ copy.checksum = file.checksum;
99
+ return copy;
100
+ };
101
+ /**
102
+ * Whether a bundle's only entry at a level is `unknown`: migrated, and not reinstalled by any tool.
103
+ * @param tools - Tool keys of the bundle's entries at the level.
104
+ */
105
+ const isLoneUnknown = (tools) => {
106
+ const names = new Set(tools);
107
+ return names.size === 1 && names.has(core_1.UNKNOWN_TOOL_NAME);
108
+ };
109
+ exports.isLoneUnknown = isLoneUnknown;
110
+ /**
111
+ * Every installed path listed by any entry of the given records.
112
+ * @param records - Records to scan.
113
+ */
114
+ const listedPaths = (records) => {
115
+ const listed = new Set();
116
+ for (const record of records) {
117
+ for (const bundle of Object.values(record.bundles)) {
118
+ for (const entry of Object.values(bundle.tools)) {
119
+ for (const file of entry.files) {
120
+ listed.add(file.path);
121
+ }
122
+ }
123
+ }
124
+ }
125
+ return listed;
126
+ };
127
+ exports.listedPaths = listedPaths;
128
+ /**
129
+ * Every MCP server any entry of the records lists, as {@link mcpServerKeyOf} keys.
130
+ * @param records - Records of one level.
131
+ */
132
+ const listedMcpServers = (records) => new Set(records.flatMap((record) => Object.values(record.bundles).flatMap((bundle) => Object.values(bundle.tools).flatMap((entry) => (entry.mcpServers ?? []).map((server) => (0, mcp_servers_1.mcpServerKeyOf)(server))))));
133
+ exports.listedMcpServers = listedMcpServers;
134
+ // `config` of an MCP file: relative to the level root, `/`-separated.
135
+ const mcpConfigPathOf = (root, file) => {
136
+ const relative = path.relative(root, path.resolve(file));
137
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
138
+ throw (0, core_1.recordError)('RECORD.PATH_OUTSIDE_ROOT', { file: path.basename(file), detail: `the MCP file ${file} is outside ${root}` });
139
+ }
140
+ return relative.split(path.sep).join('/');
141
+ };
142
+ /**
143
+ * `config` of an MCP file, checked on disk: its folders, and a symlinked file's
144
+ * target, must resolve inside the level root.
145
+ * @param fs - Filesystem port.
146
+ * @param root - Level root.
147
+ * @param file - Absolute MCP file path.
148
+ * @throws {RegistryError} `RECORD.PATH_OUTSIDE_ROOT`.
149
+ */
150
+ const confineMcpConfig = async (fs, root, file) => {
151
+ const config = mcpConfigPathOf(root, file);
152
+ await (0, confine_path_1.confinePath)(fs, root, config, config);
153
+ if ((await fs.lstat(file))?.kind === 'symlink') {
154
+ const target = await fs.realpath(file).catch(() => undefined);
155
+ if (target === undefined || (0, core_1.relativeInside)(await fs.realpath(root), target) === undefined) {
156
+ throw (0, core_1.recordError)('RECORD.PATH_OUTSIDE_ROOT', { file: config, detail: `the MCP file ${config} links outside ${root}` });
157
+ }
158
+ }
159
+ return config;
160
+ };
161
+ // Names of the servers any entry of the level records for one MCP file.
162
+ const recordedMcpServerNames = async (store, location, config) => {
163
+ const otherLocation = (0, core_1.otherRepositoryLocation)(location);
164
+ const records = [];
165
+ for (const file of otherLocation === undefined ? [location] : [location, otherLocation]) {
166
+ records.push((await store.load(file)).record);
167
+ }
168
+ return new Set(records.flatMap((record) => Object.values(record.bundles).flatMap((bundle) => Object.values(bundle.tools)
169
+ .flatMap((entry) => (entry.mcpServers ?? []).filter((server) => server.config === config).map((server) => server.name)))));
170
+ };
171
+ // One server per file and name, sorted, as prototype-free copies.
172
+ const uniqueMcpServers = (servers) => {
173
+ const byKey = new Map();
174
+ for (const server of servers) {
175
+ byKey.set((0, mcp_servers_1.mcpServerKeyOf)(server), Object.assign(Object.create(null), server));
176
+ }
177
+ return [...byKey.entries()].toSorted(([left], [right]) => (0, core_1.compareCodeUnits)(left, right)).map(([, server]) => server);
178
+ };
179
+ /**
180
+ * The bundle id a key names: the name after the source id of a source-qualified `<sourceId>/<name>` key, else the key.
181
+ * @param key - In-memory bundle key.
182
+ */
183
+ const logicalBundleIdOf = (key) => ((0, record_file_shape_1.isRecordSourceId)(key) && key.includes('/') ? key.slice(key.lastIndexOf('/') + 1) : key);
184
+ /**
185
+ * The readable id of an entry's source; a configured id an older record keeps is built from its `sources` entry.
186
+ * @param record - Record holding the entry.
187
+ * @param sourceId - The entry's `sourceId`.
188
+ */
189
+ const readableSourceIdIn = (record, sourceId) => {
190
+ if ((0, record_file_shape_1.isRecordSourceId)(sourceId) || !Object.hasOwn(record.sources, sourceId)) {
191
+ return sourceId;
192
+ }
193
+ return (0, record_file_shape_1.recordSourceIdOf)(record.sources[sourceId]);
194
+ };
195
+ const isSameSource = (left, right) => {
196
+ const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
197
+ return [...keys].every((key) => left[key] === right[key]);
198
+ };
199
+ /**
200
+ * The record's `hubs` entry for a hub id, when it is an object.
201
+ * @param record - Record to read.
202
+ * @param hubId - Hub id.
203
+ */
204
+ const hubEntryIn = (record, hubId) => {
205
+ const hubs = record?.hubs;
206
+ if (!(0, core_1.isJsonObject)(hubs) || !Object.hasOwn(hubs, hubId)) {
207
+ return undefined;
208
+ }
209
+ const entry = hubs[hubId];
210
+ return (0, core_1.isJsonObject)(entry) ? entry : undefined;
211
+ };
212
+ /**
213
+ * Record the hub a source names: the given hub, else the entry already in the
214
+ * record or in `fallback`. A `hubId` with no hub entry is removed from the source.
215
+ * @param record - Record to change.
216
+ * @param source - The recorded source; its `hubId` may be removed.
217
+ * @param hub - The source's hub, already checked by `toRecordHub`.
218
+ * @param fallback - Another record that may hold the entry.
219
+ * @returns Whether `hubs` changed.
220
+ */
221
+ /**
222
+ * The hub to record, under its readable id; the source's `hubId` is changed to
223
+ * that id when it names this hub. A hub that cannot be recorded gives `undefined`.
224
+ * @param source - Sanitized source; changed in place.
225
+ * @param input - The hub named by the source's `hubId`.
226
+ */
227
+ const recordedHubOf = (source, input) => {
228
+ const hub = input === undefined ? undefined : (0, record_hub_1.toRecordHub)(input.id, input.name, input);
229
+ if (hub === undefined) {
230
+ return undefined;
231
+ }
232
+ const id = (0, record_file_shape_1.recordHubIdOf)(hub);
233
+ if (source.hubId === hub.id) {
234
+ source.hubId = id;
235
+ }
236
+ hub.id = id;
237
+ return hub;
238
+ };
239
+ /**
240
+ * Refuse a source already recorded from another hub. Hubs are compared by
241
+ * readable id, so one hub imported under two configured ids is the same hub.
242
+ * @param files - Loaded record files of the level.
243
+ * @param sourceId - Readable source id.
244
+ * @param hubId - The install's hub: a readable id when its hub is known.
245
+ * @throws {RegistryError} `RECORD.HUB_CONFLICT` naming the file and both hubs.
246
+ */
247
+ const assertOneHub = (files, sourceId, hubId) => {
248
+ if (hubId === undefined || !(0, record_file_shape_1.isRecordHubId)(hubId)) {
249
+ return;
250
+ }
251
+ for (const file of files) {
252
+ for (const [key, recorded] of Object.entries(file.record.sources)) {
253
+ const sameSource = ((0, record_file_shape_1.isRecordSourceId)(key) ? key : (0, record_file_shape_1.recordSourceIdOf)(recorded)) === sourceId;
254
+ const recordedHubId = typeof recorded.hubId === 'string' ? (0, record_file_shape_1.recordHubKeyIn)(file.record.hubs, recorded.hubId) : undefined;
255
+ if (sameSource && recordedHubId !== undefined && recordedHubId !== hubId) {
256
+ throw (0, core_1.recordError)('RECORD.HUB_CONFLICT', {
257
+ file: path.basename(file.location.path),
258
+ detail: `source ${JSON.stringify(sourceId)} is recorded from hub ${JSON.stringify(recordedHubId)}, not ${JSON.stringify(hubId)}`,
259
+ context: { sourceId, recordedHubId, hubId }
260
+ });
261
+ }
262
+ }
263
+ }
264
+ };
265
+ const attachHub = (record, source, hub, fallback) => {
266
+ const { hubId } = source;
267
+ if (hubId === undefined) {
268
+ return false;
269
+ }
270
+ const current = hubEntryIn(record, hubId);
271
+ const entry = hub?.id === hubId ? (0, record_hub_1.hubEntryOf)(hub) : current ?? hubEntryIn(fallback, hubId);
272
+ if (entry === undefined) {
273
+ delete source.hubId;
274
+ return false;
275
+ }
276
+ if (current !== undefined && isSameSource(current, entry)) {
277
+ return false;
278
+ }
279
+ if (!(0, core_1.isJsonObject)(record.hubs)) {
280
+ record.hubs = Object.create(null);
281
+ }
282
+ (record.hubs)[hubId] = Object.assign(Object.create(null), entry);
283
+ return true;
284
+ };
285
+ /**
286
+ * Drop every `hubs` entry no recorded source names, and `hubs` itself once empty.
287
+ * @param record - Record to change.
288
+ */
289
+ const dropUnusedHubs = (record) => {
290
+ const { hubs } = record;
291
+ if (!(0, core_1.isJsonObject)(hubs)) {
292
+ return;
293
+ }
294
+ const used = new Set(Object.values(record.sources).map((source) => source.hubId));
295
+ for (const hubId of Object.keys(hubs)) {
296
+ if (!used.has(hubId)) {
297
+ delete hubs[hubId];
298
+ }
299
+ }
300
+ if (Object.keys(hubs).length === 0) {
301
+ delete record.hubs;
302
+ }
303
+ };
304
+ const remapInRecord = (record, from, to, descriptor, hub) => {
305
+ if (!Object.hasOwn(record.sources, from)) {
306
+ return false;
307
+ }
308
+ const source = Object.assign(Object.create(null), descriptor);
309
+ const recordedHubId = record.sources[from].hubId;
310
+ if (source.hubId === undefined && typeof recordedHubId === 'string') {
311
+ source.hubId = recordedHubId;
312
+ }
313
+ let changed = attachHub(record, source, hub);
314
+ for (const bundle of Object.values(record.bundles)) {
315
+ for (const entry of Object.values(bundle.tools)) {
316
+ if (entry.sourceId !== from && entry.sourceId !== to) {
317
+ continue;
318
+ }
319
+ if (entry.sourceId !== to || entry.sourceType !== source.type) {
320
+ changed = true;
321
+ }
322
+ entry.sourceId = to;
323
+ entry.sourceType = source.type;
324
+ }
325
+ }
326
+ if (from !== to) {
327
+ delete record.sources[from];
328
+ changed = true;
329
+ }
330
+ const current = Object.hasOwn(record.sources, to) ? record.sources[to] : undefined;
331
+ if (current === undefined || !isSameSource(current, source)) {
332
+ record.sources[to] = source;
333
+ changed = true;
334
+ }
335
+ return changed;
336
+ };
337
+ const sha256Hex = (data) => (0, node_crypto_1.createHash)('sha256').update(data).digest('hex');
338
+ // Every bundle file with the hash of its bytes, sorted by path.
339
+ const indexBundleFiles = (files) => [...files].map(([filePath, bytes]) => ({ path: filePath.replaceAll('\\', '/'), checksum: `sha256:${sha256Hex(bytes)}` }))
340
+ .toSorted((left, right) => (0, core_1.compareCodeUnits)(left.path, right.path));
341
+ /**
342
+ * `sha256:` of the downloaded bundle: each bundle path with its file's hash, sorted.
343
+ * The same content gives the same value however the archive was packed.
344
+ * @param index - From {@link indexBundleFiles}.
345
+ */
346
+ const integrityOf = (index) => `sha256:${sha256Hex(index.map((file) => `${file.path}\u0000${file.checksum}\n`).join(''))}`;
347
+ // Any execute bit set, as `mode & 0o111` would tell, without bitwise operators.
348
+ const isExecutable = (mode) => [mode % 8, Math.floor(mode / 8) % 8, Math.floor(mode / 64) % 8].some((bits) => bits % 2 === 1);
349
+ const stemOf = (filePath) => path.posix.basename(filePath).split('.')[0];
350
+ /**
351
+ * Path inside the bundle of a written file: the bundle file with the same bytes,
352
+ * else the same file name, else the same name stem, as when a tool renames or converts a file.
353
+ * @param recorded - The written file, hashed.
354
+ * @param index - The bundle's files.
355
+ */
356
+ const sourcePathOf = (recorded, index) => {
357
+ const base = path.posix.basename(recorded.path);
358
+ const sameBytes = index.filter((file) => file.checksum === recorded.checksum);
359
+ return (sameBytes.find((file) => path.posix.basename(file.path) === base) ?? sameBytes[0]
360
+ ?? index.find((file) => path.posix.basename(file.path) === base)
361
+ ?? index.find((file) => stemOf(file.path) === stemOf(recorded.path)))?.path;
362
+ };
363
+ /** The pending record change of each root, in this process. */
364
+ const pendingChanges = new Map();
365
+ /**
366
+ * Run record changes of one root one at a time in this process, so two
367
+ * concurrent installs cannot load the same record and lose each other's entry.
368
+ * A failed change does not stop the next one.
369
+ * @param root - Record root.
370
+ * @param change - Load, change and save of the record files at the root.
371
+ */
372
+ const serializeByRoot = async (root, change) => {
373
+ const current = (pendingChanges.get(root) ?? Promise.resolve()).catch(() => undefined).then(change);
374
+ const settled = current.catch(() => undefined);
375
+ pendingChanges.set(root, settled);
376
+ try {
377
+ return await current;
378
+ }
379
+ finally {
380
+ if (pendingChanges.get(root) === settled) {
381
+ pendingChanges.delete(root);
382
+ }
383
+ }
384
+ };
385
+ /** Records installs and uninstalls in the shared install record. */
386
+ class InstallRecordService {
387
+ store;
388
+ fs;
389
+ now;
390
+ constructor(options) {
391
+ this.store = options.store;
392
+ this.fs = options.fs;
393
+ this.now = options.now ?? (() => new Date());
394
+ }
395
+ /**
396
+ * The paths to delete that another entry lists through an aliased parent
397
+ * folder: both name the same file, so it is still owned. Parent folders are
398
+ * resolved and the leaf name kept; an unresolvable parent compares as written.
399
+ * @param root - Level root.
400
+ * @param deleted - Paths to delete.
401
+ * @param listed - Paths the level's entries still list.
402
+ */
403
+ async aliasedListedPaths(root, deleted, listed) {
404
+ if (deleted.length === 0 || listed.size === 0) {
405
+ return [];
406
+ }
407
+ const parents = new Map();
408
+ const keyOf = async (recordedPath) => {
409
+ const segments = recordedPath.split(/[/\\]/);
410
+ const leaf = segments.pop();
411
+ const parent = segments.join('/');
412
+ let resolved = parents.get(parent);
413
+ if (resolved === undefined) {
414
+ resolved = this.fs.realpath(path.join(root, ...segments)).catch(() => path.join(root, ...segments));
415
+ parents.set(parent, resolved);
416
+ }
417
+ return path.join(await resolved, leaf);
418
+ };
419
+ const listedKeys = new Set(await Promise.all([...listed].map((listedPath) => keyOf(listedPath))));
420
+ const aliased = [];
421
+ for (const recordedPath of deleted) {
422
+ if (listedKeys.has(await keyOf(recordedPath))) {
423
+ aliased.push(recordedPath);
424
+ }
425
+ }
426
+ return aliased;
427
+ }
428
+ validateInput(input) {
429
+ if (!core_1.TARGET_TYPES.includes(input.tool)) {
430
+ throw (0, core_1.recordError)('RECORD.UNKNOWN_TOOL', { detail: `tool ${JSON.stringify(input.tool)} is not a target type` });
431
+ }
432
+ if (!exports.RECORD_SOURCE_TYPES.includes(input.sourceType)) {
433
+ throw (0, core_1.recordError)('RECORD.MALFORMED', { detail: `sourceType ${JSON.stringify(input.sourceType)} is not a source type` });
434
+ }
435
+ if (input.sourceType !== input.source.type) {
436
+ throw (0, core_1.recordError)('RECORD.MALFORMED', {
437
+ detail: `sourceType ${JSON.stringify(input.sourceType)} does not match source.type ${JSON.stringify(input.source.type)}`
438
+ });
439
+ }
440
+ for (const [name, value] of [['bundleId', input.bundleId], ['sourceId', input.source.sourceId], ['version', input.version]]) {
441
+ if (typeof value !== 'string' || value === '' || core_1.FORBIDDEN_KEYS.has(value)) {
442
+ throw (0, core_1.recordError)('RECORD.MALFORMED', { detail: `${name} ${JSON.stringify(value)} cannot be recorded` });
443
+ }
444
+ }
445
+ }
446
+ /**
447
+ * A written path relative to the root; falls back to real paths when the root is behind a symlink.
448
+ * @param root - Level root.
449
+ * @param written - Absolute path from the writer.
450
+ */
451
+ async toRelative(root, written) {
452
+ const absolute = path.resolve(root, written);
453
+ const direct = (0, core_1.relativeInside)(root, absolute);
454
+ if (direct !== undefined) {
455
+ return direct;
456
+ }
457
+ try {
458
+ const realRoot = await this.fs.realpath(root);
459
+ const realParent = await this.fs.realpath(path.dirname(absolute));
460
+ const real = (0, core_1.relativeInside)(realRoot, path.join(realParent, path.basename(absolute)));
461
+ if (real !== undefined) {
462
+ return real;
463
+ }
464
+ }
465
+ catch {
466
+ // Reported below as outside the root.
467
+ }
468
+ throw (0, core_1.recordError)('RECORD.PATH_OUTSIDE_ROOT', { file: written, detail: 'the written file is outside the repository root' });
469
+ }
470
+ /**
471
+ * The workspace root relative to the record root; `''` when the same or not below it.
472
+ * @param root - Level root.
473
+ * @param workspaceRoot - Workspace root the writer installed into.
474
+ */
475
+ async workspacePrefix(root, workspaceRoot) {
476
+ if (workspaceRoot === undefined || path.resolve(workspaceRoot) === path.resolve(root)) {
477
+ return '';
478
+ }
479
+ try {
480
+ return await this.toRelative(root, workspaceRoot);
481
+ }
482
+ catch {
483
+ return '';
484
+ }
485
+ }
486
+ /**
487
+ * Recorded files for the writer's `written` list: confined, checksummed, merged MCP configs left out.
488
+ * @param root - Level root.
489
+ * @param writtenPaths - Absolute paths from the writer.
490
+ * @param workspaceRoot - Workspace root the writer installed into.
491
+ * @param bundleIndex - The downloaded bundle's files, to give each file its `sourcePath`.
492
+ */
493
+ async toRecordedFiles(root, writtenPaths, workspaceRoot, bundleIndex) {
494
+ const workspacePrefix = await this.workspacePrefix(root, workspaceRoot);
495
+ const files = new Map();
496
+ for (const written of writtenPaths) {
497
+ const relative = await (0, confine_path_1.confinePath)(this.fs, root, await this.toRelative(root, written));
498
+ if (files.has(relative) || (0, exports.isMergedMcpConfigPath)(relative, workspacePrefix)) {
499
+ continue;
500
+ }
501
+ const recorded = await (0, record_entry_1.hashRecordedFile)(this.fs, root, relative);
502
+ const sourcePath = bundleIndex === undefined ? undefined : sourcePathOf(recorded, bundleIndex);
503
+ if (sourcePath !== undefined) {
504
+ recorded.sourcePath = sourcePath;
505
+ }
506
+ // Only a regular file's mode means something; a symlink's is always 777.
507
+ const stat = await this.fs.lstat(path.join(root, ...relative.split('/')));
508
+ if (stat?.kind === 'file' && stat.mode !== undefined && isExecutable(stat.mode)) {
509
+ recorded.mode = `0${stat.mode.toString(8).padStart(3, '0')}`;
510
+ }
511
+ files.set(relative, recorded);
512
+ }
513
+ return [...files.values()];
514
+ }
515
+ // Also removes the bundle when no tool is left.
516
+ removeEntry(record, bundleId, tool) {
517
+ const bundle = Object.hasOwn(record.bundles, bundleId) ? record.bundles[bundleId] : undefined;
518
+ if (bundle === undefined || !Object.hasOwn(bundle.tools, tool)) {
519
+ return undefined;
520
+ }
521
+ const entry = bundle.tools[tool];
522
+ delete bundle.tools[tool];
523
+ if (Object.keys(bundle.tools).length === 0) {
524
+ delete record.bundles[bundleId];
525
+ }
526
+ return entry;
527
+ }
528
+ /**
529
+ * Remove the tool's entries keyed by the bundle id or by another id with the same identity.
530
+ * @param record - Record file to change.
531
+ * @param bundleId - Key of the new entry.
532
+ * @param identity - Identity of the new entry.
533
+ * @param tool - The target's type.
534
+ */
535
+ removeSameIdentity(record, bundleId, identity, tool) {
536
+ const removed = [];
537
+ for (const [key, bundle] of Object.entries(record.bundles)) {
538
+ if (Object.hasOwn(bundle.tools, tool) && (key === bundleId || (0, record_identity_1.recordIdentityOf)(key, bundle.tools[tool].version) === identity)) {
539
+ removed.push(this.removeEntry(record, key, tool));
540
+ }
541
+ }
542
+ return removed;
543
+ }
544
+ dropUnusedSource(record, sourceId) {
545
+ if (!Object.hasOwn(record.sources, sourceId)) {
546
+ return;
547
+ }
548
+ const used = Object.values(record.bundles)
549
+ .some((bundle) => Object.values(bundle.tools).some((entry) => entry.sourceId === sourceId));
550
+ if (!used) {
551
+ delete record.sources[sourceId];
552
+ }
553
+ }
554
+ // Clears the `unknown` entries of the same identity and the sources only they used; `true` when there was one.
555
+ clearUnknown(record, bundleId, identity) {
556
+ const removed = this.removeSameIdentity(record, bundleId, identity, core_1.UNKNOWN_TOOL_NAME);
557
+ for (const entry of removed) {
558
+ this.dropUnusedSource(record, entry.sourceId);
559
+ }
560
+ return removed.length > 0;
561
+ }
562
+ /**
563
+ * Save a record file, without the `hubs` entries no source names.
564
+ * @param location - Record file.
565
+ * @param record - Its content.
566
+ */
567
+ save(location, record) {
568
+ dropUnusedHubs(record);
569
+ return this.store.save(location, record);
570
+ }
571
+ /**
572
+ * Save a changed record file, or remove a repository file with no bundles left.
573
+ * An empty user record is kept so its import marker survives.
574
+ * @param other - The loaded, changed file.
575
+ */
576
+ async saveOther(other) {
577
+ if (other.location.level !== 'repository' || Object.keys(other.record.bundles).length > 0) {
578
+ return (await this.save(other.location, other.record)).warnings;
579
+ }
580
+ const name = path.basename(other.location.path);
581
+ try {
582
+ await this.fs.unlink(other.location.path);
583
+ }
584
+ catch (error) {
585
+ // Keep the record true to disk: save it empty, so it lists no file the caller then deletes.
586
+ const saved = await this.store.save(other.location, other.record);
587
+ return [`Could not remove the empty record ${name}: ${error instanceof Error ? error.message : String(error)}`, ...saved.warnings];
588
+ }
589
+ if (other.location.commitMode === 'local-only') {
590
+ const excluded = await (0, git_root_1.removeExcluded)(this.fs, other.location.root, name);
591
+ return excluded.warning === undefined ? [] : [excluded.warning];
592
+ }
593
+ return [];
594
+ }
595
+ /**
596
+ * Bring sibling entries that share the installed tool's files to its version, in memory.
597
+ * A sibling held under another key of the same identity moves to the installed key.
598
+ * @param loaded - The target file, then the other repository file.
599
+ * @param change - What the installed tool wrote.
600
+ * @param change.bundleId - Bundle id.
601
+ * @param change.identity - Its bundle identity.
602
+ * @param change.tool - The installed tool.
603
+ * @param change.sourceId - Readable id of its source; another source's entry is not a sibling.
604
+ * @param change.version - Its new version.
605
+ * @param change.integrity - The new version's bundle integrity, when known.
606
+ * @param change.files - Its new recorded files.
607
+ * @param change.previousPaths - Paths its previous entry listed.
608
+ * @param change.accepts - Which sibling tools to sync.
609
+ * @returns The siblings found, sorted by tool, and the files changed.
610
+ */
611
+ syncSiblingEntries(loaded, change) {
612
+ const newByPath = new Map(change.files.map((file) => [file.path, file]));
613
+ const isShared = (recorded) => change.previousPaths.has(recorded.path) || newByPath.has(recorded.path);
614
+ const siblings = [];
615
+ const changed = new Set();
616
+ const logicalIdentity = (0, record_identity_1.recordIdentityOf)(logicalBundleIdOf(change.bundleId), change.version);
617
+ for (const file of loaded) {
618
+ const { bundles } = file.record;
619
+ const holdsTool = (tool) => Object.hasOwn(bundles, change.bundleId) && Object.hasOwn(bundles[change.bundleId].tools, tool);
620
+ const handled = new Set();
621
+ for (const [key, bundle] of Object.entries(bundles)) {
622
+ for (const [tool, entry] of Object.entries(bundle.tools)) {
623
+ // Compared by logical name: a source-qualified key holds the same bundle as the plain one.
624
+ const sameBundle = (key === change.bundleId || (0, record_identity_1.recordIdentityOf)(logicalBundleIdOf(key), entry.version) === logicalIdentity)
625
+ && readableSourceIdIn(file.record, entry.sourceId) === change.sourceId;
626
+ if (!sameBundle || handled.has(tool) || tool === change.tool || tool === core_1.UNKNOWN_TOOL_NAME
627
+ || !entry.files.some((recorded) => isShared(recorded)) || (key !== change.bundleId && holdsTool(tool))) {
628
+ continue;
629
+ }
630
+ handled.add(tool);
631
+ if (!change.accepts(tool)) {
632
+ siblings.push({ tool, version: entry.version, location: file.location, synced: false });
633
+ continue;
634
+ }
635
+ entry.files = entry.files.flatMap((recorded) => {
636
+ if (!isShared(recorded)) {
637
+ return [recorded];
638
+ }
639
+ const written = newByPath.get(recorded.path);
640
+ return written === undefined ? [] : [copyRecordedFile(written)];
641
+ });
642
+ entry.version = change.version;
643
+ entry.installedAt = this.now().toISOString();
644
+ // The sibling now holds the new version's content; an unknown one leaves no stale value.
645
+ if (change.integrity === undefined) {
646
+ delete entry.integrity;
647
+ }
648
+ else {
649
+ entry.integrity = change.integrity;
650
+ }
651
+ if (key !== change.bundleId) {
652
+ this.removeEntry(file.record, key, tool);
653
+ if (!Object.hasOwn(bundles, change.bundleId)) {
654
+ bundles[change.bundleId] = (0, record_entry_1.createBundle)();
655
+ }
656
+ bundles[change.bundleId].tools[tool] = entry;
657
+ }
658
+ siblings.push({ tool, version: change.version, location: file.location, synced: true });
659
+ changed.add(file);
660
+ }
661
+ }
662
+ }
663
+ return { siblings: siblings.toSorted((left, right) => (0, core_1.compareCodeUnits)(left.tool, right.tool)), changed };
664
+ }
665
+ /**
666
+ * Tool entries of the given record files, one per level, root, bundle and
667
+ * tool; an entry in both repository files at one root comes from the committed file.
668
+ * @param locations - Record files to read.
669
+ * @param bundleId - Only this bundle's entries, when given.
670
+ * @param tool - Only this tool's entries, when given.
671
+ */
672
+ async locateEntries(locations, bundleId, tool) {
673
+ const found = new Map();
674
+ for (const location of locations) {
675
+ const { record } = await this.store.load(location);
676
+ const bundles = Object.entries(record.bundles).filter(([id]) => bundleId === undefined || id === bundleId);
677
+ for (const [id, bundle] of bundles) {
678
+ for (const [key, entry] of Object.entries(bundle.tools).filter(([name]) => tool === undefined || name === tool)) {
679
+ const dedupeKey = JSON.stringify([location.level, location.root, id, key]);
680
+ const existing = found.get(dedupeKey);
681
+ if (existing !== undefined && (existing.location.commitMode !== 'local-only' || location.commitMode === 'local-only')) {
682
+ continue;
683
+ }
684
+ found.set(dedupeKey, { location, bundleId: id, tool: key, entry });
685
+ }
686
+ }
687
+ }
688
+ return [...found.values()];
689
+ }
690
+ /**
691
+ * Record that a tool installed a bundle, moving the entry out of the other
692
+ * repository file, syncing siblings and clearing the bundle's `unknown` entry.
693
+ * The tool's entries with the same bundle identity in either file are
694
+ * replaced. Saves the target file first; deletes nothing.
695
+ * @param input - Install to record.
696
+ * @returns The change, with the superseded files to delete after the save and the siblings found.
697
+ * @throws {RegistryError} A `RECORD.*` error; the record is unchanged when the target save fails.
698
+ */
699
+ recordInstall(input) {
700
+ return serializeByRoot(input.location.root, () => this.applyInstall(input));
701
+ }
702
+ /**
703
+ * Refuse, before any file is written, an install of a source the record holds from another hub.
704
+ * @param location - Record file the install will change.
705
+ * @param source - Source to record.
706
+ * @param hub - The hub named by `source.hubId`.
707
+ * @throws {RegistryError} `RECORD.HUB_CONFLICT`, or any `RECORD.*` load error.
708
+ */
709
+ async checkSourceHub(location, source, hub) {
710
+ const sanitized = (0, sanitize_source_1.sanitizeSource)(source);
711
+ recordedHubOf(sanitized, hub);
712
+ const otherLocation = (0, core_1.otherRepositoryLocation)(location);
713
+ const files = [await this.store.load(location), ...(otherLocation === undefined ? [] : [await this.store.load(otherLocation)])];
714
+ assertOneHub(files, (0, record_file_shape_1.recordSourceIdOf)(sanitized), sanitized.hubId);
715
+ }
716
+ // eslint-disable-next-line @typescript-eslint/member-ordering -- kept next to the public method that serializes it
717
+ async applyInstall(input) {
718
+ this.validateInput(input);
719
+ const source = (0, sanitize_source_1.sanitizeSource)(input.source);
720
+ // Recorded under its readable id, the same on every machine, whatever the configured id.
721
+ const sourceId = (0, record_file_shape_1.recordSourceIdOf)(source);
722
+ const hub = recordedHubOf(source, input.hub);
723
+ const { location, tool } = input;
724
+ const target = await this.store.load(location);
725
+ const otherLocation = (0, core_1.otherRepositoryLocation)(location);
726
+ const other = otherLocation === undefined ? undefined : await this.store.load(otherLocation);
727
+ // Another source's entry of the same name keeps the plain key, and this source's entry its own key
728
+ // (see `fromRecordFile`): a reinstall from this source updates its own entry, not the other one.
729
+ const ownKey = (0, record_file_shape_1.recordBundleKeyOf)(sourceId, (0, record_file_shape_1.recordBundleNameOf)(input.name ?? input.bundleId, input.version));
730
+ const hasOwnKey = ownKey !== input.bundleId && [target, other].some((file) => file !== undefined
731
+ && Object.hasOwn(file.record.bundles, ownKey) && Object.hasOwn(file.record.bundles[ownKey].tools, tool));
732
+ const bundleId = hasOwnKey ? ownKey : input.bundleId;
733
+ assertOneHub(other === undefined ? [target] : [target, other], sourceId, source.hubId);
734
+ // Without the hub's details, a configured hub id keeps the hub the source is recorded from.
735
+ if (hub === undefined && source.hubId !== undefined && !(0, record_file_shape_1.isRecordHubId)(source.hubId)) {
736
+ const recordedHubId = [target, other]
737
+ .map((file) => file !== undefined && Object.hasOwn(file.record.sources, sourceId) ? file.record.sources[sourceId].hubId : undefined)
738
+ .find((id) => id !== undefined && (0, record_file_shape_1.isRecordHubId)(id));
739
+ if (recordedHubId !== undefined) {
740
+ source.hubId = recordedHubId;
741
+ }
742
+ }
743
+ const bundleIndex = input.bundleFiles === undefined ? undefined : indexBundleFiles(input.bundleFiles);
744
+ const written = await this.toRecordedFiles(location.root, input.writtenPaths, input.workspaceRoot, bundleIndex);
745
+ const identity = (0, record_identity_1.recordIdentityOf)(bundleId, input.version);
746
+ const previous = this.removeSameIdentity(target.record, bundleId, identity, tool);
747
+ const moved = other === undefined ? [] : this.removeSameIdentity(other.record, bundleId, identity, tool);
748
+ previous.push(...moved);
749
+ if (other !== undefined) {
750
+ for (const prior of moved) {
751
+ this.dropUnusedSource(other.record, prior.sourceId);
752
+ }
753
+ }
754
+ const previousMcp = previous.flatMap((prior) => prior.mcpServers ?? []);
755
+ const mcpServers = input.mcpServers === undefined ? uniqueMcpServers(previousMcp) : uniqueMcpServers(input.mcpServers);
756
+ const entry = (0, record_entry_1.putToolEntry)(target.record, bundleId, tool, {
757
+ version: input.version,
758
+ sourceId,
759
+ sourceType: input.sourceType,
760
+ installedAt: this.now().toISOString(),
761
+ ...(bundleIndex === undefined ? {} : { integrity: integrityOf(bundleIndex) }),
762
+ files: written
763
+ });
764
+ const { files } = entry;
765
+ if (mcpServers.length > 0) {
766
+ entry.mcpServers = mcpServers;
767
+ }
768
+ if (input.name !== undefined && input.name !== '') {
769
+ target.record.bundles[bundleId].name = (0, record_file_shape_1.recordBundleNameOf)(input.name, input.version);
770
+ }
771
+ target.record.sources[sourceId] = source;
772
+ attachHub(target.record, source, hub, other?.record);
773
+ const loaded = other === undefined ? [target] : [target, other];
774
+ const sync = input.syncSiblings === false
775
+ ? { siblings: [], changed: new Set() }
776
+ : this.syncSiblingEntries(loaded, {
777
+ bundleId,
778
+ identity,
779
+ tool,
780
+ sourceId,
781
+ version: input.version,
782
+ ...(entry.integrity === undefined ? {} : { integrity: entry.integrity }),
783
+ files,
784
+ previousPaths: new Set(previous.flatMap((prior) => prior.files.map((file) => file.path))),
785
+ accepts: typeof input.syncSiblings === 'function' ? input.syncSiblings : () => true
786
+ });
787
+ const newPaths = new Set(files.map((file) => file.path));
788
+ const stillListed = (0, exports.listedPaths)(loaded.map((file) => file.record));
789
+ const deletedFiles = [];
790
+ const keptSharedFiles = [];
791
+ for (const old of previous.flatMap((prior) => prior.files)) {
792
+ const oldPath = old.path;
793
+ if (newPaths.has(oldPath) || deletedFiles.includes(oldPath) || keptSharedFiles.includes(oldPath)) {
794
+ continue;
795
+ }
796
+ (stillListed.has(oldPath) ? keptSharedFiles : deletedFiles).push(oldPath);
797
+ }
798
+ for (const aliased of await this.aliasedListedPaths(location.root, deletedFiles, stillListed)) {
799
+ deletedFiles.splice(deletedFiles.indexOf(aliased), 1);
800
+ keptSharedFiles.push(aliased);
801
+ }
802
+ const stillListedMcp = (0, exports.listedMcpServers)(loaded.map((file) => file.record));
803
+ const removedMcpServers = uniqueMcpServers(previousMcp.filter((server) => !stillListedMcp.has((0, mcp_servers_1.mcpServerKeyOf)(server))));
804
+ // A reinstall clears the bundle's `unknown` entries of any version; their files are only no longer listed.
805
+ const clearedOther = other !== undefined && this.clearUnknown(other.record, bundleId, identity);
806
+ this.clearUnknown(target.record, bundleId, identity);
807
+ const warnings = [...(await this.save(location, target.record)).warnings];
808
+ if (other !== undefined && (moved.length > 0 || clearedOther || sync.changed.has(other))) {
809
+ warnings.push(...(await this.saveOther(other)));
810
+ }
811
+ const synced = sync.siblings.filter((sibling) => sibling.synced);
812
+ return {
813
+ changedEntries: [{ bundleId, tool }, ...synced.map((sibling) => ({ bundleId, tool: sibling.tool }))],
814
+ deletedFiles: deletedFiles.toSorted(core_1.compareCodeUnits),
815
+ keptSharedFiles: keptSharedFiles.toSorted(core_1.compareCodeUnits),
816
+ ...(removedMcpServers.length > 0 ? { removedMcpServers } : {}),
817
+ location,
818
+ warnings,
819
+ siblings: sync.siblings
820
+ };
821
+ }
822
+ /**
823
+ * Record that a tool's install of a bundle was removed, from whichever
824
+ * repository file holds it. Paths another entry still lists go to
825
+ * `keptSharedFiles`. Deletes no installed file.
826
+ * @param input - Location, bundle id and tool.
827
+ * @param input.location - Either repository record location; both files at its root are read.
828
+ * @param input.bundleId - Bundle id.
829
+ * @param input.tool - The target's type.
830
+ * @throws {RegistryError} `RECORD.ENTRY_NOT_FOUND` when neither file has the entry.
831
+ */
832
+ recordUninstall(input) {
833
+ return serializeByRoot(input.location.root, () => this.applyUninstall(input));
834
+ }
835
+ // eslint-disable-next-line @typescript-eslint/member-ordering -- kept next to the public method that serializes it
836
+ async applyUninstall(input) {
837
+ const { location, bundleId, tool } = input;
838
+ const first = await this.store.load(location);
839
+ const otherLocation = (0, core_1.otherRepositoryLocation)(location);
840
+ const loaded = otherLocation === undefined ? [first] : [first, await this.store.load(otherLocation)];
841
+ const changed = [];
842
+ for (const file of loaded) {
843
+ const entry = this.removeEntry(file.record, bundleId, tool);
844
+ if (entry !== undefined) {
845
+ changed.push({ file, entry });
846
+ }
847
+ }
848
+ if (changed.length === 0) {
849
+ throw (0, core_1.recordError)('RECORD.ENTRY_NOT_FOUND', {
850
+ file: path.basename(location.path),
851
+ detail: `no entry for bundle ${JSON.stringify(bundleId)} and tool ${JSON.stringify(tool)}`,
852
+ context: { bundleId, tool }
853
+ });
854
+ }
855
+ const stillListed = (0, exports.listedPaths)(loaded.map((file) => file.record));
856
+ const deletedFiles = new Set();
857
+ const keptSharedFiles = new Set();
858
+ for (const { file, entry } of changed) {
859
+ for (const recorded of entry.files) {
860
+ (stillListed.has(recorded.path) ? keptSharedFiles : deletedFiles).add(recorded.path);
861
+ }
862
+ this.dropUnusedSource(file.record, entry.sourceId);
863
+ }
864
+ for (const aliased of await this.aliasedListedPaths(location.root, [...deletedFiles], stillListed)) {
865
+ deletedFiles.delete(aliased);
866
+ keptSharedFiles.add(aliased);
867
+ }
868
+ // A server another entry lists, such as a sibling tool sharing the MCP file, stays.
869
+ const stillListedMcp = (0, exports.listedMcpServers)(loaded.map((file) => file.record));
870
+ const removedMcpServers = uniqueMcpServers(changed.flatMap(({ entry }) => entry.mcpServers ?? [])
871
+ .filter((server) => !stillListedMcp.has((0, mcp_servers_1.mcpServerKeyOf)(server))));
872
+ const warnings = [];
873
+ for (const { file } of changed) {
874
+ warnings.push(...(await this.saveOther(file)));
875
+ }
876
+ return {
877
+ changedEntries: [{ bundleId, tool }],
878
+ deletedFiles: [...deletedFiles].toSorted(core_1.compareCodeUnits),
879
+ keptSharedFiles: [...keptSharedFiles].toSorted(core_1.compareCodeUnits),
880
+ ...(removedMcpServers.length > 0 ? { removedMcpServers } : {}),
881
+ location: changed[0].file.location,
882
+ warnings,
883
+ siblings: []
884
+ };
885
+ }
886
+ /**
887
+ * Uninstall one tool's entry and delete its files, keeping files another
888
+ * entry lists, files changed or missing since the install, and `keep`.
889
+ * @param input - The file holding the entry, the bundle id, the tool and extra paths to keep.
890
+ * @throws {RegistryError} `RECORD.ENTRY_NOT_FOUND`, or any `RECORD.*` load or save error.
891
+ */
892
+ async uninstallEntry(input) {
893
+ const { location, bundleId, tool } = input;
894
+ const other = (0, core_1.otherRepositoryLocation)(location);
895
+ const recorded = [];
896
+ for (const file of other === undefined ? [location] : [location, other]) {
897
+ const { record } = await this.store.load(file);
898
+ const bundle = Object.hasOwn(record.bundles, bundleId) ? record.bundles[bundleId] : undefined;
899
+ recorded.push(...(bundle !== undefined && Object.hasOwn(bundle.tools, tool) ? bundle.tools[tool].files : []));
900
+ }
901
+ const changedOrMissing = new Set(await (0, modified_files_1.findModifiedFiles)(this.fs, location.root, recorded));
902
+ const change = await this.recordUninstall({ location, bundleId, tool });
903
+ const isKept = (recordedPath) => changedOrMissing.has(recordedPath) || input.keep?.has(recordedPath) === true;
904
+ const removal = await this.deleteSuperseded({
905
+ location: change.location,
906
+ deletedFiles: change.deletedFiles.filter((recordedPath) => !isKept(recordedPath)),
907
+ ...(change.removedMcpServers === undefined ? {} : { removedMcpServers: change.removedMcpServers })
908
+ });
909
+ const keptOwn = change.deletedFiles.filter((recordedPath) => isKept(recordedPath));
910
+ const modified = [];
911
+ for (const recordedPath of keptOwn.filter((candidate) => changedOrMissing.has(candidate))) {
912
+ const stat = await this.fs.lstat(path.join(change.location.root, ...recordedPath.split('/'))).catch(() => undefined);
913
+ if (stat !== undefined) {
914
+ modified.push(recordedPath);
915
+ }
916
+ }
917
+ return {
918
+ change,
919
+ deleted: removal.deleted,
920
+ kept: [...change.keptSharedFiles, ...keptOwn],
921
+ modified,
922
+ mcpServersRemoved: removal.mcpServersRemoved,
923
+ mcpServersModified: removal.mcpServersModified,
924
+ warnings: [...change.warnings, ...removal.warnings]
925
+ };
926
+ }
927
+ /**
928
+ * Bundles whose only entries across the given record files, under any key
929
+ * of the same identity, are `unknown`, each with its entry.
930
+ * @param locations - Record files of one level, committed first.
931
+ * @throws {RegistryError} Any `RECORD.*` error from loading a file.
932
+ */
933
+ async findLoneUnknown(locations) {
934
+ const byIdentity = new Map();
935
+ for (const located of await this.listToolEntries(locations)) {
936
+ const identity = (0, record_identity_1.recordIdentityOf)(located.bundleId, located.entry.version);
937
+ byIdentity.set(identity, [...(byIdentity.get(identity) ?? []), located]);
938
+ }
939
+ return new Map([...byIdentity.values()]
940
+ .filter((entries) => (0, exports.isLoneUnknown)(entries.map((located) => located.tool)))
941
+ .flatMap((entries) => entries.map((located) => [located.bundleId, located])));
942
+ }
943
+ /**
944
+ * Remove a bundle's `unknown` entry, and those of the same identity under
945
+ * other keys, keeping every file they list, since no tool is known to own them.
946
+ * @param location - A record file of the level.
947
+ * @param bundleId - Bundle id.
948
+ * @throws {RegistryError} `RECORD.ENTRY_NOT_FOUND` when no file has the entry, or another `RECORD.*` error.
949
+ */
950
+ async removeUnknownEntry(location, bundleId) {
951
+ const other = (0, core_1.otherRepositoryLocation)(location);
952
+ const files = other === undefined ? [location] : [location, other];
953
+ const unknown = [];
954
+ // Each file on its own: an interrupted move can leave two copies with different files.
955
+ for (const file of files) {
956
+ unknown.push(...(await this.locateEntries([file], undefined, core_1.UNKNOWN_TOOL_NAME)));
957
+ }
958
+ const identities = new Set(unknown.filter((located) => located.bundleId === bundleId)
959
+ .map((located) => (0, record_identity_1.recordIdentityOf)(bundleId, located.entry.version)));
960
+ const sameIdentity = unknown.filter((located) => identities.has((0, record_identity_1.recordIdentityOf)(located.bundleId, located.entry.version)));
961
+ const keep = new Set(sameIdentity.flatMap((located) => located.entry.files.map((recorded) => recorded.path)));
962
+ const result = await this.uninstallEntry({ location, bundleId, tool: core_1.UNKNOWN_TOOL_NAME, keep });
963
+ const warnings = [...result.warnings];
964
+ for (const otherKey of new Set(sameIdentity.map((located) => located.bundleId).filter((key) => key !== bundleId))) {
965
+ warnings.push(...(await this.recordUninstall({ location, bundleId: otherKey, tool: core_1.UNKNOWN_TOOL_NAME })).warnings);
966
+ }
967
+ return { ...result, kept: [...new Set([...result.kept, ...keep])].toSorted(core_1.compareCodeUnits), warnings };
968
+ }
969
+ /**
970
+ * Move one tool's entry, unchanged, between the committed and the local-only
971
+ * repository file. The tool's entries with the same bundle identity in the
972
+ * target are replaced, so its copy from an interrupted move is too. The
973
+ * target is saved first; deletes nothing.
974
+ * @param input - The file holding the entry, the bundle id and the tool.
975
+ * @returns Both files, with the replaced entries' files to delete after the save.
976
+ * @throws {RegistryError} `RECORD.ENTRY_NOT_FOUND` or `RECORD.MALFORMED`, or any `RECORD.*` load or save error.
977
+ */
978
+ moveEntry(input) {
979
+ return serializeByRoot(input.location.root, () => this.applyMove(input));
980
+ }
981
+ // eslint-disable-next-line @typescript-eslint/member-ordering -- kept next to the public method that serializes it
982
+ async applyMove(input) {
983
+ const { location, bundleId, tool } = input;
984
+ const targetLocation = (0, core_1.otherRepositoryLocation)(location);
985
+ if (targetLocation === undefined) {
986
+ throw (0, core_1.recordError)('RECORD.MALFORMED', { file: path.basename(location.path), detail: 'only a repository entry can change commit mode' });
987
+ }
988
+ const from = await this.store.load(location);
989
+ const to = await this.store.load(targetLocation);
990
+ const entry = this.removeEntry(from.record, bundleId, tool);
991
+ if (entry === undefined) {
992
+ throw (0, core_1.recordError)('RECORD.ENTRY_NOT_FOUND', {
993
+ file: path.basename(location.path),
994
+ detail: `no entry for bundle ${JSON.stringify(bundleId)} and tool ${JSON.stringify(tool)}`,
995
+ context: { bundleId, tool }
996
+ });
997
+ }
998
+ // The store's load checked that the source exists.
999
+ const source = Object.assign(Object.create(null), from.record.sources[entry.sourceId]);
1000
+ this.dropUnusedSource(from.record, entry.sourceId);
1001
+ const replaced = this.removeSameIdentity(to.record, bundleId, (0, record_identity_1.recordIdentityOf)(bundleId, entry.version), tool);
1002
+ (0, record_entry_1.putToolEntry)(to.record, bundleId, tool, entry);
1003
+ to.record.sources[entry.sourceId] = source;
1004
+ attachHub(to.record, source, undefined, from.record);
1005
+ for (const prior of replaced) {
1006
+ this.dropUnusedSource(to.record, prior.sourceId);
1007
+ }
1008
+ const movedPaths = new Set(entry.files.map((file) => file.path));
1009
+ const stillListed = (0, exports.listedPaths)([to.record, from.record]);
1010
+ const deletedFiles = new Set();
1011
+ const keptSharedFiles = new Set();
1012
+ for (const old of replaced.flatMap((prior) => prior.files)) {
1013
+ if (!movedPaths.has(old.path)) {
1014
+ (stillListed.has(old.path) ? keptSharedFiles : deletedFiles).add(old.path);
1015
+ }
1016
+ }
1017
+ const saved = await this.save(targetLocation, to.record);
1018
+ const warnings = [...saved.warnings, ...(await this.saveOther(from))];
1019
+ return {
1020
+ from: location,
1021
+ to: targetLocation,
1022
+ deletedFiles: [...deletedFiles].toSorted(core_1.compareCodeUnits),
1023
+ keptSharedFiles: [...keptSharedFiles].toSorted(core_1.compareCodeUnits),
1024
+ warnings
1025
+ };
1026
+ }
1027
+ /**
1028
+ * Rewrite a source id, and the matching entries' `sourceType`, in both
1029
+ * repository files at a root. Both files load before anything is saved, and
1030
+ * running it again is a no-op.
1031
+ * @param input - Root, the two ids and the source fields for `to`.
1032
+ * @throws {RegistryError} `RECORD.MALFORMED` for a bad id or source, or any `RECORD.*` load or save error.
1033
+ */
1034
+ async remapSource(input) {
1035
+ const { root, from, to } = input;
1036
+ for (const [name, value] of [['from', from], ['to', to]]) {
1037
+ if (typeof value !== 'string' || value === '' || core_1.FORBIDDEN_KEYS.has(value)) {
1038
+ throw (0, core_1.recordError)('RECORD.MALFORMED', { detail: `source id ${name} ${JSON.stringify(value)} cannot be recorded` });
1039
+ }
1040
+ }
1041
+ if (!exports.RECORD_SOURCE_TYPES.includes(input.descriptor.type)) {
1042
+ throw (0, core_1.recordError)('RECORD.MALFORMED', { detail: `source type ${JSON.stringify(input.descriptor.type)} is not a source type` });
1043
+ }
1044
+ const source = (0, sanitize_source_1.sanitizeSource)(input.descriptor);
1045
+ const [committedLocation, localOnlyLocation] = (0, core_1.repositoryLocations)(root);
1046
+ const committedFile = await this.store.load(committedLocation);
1047
+ const loaded = [committedFile, await this.store.load(localOnlyLocation)];
1048
+ const hub = recordedHubOf(source, input.hub);
1049
+ // Records name a source by its readable id; older ones by the configured id.
1050
+ const toId = (0, record_file_shape_1.recordSourceIdOf)(source);
1051
+ const fromIds = [from, ...(input.fromDescriptor === undefined ? [] : [(0, record_file_shape_1.recordSourceIdOf)((0, sanitize_source_1.sanitizeSource)(input.fromDescriptor))])];
1052
+ const changed = loaded.filter((file) => fromIds.map((fromId) => remapInRecord(file.record, fromId, toId, source, hub)).includes(true));
1053
+ const warnings = [];
1054
+ for (const file of changed) {
1055
+ warnings.push(...(await this.save(file.location, file.record)).warnings);
1056
+ }
1057
+ return { changed: changed.map((file) => file.location), warnings };
1058
+ }
1059
+ /**
1060
+ * One status row per (bundle, tool) entry of the given record files, sorted.
1061
+ * An entry in both repository files at one root is listed once.
1062
+ * @param locations - Record files to list.
1063
+ * @throws {RegistryError} Any `RECORD.*` error from loading a file.
1064
+ */
1065
+ async listEntries(locations) {
1066
+ const sources = new Map();
1067
+ for (const location of locations) {
1068
+ sources.set(location.path, (await this.store.load(location)).record.sources);
1069
+ }
1070
+ const rows = (await this.listToolEntries(locations)).map(({ location, bundleId, tool, entry }) => {
1071
+ const recorded = sources.get(location.path);
1072
+ const hubId = recorded !== undefined && Object.hasOwn(recorded, entry.sourceId) ? recorded[entry.sourceId].hubId : undefined;
1073
+ return {
1074
+ bundleId,
1075
+ tool,
1076
+ level: location.level,
1077
+ version: entry.version,
1078
+ record: location.path,
1079
+ needsReinstall: tool === core_1.UNKNOWN_TOOL_NAME || entry.needsReinstall === true,
1080
+ ...(typeof hubId === 'string' && hubId !== '' ? { hubId } : {})
1081
+ };
1082
+ });
1083
+ return rows.toSorted((left, right) => (0, core_1.compareCodeUnits)(left.bundleId, right.bundleId) || (0, core_1.compareCodeUnits)(left.tool, right.tool) || (0, core_1.compareCodeUnits)(left.record, right.record));
1084
+ }
1085
+ /**
1086
+ * A bundle's tool entries in the given record files, in file order.
1087
+ * @param locations - Record files to search, committed first.
1088
+ * @param bundleId - Bundle id.
1089
+ * @param tool - Only this tool's entry, when given.
1090
+ * @throws {RegistryError} Any `RECORD.*` error from loading a file.
1091
+ */
1092
+ findEntries(locations, bundleId, tool) {
1093
+ return this.locateEntries(locations, bundleId, tool);
1094
+ }
1095
+ /**
1096
+ * Every tool entry of every bundle in the given record files, in file order.
1097
+ * @param locations - Record files to list.
1098
+ * @throws {RegistryError} Any `RECORD.*` error from loading a file.
1099
+ */
1100
+ listToolEntries(locations) {
1101
+ return this.locateEntries(locations);
1102
+ }
1103
+ /**
1104
+ * The record file that holds the entry, so a re-record keeps its commit mode.
1105
+ * @param locations - Record files to search, committed first.
1106
+ * @param bundleId - Bundle id.
1107
+ * @param tool - Tool key.
1108
+ * @returns The file holding the entry, the committed one when both do.
1109
+ * @throws {RegistryError} Any `RECORD.*` error from loading a file.
1110
+ */
1111
+ async holdingLocation(locations, bundleId, tool) {
1112
+ return (await this.findEntries(locations, bundleId, tool))[0]?.location;
1113
+ }
1114
+ /**
1115
+ * Recorded paths by bundle id for every bundle with an entry for `tool`, merged across the files.
1116
+ * @param locations - Record files to read.
1117
+ * @param tool - Tool key.
1118
+ * @throws {RegistryError} Any `RECORD.*` error from loading a file.
1119
+ */
1120
+ async entriesForTool(locations, tool) {
1121
+ const entries = new Map();
1122
+ for (const location of locations) {
1123
+ const { record } = await this.store.load(location);
1124
+ for (const [bundleId, bundle] of Object.entries(record.bundles)) {
1125
+ if (Object.hasOwn(bundle.tools, tool)) {
1126
+ const paths = bundle.tools[tool].files.map((file) => file.path);
1127
+ entries.set(bundleId, [...new Set([...(entries.get(bundleId) ?? []), ...paths])]);
1128
+ }
1129
+ }
1130
+ }
1131
+ return new Map([...entries].toSorted(([left], [right]) => (0, core_1.compareCodeUnits)(left, right)));
1132
+ }
1133
+ /**
1134
+ * Delete the files of a saved change. Only regular files and symlinks are
1135
+ * removed; anything refused or failing becomes a warning.
1136
+ * @param change - The saved change.
1137
+ */
1138
+ async deleteSuperseded(change) {
1139
+ const deleted = [];
1140
+ const warnings = [];
1141
+ const mcp = await this.removeRecordedMcpServers(change.location.root, change.removedMcpServers ?? []);
1142
+ warnings.push(...mcp.warnings);
1143
+ for (const recordedPath of change.deletedFiles) {
1144
+ try {
1145
+ const decision = await (0, confine_path_1.resolveDeleteTarget)(this.fs, change.location.root, recordedPath);
1146
+ if (decision.status === 'missing') {
1147
+ continue;
1148
+ }
1149
+ if (decision.status === 'skip') {
1150
+ warnings.push(`Did not remove ${recordedPath}: ${decision.reason}.`);
1151
+ continue;
1152
+ }
1153
+ await this.fs.unlink(decision.absolute);
1154
+ deleted.push(recordedPath);
1155
+ }
1156
+ catch (error) {
1157
+ warnings.push(`Could not remove ${recordedPath}: ${error instanceof Error ? error.message : String(error)}`);
1158
+ }
1159
+ }
1160
+ return { deleted, mcpServersRemoved: mcp.removed, mcpServersModified: mcp.modified, warnings };
1161
+ }
1162
+ /**
1163
+ * Write a bundle's MCP servers into a tool's MCP file under the level root. A
1164
+ * name the file has is replaced only when an entry of the level records it.
1165
+ * @param input - The level's record file, the MCP file and the servers.
1166
+ * @param input.location - Record file the install is recorded in.
1167
+ * @param input.file - The tool's MCP file; it must be inside the level root.
1168
+ * @param input.servers - Servers to write.
1169
+ * @returns The servers as recorded, `config` relative to the level root.
1170
+ * @throws {RegistryError} `RECORD.PATH_OUTSIDE_ROOT`, `RECORD.MCP_CONFLICT` or `RECORD.MCP_CONFIG_UNREADABLE`; the file is then unchanged.
1171
+ */
1172
+ writeMcpServers(input) {
1173
+ // The read-merge-write of the MCP file runs on the root's queue, as record changes do.
1174
+ return serializeByRoot(input.location.root, async () => {
1175
+ const config = await confineMcpConfig(this.fs, input.location.root, input.file.path);
1176
+ const listed = await recordedMcpServerNames(this.store, input.location, config);
1177
+ const written = await (0, mcp_servers_1.writeMcpServers)(this.fs, input.file, input.servers, { isRecorded: (name) => listed.has(name), label: config });
1178
+ return written.map((server) => ({ config, ...server }));
1179
+ });
1180
+ }
1181
+ /**
1182
+ * Check that servers can be written into a tool's MCP file, writing nothing, so
1183
+ * an install can refuse before it writes its other files.
1184
+ * @param input - The level's record file, the MCP file and the servers.
1185
+ * @param input.location - Record file the install is recorded in.
1186
+ * @param input.file - The tool's MCP file; it must be inside the level root.
1187
+ * @param input.servers - Servers to write.
1188
+ * @throws {RegistryError} `RECORD.PATH_OUTSIDE_ROOT`, `RECORD.MCP_CONFLICT` or `RECORD.MCP_CONFIG_UNREADABLE`.
1189
+ */
1190
+ async checkMcpServers(input) {
1191
+ const config = await confineMcpConfig(this.fs, input.location.root, input.file.path);
1192
+ const listed = await recordedMcpServerNames(this.store, input.location, config);
1193
+ await (0, mcp_servers_1.checkMcpServers)(this.fs, input.file, input.servers, { isRecorded: (name) => listed.has(name), label: config });
1194
+ }
1195
+ /**
1196
+ * Add MCP servers to an entry that already exists, as a migration from another
1197
+ * store of them does. Servers the entry lists are left as they are.
1198
+ * @param input - Record file, bundle id, tool and servers.
1199
+ * @param input.location - Either record file of the level; both repository files are searched.
1200
+ * @param input.bundleId - Bundle id.
1201
+ * @param input.tool - Tool key.
1202
+ * @param input.servers - Servers to add, `config` relative to the level root.
1203
+ * @returns `true` when an entry took the servers.
1204
+ * @throws {RegistryError} Any `RECORD.*` load or save error.
1205
+ */
1206
+ addMcpServers(input) {
1207
+ return serializeByRoot(input.location.root, async () => {
1208
+ const otherLocation = (0, core_1.otherRepositoryLocation)(input.location);
1209
+ for (const location of otherLocation === undefined ? [input.location] : [input.location, otherLocation]) {
1210
+ const file = await this.store.load(location);
1211
+ const bundle = Object.hasOwn(file.record.bundles, input.bundleId) ? file.record.bundles[input.bundleId] : undefined;
1212
+ const entry = bundle !== undefined && Object.hasOwn(bundle.tools, input.tool) ? bundle.tools[input.tool] : undefined;
1213
+ if (entry === undefined) {
1214
+ continue;
1215
+ }
1216
+ const merged = uniqueMcpServers([...(entry.mcpServers ?? []), ...input.servers.filter((server) => !(entry.mcpServers ?? []).some((recorded) => (0, mcp_servers_1.mcpServerKeyOf)(recorded) === (0, mcp_servers_1.mcpServerKeyOf)(server)))]);
1217
+ if (merged.length !== (entry.mcpServers ?? []).length) {
1218
+ entry.mcpServers = merged;
1219
+ await this.save(location, file.record);
1220
+ }
1221
+ return true;
1222
+ }
1223
+ return false;
1224
+ });
1225
+ }
1226
+ /**
1227
+ * Every MCP server the entries of a level list for one MCP file, by name, with
1228
+ * the bundle id of an entry listing it.
1229
+ * @param location - Either record file of the level.
1230
+ * @param file - The tool's MCP file; a file outside the level root has none.
1231
+ * @throws {RegistryError} Any `RECORD.*` load error.
1232
+ */
1233
+ async recordedMcpServersIn(location, file) {
1234
+ let config;
1235
+ try {
1236
+ config = mcpConfigPathOf(location.root, file);
1237
+ }
1238
+ catch {
1239
+ return new Map();
1240
+ }
1241
+ const otherLocation = (0, core_1.otherRepositoryLocation)(location);
1242
+ const owners = new Map();
1243
+ for (const recordFile of otherLocation === undefined ? [location] : [location, otherLocation]) {
1244
+ const { record } = await this.store.load(recordFile);
1245
+ for (const [bundleId, bundle] of Object.entries(record.bundles)) {
1246
+ for (const entry of Object.values(bundle.tools)) {
1247
+ for (const server of entry.mcpServers ?? []) {
1248
+ if (server.config === config && !owners.has(server.name)) {
1249
+ owners.set(server.name, bundleId);
1250
+ }
1251
+ }
1252
+ }
1253
+ }
1254
+ }
1255
+ return owners;
1256
+ }
1257
+ /**
1258
+ * Describe servers another writer put in a tool's MCP file, as an entry records them.
1259
+ * Names the file does not have are left out.
1260
+ * @param root - Level root.
1261
+ * @param file - The tool's MCP file; it must be inside the level root.
1262
+ * @param servers - Server names with the bundle item each came from.
1263
+ * @throws {RegistryError} `RECORD.PATH_OUTSIDE_ROOT` or `RECORD.MCP_CONFIG_UNREADABLE`.
1264
+ */
1265
+ async describeMcpServers(root, file, servers) {
1266
+ const config = await confineMcpConfig(this.fs, root, file.path);
1267
+ const current = await (0, mcp_servers_1.readMcpConfig)(this.fs, file, config);
1268
+ const map = (0, core_1.isJsonObject)(current[file.serversKey]) ? current[file.serversKey] : {};
1269
+ return servers.filter((server) => Object.hasOwn(map, server.name)).map((server) => ({
1270
+ config,
1271
+ name: server.name,
1272
+ ...(server.item === undefined ? {} : { item: server.item }),
1273
+ checksum: (0, mcp_servers_1.mcpServerChecksumOf)(map[server.name])
1274
+ }));
1275
+ }
1276
+ /**
1277
+ * Remove recorded MCP servers from their files under a level root, keeping
1278
+ * those whose definition changed; a file outside the root is never touched.
1279
+ * @param root - Level root the `config` paths are relative to.
1280
+ * @param servers - Servers to remove.
1281
+ */
1282
+ async removeRecordedMcpServers(root, servers) {
1283
+ const result = { removed: [], modified: [], warnings: [] };
1284
+ const byConfig = new Map();
1285
+ for (const server of servers) {
1286
+ byConfig.set(server.config, [...(byConfig.get(server.config) ?? []), server]);
1287
+ }
1288
+ for (const [config, ofConfig] of byConfig) {
1289
+ const absolute = path.resolve(root, ...config.split('/'));
1290
+ const confined = await confineMcpConfig(this.fs, root, absolute).then(() => true, () => false);
1291
+ if (!confined) {
1292
+ result.warnings.push(`Did not change ${config}: it is outside ${root}.`);
1293
+ continue;
1294
+ }
1295
+ for (const serversKey of ['servers', 'mcpServers']) {
1296
+ try {
1297
+ const removal = await (0, mcp_servers_1.removeMcpServers)(this.fs, { path: absolute, serversKey }, ofConfig, config);
1298
+ const named = (names) => ofConfig.filter((server) => names.includes(server.name));
1299
+ result.removed.push(...named(removal.removed));
1300
+ result.modified.push(...named(removal.modified));
1301
+ }
1302
+ catch (error) {
1303
+ result.warnings.push(`Did not remove the MCP servers of ${config}: ${error instanceof Error ? error.message : String(error)}`);
1304
+ break;
1305
+ }
1306
+ }
1307
+ }
1308
+ for (const server of result.modified) {
1309
+ result.warnings.push(`Kept MCP server ${server.name} in ${server.config}: it was changed since the install.`);
1310
+ }
1311
+ return result;
1312
+ }
1313
+ /**
1314
+ * Delete the superseded files of several changes saved in one run, keeping
1315
+ * any path a later change listed again.
1316
+ * @param changes - The saved changes, in order.
1317
+ * @throws {RegistryError} Any `RECORD.*` error from loading a file.
1318
+ */
1319
+ async deleteSupersededAfterAll(changes) {
1320
+ const listedByRecord = new Map();
1321
+ const listedMcpByRecord = new Map();
1322
+ const handled = new Set();
1323
+ const result = { deleted: [], mcpServersRemoved: [], mcpServersModified: [], warnings: [] };
1324
+ for (const change of changes) {
1325
+ let listed = listedByRecord.get(change.location.path);
1326
+ if (listed === undefined) {
1327
+ const other = (0, core_1.otherRepositoryLocation)(change.location);
1328
+ const locations = other === undefined ? [change.location] : [change.location, other];
1329
+ const records = [];
1330
+ for (const location of locations) {
1331
+ records.push((await this.store.load(location)).record);
1332
+ }
1333
+ listed = (0, exports.listedPaths)(records);
1334
+ listedByRecord.set(change.location.path, listed);
1335
+ listedMcpByRecord.set(change.location.path, (0, exports.listedMcpServers)(records));
1336
+ }
1337
+ const stillMcp = listedMcpByRecord.get(change.location.path) ?? new Set();
1338
+ const removedMcpServers = (change.removedMcpServers ?? []).filter((server) => {
1339
+ const key = `${change.location.root}\u0000mcp\u0000${(0, mcp_servers_1.mcpServerKeyOf)(server)}`;
1340
+ if (stillMcp.has((0, mcp_servers_1.mcpServerKeyOf)(server)) || handled.has(key)) {
1341
+ return false;
1342
+ }
1343
+ handled.add(key);
1344
+ return true;
1345
+ });
1346
+ const still = listed;
1347
+ const deletedFiles = change.deletedFiles.filter((recordedPath) => {
1348
+ const key = `${change.location.root}\u0000${recordedPath}`;
1349
+ if (still.has(recordedPath) || handled.has(key)) {
1350
+ return false;
1351
+ }
1352
+ handled.add(key);
1353
+ return true;
1354
+ });
1355
+ const removal = await this.deleteSuperseded({ deletedFiles, location: change.location, removedMcpServers });
1356
+ result.deleted.push(...removal.deleted);
1357
+ result.mcpServersRemoved.push(...removal.mcpServersRemoved);
1358
+ result.mcpServersModified.push(...removal.mcpServersModified);
1359
+ result.warnings.push(...removal.warnings);
1360
+ }
1361
+ return result;
1362
+ }
1363
+ }
1364
+ exports.InstallRecordService = InstallRecordService;
1365
+ //# sourceMappingURL=install-record-service.js.map