harnesstap 1.2.0 → 1.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 (202) hide show
  1. package/README.md +28 -15
  2. package/dist/apply-QSS4242W.js +67 -0
  3. package/dist/apply-QSS4242W.js.map +1 -0
  4. package/dist/approve-CNYQY6DC.js +181 -0
  5. package/dist/approve-CNYQY6DC.js.map +1 -0
  6. package/dist/audit-V4SUV7KA.js +434 -0
  7. package/dist/audit-V4SUV7KA.js.map +1 -0
  8. package/dist/auth-63FOHIQ3.js +220 -0
  9. package/dist/auth-63FOHIQ3.js.map +1 -0
  10. package/dist/bin.js +166 -0
  11. package/dist/bin.js.map +1 -0
  12. package/dist/chunk-2H7UOFLK.js +11 -0
  13. package/dist/chunk-2H7UOFLK.js.map +1 -0
  14. package/dist/chunk-2NE3QYMP.js +103 -0
  15. package/dist/chunk-2NE3QYMP.js.map +1 -0
  16. package/dist/chunk-2P2EOYEW.js +1140 -0
  17. package/dist/chunk-2P2EOYEW.js.map +1 -0
  18. package/dist/chunk-37E5M4JX.js +34 -0
  19. package/dist/chunk-37E5M4JX.js.map +1 -0
  20. package/dist/chunk-37LQQWMF.js +496 -0
  21. package/dist/chunk-37LQQWMF.js.map +1 -0
  22. package/dist/chunk-3FIWOI3H.js +98 -0
  23. package/dist/chunk-3FIWOI3H.js.map +1 -0
  24. package/dist/chunk-3PGC6OA3.js +540 -0
  25. package/dist/chunk-3PGC6OA3.js.map +1 -0
  26. package/dist/chunk-4IHKBIY3.js +118 -0
  27. package/dist/chunk-4IHKBIY3.js.map +1 -0
  28. package/dist/chunk-4ZUBRLSP.js +17 -0
  29. package/dist/chunk-4ZUBRLSP.js.map +1 -0
  30. package/dist/chunk-5F3LNDZG.js +9 -0
  31. package/dist/chunk-5F3LNDZG.js.map +1 -0
  32. package/dist/chunk-5TXI6BI2.js +1359 -0
  33. package/dist/chunk-5TXI6BI2.js.map +1 -0
  34. package/dist/chunk-6P5IO4BX.js +235 -0
  35. package/dist/chunk-6P5IO4BX.js.map +1 -0
  36. package/dist/chunk-ABXUKHAU.js +571 -0
  37. package/dist/chunk-ABXUKHAU.js.map +1 -0
  38. package/dist/chunk-AOUDSNRK.js +1357 -0
  39. package/dist/chunk-AOUDSNRK.js.map +1 -0
  40. package/dist/chunk-BNDJJAEI.js +311 -0
  41. package/dist/chunk-BNDJJAEI.js.map +1 -0
  42. package/dist/chunk-C2IWSFF5.js +818 -0
  43. package/dist/chunk-C2IWSFF5.js.map +1 -0
  44. package/dist/chunk-CHQGE2HF.js +283 -0
  45. package/dist/chunk-CHQGE2HF.js.map +1 -0
  46. package/dist/chunk-DEJLP7QJ.js +681 -0
  47. package/dist/chunk-DEJLP7QJ.js.map +1 -0
  48. package/dist/chunk-DJ6FN6EW.js +532 -0
  49. package/dist/chunk-DJ6FN6EW.js.map +1 -0
  50. package/dist/chunk-E4WRTRMH.js +1173 -0
  51. package/dist/chunk-E4WRTRMH.js.map +1 -0
  52. package/dist/chunk-E5QXNU3K.js +238 -0
  53. package/dist/chunk-E5QXNU3K.js.map +1 -0
  54. package/dist/chunk-EMTBGOR3.js +2959 -0
  55. package/dist/chunk-EMTBGOR3.js.map +1 -0
  56. package/dist/chunk-FFWYIGQ4.js +18 -0
  57. package/dist/chunk-FFWYIGQ4.js.map +1 -0
  58. package/dist/chunk-I6XFZLTJ.js +9 -0
  59. package/dist/chunk-I6XFZLTJ.js.map +1 -0
  60. package/dist/chunk-IHWAOIAU.js +172 -0
  61. package/dist/chunk-IHWAOIAU.js.map +1 -0
  62. package/dist/chunk-IHZUYG66.js +583 -0
  63. package/dist/chunk-IHZUYG66.js.map +1 -0
  64. package/dist/chunk-JQOKQKQT.js +158 -0
  65. package/dist/chunk-JQOKQKQT.js.map +1 -0
  66. package/dist/chunk-JRFUTIEH.js +426 -0
  67. package/dist/chunk-JRFUTIEH.js.map +1 -0
  68. package/dist/chunk-KCBI6JQC.js +115 -0
  69. package/dist/chunk-KCBI6JQC.js.map +1 -0
  70. package/dist/chunk-KDUQMINL.js +60 -0
  71. package/dist/chunk-KDUQMINL.js.map +1 -0
  72. package/dist/chunk-KLR2DURP.js +656 -0
  73. package/dist/chunk-KLR2DURP.js.map +1 -0
  74. package/dist/chunk-KRI4R7EM.js +25 -0
  75. package/dist/chunk-KRI4R7EM.js.map +1 -0
  76. package/dist/chunk-LYQMK6SV.js +87 -0
  77. package/dist/chunk-LYQMK6SV.js.map +1 -0
  78. package/dist/chunk-MK3Q37ZN.js +183 -0
  79. package/dist/chunk-MK3Q37ZN.js.map +1 -0
  80. package/dist/chunk-MSGAGV7B.js +346 -0
  81. package/dist/chunk-MSGAGV7B.js.map +1 -0
  82. package/dist/chunk-MZQRSERO.js +430 -0
  83. package/dist/chunk-MZQRSERO.js.map +1 -0
  84. package/dist/chunk-N3WIJXXM.js +691 -0
  85. package/dist/chunk-N3WIJXXM.js.map +1 -0
  86. package/dist/chunk-NAGAJ5UM.js +145 -0
  87. package/dist/chunk-NAGAJ5UM.js.map +1 -0
  88. package/dist/chunk-NFYPBTKO.js +302 -0
  89. package/dist/chunk-NFYPBTKO.js.map +1 -0
  90. package/dist/chunk-NPO2IG6G.js +491 -0
  91. package/dist/chunk-NPO2IG6G.js.map +1 -0
  92. package/dist/chunk-OS6NUIBJ.js +38 -0
  93. package/dist/chunk-OS6NUIBJ.js.map +1 -0
  94. package/dist/chunk-PFUK3HJ4.js +296 -0
  95. package/dist/chunk-PFUK3HJ4.js.map +1 -0
  96. package/dist/chunk-PMQ55GDB.js +115 -0
  97. package/dist/chunk-PMQ55GDB.js.map +1 -0
  98. package/dist/chunk-QIVE2YFJ.js +514 -0
  99. package/dist/chunk-QIVE2YFJ.js.map +1 -0
  100. package/dist/chunk-QKXD3EUF.js +691 -0
  101. package/dist/chunk-QKXD3EUF.js.map +1 -0
  102. package/dist/chunk-RNQYUWF6.js +32 -0
  103. package/dist/chunk-RNQYUWF6.js.map +1 -0
  104. package/dist/chunk-S2E4SSQV.js +41 -0
  105. package/dist/chunk-S2E4SSQV.js.map +1 -0
  106. package/dist/chunk-SN4BXX3B.js +186 -0
  107. package/dist/chunk-SN4BXX3B.js.map +1 -0
  108. package/dist/chunk-SNVAMWB7.js +40 -0
  109. package/dist/chunk-SNVAMWB7.js.map +1 -0
  110. package/dist/chunk-T5VRREN4.js +696 -0
  111. package/dist/chunk-T5VRREN4.js.map +1 -0
  112. package/dist/chunk-TKBMHZTS.js +10945 -0
  113. package/dist/chunk-TKBMHZTS.js.map +1 -0
  114. package/dist/chunk-TNJPTUE4.js +35 -0
  115. package/dist/chunk-TNJPTUE4.js.map +1 -0
  116. package/dist/chunk-TQ2NA4Z4.js +24 -0
  117. package/dist/chunk-TQ2NA4Z4.js.map +1 -0
  118. package/dist/chunk-TXXDMDPN.js +998 -0
  119. package/dist/chunk-TXXDMDPN.js.map +1 -0
  120. package/dist/chunk-UWXUBU7V.js +184 -0
  121. package/dist/chunk-UWXUBU7V.js.map +1 -0
  122. package/dist/chunk-UYRK2H24.js +141 -0
  123. package/dist/chunk-UYRK2H24.js.map +1 -0
  124. package/dist/chunk-V4IXIM3C.js +806 -0
  125. package/dist/chunk-V4IXIM3C.js.map +1 -0
  126. package/dist/chunk-VFHVXXP4.js +6438 -0
  127. package/dist/chunk-VFHVXXP4.js.map +1 -0
  128. package/dist/chunk-VQVUJYYY.js +244 -0
  129. package/dist/chunk-VQVUJYYY.js.map +1 -0
  130. package/dist/chunk-VZQG2JDV.js +9 -0
  131. package/dist/chunk-VZQG2JDV.js.map +1 -0
  132. package/dist/chunk-W7HQ5X3S.js +610 -0
  133. package/dist/chunk-W7HQ5X3S.js.map +1 -0
  134. package/dist/chunk-WMSQAFK5.js +65 -0
  135. package/dist/chunk-WMSQAFK5.js.map +1 -0
  136. package/dist/chunk-WMYTBJPB.js +364 -0
  137. package/dist/chunk-WMYTBJPB.js.map +1 -0
  138. package/dist/chunk-WNLFNCOH.js +7795 -0
  139. package/dist/chunk-WNLFNCOH.js.map +1 -0
  140. package/dist/chunk-WRX7CB2M.js +6448 -0
  141. package/dist/chunk-WRX7CB2M.js.map +1 -0
  142. package/dist/chunk-XGTTOO4R.js +84 -0
  143. package/dist/chunk-XGTTOO4R.js.map +1 -0
  144. package/dist/chunk-YSXRBUR4.js +682 -0
  145. package/dist/chunk-YSXRBUR4.js.map +1 -0
  146. package/dist/chunk-YTC2EG64.js +1759 -0
  147. package/dist/chunk-YTC2EG64.js.map +1 -0
  148. package/dist/compile-J3UGQSS3.js +161 -0
  149. package/dist/compile-J3UGQSS3.js.map +1 -0
  150. package/dist/config-5BPSZND3.js +438 -0
  151. package/dist/config-5BPSZND3.js.map +1 -0
  152. package/dist/doctor-BVFKLJVO.js +111 -0
  153. package/dist/doctor-BVFKLJVO.js.map +1 -0
  154. package/dist/environment-3RI5H32O.js +2745 -0
  155. package/dist/environment-3RI5H32O.js.map +1 -0
  156. package/dist/github-YFJQVH5K.js +114 -0
  157. package/dist/github-YFJQVH5K.js.map +1 -0
  158. package/dist/harness-ECGHPEKA.js +746 -0
  159. package/dist/harness-ECGHPEKA.js.map +1 -0
  160. package/dist/help-ELPNPPEM.js +2079 -0
  161. package/dist/help-ELPNPPEM.js.map +1 -0
  162. package/dist/help-UL5XLY3I.js +1892 -0
  163. package/dist/help-UL5XLY3I.js.map +1 -0
  164. package/dist/index.d.ts +164 -1
  165. package/dist/index.js +50 -59246
  166. package/dist/index.js.map +1 -1
  167. package/dist/init-UJQTDHW7.js +873 -0
  168. package/dist/init-UJQTDHW7.js.map +1 -0
  169. package/dist/lock-XUMJ63NZ.js +455 -0
  170. package/dist/lock-XUMJ63NZ.js.map +1 -0
  171. package/dist/marketplace-ZUMOLVXE.js +495 -0
  172. package/dist/marketplace-ZUMOLVXE.js.map +1 -0
  173. package/dist/mcp-RZA5O2ND.js +202 -0
  174. package/dist/mcp-RZA5O2ND.js.map +1 -0
  175. package/dist/migrate-CYQI2FH6.js +1043 -0
  176. package/dist/migrate-CYQI2FH6.js.map +1 -0
  177. package/dist/open-AWOAWLKO.js +32 -0
  178. package/dist/open-AWOAWLKO.js.map +1 -0
  179. package/dist/pack-2QD5ZUIO.js +99 -0
  180. package/dist/pack-2QD5ZUIO.js.map +1 -0
  181. package/dist/plugin-GQSSSFX4.js +64 -0
  182. package/dist/plugin-GQSSSFX4.js.map +1 -0
  183. package/dist/plugin-from-project-SIQUFYIO.js +16 -0
  184. package/dist/plugin-from-project-SIQUFYIO.js.map +1 -0
  185. package/dist/policy-CT4JRCJI.js +105 -0
  186. package/dist/policy-CT4JRCJI.js.map +1 -0
  187. package/dist/profile-4JQ6LECP.js +1886 -0
  188. package/dist/profile-4JQ6LECP.js.map +1 -0
  189. package/dist/project-JG7QWXRG.js +1392 -0
  190. package/dist/project-JG7QWXRG.js.map +1 -0
  191. package/dist/resource-QRMR6CSD.js +555 -0
  192. package/dist/resource-QRMR6CSD.js.map +1 -0
  193. package/dist/version-LZ5POOXY.js +17 -0
  194. package/dist/version-LZ5POOXY.js.map +1 -0
  195. package/package.json +21 -14
  196. package/schemas/ap-package.v1.json +36 -0
  197. package/schemas/fixtures/catalog-missing-schema.ap.json +13 -0
  198. package/schemas/fixtures/confidence.ap.json +13 -0
  199. package/schemas/fixtures/context7.ap.json +13 -0
  200. package/schemas/fixtures/minimal-with-schema.ap.json +13 -0
  201. package/schemas/fixtures/superpowers.ap.json +13 -0
  202. package/schemas/fixtures/third-party-skills.ap.json +13 -0
@@ -0,0 +1,1759 @@
1
+ import {
2
+ registerResourceDirectoriesCommand
3
+ } from "./chunk-SN4BXX3B.js";
4
+ import {
5
+ resolvePluginMutationTarget
6
+ } from "./chunk-QIVE2YFJ.js";
7
+ import {
8
+ buildHarnessLiveStatusMap,
9
+ buildUnifiedDiffLines,
10
+ declaredMcpFromExpectedFiles,
11
+ scopeHostConfigToResource,
12
+ scopeMcpConfigToServer,
13
+ withAffectedResources
14
+ } from "./chunk-V4IXIM3C.js";
15
+ import {
16
+ renderCliError
17
+ } from "./chunk-37LQQWMF.js";
18
+ import {
19
+ addAllUntrackedResourcesToProfile,
20
+ addResourceToProfile,
21
+ applyProfilePlugin,
22
+ buildHostManagedStatus,
23
+ buildProfileContents,
24
+ clearGlobalProfileApply,
25
+ collectProfilePluginIds,
26
+ commitManagedPathFromLive,
27
+ commitManagedResourceFromLive,
28
+ detectNotStagedProfileResources,
29
+ emptyPlannedRemovals,
30
+ fileContentsEquivalentForDrift,
31
+ generateFiles,
32
+ getActiveProfileName,
33
+ getGitOrigin,
34
+ groupPlannedRemovals,
35
+ hostPluginPinIsInstalled,
36
+ isMcpConfigManagedPath,
37
+ listHostNativeMcpNames,
38
+ mergePluginsForApply,
39
+ normalizeGitUrl,
40
+ normalizeManagedPath,
41
+ planSafeFileRemovals,
42
+ profileSkillNameMap,
43
+ resourceKeyFromManagedPath,
44
+ toContentsResource
45
+ } from "./chunk-WNLFNCOH.js";
46
+ import {
47
+ isPromptCancellationError,
48
+ promptForConfirmation,
49
+ shouldUseBrowsePicker
50
+ } from "./chunk-NAGAJ5UM.js";
51
+ import {
52
+ initializeSchema
53
+ } from "./chunk-N3WIJXXM.js";
54
+ import {
55
+ isEmptyBuiltinProfile,
56
+ isProfilePlugin
57
+ } from "./chunk-TNJPTUE4.js";
58
+ import {
59
+ getLatestSnapshot
60
+ } from "./chunk-KDUQMINL.js";
61
+ import {
62
+ getHarnessPreference,
63
+ getProjectByLocalPath,
64
+ getProjectByOrigin,
65
+ registeredHarnessesOf
66
+ } from "./chunk-PFUK3HJ4.js";
67
+ import {
68
+ detectPlatforms,
69
+ isPortableMcpResource
70
+ } from "./chunk-WRX7CB2M.js";
71
+ import {
72
+ MATERIAL_RESOURCE_TYPES,
73
+ SingletonConflictError,
74
+ UnsatisfiableConstraintError,
75
+ findResourceByKey,
76
+ getPlatform,
77
+ getPluginResources,
78
+ getResource,
79
+ isMergeableHostConfigPath,
80
+ markPluginDirty,
81
+ mcpConfigContentsEquivalent,
82
+ parseMcpServersDocument,
83
+ parseResourceSelector,
84
+ removeResourceFromPlugin,
85
+ resolveHomeRoot,
86
+ resolvePluginSelector,
87
+ resolveResource,
88
+ resourceHarnessScope,
89
+ touchPluginUpdatedAt
90
+ } from "./chunk-TKBMHZTS.js";
91
+ import {
92
+ COMMAND_HELP_REGISTRY
93
+ } from "./chunk-5TXI6BI2.js";
94
+ import {
95
+ parseOutputFormat,
96
+ printJson
97
+ } from "./chunk-TQ2NA4Z4.js";
98
+ import {
99
+ CliUsageError,
100
+ fail,
101
+ formatCommand,
102
+ missingRequiredArg
103
+ } from "./chunk-NFYPBTKO.js";
104
+ import {
105
+ formatCount,
106
+ ui
107
+ } from "./chunk-ABXUKHAU.js";
108
+ import {
109
+ getDb
110
+ } from "./chunk-KLR2DURP.js";
111
+
112
+ // src/copy/scope.ts
113
+ var SCOPE_COPY = {
114
+ appliesToAll: "Applies to all your harnesses",
115
+ notSetUp: "Not set up for any harness yet",
116
+ detectHarnesses: "Detect harnesses",
117
+ foundInSettingsSuffix: "Found in its settings.",
118
+ useOn: "Use on",
119
+ selectAll: "Select all",
120
+ none: "None",
121
+ emptyHint: "Pick at least one harness",
122
+ linkedTooltip: "These read the same folder, so they share one setting",
123
+ allTooltip: "On all harnesses. Pick which ones",
124
+ orphanedTooltip: "Its harnesses are gone. Pick new ones",
125
+ main: "Main",
126
+ mainTooltip: "Your main harness. It wins when harnesses disagree.",
127
+ alsoUseOnPrefix: "Also use on",
128
+ notNow: "Not now",
129
+ willWrite: "Will write",
130
+ upToDate: "Up to date",
131
+ notInProfile: "Not in profile",
132
+ willRemove: "Will remove",
133
+ keptYouChanged: "Kept. You changed it.",
134
+ keptNotMadeByHarnessTap: "Kept. Not made by HarnessTap."
135
+ };
136
+ function harnessDisplayName(id) {
137
+ return getPlatform(id)?.name ?? id;
138
+ }
139
+ function formatHarnessList(names) {
140
+ if (names.length === 0) {
141
+ return "";
142
+ }
143
+ if (names.length === 1) {
144
+ return names[0] ?? "";
145
+ }
146
+ if (names.length === 2) {
147
+ return `${names[0]} and ${names[1]}`;
148
+ }
149
+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
150
+ }
151
+ function formatHarnessIds(ids) {
152
+ return formatHarnessList(ids.map(harnessDisplayName));
153
+ }
154
+ function subsetScopeLine(ids) {
155
+ if (ids.length === 0) {
156
+ return SCOPE_COPY.notSetUp;
157
+ }
158
+ if (ids.length <= 3) {
159
+ return `Only on ${formatHarnessIds(ids)}`;
160
+ }
161
+ const visible = ids.slice(0, 3).map(harnessDisplayName);
162
+ const extra = ids.length - visible.length;
163
+ return `Only on ${visible.join(", ")} and ${extra} more`;
164
+ }
165
+ function scopeLine(scope, options) {
166
+ if (scope.kind === "all") {
167
+ return SCOPE_COPY.appliesToAll;
168
+ }
169
+ const line = subsetScopeLine(scope.harnesses);
170
+ if (options?.originPortable && scope.harnesses.length === 1) {
171
+ return `${line}. ${SCOPE_COPY.foundInSettingsSuffix}`;
172
+ }
173
+ return line;
174
+ }
175
+ function portableScopeTip(input) {
176
+ return `Tip: "${input.resourceName}" also works on ${formatHarnessIds(input.targetIds)}. Run ${input.command}.`;
177
+ }
178
+
179
+ // src/cli/commands/profile-live-files.ts
180
+ import { Option } from "commander";
181
+
182
+ // src/services/profile-file-diff.ts
183
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
184
+ import { isAbsolute, join as join2 } from "path";
185
+
186
+ // src/services/profile-apply-preview.ts
187
+ import { existsSync, readFileSync } from "fs";
188
+ import { join, resolve } from "path";
189
+
190
+ // src/services/apply-preview-inherited.ts
191
+ var MATERIAL_TYPE_SET = new Set(MATERIAL_RESOURCE_TYPES);
192
+ function findMaterialResource(type, name) {
193
+ if (!MATERIAL_TYPE_SET.has(type)) {
194
+ return void 0;
195
+ }
196
+ return getResource(`${type}:${name}`) ?? findResourceByKey(type, name, "");
197
+ }
198
+ function nativeMcpNamesForPath(homeRoot, path) {
199
+ const normalized = path.replace(/\\/g, "/");
200
+ if (normalized.includes(".cursor/") && /(^|\/)mcp\.json$/i.test(normalized)) {
201
+ return listHostNativeMcpNames(homeRoot, "cursor");
202
+ }
203
+ if (/(^|\/)\.mcp\.json$/i.test(normalized) || /(^|\/)\.claude\.json$/i.test(normalized)) {
204
+ return listHostNativeMcpNames(homeRoot, "claude-code");
205
+ }
206
+ return /* @__PURE__ */ new Set();
207
+ }
208
+ function mcpPreviewContentsEquivalent(current, expected, nativeNames) {
209
+ let expectedDocument;
210
+ try {
211
+ expectedDocument = JSON.parse(expected);
212
+ } catch {
213
+ return false;
214
+ }
215
+ const expectedServers = parseMcpServersDocument(expectedDocument);
216
+ const expectedNames = Object.keys(expectedServers);
217
+ const nonNativeExpected = expectedNames.filter((name) => !nativeNames.has(name));
218
+ if (current === null) {
219
+ return expectedNames.length === 0 || nonNativeExpected.length === 0;
220
+ }
221
+ let currentDocument;
222
+ try {
223
+ currentDocument = JSON.parse(current);
224
+ } catch {
225
+ return false;
226
+ }
227
+ const currentServers = parseMcpServersDocument(currentDocument);
228
+ const mergedCurrent = {
229
+ ...currentServers
230
+ };
231
+ for (const name of expectedNames) {
232
+ const expectedMeta = expectedServers[name];
233
+ if (nativeNames.has(name) && expectedMeta && !(name in mergedCurrent)) {
234
+ mergedCurrent[name] = expectedMeta;
235
+ }
236
+ }
237
+ return mcpConfigContentsEquivalent(
238
+ JSON.stringify({ mcpServers: mergedCurrent }),
239
+ JSON.stringify({ mcpServers: expectedServers })
240
+ );
241
+ }
242
+ function collectOwnedPreviewResources(expectedFiles) {
243
+ const order = [];
244
+ const byKey = /* @__PURE__ */ new Map();
245
+ const add = (type, name) => {
246
+ const key = `${type}:${name}`;
247
+ if (byKey.has(key)) {
248
+ return;
249
+ }
250
+ order.push(key);
251
+ byKey.set(key, { type, name });
252
+ };
253
+ for (const file of expectedFiles) {
254
+ const mapped = resourceKeyFromManagedPath(file.path);
255
+ if (mapped) {
256
+ add(mapped.type, mapped.name);
257
+ }
258
+ if (!isMcpConfigManagedPath(file.path)) {
259
+ continue;
260
+ }
261
+ try {
262
+ const document = JSON.parse(file.content);
263
+ for (const name of Object.keys(parseMcpServersDocument(document))) {
264
+ add("mcp_server", name);
265
+ }
266
+ } catch {
267
+ }
268
+ }
269
+ return order.map((key) => byKey.get(key)).filter((entry) => entry !== void 0);
270
+ }
271
+ function resourceIsDeployedHostPluginOwned(type, name, homeRoot) {
272
+ const resource = findMaterialResource(type, name);
273
+ if (!resource || resource.origin_kind !== "marketplace_link" || !resource.origin_ref) {
274
+ return null;
275
+ }
276
+ return {
277
+ originRef: resource.origin_ref,
278
+ installed: hostPluginPinIsInstalled(homeRoot, resource.origin_ref)
279
+ };
280
+ }
281
+ function omitInheritedPluginFileChanges(homeRoot, changes, targetPinRefs2) {
282
+ return changes.filter((change) => {
283
+ if (isMcpConfigManagedPath(change.path)) {
284
+ return true;
285
+ }
286
+ const mapped = change.resource ?? resourceKeyFromManagedPath(change.path);
287
+ if (!mapped || mapped.type === "mcp_server") {
288
+ return true;
289
+ }
290
+ const owned = resourceIsDeployedHostPluginOwned(
291
+ mapped.type,
292
+ mapped.name,
293
+ homeRoot
294
+ );
295
+ if (!owned?.installed) {
296
+ return true;
297
+ }
298
+ switch (change.type) {
299
+ case "deleted":
300
+ case "modified":
301
+ return false;
302
+ case "added":
303
+ return !targetPinRefs2.has(owned.originRef);
304
+ default: {
305
+ const neverType = change.type;
306
+ return neverType;
307
+ }
308
+ }
309
+ });
310
+ }
311
+ function expectedFileMatchesLiveForPreview(homeRoot, file, current) {
312
+ if (isMcpConfigManagedPath(file.path)) {
313
+ const nativeNames = nativeMcpNamesForPath(homeRoot, file.path);
314
+ if (nativeNames.size > 0) {
315
+ return mcpPreviewContentsEquivalent(current, file.content, nativeNames);
316
+ }
317
+ }
318
+ if (current === null) {
319
+ return false;
320
+ }
321
+ return fileContentsEquivalentForDrift(file.path, current, file.content);
322
+ }
323
+
324
+ // src/services/profile-apply-preview.ts
325
+ function warningFromError(error) {
326
+ if (error instanceof UnsatisfiableConstraintError) {
327
+ return {
328
+ warning: error.message,
329
+ recovery_actions: error.actions
330
+ };
331
+ }
332
+ if (error instanceof SingletonConflictError) {
333
+ return {
334
+ warning: error.message,
335
+ recovery_actions: error.actions
336
+ };
337
+ }
338
+ return {
339
+ warning: error instanceof Error ? error.message : String(error)
340
+ };
341
+ }
342
+ function notProfileWarning(pluginName) {
343
+ return {
344
+ warning: `plugin "${pluginName}" is not tagged as a profile`,
345
+ recovery_actions: [
346
+ {
347
+ id: "tag-as-profile",
348
+ label: `Tag ${pluginName} as a profile`,
349
+ pluginName
350
+ }
351
+ ]
352
+ };
353
+ }
354
+ function spreadWarningFields(input) {
355
+ return {
356
+ ...input.warning ? { warning: input.warning } : {},
357
+ ...input.recovery_actions ? { recovery_actions: input.recovery_actions } : {}
358
+ };
359
+ }
360
+ function readRootFile(rootPath, relativePath) {
361
+ const fullPath = join(rootPath, relativePath);
362
+ if (!existsSync(fullPath)) {
363
+ return null;
364
+ }
365
+ try {
366
+ return readFileSync(fullPath, "utf-8");
367
+ } catch {
368
+ return null;
369
+ }
370
+ }
371
+ function declaredMcpFromExpectedApply(expectedApply) {
372
+ return declaredMcpFromExpectedFiles(
373
+ expectedApply.harnesses,
374
+ expectedApply.expected_files ?? []
375
+ );
376
+ }
377
+ function uniqueExpectedFiles(expectedFiles) {
378
+ const seen = /* @__PURE__ */ new Set();
379
+ const unique = [];
380
+ for (const file of expectedFiles) {
381
+ if (seen.has(file.path)) {
382
+ continue;
383
+ }
384
+ seen.add(file.path);
385
+ unique.push(file);
386
+ }
387
+ return unique;
388
+ }
389
+ function compareExpectedFiles(rootPath, expectedFiles) {
390
+ const changes = [];
391
+ const homeRoot = resolveHomeRoot();
392
+ for (const file of uniqueExpectedFiles(expectedFiles)) {
393
+ const current = readRootFile(rootPath, file.path);
394
+ if (expectedFileMatchesLiveForPreview(homeRoot, file, current)) {
395
+ continue;
396
+ }
397
+ if (current === null) {
398
+ changes.push(
399
+ withAffectedResources({ path: file.path, type: "deleted" }, file.content, null)
400
+ );
401
+ continue;
402
+ }
403
+ if (!fileContentsEquivalentForDrift(file.path, current, file.content)) {
404
+ changes.push(
405
+ withAffectedResources(
406
+ { path: file.path, type: "modified" },
407
+ file.content,
408
+ current
409
+ )
410
+ );
411
+ }
412
+ }
413
+ return changes;
414
+ }
415
+ function omitTransparentCrossHarnessAdds(rootPath, expectedFiles, changes) {
416
+ const siblingPathsByResource = /* @__PURE__ */ new Map();
417
+ for (const file of uniqueExpectedFiles(expectedFiles)) {
418
+ const mapped = resourceKeyFromManagedPath(file.path);
419
+ if (!mapped) {
420
+ continue;
421
+ }
422
+ const key = `${mapped.type}:${mapped.name}`;
423
+ const siblings = siblingPathsByResource.get(key) ?? [];
424
+ siblings.push(file.path);
425
+ siblingPathsByResource.set(key, siblings);
426
+ }
427
+ return changes.filter((change) => {
428
+ const mapped = resourceKeyFromManagedPath(change.path);
429
+ if (!mapped) {
430
+ return true;
431
+ }
432
+ const siblings = siblingPathsByResource.get(`${mapped.type}:${mapped.name}`) ?? [];
433
+ switch (change.type) {
434
+ case "deleted": {
435
+ const materializedElsewhere = siblings.some(
436
+ (path) => path !== change.path && readRootFile(rootPath, path) !== null
437
+ );
438
+ return !materializedElsewhere;
439
+ }
440
+ case "added":
441
+ return siblings.length === 0;
442
+ case "modified": {
443
+ const siblingMatches = siblings.some((path) => {
444
+ if (path === change.path) {
445
+ return false;
446
+ }
447
+ const expected = expectedFiles.find((file) => file.path === path);
448
+ if (!expected) {
449
+ return false;
450
+ }
451
+ const current = readRootFile(rootPath, path);
452
+ if (current === null) {
453
+ return false;
454
+ }
455
+ return fileContentsEquivalentForDrift(
456
+ path,
457
+ current,
458
+ expected.content
459
+ );
460
+ });
461
+ return !siblingMatches;
462
+ }
463
+ default: {
464
+ const neverType = change.type;
465
+ return neverType;
466
+ }
467
+ }
468
+ });
469
+ }
470
+ function omitMergeableHostConfigRemovals(changes) {
471
+ return changes.filter(
472
+ (change) => !(change.type === "added" && isMergeableHostConfigPath(change.path))
473
+ );
474
+ }
475
+ function withMappedResources(changes) {
476
+ return changes.map((change) => {
477
+ const mapped = resourceKeyFromManagedPath(change.path);
478
+ return mapped ? { ...change, resource: mapped } : change;
479
+ });
480
+ }
481
+ function pushRemovalChange(next, seen, rootPath, path, removal_group) {
482
+ if (seen.has(path) || isMergeableHostConfigPath(path)) {
483
+ return;
484
+ }
485
+ if (readRootFile(rootPath, path) === null) {
486
+ return;
487
+ }
488
+ seen.add(path);
489
+ next.push({ path, type: "added", removal_group });
490
+ }
491
+ function classifyPreviewRemovals(rootPath, removedFiles, skippedRemovals, extraPaths = []) {
492
+ const candidates = [
493
+ .../* @__PURE__ */ new Set([
494
+ ...removedFiles ?? [],
495
+ ...(skippedRemovals ?? []).filter((skip) => skip.reason !== "missing").map((skip) => skip.path),
496
+ ...extraPaths
497
+ ])
498
+ ];
499
+ const groups = groupPlannedRemovals(planSafeFileRemovals(rootPath, candidates));
500
+ const pull = (list, path) => {
501
+ const index = list.indexOf(path);
502
+ if (index >= 0) {
503
+ list.splice(index, 1);
504
+ }
505
+ };
506
+ for (const skip of skippedRemovals ?? []) {
507
+ if (skip.reason === "missing") {
508
+ continue;
509
+ }
510
+ if (skip.reason === "modified") {
511
+ pull(groups.owned_unmodified, skip.path);
512
+ pull(groups.unmanaged, skip.path);
513
+ if (!groups.owned_modified.includes(skip.path)) {
514
+ groups.owned_modified.push(skip.path);
515
+ }
516
+ continue;
517
+ }
518
+ if (skip.reason === "unmanaged" || skip.reason === "preexisting") {
519
+ pull(groups.owned_unmodified, skip.path);
520
+ pull(groups.owned_modified, skip.path);
521
+ if (!groups.unmanaged.includes(skip.path)) {
522
+ groups.unmanaged.push(skip.path);
523
+ }
524
+ }
525
+ }
526
+ return groups;
527
+ }
528
+ function withManagedRemovals(rootPath, changes, removedFiles, skippedRemovals) {
529
+ const groups = classifyPreviewRemovals(
530
+ rootPath,
531
+ removedFiles,
532
+ skippedRemovals
533
+ );
534
+ const classified = changes.filter((change) => change.type !== "added");
535
+ const seen = new Set(classified.map((change) => change.path));
536
+ for (const path of groups.owned_unmodified) {
537
+ pushRemovalChange(classified, seen, rootPath, path, "owned_unmodified");
538
+ }
539
+ for (const path of groups.owned_modified) {
540
+ pushRemovalChange(classified, seen, rootPath, path, "owned_modified");
541
+ }
542
+ for (const path of groups.unmanaged) {
543
+ pushRemovalChange(classified, seen, rootPath, path, "unmanaged");
544
+ }
545
+ return classified;
546
+ }
547
+ function targetPinRefs(pluginIds) {
548
+ if (!pluginIds || pluginIds.length === 0) {
549
+ return /* @__PURE__ */ new Set();
550
+ }
551
+ return new Set(
552
+ mergePluginsForApply(pluginIds).pluginPins.map((pin) => pin.ref)
553
+ );
554
+ }
555
+ function buildPreviewFileChanges(rootPath, expectedFiles, removedFiles, pluginIds, skippedRemovals) {
556
+ const mapped = withMappedResources(
557
+ omitMergeableHostConfigRemovals(
558
+ omitTransparentCrossHarnessAdds(
559
+ rootPath,
560
+ expectedFiles,
561
+ withManagedRemovals(
562
+ rootPath,
563
+ compareExpectedFiles(rootPath, expectedFiles),
564
+ removedFiles,
565
+ skippedRemovals
566
+ )
567
+ )
568
+ )
569
+ );
570
+ return omitInheritedPluginFileChanges(
571
+ resolveHomeRoot(),
572
+ mapped,
573
+ targetPinRefs(pluginIds)
574
+ );
575
+ }
576
+ function previewFilesResult(rootPath, expectedFiles, removedFiles, pluginIds, skippedRemovals) {
577
+ return {
578
+ expected_count: expectedFiles.length,
579
+ changes: buildPreviewFileChanges(
580
+ rootPath,
581
+ expectedFiles,
582
+ removedFiles,
583
+ pluginIds,
584
+ skippedRemovals
585
+ ),
586
+ root_path: rootPath,
587
+ owned_resources: collectOwnedPreviewResources(expectedFiles)
588
+ };
589
+ }
590
+ function previewRemovals(rootPath, removedFiles, skippedRemovals) {
591
+ return classifyPreviewRemovals(rootPath, removedFiles, skippedRemovals);
592
+ }
593
+ function isMaterialResource(resource) {
594
+ return resource.type !== "plugin";
595
+ }
596
+ async function collectHomeExpectedManagedFiles(profile, harness) {
597
+ const homeRoot = resolveHomeRoot();
598
+ if (isEmptyBuiltinProfile(profile)) {
599
+ try {
600
+ const expectedApply = await clearGlobalProfileApply({
601
+ dryRun: true,
602
+ harness,
603
+ conflictPolicy: "replace",
604
+ pull: false
605
+ });
606
+ return {
607
+ rootPath: homeRoot,
608
+ expectedFiles: uniqueExpectedFiles(expectedApply.expected_files ?? []),
609
+ expectedApply,
610
+ removedFiles: expectedApply.removed_files
611
+ };
612
+ } catch (error) {
613
+ return {
614
+ rootPath: homeRoot,
615
+ expectedFiles: [],
616
+ ...warningFromError(error)
617
+ };
618
+ }
619
+ }
620
+ const plugin = resolvePluginSelector(profile);
621
+ if (!plugin) {
622
+ return {
623
+ rootPath: homeRoot,
624
+ expectedFiles: [],
625
+ warning: `missing plugin "${profile}"`
626
+ };
627
+ }
628
+ if (!isProfilePlugin(plugin)) {
629
+ return {
630
+ rootPath: homeRoot,
631
+ expectedFiles: [],
632
+ ...notProfileWarning(plugin.name)
633
+ };
634
+ }
635
+ const pluginIds = collectProfilePluginIds(plugin);
636
+ try {
637
+ const expectedApply = await applyProfilePlugin(profile, {
638
+ dryRun: true,
639
+ harness,
640
+ conflictPolicy: "replace",
641
+ pull: false
642
+ });
643
+ return {
644
+ rootPath: homeRoot,
645
+ expectedFiles: uniqueExpectedFiles(expectedApply.expected_files ?? []),
646
+ expectedApply,
647
+ pluginIds,
648
+ removedFiles: expectedApply.removed_files
649
+ };
650
+ } catch (error) {
651
+ return {
652
+ rootPath: homeRoot,
653
+ expectedFiles: [],
654
+ pluginIds,
655
+ ...warningFromError(error)
656
+ };
657
+ }
658
+ }
659
+ function snapshotPreviousPaths(resolvedRoot) {
660
+ const gitOriginRaw = getGitOrigin(resolvedRoot);
661
+ const gitOrigin = gitOriginRaw ? normalizeGitUrl(gitOriginRaw) : null;
662
+ const project = getProjectByLocalPath(resolvedRoot) ?? (gitOrigin ? getProjectByOrigin(gitOrigin) : void 0) ?? null;
663
+ const snapshot = project ? getLatestSnapshot(project.id) : null;
664
+ return snapshot ? Object.values(snapshot.state.platform_files).flatMap(
665
+ (files) => Object.keys(files)
666
+ ) : [];
667
+ }
668
+ async function collectProjectExpectedManagedFiles(profile, projectPath, harness) {
669
+ if (!projectPath) {
670
+ return {
671
+ rootPath: resolve(""),
672
+ expectedFiles: [],
673
+ warning: "projectPath is required for project scope"
674
+ };
675
+ }
676
+ const resolvedRoot = resolve(projectPath);
677
+ const plugin = resolvePluginSelector(profile);
678
+ if (!plugin) {
679
+ return {
680
+ rootPath: resolvedRoot,
681
+ expectedFiles: [],
682
+ warning: `missing plugin "${profile}"`
683
+ };
684
+ }
685
+ if (!isProfilePlugin(plugin) && !isEmptyBuiltinProfile(profile)) {
686
+ return {
687
+ rootPath: resolvedRoot,
688
+ expectedFiles: [],
689
+ ...notProfileWarning(plugin.name)
690
+ };
691
+ }
692
+ const detected = detectPlatforms(resolvedRoot);
693
+ const platformIds = harness ? detected.filter((id) => id === harness) : detected;
694
+ if (isEmptyBuiltinProfile(profile) || platformIds.length === 0) {
695
+ return {
696
+ rootPath: resolvedRoot,
697
+ expectedFiles: [],
698
+ removedFiles: snapshotPreviousPaths(resolvedRoot)
699
+ };
700
+ }
701
+ const pluginIds = collectProfilePluginIds(plugin);
702
+ const merged = mergePluginsForApply(pluginIds);
703
+ const material = merged.resources.filter(isMaterialResource);
704
+ try {
705
+ const generated = await generateFiles(material, platformIds, resolvedRoot, {
706
+ target: "project",
707
+ claudeConfig: merged.claude
708
+ });
709
+ const expectedFiles = uniqueExpectedFiles(
710
+ generated.flatMap(
711
+ (result) => result.files.map((file) => ({ path: file.path, content: file.content }))
712
+ )
713
+ );
714
+ const previousPaths = snapshotPreviousPaths(resolvedRoot);
715
+ const desired = new Set(expectedFiles.map((file) => file.path));
716
+ const removedFiles = previousPaths.filter((path) => !desired.has(path));
717
+ return {
718
+ rootPath: resolvedRoot,
719
+ expectedFiles,
720
+ pluginIds,
721
+ removedFiles
722
+ };
723
+ } catch (error) {
724
+ return {
725
+ rootPath: resolvedRoot,
726
+ expectedFiles: [],
727
+ pluginIds,
728
+ ...warningFromError(error)
729
+ };
730
+ }
731
+ }
732
+ async function collectExpectedManagedFiles(input) {
733
+ if (input.scope === "project") {
734
+ return collectProjectExpectedManagedFiles(
735
+ input.profile,
736
+ input.projectPath,
737
+ input.harness
738
+ );
739
+ }
740
+ return collectHomeExpectedManagedFiles(input.profile, input.harness);
741
+ }
742
+ async function previewHomeApply(profile, harness) {
743
+ const collected = await collectHomeExpectedManagedFiles(profile, harness);
744
+ if (collected.warning) {
745
+ if (collected.pluginIds) {
746
+ const merged = mergePluginsForApply(collected.pluginIds);
747
+ const declaredMcpByHarness = {
748
+ "claude-code": merged.resources.filter((resource) => resource.type === "mcp_server").map((resource) => resource.name),
749
+ cursor: merged.resources.filter((resource) => resource.type === "mcp_server").map((resource) => resource.name)
750
+ };
751
+ return {
752
+ harnesses: buildHarnessLiveStatusMap({
753
+ depth: "full",
754
+ homeRoot: collected.rootPath,
755
+ declaredPins: merged.pluginPins,
756
+ declaredMcpByHarness
757
+ }),
758
+ files: {
759
+ expected_count: 0,
760
+ changes: withMappedResources([]),
761
+ root_path: collected.rootPath
762
+ },
763
+ removals: emptyPlannedRemovals(),
764
+ ...spreadWarningFields(collected)
765
+ };
766
+ }
767
+ return {
768
+ files: {
769
+ expected_count: 0,
770
+ changes: withMappedResources([]),
771
+ root_path: collected.rootPath
772
+ },
773
+ removals: emptyPlannedRemovals(),
774
+ ...spreadWarningFields(collected)
775
+ };
776
+ }
777
+ if (isEmptyBuiltinProfile(profile)) {
778
+ return {
779
+ harnesses: buildHarnessLiveStatusMap({
780
+ depth: "full",
781
+ homeRoot: collected.rootPath,
782
+ declaredPins: [],
783
+ declaredMcpByHarness: {}
784
+ }),
785
+ files: previewFilesResult(
786
+ collected.rootPath,
787
+ collected.expectedFiles,
788
+ collected.removedFiles,
789
+ collected.pluginIds,
790
+ collected.expectedApply?.skipped_removals
791
+ ),
792
+ removals: previewRemovals(
793
+ collected.rootPath,
794
+ collected.removedFiles,
795
+ collected.expectedApply?.skipped_removals
796
+ )
797
+ };
798
+ }
799
+ const declaredPins = collected.pluginIds ? mergePluginsForApply(collected.pluginIds).pluginPins : [];
800
+ const declaredMcp = collected.expectedApply ? declaredMcpFromExpectedApply(collected.expectedApply) : { namesByHarness: {}, configsByHarness: {} };
801
+ return {
802
+ harnesses: buildHarnessLiveStatusMap({
803
+ depth: "full",
804
+ homeRoot: collected.rootPath,
805
+ declaredPins,
806
+ declaredMcpByHarness: declaredMcp.namesByHarness,
807
+ expectedMcpConfigsByHarness: declaredMcp.configsByHarness
808
+ }),
809
+ files: previewFilesResult(
810
+ collected.rootPath,
811
+ collected.expectedFiles,
812
+ collected.removedFiles,
813
+ collected.pluginIds,
814
+ collected.expectedApply?.skipped_removals
815
+ ),
816
+ removals: previewRemovals(
817
+ collected.rootPath,
818
+ collected.removedFiles,
819
+ collected.expectedApply?.skipped_removals
820
+ )
821
+ };
822
+ }
823
+ async function previewProjectApply(profile, projectPath, harness) {
824
+ const collected = await collectProjectExpectedManagedFiles(
825
+ profile,
826
+ projectPath,
827
+ harness
828
+ );
829
+ return {
830
+ files: previewFilesResult(
831
+ collected.rootPath,
832
+ collected.expectedFiles,
833
+ collected.removedFiles,
834
+ collected.pluginIds,
835
+ collected.expectedApply?.skipped_removals
836
+ ),
837
+ removals: previewRemovals(
838
+ collected.rootPath,
839
+ collected.removedFiles,
840
+ collected.expectedApply?.skipped_removals
841
+ ),
842
+ ...spreadWarningFields(collected)
843
+ };
844
+ }
845
+ async function previewProfileApply(input) {
846
+ const profile = input.profile.trim();
847
+ const contents = buildProfileContents(profile);
848
+ const relativeToActive = getActiveProfileName() === profile;
849
+ const notStaged = await detectNotStagedProfileResources({
850
+ profileSelector: profile,
851
+ scope: input.scope,
852
+ ...input.projectPath ? { projectPath: input.projectPath } : {},
853
+ ...input.harness ? { harness: input.harness } : {}
854
+ });
855
+ if (input.scope === "project") {
856
+ const projectPreview = await previewProjectApply(
857
+ profile,
858
+ input.projectPath,
859
+ input.harness
860
+ );
861
+ return {
862
+ profile,
863
+ scope: "project",
864
+ contents,
865
+ not_staged: notStaged,
866
+ untracked_resources: notStaged,
867
+ files: projectPreview.files,
868
+ removals: projectPreview.removals,
869
+ relative_to_active: relativeToActive,
870
+ ...spreadWarningFields(projectPreview)
871
+ };
872
+ }
873
+ const homePreview = await previewHomeApply(profile, input.harness);
874
+ return {
875
+ profile,
876
+ scope: "home",
877
+ contents,
878
+ not_staged: notStaged,
879
+ untracked_resources: notStaged,
880
+ ...homePreview.harnesses ? { harnesses: homePreview.harnesses } : {},
881
+ files: homePreview.files,
882
+ removals: homePreview.removals,
883
+ relative_to_active: relativeToActive,
884
+ host_managed: buildHostManagedStatus({
885
+ homeRoot: homePreview.files.root_path,
886
+ profileSkills: profileSkillNameMap(contents?.resources ?? [])
887
+ }),
888
+ ...spreadWarningFields(homePreview)
889
+ };
890
+ }
891
+
892
+ // src/services/profile-file-diff.ts
893
+ var ONE_TO_ONE_DIFF_TYPES = /* @__PURE__ */ new Set(["skill", "agent", "command", "rule", "instruction"]);
894
+ var HOST_CONFIG_DIFF_TYPES = /* @__PURE__ */ new Set(["permission", "hook", "env_var"]);
895
+ function readLiveFile(absolutePath) {
896
+ if (!existsSync2(absolutePath)) {
897
+ return null;
898
+ }
899
+ try {
900
+ return readFileSync2(absolutePath, "utf-8");
901
+ } catch {
902
+ return null;
903
+ }
904
+ }
905
+ function namesEqualIgnoreCase(left, right) {
906
+ return left.toLowerCase() === right.toLowerCase();
907
+ }
908
+ function pathsReferToSameManagedFile(left, right, rootPath) {
909
+ const a = normalizeManagedPath(left, rootPath);
910
+ const b = normalizeManagedPath(right, rootPath);
911
+ if (a === b) {
912
+ return true;
913
+ }
914
+ return a.endsWith(`/${b}`) || b.endsWith(`/${a}`);
915
+ }
916
+ function resolveLiveAbsolute(path, rootPath) {
917
+ const normalized = normalizeManagedPath(path, rootPath);
918
+ if (isAbsolute(normalized)) {
919
+ return normalized;
920
+ }
921
+ return join2(rootPath, normalized);
922
+ }
923
+ function resourceMatchesFile(resource, filePath, rootPath) {
924
+ const mapped = resourceKeyFromManagedPath(filePath, rootPath);
925
+ return mapped !== null && mapped.type === resource.type && namesEqualIgnoreCase(mapped.name, resource.name);
926
+ }
927
+ function findExpectedManagedFile(input) {
928
+ const byPath = input.expectedFiles.find(
929
+ (file) => pathsReferToSameManagedFile(file.path, input.requestedPath, input.rootPath)
930
+ );
931
+ const resource = input.resource;
932
+ if (!resource?.type || !resource.name.trim()) {
933
+ return byPath;
934
+ }
935
+ const byIdentity = input.expectedFiles.find(
936
+ (file) => resourceMatchesFile(resource, file.path, input.rootPath)
937
+ );
938
+ if (ONE_TO_ONE_DIFF_TYPES.has(resource.type)) {
939
+ if (byPath && resourceMatchesFile(resource, byPath.path, input.rootPath)) {
940
+ return byPath;
941
+ }
942
+ return byIdentity ?? byPath;
943
+ }
944
+ if (resource.type === "mcp_server") {
945
+ if (byPath && isMcpConfigManagedPath(byPath.path, input.rootPath)) {
946
+ return byPath;
947
+ }
948
+ return input.expectedFiles.find(
949
+ (file) => isMcpConfigManagedPath(file.path, input.rootPath)
950
+ ) ?? byPath;
951
+ }
952
+ if (HOST_CONFIG_DIFF_TYPES.has(resource.type)) {
953
+ if (byPath && isMergeableHostConfigPath(byPath.path)) {
954
+ return byPath;
955
+ }
956
+ return input.expectedFiles.find((file) => isMergeableHostConfigPath(file.path)) ?? byPath;
957
+ }
958
+ return byIdentity ?? byPath;
959
+ }
960
+ function resolveCurrentAbsolute(input) {
961
+ const matchAbs = join2(
962
+ input.rootPath,
963
+ normalizeManagedPath(input.matchPath, input.rootPath)
964
+ );
965
+ const requestedAbs = resolveLiveAbsolute(input.requestedPath, input.rootPath);
966
+ if (input.resource && ONE_TO_ONE_DIFF_TYPES.has(input.resource.type)) {
967
+ return matchAbs;
968
+ }
969
+ if (existsSync2(requestedAbs)) {
970
+ return requestedAbs;
971
+ }
972
+ return matchAbs;
973
+ }
974
+ function applyResourceScope(input) {
975
+ const resourceName = input.resource?.name.trim() ?? "";
976
+ const resourceType = input.resource?.type ?? "";
977
+ if (!resourceName || !resourceType) {
978
+ return { expected: input.expected, current: input.current };
979
+ }
980
+ if (resourceType === "mcp_server" && isMcpConfigManagedPath(input.relativePath, input.rootPath)) {
981
+ return {
982
+ expected: scopeMcpConfigToServer(input.expected, resourceName) ?? input.expected,
983
+ current: scopeMcpConfigToServer(input.current, resourceName)
984
+ };
985
+ }
986
+ if (HOST_CONFIG_DIFF_TYPES.has(resourceType) && isMergeableHostConfigPath(input.relativePath)) {
987
+ const resource = { type: resourceType, name: resourceName };
988
+ return {
989
+ expected: scopeHostConfigToResource(input.expected, resource) ?? input.expected,
990
+ current: scopeHostConfigToResource(input.current, resource)
991
+ };
992
+ }
993
+ return { expected: input.expected, current: input.current };
994
+ }
995
+ async function getManagedFileDiff(input) {
996
+ const profile = input.profileSelector.trim();
997
+ const requestedPath = input.path.trim();
998
+ const collected = await collectExpectedManagedFiles({
999
+ profile,
1000
+ scope: input.scope,
1001
+ ...input.projectPath ? { projectPath: input.projectPath } : {},
1002
+ ...input.harness ? { harness: input.harness } : {}
1003
+ });
1004
+ if (collected.warning) {
1005
+ throw new Error(collected.warning);
1006
+ }
1007
+ const match = findExpectedManagedFile({
1008
+ expectedFiles: collected.expectedFiles,
1009
+ requestedPath,
1010
+ rootPath: collected.rootPath,
1011
+ ...input.resource ? { resource: input.resource } : {}
1012
+ });
1013
+ if (!match) {
1014
+ const liveAbsolute = resolveLiveAbsolute(requestedPath, collected.rootPath);
1015
+ if (input.resource?.type === "agent" && readLiveFile(liveAbsolute) !== null) {
1016
+ const relativePath2 = normalizeManagedPath(liveAbsolute, collected.rootPath);
1017
+ const live = readLiveFile(liveAbsolute) ?? "";
1018
+ return {
1019
+ path: relativePath2,
1020
+ absolute_path: liveAbsolute,
1021
+ expected: live,
1022
+ current: live
1023
+ };
1024
+ }
1025
+ throw new Error(`Path is not a managed file for this profile: ${input.path}`);
1026
+ }
1027
+ const relativePath = normalizeManagedPath(match.path, collected.rootPath);
1028
+ const absolutePath = resolveCurrentAbsolute({
1029
+ requestedPath,
1030
+ matchPath: match.path,
1031
+ rootPath: collected.rootPath,
1032
+ ...input.resource ? { resource: input.resource } : {}
1033
+ });
1034
+ const scoped = applyResourceScope({
1035
+ relativePath,
1036
+ rootPath: collected.rootPath,
1037
+ expected: match.content,
1038
+ current: readLiveFile(absolutePath),
1039
+ ...input.resource ? { resource: input.resource } : {}
1040
+ });
1041
+ return {
1042
+ path: relativePath,
1043
+ absolute_path: absolutePath,
1044
+ expected: scoped.expected,
1045
+ current: scoped.current
1046
+ };
1047
+ }
1048
+
1049
+ // src/services/profile-remove-resource.ts
1050
+ var COMPOSITION_RESOURCE_TYPES = /* @__PURE__ */ new Set(["plugin"]);
1051
+ function removeResourceFromProfile(input) {
1052
+ const profilePlugin = resolvePluginSelector(input.profileSelector);
1053
+ if (!profilePlugin) {
1054
+ throw new Error(`Profile not found: ${input.profileSelector}`);
1055
+ }
1056
+ if (!isProfilePlugin(profilePlugin)) {
1057
+ throw new Error(`Plugin "${profilePlugin.name}" is not tagged as a profile`);
1058
+ }
1059
+ if (COMPOSITION_RESOURCE_TYPES.has(input.resourceType)) {
1060
+ throw new Error(`Cannot remove composition resource type: ${input.resourceType}`);
1061
+ }
1062
+ const stackPluginIds = collectProfilePluginIds(profilePlugin);
1063
+ const stackPluginIdSet = new Set(stackPluginIds);
1064
+ if (input.pluginId && !stackPluginIdSet.has(input.pluginId)) {
1065
+ throw new Error(`Plugin is not part of profile stack: ${input.pluginId}`);
1066
+ }
1067
+ const selector = `${input.resourceType}:${input.resourceName}`;
1068
+ const resolved = resolveResource(selector, { mode: "compose" });
1069
+ if (resolved.status === "not_found") {
1070
+ throw new Error(`Resource not found in profile: ${selector}`);
1071
+ }
1072
+ if (resolved.status === "ambiguous") {
1073
+ throw new Error(`Ambiguous resource selector: ${selector}`);
1074
+ }
1075
+ const resourceId = resolved.resource.id;
1076
+ const searchPluginIds = input.pluginId ? [input.pluginId] : stackPluginIds;
1077
+ let removedFromPluginId = null;
1078
+ for (const pluginId of searchPluginIds) {
1079
+ const attached = getPluginResources(pluginId);
1080
+ if (attached.some((resource) => resource.id === resourceId)) {
1081
+ markPluginDirty(pluginId);
1082
+ removeResourceFromPlugin(pluginId, resourceId);
1083
+ touchPluginUpdatedAt(pluginId);
1084
+ removedFromPluginId = pluginId;
1085
+ break;
1086
+ }
1087
+ }
1088
+ if (!removedFromPluginId) {
1089
+ throw new Error(`Resource is not attached to profile: ${selector}`);
1090
+ }
1091
+ return toContentsResource(resolved.resource);
1092
+ }
1093
+
1094
+ // src/services/profile-restore-file.ts
1095
+ import { mkdirSync, writeFileSync } from "fs";
1096
+ import { dirname, join as join3 } from "path";
1097
+ async function restoreManagedFile(input) {
1098
+ const profile = input.profileSelector.trim();
1099
+ const requestedPath = normalizeManagedPath(input.path.trim());
1100
+ const collected = await collectExpectedManagedFiles({
1101
+ profile,
1102
+ scope: input.scope,
1103
+ ...input.projectPath ? { projectPath: input.projectPath } : {},
1104
+ ...input.harness ? { harness: input.harness } : {}
1105
+ });
1106
+ if (collected.warning) {
1107
+ throw new Error(collected.warning);
1108
+ }
1109
+ const match = collected.expectedFiles.find((file) => {
1110
+ const normalized = normalizeManagedPath(file.path, collected.rootPath);
1111
+ return normalized === requestedPath || normalizeManagedPath(file.path) === requestedPath;
1112
+ });
1113
+ if (!match) {
1114
+ throw new Error(`Path is not a managed file for this profile: ${input.path}`);
1115
+ }
1116
+ const relativePath = normalizeManagedPath(match.path, collected.rootPath);
1117
+ const absolutePath = join3(collected.rootPath, relativePath);
1118
+ mkdirSync(dirname(absolutePath), { recursive: true });
1119
+ writeFileSync(absolutePath, match.content, "utf-8");
1120
+ return { path: relativePath, absolute_path: absolutePath };
1121
+ }
1122
+
1123
+ // src/cli/handlers/profile-live-files.ts
1124
+ function initDb() {
1125
+ const db = getDb();
1126
+ initializeSchema(db);
1127
+ }
1128
+ function requireTypeNameSelector(raw, commandPath) {
1129
+ if (!raw) {
1130
+ throw missingRequiredArg("selector", commandPath);
1131
+ }
1132
+ const parsed = parseResourceSelector(raw);
1133
+ if (!parsed.type || parsed.name.trim().length === 0) {
1134
+ throw missingRequiredArg("selector", commandPath);
1135
+ }
1136
+ return { type: parsed.type, name: parsed.name };
1137
+ }
1138
+ function requireLiveScope(opts, commandPath) {
1139
+ if (opts.scope !== "home" && opts.scope !== "project") {
1140
+ throw missingRequiredArg("scope", commandPath);
1141
+ }
1142
+ const harness = opts.harness?.trim();
1143
+ if (opts.scope === "project") {
1144
+ const projectPath = opts.project?.trim();
1145
+ if (!projectPath) {
1146
+ throw missingRequiredArg("project", commandPath);
1147
+ }
1148
+ return {
1149
+ scope: opts.scope,
1150
+ projectPath,
1151
+ ...harness ? { harness } : {}
1152
+ };
1153
+ }
1154
+ return {
1155
+ scope: opts.scope,
1156
+ ...harness ? { harness } : {}
1157
+ };
1158
+ }
1159
+ async function confirmOrRefuse(input) {
1160
+ if (input.yes) {
1161
+ return "proceed";
1162
+ }
1163
+ if (shouldUseBrowsePicker({
1164
+ noInteractive: input.noInteractive,
1165
+ format: input.format
1166
+ })) {
1167
+ const confirmed = await promptForConfirmation({
1168
+ message: input.message,
1169
+ default: false
1170
+ });
1171
+ if (!confirmed) {
1172
+ ui.info("Operation cancelled.");
1173
+ return "cancelled";
1174
+ }
1175
+ return "proceed";
1176
+ }
1177
+ process.exitCode = 1;
1178
+ ui.hint("Pass -y to confirm.");
1179
+ return "refused";
1180
+ }
1181
+ async function handleProfileAddResourceCommand(name, opts) {
1182
+ initDb();
1183
+ const format = parseOutputFormat(opts.format);
1184
+ const selector = requireTypeNameSelector(opts.selector, "profile add-resource");
1185
+ const scope = requireLiveScope(opts, "profile add-resource");
1186
+ const resource = await addResourceToProfile({
1187
+ profileSelector: name,
1188
+ resourceType: selector.type,
1189
+ resourceName: selector.name,
1190
+ ...scope
1191
+ });
1192
+ if (format === "json") {
1193
+ printJson({ resource });
1194
+ return;
1195
+ }
1196
+ ui.success(`Added ${selector.type}:${selector.name} to profile ${name}.`);
1197
+ }
1198
+ async function handleProfileAddAllResourcesCommand(name, opts) {
1199
+ initDb();
1200
+ const format = parseOutputFormat(opts.format);
1201
+ const scope = requireLiveScope(opts, "profile add-all-resources");
1202
+ const result = await addAllUntrackedResourcesToProfile({
1203
+ profileSelector: name,
1204
+ ...scope
1205
+ });
1206
+ if (format === "json") {
1207
+ printJson(result);
1208
+ return;
1209
+ }
1210
+ const noun = result.added_count === 1 ? "resource" : "resources";
1211
+ ui.success(`Added ${result.added_count} ${noun} to profile ${name}.`);
1212
+ }
1213
+ async function handleProfileCommitResourceCommand(name, opts) {
1214
+ initDb();
1215
+ const format = parseOutputFormat(opts.format);
1216
+ const scope = requireLiveScope(opts, "profile commit-resource");
1217
+ const path = opts.path?.trim() ?? "";
1218
+ const hasSelector = Boolean(opts.selector?.trim());
1219
+ if (!path && !hasSelector) {
1220
+ throw missingRequiredArg("path", "profile commit-resource");
1221
+ }
1222
+ if (path && !hasSelector) {
1223
+ const resources = await commitManagedPathFromLive({
1224
+ profileSelector: name,
1225
+ path,
1226
+ ...scope
1227
+ });
1228
+ if (format === "json") {
1229
+ printJson({ resource: resources[0] ?? null, resources });
1230
+ return;
1231
+ }
1232
+ ui.success(`Committed ${path} into profile ${name}.`);
1233
+ return;
1234
+ }
1235
+ const selector = requireTypeNameSelector(opts.selector, "profile commit-resource");
1236
+ if (path) {
1237
+ const resources = await commitManagedPathFromLive({
1238
+ profileSelector: name,
1239
+ path,
1240
+ resourceType: selector.type,
1241
+ resourceName: selector.name,
1242
+ ...scope
1243
+ });
1244
+ if (format === "json") {
1245
+ printJson({ resource: resources[0] ?? null, resources });
1246
+ return;
1247
+ }
1248
+ ui.success(`Committed ${path} into profile ${name}.`);
1249
+ return;
1250
+ }
1251
+ const resource = await commitManagedResourceFromLive({
1252
+ profileSelector: name,
1253
+ resourceType: selector.type,
1254
+ resourceName: selector.name,
1255
+ ...scope
1256
+ });
1257
+ if (format === "json") {
1258
+ printJson({ resource });
1259
+ return;
1260
+ }
1261
+ ui.success(`Committed ${selector.type}:${selector.name} into profile ${name}.`);
1262
+ }
1263
+ async function handleProfileRemoveResourceCommand(name, opts) {
1264
+ initDb();
1265
+ const format = parseOutputFormat(opts.format);
1266
+ const selector = requireTypeNameSelector(opts.selector, "profile remove-resource");
1267
+ const gate = await confirmOrRefuse({
1268
+ message: `Remove ${selector.type}:${selector.name} from profile ${name}?`,
1269
+ yes: opts.yes,
1270
+ format: opts.format,
1271
+ noInteractive: opts.noInteractive
1272
+ });
1273
+ if (gate !== "proceed") {
1274
+ return;
1275
+ }
1276
+ const resource = removeResourceFromProfile({
1277
+ profileSelector: name,
1278
+ resourceType: selector.type,
1279
+ resourceName: selector.name,
1280
+ ...opts.pluginId?.trim() ? { pluginId: opts.pluginId.trim() } : {}
1281
+ });
1282
+ if (format === "json") {
1283
+ printJson({ resource });
1284
+ return;
1285
+ }
1286
+ ui.success(`Removed ${selector.type}:${selector.name} from profile ${name}.`);
1287
+ }
1288
+ async function handleProfileRestoreFileCommand(name, opts) {
1289
+ initDb();
1290
+ const format = parseOutputFormat(opts.format);
1291
+ const scope = requireLiveScope(opts, "profile restore-file");
1292
+ const path = opts.path?.trim() ?? "";
1293
+ if (!path) {
1294
+ throw missingRequiredArg("path", "profile restore-file");
1295
+ }
1296
+ const gate = await confirmOrRefuse({
1297
+ message: `Overwrite ${path} with the profile version? Live edits cannot be restored.`,
1298
+ yes: opts.yes,
1299
+ format: opts.format,
1300
+ noInteractive: opts.noInteractive
1301
+ });
1302
+ if (gate !== "proceed") {
1303
+ return;
1304
+ }
1305
+ const result = await restoreManagedFile({
1306
+ profileSelector: name,
1307
+ path,
1308
+ ...scope
1309
+ });
1310
+ if (format === "json") {
1311
+ printJson(result);
1312
+ return;
1313
+ }
1314
+ ui.success(`Restored ${result.path}.`);
1315
+ }
1316
+ async function handleProfileFileDiffCommand(name, opts) {
1317
+ initDb();
1318
+ const format = parseOutputFormat(opts.format);
1319
+ const scope = requireLiveScope(opts, "profile file-diff");
1320
+ const path = opts.path?.trim() ?? "";
1321
+ if (!path) {
1322
+ throw missingRequiredArg("path", "profile file-diff");
1323
+ }
1324
+ const diff = await getManagedFileDiff({
1325
+ profileSelector: name,
1326
+ path,
1327
+ ...scope
1328
+ });
1329
+ if (format === "json") {
1330
+ printJson({
1331
+ path: diff.path,
1332
+ absolute_path: diff.absolute_path,
1333
+ expected: diff.expected,
1334
+ current: diff.current
1335
+ });
1336
+ return;
1337
+ }
1338
+ const lines = buildUnifiedDiffLines(diff.path, diff.current ?? "", diff.expected);
1339
+ console.log(lines.map((line) => line.text).join("\n"));
1340
+ }
1341
+
1342
+ // src/cli/commands/profile-live-files.ts
1343
+ function addFormatInteractiveOptions(cmd) {
1344
+ return cmd.option("--format <mode>", "Output format: human or json", "human").option("--no-interactive", "Disable interactive prompts").option("--interactive", "Enable interactive prompts");
1345
+ }
1346
+ function addLiveScopeOptions(cmd) {
1347
+ return addFormatInteractiveOptions(cmd).addOption(
1348
+ new Option("--scope <home|project>", "home or project").choices(["home", "project"]).makeOptionMandatory()
1349
+ ).option("--project <path>", "Project path (required when --scope project)").option("--harness <slug>", "Harness slug");
1350
+ }
1351
+ async function runLiveAction(work) {
1352
+ try {
1353
+ await work();
1354
+ } catch (err) {
1355
+ if (isPromptCancellationError(err)) {
1356
+ ui.info("Operation cancelled.");
1357
+ process.exitCode = 0;
1358
+ return;
1359
+ }
1360
+ process.exitCode = 1;
1361
+ if (err instanceof CliUsageError) {
1362
+ renderCliError(err);
1363
+ return;
1364
+ }
1365
+ fail(err instanceof Error ? err.message : String(err));
1366
+ }
1367
+ }
1368
+ function assignLiveFileHelp() {
1369
+ COMMAND_HELP_REGISTRY["profile.add-resource"] = {
1370
+ description: "Adopt one untracked on-disk resource into the profile library",
1371
+ examples: [
1372
+ "profile add-resource work --selector skill:foo --scope home",
1373
+ "profile add-resource work --selector skill:foo --scope project --project . --format json"
1374
+ ]
1375
+ };
1376
+ COMMAND_HELP_REGISTRY["profile.add-all-resources"] = {
1377
+ description: "Adopt every untracked material resource in the scope",
1378
+ examples: [
1379
+ "profile add-all-resources work --scope home",
1380
+ "profile add-all-resources work --scope project --project . --format json"
1381
+ ]
1382
+ };
1383
+ COMMAND_HELP_REGISTRY["profile.commit-resource"] = {
1384
+ description: "Snapshot live disk into the profile library",
1385
+ examples: [
1386
+ "profile commit-resource work --path .claude/skills/foo/SKILL.md --scope home",
1387
+ "profile commit-resource work --selector skill:foo --scope home --format json"
1388
+ ]
1389
+ };
1390
+ COMMAND_HELP_REGISTRY["profile.remove-resource"] = {
1391
+ description: "Detach a material resource from the profile stack",
1392
+ examples: [
1393
+ "profile remove-resource work --selector skill:foo -y",
1394
+ "profile remove-resource work --selector skill:foo --format json -y"
1395
+ ]
1396
+ };
1397
+ COMMAND_HELP_REGISTRY["profile.restore-file"] = {
1398
+ description: "Overwrite the live managed file with the profile snapshot",
1399
+ examples: [
1400
+ "profile restore-file work --path .claude/skills/foo/SKILL.md --scope home -y",
1401
+ "profile restore-file work --path .claude/skills/foo/SKILL.md --scope home --format json -y"
1402
+ ]
1403
+ };
1404
+ COMMAND_HELP_REGISTRY["profile.file-diff"] = {
1405
+ description: "Show live content vs after-apply (profile) as a unified diff",
1406
+ examples: [
1407
+ "profile file-diff work --path .claude/skills/foo/SKILL.md --scope home",
1408
+ "profile file-diff work --path .claude/skills/foo/SKILL.md --scope home --format json"
1409
+ ]
1410
+ };
1411
+ }
1412
+ function registerProfileLiveFileCommands(profileCmd) {
1413
+ assignLiveFileHelp();
1414
+ addLiveScopeOptions(
1415
+ profileCmd.command("add-resource").argument("<name>", "Profile plugin name or selector").requiredOption("--selector <type:name>", "Resource selector").description("Adopt one untracked on-disk resource into the profile library")
1416
+ ).action(async (name, opts) => {
1417
+ await runLiveAction(() => handleProfileAddResourceCommand(name, opts));
1418
+ });
1419
+ addLiveScopeOptions(
1420
+ profileCmd.command("add-all-resources").argument("<name>", "Profile plugin name or selector").description("Adopt every untracked material resource in the scope")
1421
+ ).action(async (name, opts) => {
1422
+ await runLiveAction(() => handleProfileAddAllResourcesCommand(name, opts));
1423
+ });
1424
+ addLiveScopeOptions(
1425
+ profileCmd.command("commit-resource").argument("<name>", "Profile plugin name or selector").option("--path <path>", "Managed relative path").option("--selector <type:name>", "Resource selector").description("Snapshot live disk into the profile library")
1426
+ ).action(async (name, opts) => {
1427
+ await runLiveAction(() => handleProfileCommitResourceCommand(name, opts));
1428
+ });
1429
+ addFormatInteractiveOptions(
1430
+ profileCmd.command("remove-resource").argument("<name>", "Profile plugin name or selector").requiredOption("--selector <type:name>", "Resource selector").option("--plugin-id <id>", "Plugin id in the profile stack").option("-y, --yes", "Skip the confirmation prompt").description("Detach a material resource from the profile stack")
1431
+ ).action(async (name, opts) => {
1432
+ await runLiveAction(() => handleProfileRemoveResourceCommand(name, opts));
1433
+ });
1434
+ addLiveScopeOptions(
1435
+ profileCmd.command("restore-file").argument("<name>", "Profile plugin name or selector").requiredOption("--path <path>", "Managed relative path").option("-y, --yes", "Skip the confirmation prompt").description("Overwrite the live managed file with the profile snapshot")
1436
+ ).action(async (name, opts) => {
1437
+ await runLiveAction(() => handleProfileRestoreFileCommand(name, opts));
1438
+ });
1439
+ addLiveScopeOptions(
1440
+ profileCmd.command("file-diff").argument("<name>", "Profile plugin name or selector").requiredOption("--path <path>", "Managed relative path").description("Show live content vs after-apply (profile) as a unified diff")
1441
+ ).action(async (name, opts) => {
1442
+ await runLiveAction(() => handleProfileFileDiffCommand(name, opts));
1443
+ });
1444
+ }
1445
+
1446
+ // src/cli/commands/profile-preview.ts
1447
+ var CLI_PREVIEW_SCOPES = ["home", "project", "both"];
1448
+ var PROFILE_PREVIEW_HELP = {
1449
+ description: "Show apply preview for a profile (contents, files, untracked, recovery) without writing",
1450
+ examples: [
1451
+ "profile preview",
1452
+ "profile preview work --format json",
1453
+ "profile preview work --scope project --project .",
1454
+ "profile preview work --scope both"
1455
+ ]
1456
+ };
1457
+ function isCliPreviewScope(value) {
1458
+ return CLI_PREVIEW_SCOPES.includes(value);
1459
+ }
1460
+ function parseCliPreviewScope(value) {
1461
+ const scope = value ?? "home";
1462
+ if (!isCliPreviewScope(scope)) {
1463
+ throw new CliUsageError(
1464
+ `Invalid --scope value: ${scope}. Use home, project, or both.`
1465
+ );
1466
+ }
1467
+ return scope;
1468
+ }
1469
+ function resolveProjectPathForScope(scope, project) {
1470
+ if (scope === "home") {
1471
+ return void 0;
1472
+ }
1473
+ const projectPath = (project ?? ".").trim();
1474
+ if (!projectPath) {
1475
+ throw new CliUsageError("projectPath is required for project scope");
1476
+ }
1477
+ return projectPath;
1478
+ }
1479
+ async function resolvePreviewProfileName(input) {
1480
+ const trimmed = input.name?.trim();
1481
+ if (trimmed) {
1482
+ return trimmed;
1483
+ }
1484
+ const active = getActiveProfileName();
1485
+ if (active) {
1486
+ return active;
1487
+ }
1488
+ return resolvePluginMutationTarget({
1489
+ pluginName: void 0,
1490
+ profileMode: true,
1491
+ interactive: input.interactive,
1492
+ noInteractive: input.noInteractive,
1493
+ format: input.format,
1494
+ message: "Which profile do you want to preview?"
1495
+ });
1496
+ }
1497
+ function engineScopes(scope) {
1498
+ switch (scope) {
1499
+ case "home":
1500
+ return ["home"];
1501
+ case "project":
1502
+ return ["project"];
1503
+ case "both":
1504
+ return ["home", "project"];
1505
+ default: {
1506
+ const _exhaustive = scope;
1507
+ return _exhaustive;
1508
+ }
1509
+ }
1510
+ }
1511
+ async function loadPreview(input) {
1512
+ return previewProfileApply({
1513
+ profile: input.profile,
1514
+ scope: input.scope,
1515
+ ...input.projectPath ? { projectPath: input.projectPath } : {},
1516
+ ...input.harness ? { harness: input.harness } : {}
1517
+ });
1518
+ }
1519
+ function printInstallGaps(preview) {
1520
+ if (preview.scope !== "home" || !preview.harnesses) {
1521
+ return;
1522
+ }
1523
+ for (const status of Object.values(preview.harnesses)) {
1524
+ for (const plugin of status.plugins) {
1525
+ if (plugin.state === "missing") {
1526
+ ui.dim(`plugin ${plugin.id} not installed`);
1527
+ }
1528
+ }
1529
+ for (const mcp of status.mcp) {
1530
+ switch (mcp.state) {
1531
+ case "missing":
1532
+ ui.dim(`mcp ${mcp.name} not installed`);
1533
+ break;
1534
+ case "mismatch":
1535
+ ui.dim(`mcp ${mcp.name} different value`);
1536
+ break;
1537
+ case "present":
1538
+ case "extra":
1539
+ break;
1540
+ default: {
1541
+ const _exhaustive = mcp.state;
1542
+ void _exhaustive;
1543
+ break;
1544
+ }
1545
+ }
1546
+ }
1547
+ }
1548
+ }
1549
+ function printHostManagedCollisions(preview) {
1550
+ const collisionCount = preview.host_managed?.cursor?.collisions.length ?? 0;
1551
+ if (collisionCount > 0) {
1552
+ ui.warn(
1553
+ `${formatCount(collisionCount, "Cursor host-managed skill name collision")} with user or profile skills.`
1554
+ );
1555
+ }
1556
+ }
1557
+ function previewChangeLabel(change) {
1558
+ switch (change.type) {
1559
+ case "added":
1560
+ case "modified":
1561
+ return SCOPE_COPY.willWrite;
1562
+ case "deleted":
1563
+ return SCOPE_COPY.willRemove;
1564
+ default: {
1565
+ const unhandled = change.type;
1566
+ return String(unhandled);
1567
+ }
1568
+ }
1569
+ }
1570
+ function printPortableMcpTips(preview) {
1571
+ const plugin = resolvePluginSelector(preview.profile);
1572
+ if (!plugin) {
1573
+ return;
1574
+ }
1575
+ const registered = registeredHarnessesOf(getHarnessPreference());
1576
+ if (registered.length === 0) {
1577
+ return;
1578
+ }
1579
+ const resources = mergePluginsForApply(collectProfilePluginIds(plugin)).resources;
1580
+ for (const resource of resources) {
1581
+ if (!isPortableMcpResource(resource)) {
1582
+ continue;
1583
+ }
1584
+ const scope = resourceHarnessScope(resource);
1585
+ if (scope.kind !== "subset") {
1586
+ continue;
1587
+ }
1588
+ const extra = registered.filter((id) => !scope.harnesses.includes(id));
1589
+ if (extra.length === 0) {
1590
+ continue;
1591
+ }
1592
+ const command = formatCommand([
1593
+ "resource",
1594
+ "scope",
1595
+ resource.name,
1596
+ "--add",
1597
+ extra.join(",")
1598
+ ]);
1599
+ ui.hint(
1600
+ portableScopeTip({
1601
+ resourceName: resource.name,
1602
+ targetIds: extra,
1603
+ command
1604
+ })
1605
+ );
1606
+ }
1607
+ }
1608
+ function printHumanPreview(preview) {
1609
+ ui.info(
1610
+ `Profile ${preview.profile} scope=${preview.scope} root=${preview.files.root_path}`
1611
+ );
1612
+ if (preview.relative_to_active) {
1613
+ ui.dim("already active");
1614
+ }
1615
+ if (preview.warning) {
1616
+ ui.warn(preview.warning);
1617
+ }
1618
+ ui.subheader("Contents");
1619
+ const contents = preview.contents;
1620
+ const hasPlugins = (contents?.plugins.length ?? 0) > 0;
1621
+ const hasPins = (contents?.plugin_pins.length ?? 0) > 0;
1622
+ if (contents?.stack_summary) {
1623
+ ui.dim(contents.stack_summary);
1624
+ }
1625
+ if (!contents || !hasPlugins && !hasPins) {
1626
+ ui.hint("Add plugins or resources from your library.");
1627
+ } else {
1628
+ for (const plugin of contents.plugins) {
1629
+ ui.info(`plugin ${plugin.name}@${plugin.version}`);
1630
+ for (const resource of plugin.resources) {
1631
+ const scope = resource.harness_scope ? scopeLine(
1632
+ Array.isArray(resource.harness_scope) ? { kind: "subset", harnesses: resource.harness_scope } : { kind: "all" }
1633
+ ) : SCOPE_COPY.appliesToAll;
1634
+ ui.dim(` ${resource.type}:${resource.name} ${scope}`);
1635
+ }
1636
+ }
1637
+ for (const pin of contents.plugin_pins) {
1638
+ ui.info(`pin ${pin.ref}@${pin.version_constraint}`);
1639
+ }
1640
+ }
1641
+ ui.subheader("Files");
1642
+ const changeCount = preview.files.changes.length;
1643
+ ui.dim(`${changeCount} would change \xB7 ${preview.files.expected_count} managed`);
1644
+ if (changeCount === 0) {
1645
+ ui.hint("No file changes.");
1646
+ } else {
1647
+ for (const change of preview.files.changes) {
1648
+ const resource = change.resource ? ` [${change.resource.type}:${change.resource.name}]` : "";
1649
+ ui.info(`${previewChangeLabel(change)} ${change.path}${resource}`);
1650
+ }
1651
+ }
1652
+ printInstallGaps(preview);
1653
+ const untracked = preview.not_staged.length > 0 ? preview.not_staged : preview.untracked_resources;
1654
+ if (untracked.length > 0) {
1655
+ ui.subheader(SCOPE_COPY.notInProfile);
1656
+ for (const resource of untracked) {
1657
+ ui.info(`${resource.type}:${resource.name} ${resource.source}`);
1658
+ }
1659
+ }
1660
+ if (preview.recovery_actions && preview.recovery_actions.length > 0) {
1661
+ ui.subheader("Recovery");
1662
+ for (const action of preview.recovery_actions) {
1663
+ ui.warn(`${action.id} ${action.label}`);
1664
+ }
1665
+ ui.hint("Recovery stays interactive on apply; preview does not run these.");
1666
+ ui.hint("File adopt/restore is a separate command.");
1667
+ }
1668
+ printHostManagedCollisions(preview);
1669
+ printPortableMcpTips(preview);
1670
+ }
1671
+ async function handleProfilePreviewCommand(name, opts) {
1672
+ const db = getDb();
1673
+ initializeSchema(db);
1674
+ const format = parseOutputFormat(opts.format);
1675
+ const cliScope = parseCliPreviewScope(opts.scope);
1676
+ const projectPath = resolveProjectPathForScope(cliScope, opts.project);
1677
+ const harness = opts.harness?.trim() || void 0;
1678
+ const resolvedName = await resolvePreviewProfileName({
1679
+ name,
1680
+ format: opts.format,
1681
+ interactive: opts.interactive,
1682
+ noInteractive: opts.noInteractive
1683
+ });
1684
+ if (!resolvedName) {
1685
+ process.exitCode = 1;
1686
+ renderCliError(missingRequiredArg("name", "profile preview"));
1687
+ return;
1688
+ }
1689
+ const scopes = engineScopes(cliScope);
1690
+ const previews = [];
1691
+ for (const scope of scopes) {
1692
+ previews.push(
1693
+ await loadPreview({
1694
+ profile: resolvedName,
1695
+ scope,
1696
+ projectPath,
1697
+ harness
1698
+ })
1699
+ );
1700
+ }
1701
+ if (format === "json") {
1702
+ if (cliScope === "both") {
1703
+ printJson({ home: previews[0], project: previews[1] });
1704
+ } else {
1705
+ printJson(previews[0]);
1706
+ }
1707
+ return;
1708
+ }
1709
+ if (cliScope === "both") {
1710
+ const [homePreview, projectPreview] = previews;
1711
+ if (homePreview === void 0 || projectPreview === void 0) {
1712
+ throw new Error("expected home and project apply previews");
1713
+ }
1714
+ ui.header("Home");
1715
+ printHumanPreview(homePreview);
1716
+ ui.header("Project");
1717
+ printHumanPreview(projectPreview);
1718
+ return;
1719
+ }
1720
+ const [preview] = previews;
1721
+ if (preview === void 0) {
1722
+ throw new Error("expected apply preview");
1723
+ }
1724
+ printHumanPreview(preview);
1725
+ }
1726
+ function registerProfilePreviewCommand(profileCmd) {
1727
+ COMMAND_HELP_REGISTRY["profile.preview"] = {
1728
+ description: PROFILE_PREVIEW_HELP.description,
1729
+ examples: [...PROFILE_PREVIEW_HELP.examples]
1730
+ };
1731
+ profileCmd.command("preview").argument("[name]", "Profile plugin name or selector").option("--scope <home|project|both>", "Apply preview scope", "home").option("--project <path>", "Project directory for project scope", ".").option("--harness <slugs>", "Comma-separated harness slugs forwarded to preview").option("--format <mode>", "Output format: human or json", "human").option("--no-interactive", "Disable interactive wizards").option("--interactive", "Prompt instead of relying on explicit flags").description(PROFILE_PREVIEW_HELP.description).action(async (name, opts) => {
1732
+ try {
1733
+ await handleProfilePreviewCommand(name, opts);
1734
+ } catch (error) {
1735
+ if (isPromptCancellationError(error)) {
1736
+ process.exitCode = 1;
1737
+ return;
1738
+ }
1739
+ process.exitCode = 1;
1740
+ renderCliError(error);
1741
+ }
1742
+ });
1743
+ }
1744
+
1745
+ // src/cli/commands/parity-register.ts
1746
+ function registerProfileParityCommands(profileCmd) {
1747
+ registerProfilePreviewCommand(profileCmd);
1748
+ registerProfileLiveFileCommands(profileCmd);
1749
+ }
1750
+ function registerResourceParityCommands(resourceCmd) {
1751
+ registerResourceDirectoriesCommand(resourceCmd);
1752
+ }
1753
+
1754
+ export {
1755
+ scopeLine,
1756
+ registerProfileParityCommands,
1757
+ registerResourceParityCommands
1758
+ };
1759
+ //# sourceMappingURL=chunk-YTC2EG64.js.map