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,1357 @@
1
+ import {
2
+ buildHarnessLiveStatusMap,
3
+ classifyGlobalDriftChanges,
4
+ collectOwnedGlobalProfileFiles,
5
+ computeGlobalProfilePanelStatus,
6
+ countMissingHarnessRows,
7
+ declaredMcpFromExpectedFiles,
8
+ resolveProjectDriftSummary,
9
+ withAffectedResources
10
+ } from "./chunk-V4IXIM3C.js";
11
+ import {
12
+ formatEnvironmentToml,
13
+ importEnvironmentToml
14
+ } from "./chunk-UYRK2H24.js";
15
+ import {
16
+ MISSING_PROJECT_CONFIG_MESSAGE
17
+ } from "./chunk-VZQG2JDV.js";
18
+ import {
19
+ applyProfilePlugin,
20
+ buildContentsFromResources,
21
+ buildHostManagedStatus,
22
+ buildProfileContents,
23
+ captureUntrackedResourcesForStash,
24
+ clearActiveProfileName,
25
+ clearGlobalProfileApply,
26
+ collectProfilePluginIds,
27
+ commitManagedPathFromLive,
28
+ detectNotStagedProfileResources,
29
+ fileContentsEquivalentForDrift,
30
+ flattenLiveRestoreFiles,
31
+ getActiveProfileName,
32
+ getGlobalActiveEnvironmentName,
33
+ getLatestGlobalApplySnapshotForProfile,
34
+ hashOnDiskFile,
35
+ installPluginFromCatalog,
36
+ listMaterializationsForRootPath,
37
+ mergePluginsForApply,
38
+ profileSkillNameMap,
39
+ removeUntrackedStashFiles,
40
+ restoreUntrackedStashFiles,
41
+ stashedFilesToDriftChanges,
42
+ useEnvironmentCommand,
43
+ useProfileCommand,
44
+ withProfileApplyLock
45
+ } from "./chunk-WNLFNCOH.js";
46
+ import {
47
+ promptForChoice,
48
+ promptForConfirmation,
49
+ promptForSearchableChoice,
50
+ shouldUseBrowsePicker,
51
+ shouldUseWizard
52
+ } from "./chunk-NAGAJ5UM.js";
53
+ import {
54
+ isEmptyBuiltinProfile,
55
+ isProfilePlugin
56
+ } from "./chunk-TNJPTUE4.js";
57
+ import {
58
+ findProjectConfig,
59
+ getProfileEntry,
60
+ resolveProfileEnvironment
61
+ } from "./chunk-MSGAGV7B.js";
62
+ import {
63
+ addResourceToPlugin,
64
+ createPlugin,
65
+ normalizeResourceInput,
66
+ resolveHomeRoot,
67
+ resolvePluginSelector,
68
+ upsertResource
69
+ } from "./chunk-TKBMHZTS.js";
70
+ import {
71
+ ON_CONFLICT_VALUE_HELP,
72
+ parseOnConflict
73
+ } from "./chunk-NFYPBTKO.js";
74
+ import {
75
+ ui
76
+ } from "./chunk-ABXUKHAU.js";
77
+ import {
78
+ parsePluginSelector,
79
+ resolveRemotePluginSelector
80
+ } from "./chunk-2P2EOYEW.js";
81
+ import {
82
+ CLI_COPY,
83
+ SWITCH_CHANGES_VALUES,
84
+ applyHeaderLine,
85
+ applyWroteLine,
86
+ discardConfirm,
87
+ discardedChangesLine,
88
+ dryRunSectionHeader,
89
+ dryRunWouldLine,
90
+ getHarnesstapDir,
91
+ keptFilesHeader,
92
+ keptReasonLabel,
93
+ savedChangesLine,
94
+ snapshotSavedUndoLine,
95
+ stashedChangesLine,
96
+ unsavedChangesFlagHint,
97
+ unsavedChangesLine
98
+ } from "./chunk-KLR2DURP.js";
99
+
100
+ // src/utils/user-path.ts
101
+ import { existsSync } from "fs";
102
+ import { isAbsolute, join, resolve } from "path";
103
+ var UserPathError = class extends Error {
104
+ input;
105
+ constructor(input, resolved) {
106
+ super(`Directory not found: ${input}.`);
107
+ this.name = "UserPathError";
108
+ this.input = input;
109
+ this.resolved = resolved;
110
+ }
111
+ resolved;
112
+ };
113
+ function expandUserPath(arg, home = resolveHomeRoot()) {
114
+ const trimmed = arg.trim();
115
+ if (trimmed === "~") {
116
+ return home;
117
+ }
118
+ if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) {
119
+ return join(home, trimmed.slice(2));
120
+ }
121
+ return isAbsolute(trimmed) ? trimmed : resolve(trimmed);
122
+ }
123
+ function resolveUserPath(arg, opts) {
124
+ const resolved = resolve(expandUserPath(arg, opts?.home ?? resolveHomeRoot()));
125
+ if (opts?.mustExist && !existsSync(resolved)) {
126
+ throw new UserPathError(arg, resolved);
127
+ }
128
+ return resolved;
129
+ }
130
+
131
+ // src/services/materialization-conflicts.ts
132
+ function resolveApplyConflictPolicy(opts) {
133
+ const parsed = opts.onConflict ? parseOnConflict(opts.onConflict) : void 0;
134
+ if (parsed === "replace" || parsed === "skip" || parsed === "prompt" || parsed === "cancel") {
135
+ return parsed;
136
+ }
137
+ if (opts.noInteractive || process.env.CI === "true" || process.env.HARNESSTAP_NO_INTERACTIVE === "1" || !process.stdin.isTTY || !process.stdout.isTTY) {
138
+ return "cancel";
139
+ }
140
+ return "prompt";
141
+ }
142
+ async function promptMaterializationConflict(conflict) {
143
+ const ownerSummary = conflict.owners.length > 0 ? conflict.owners.map((owner) => `${owner.plugin_name}@${owner.plugin_version ?? "?"}`).join(", ") : "another plugin or manual edit";
144
+ ui.warn(`File already exists: ${conflict.path}`);
145
+ ui.dim(` Previously written by: ${ownerSummary}`);
146
+ return promptForChoice({
147
+ message: `How should HarnessTap handle ${conflict.path}?`,
148
+ choices: [
149
+ { name: ON_CONFLICT_VALUE_HELP.replace, value: "replace" },
150
+ { name: ON_CONFLICT_VALUE_HELP.skip, value: "skip" },
151
+ { name: ON_CONFLICT_VALUE_HELP.cancel, value: "cancel" }
152
+ ]
153
+ });
154
+ }
155
+
156
+ // src/cli/print-apply-summary.ts
157
+ function keptFromSkippedRemovals(skipped) {
158
+ return (skipped ?? []).flatMap((entry) => {
159
+ const reason = removalSkipReason(entry.reason);
160
+ return reason ? [{ path: entry.path, reason }] : [];
161
+ });
162
+ }
163
+ function printApplyPayload(payload) {
164
+ const kept = keptFromSkippedRemovals(payload.skipped_removals);
165
+ const unchanged = Math.max(0, payload.files.length - payload.written_files.length);
166
+ if (payload.dry_run) {
167
+ printApplyDryRun({
168
+ wouldWrite: payload.written_files,
169
+ wouldRemove: payload.removed_files ?? [],
170
+ wouldKeep: kept,
171
+ unchanged
172
+ });
173
+ } else {
174
+ printApplySuccess({
175
+ name: payload.profile_name,
176
+ harnessCount: payload.harnesses.length,
177
+ wrote: payload.written_files.length,
178
+ removed: payload.removed_files?.length ?? 0,
179
+ kept,
180
+ unchanged,
181
+ snapshotId: payload.snapshot_id
182
+ });
183
+ }
184
+ for (const skipped of payload.skipped_removals ?? []) {
185
+ if (skipped.reason === "missing") {
186
+ continue;
187
+ }
188
+ if (skipped.message) {
189
+ ui.warn(skipped.message);
190
+ }
191
+ }
192
+ if (!payload.dry_run && payload.removal_backup && (payload.removed_files?.length ?? 0) > 0) {
193
+ ui.info(`Backup: ${payload.removal_backup}`);
194
+ }
195
+ }
196
+ function printApplyDryRun(input) {
197
+ if (input.header !== false) {
198
+ console.log(input.header ?? CLI_COPY.dryRunNothingChanged);
199
+ console.log("");
200
+ }
201
+ if (input.wouldWrite.length > 0) {
202
+ console.log(dryRunSectionHeader("write", input.wouldWrite.length));
203
+ for (const path of input.wouldWrite) {
204
+ console.log(` ${path}`);
205
+ }
206
+ }
207
+ if (input.wouldRemove.length > 0) {
208
+ console.log(dryRunSectionHeader("remove", input.wouldRemove.length));
209
+ for (const path of input.wouldRemove) {
210
+ console.log(` ${path}`);
211
+ }
212
+ }
213
+ if (input.wouldKeep.length > 0) {
214
+ console.log(dryRunSectionHeader("keep", input.wouldKeep.length));
215
+ for (const entry of input.wouldKeep) {
216
+ console.log(` ${entry.path} ${keptReasonLabel(entry.reason)}`);
217
+ }
218
+ }
219
+ console.log("");
220
+ console.log(
221
+ dryRunWouldLine({
222
+ write: input.wouldWrite.length,
223
+ remove: input.wouldRemove.length,
224
+ keep: input.wouldKeep.length,
225
+ unchanged: input.unchanged
226
+ })
227
+ );
228
+ }
229
+ function printKeptFiles(kept) {
230
+ if (kept.length === 0) {
231
+ return;
232
+ }
233
+ console.log(keptFilesHeader(kept.length));
234
+ for (const entry of kept) {
235
+ console.log(` ${entry.path} ${keptReasonLabel(entry.reason)}`);
236
+ }
237
+ console.log(`${CLI_COPY.forceRemoveHint} ht apply --force-remove`);
238
+ }
239
+ function printApplySuccess(input) {
240
+ console.log(applyHeaderLine(input.name, input.harnessCount));
241
+ console.log(
242
+ applyWroteLine({
243
+ wrote: input.wrote,
244
+ removed: input.removed,
245
+ kept: input.kept.length,
246
+ unchanged: input.unchanged
247
+ })
248
+ );
249
+ if (input.wrote > 0 || input.removed > 0) {
250
+ printKeptFiles(input.kept);
251
+ }
252
+ if (input.snapshotId) {
253
+ console.log(snapshotSavedUndoLine(`ht revert ${input.snapshotId}`));
254
+ }
255
+ }
256
+ function removalSkipReason(reason) {
257
+ if (reason === "modified") {
258
+ return "modified";
259
+ }
260
+ if (reason === "unmanaged" || reason === "preexisting") {
261
+ return "unmanaged";
262
+ }
263
+ return void 0;
264
+ }
265
+
266
+ // src/services/global-profile-drift.ts
267
+ import { existsSync as existsSync2, readFileSync } from "fs";
268
+ import { join as join2 } from "path";
269
+ function readGlobalFile(homeRoot, relativePath) {
270
+ const fullPath = join2(homeRoot, relativePath);
271
+ if (!existsSync2(fullPath)) {
272
+ return null;
273
+ }
274
+ try {
275
+ return readFileSync(fullPath, "utf-8");
276
+ } catch {
277
+ return null;
278
+ }
279
+ }
280
+ function pluginIdsMatch(left, right) {
281
+ if (left.length !== right.length) {
282
+ return false;
283
+ }
284
+ return left.every((pluginId, index) => pluginId === right[index]);
285
+ }
286
+ function declaredMcpFromExpectedApply(expectedApply) {
287
+ return declaredMcpFromExpectedFiles(
288
+ expectedApply.harnesses,
289
+ expectedApply.expected_files ?? []
290
+ );
291
+ }
292
+ function declaredMcpNamesFromMergedPlugins(pluginIds) {
293
+ const merged = mergePluginsForApply(pluginIds);
294
+ const names = merged.resources.filter((resource) => resource.type === "mcp_server").map((resource) => resource.name);
295
+ return {
296
+ "claude-code": names,
297
+ cursor: names
298
+ };
299
+ }
300
+ function buildBaseStatusFields(input) {
301
+ const asOf = (/* @__PURE__ */ new Date()).toISOString();
302
+ const homeRoot = resolveHomeRoot();
303
+ const ownedFiles = collectOwnedGlobalProfileFiles(input.snapshotId);
304
+ const { owned, nonOwned } = classifyGlobalDriftChanges(input.changes, ownedFiles);
305
+ const declaredPins = input.pluginIds && input.pluginIds.length > 0 ? mergePluginsForApply(input.pluginIds).pluginPins : [];
306
+ const declaredFromExpected = input.expectedApply ? declaredMcpFromExpectedApply(input.expectedApply) : null;
307
+ const declaredMcpByHarness = declaredFromExpected?.namesByHarness ?? (input.pluginIds ? declaredMcpNamesFromMergedPlugins(input.pluginIds) : { "claude-code": [], cursor: [] });
308
+ const harnesses = buildHarnessLiveStatusMap({
309
+ depth: input.depth,
310
+ homeRoot,
311
+ declaredPins,
312
+ declaredMcpByHarness,
313
+ ...declaredFromExpected ? { expectedMcpConfigsByHarness: declaredFromExpected.configsByHarness } : {}
314
+ });
315
+ const { missingPlugins, missingMcp } = input.depth === "full" ? countMissingHarnessRows(harnesses) : { missingPlugins: 0, missingMcp: 0 };
316
+ const contents = input.activeProfile ? buildProfileContents(input.activeProfile) : null;
317
+ const hostManaged = input.depth === "full" ? buildHostManagedStatus({
318
+ homeRoot,
319
+ profileSkills: profileSkillNameMap(contents?.resources ?? [])
320
+ }) : void 0;
321
+ const projectDrift = resolveProjectDriftSummary(input.projectPath);
322
+ const panel = computeGlobalProfilePanelStatus({
323
+ depth: input.depth,
324
+ applied: input.applied,
325
+ activeProfile: input.activeProfile,
326
+ stackInSync: input.stackInSync,
327
+ ownedDriftCount: owned.length,
328
+ nonOwnedDriftCount: nonOwned.length,
329
+ missingPluginCount: missingPlugins,
330
+ missingMcpCount: missingMcp,
331
+ projectDrift,
332
+ warning: input.warning,
333
+ hostManagedCollisionCount: hostManaged?.cursor?.collisions.length ?? 0
334
+ });
335
+ const driftSummary = {
336
+ global: {
337
+ status: !input.applied ? "pending" : input.hasDrift ? "drifted" : "clean",
338
+ owned_changes: owned.length,
339
+ non_owned_changes: nonOwned.length
340
+ },
341
+ ...projectDrift ? { project: projectDrift } : {}
342
+ };
343
+ return {
344
+ active_profile: input.activeProfile,
345
+ profile_exists: input.profileExists,
346
+ applied: input.applied,
347
+ snapshot_id: input.snapshotId,
348
+ snapshot_at: input.snapshotAt,
349
+ stack_in_sync: input.stackInSync,
350
+ has_drift: input.hasDrift,
351
+ changes: input.changes,
352
+ ...input.warning ? { warning: input.warning } : {},
353
+ depth: input.depth,
354
+ as_of: asOf,
355
+ panel,
356
+ harnesses,
357
+ drift_summary: driftSummary,
358
+ contents,
359
+ ...hostManaged ? { host_managed: hostManaged } : {}
360
+ };
361
+ }
362
+ async function finalizeGlobalProfileStatus(fields, harness) {
363
+ const status = buildBaseStatusFields(fields);
364
+ if (fields.depth !== "full" || !status.active_profile || isEmptyBuiltinProfile(status.active_profile)) {
365
+ return status;
366
+ }
367
+ try {
368
+ const notStaged = await detectNotStagedProfileResources({
369
+ profileSelector: status.active_profile,
370
+ scope: "home",
371
+ ...harness ? { harness } : {}
372
+ });
373
+ return {
374
+ ...status,
375
+ untracked_resource_count: notStaged.length,
376
+ not_staged_count: notStaged.length
377
+ };
378
+ } catch {
379
+ return status;
380
+ }
381
+ }
382
+ async function detectGlobalProfileStatus(input = {}) {
383
+ const depth = input.depth ?? "full";
384
+ const activeProfile = getActiveProfileName() ?? null;
385
+ if (!activeProfile) {
386
+ return finalizeGlobalProfileStatus(
387
+ {
388
+ depth,
389
+ activeProfile: null,
390
+ profileExists: false,
391
+ applied: false,
392
+ snapshotId: null,
393
+ snapshotAt: null,
394
+ stackInSync: false,
395
+ hasDrift: false,
396
+ changes: [],
397
+ projectPath: input.projectPath
398
+ },
399
+ input.harness
400
+ );
401
+ }
402
+ const plugin = resolvePluginSelector(activeProfile);
403
+ if (!plugin) {
404
+ if (isEmptyBuiltinProfile(activeProfile)) {
405
+ const latestSnapshot2 = getLatestGlobalApplySnapshotForProfile(activeProfile);
406
+ let expectedApply2;
407
+ try {
408
+ expectedApply2 = await clearGlobalProfileApply({
409
+ dryRun: true,
410
+ harness: input.harness,
411
+ conflictPolicy: "replace",
412
+ pull: false
413
+ });
414
+ } catch (error) {
415
+ return finalizeGlobalProfileStatus({
416
+ depth,
417
+ activeProfile,
418
+ profileExists: true,
419
+ applied: Boolean(latestSnapshot2),
420
+ snapshotId: latestSnapshot2?.id ?? null,
421
+ snapshotAt: latestSnapshot2?.created_at ?? null,
422
+ stackInSync: false,
423
+ hasDrift: true,
424
+ changes: [],
425
+ warning: error instanceof Error ? error.message : String(error),
426
+ projectPath: input.projectPath,
427
+ pluginIds: []
428
+ });
429
+ }
430
+ const stackInSync2 = latestSnapshot2 ? pluginIdsMatch(latestSnapshot2.plugin_ids, expectedApply2.configured_plugin_ids) : false;
431
+ const applied2 = Boolean(latestSnapshot2);
432
+ const hasDrift2 = !applied2 || !stackInSync2;
433
+ return finalizeGlobalProfileStatus({
434
+ depth,
435
+ activeProfile,
436
+ profileExists: true,
437
+ applied: applied2,
438
+ snapshotId: latestSnapshot2?.id ?? null,
439
+ snapshotAt: latestSnapshot2?.created_at ?? null,
440
+ stackInSync: stackInSync2,
441
+ hasDrift: hasDrift2,
442
+ changes: [],
443
+ projectPath: input.projectPath,
444
+ expectedApply: expectedApply2,
445
+ pluginIds: []
446
+ });
447
+ }
448
+ return finalizeGlobalProfileStatus({
449
+ depth,
450
+ activeProfile,
451
+ profileExists: false,
452
+ applied: false,
453
+ snapshotId: null,
454
+ snapshotAt: null,
455
+ stackInSync: false,
456
+ hasDrift: true,
457
+ changes: [],
458
+ warning: `missing plugin "${activeProfile}"`,
459
+ projectPath: input.projectPath
460
+ });
461
+ }
462
+ if (!isProfilePlugin(plugin)) {
463
+ return finalizeGlobalProfileStatus({
464
+ depth,
465
+ activeProfile,
466
+ profileExists: true,
467
+ applied: false,
468
+ snapshotId: null,
469
+ snapshotAt: null,
470
+ stackInSync: false,
471
+ hasDrift: true,
472
+ changes: [],
473
+ warning: `plugin "${plugin.name}" is not tagged as a profile`,
474
+ projectPath: input.projectPath
475
+ });
476
+ }
477
+ const latestSnapshot = getLatestGlobalApplySnapshotForProfile(activeProfile);
478
+ const homeRoot = resolveHomeRoot();
479
+ const pluginIds = collectProfilePluginIds(plugin);
480
+ let expectedApply;
481
+ try {
482
+ expectedApply = await applyProfilePlugin(activeProfile, {
483
+ dryRun: true,
484
+ harness: input.harness,
485
+ conflictPolicy: "replace",
486
+ pull: false,
487
+ pinSkillEmits: false,
488
+ mergeLiveSkillMarkdown: false
489
+ });
490
+ } catch (error) {
491
+ return finalizeGlobalProfileStatus({
492
+ depth,
493
+ activeProfile,
494
+ profileExists: true,
495
+ applied: Boolean(latestSnapshot),
496
+ snapshotId: latestSnapshot?.id ?? null,
497
+ snapshotAt: latestSnapshot?.created_at ?? null,
498
+ stackInSync: false,
499
+ hasDrift: true,
500
+ changes: [],
501
+ warning: error instanceof Error ? error.message : String(error),
502
+ projectPath: input.projectPath,
503
+ pluginIds
504
+ });
505
+ }
506
+ const stackInSync = latestSnapshot ? pluginIdsMatch(latestSnapshot.plugin_ids, expectedApply.configured_plugin_ids) : false;
507
+ const changes = [];
508
+ for (const file of expectedApply.expected_files ?? []) {
509
+ const current = readGlobalFile(homeRoot, file.path);
510
+ const owned = listMaterializationsForRootPath(homeRoot, file.path);
511
+ if (current === null) {
512
+ if (owned.length === 0) {
513
+ continue;
514
+ }
515
+ changes.push(
516
+ withAffectedResources({ path: file.path, type: "deleted" }, file.content, null)
517
+ );
518
+ continue;
519
+ }
520
+ if (owned.length > 0) {
521
+ const diskHash = hashOnDiskFile(join2(homeRoot, file.path));
522
+ if (owned.some((row) => row.generated_hash === diskHash)) {
523
+ continue;
524
+ }
525
+ if (fileContentsEquivalentForDrift(file.path, current, file.content)) {
526
+ continue;
527
+ }
528
+ changes.push(
529
+ withAffectedResources(
530
+ { path: file.path, type: "modified" },
531
+ file.content,
532
+ current
533
+ )
534
+ );
535
+ continue;
536
+ }
537
+ if (!fileContentsEquivalentForDrift(file.path, current, file.content)) {
538
+ changes.push(
539
+ withAffectedResources(
540
+ { path: file.path, type: "modified" },
541
+ file.content,
542
+ current
543
+ )
544
+ );
545
+ }
546
+ }
547
+ const applied = Boolean(latestSnapshot);
548
+ const hasDrift = !applied || !stackInSync || changes.length > 0;
549
+ return finalizeGlobalProfileStatus(
550
+ {
551
+ depth,
552
+ activeProfile,
553
+ profileExists: true,
554
+ applied,
555
+ snapshotId: latestSnapshot?.id ?? null,
556
+ snapshotAt: latestSnapshot?.created_at ?? null,
557
+ stackInSync,
558
+ hasDrift,
559
+ changes,
560
+ projectPath: input.projectPath,
561
+ expectedApply,
562
+ pluginIds
563
+ },
564
+ input.harness
565
+ );
566
+ }
567
+
568
+ // src/services/profile-stash.ts
569
+ import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
570
+ import { dirname, join as join3, resolve as resolve2 } from "path";
571
+ import { ulid } from "ulid";
572
+ var ProfileStashError = class extends Error {
573
+ constructor(message) {
574
+ super(message);
575
+ this.name = "ProfileStashError";
576
+ }
577
+ };
578
+ function emptyProfileContents() {
579
+ return {
580
+ plugins: [],
581
+ stack_resource_count: 0,
582
+ stack_summary: null,
583
+ type_counts: {},
584
+ resources: [],
585
+ plugin_pins: [],
586
+ mcp_servers: []
587
+ };
588
+ }
589
+ function getProfileStashPath() {
590
+ return join3(getHarnesstapDir(), "profile-stash.json");
591
+ }
592
+ function isProfileContents(value) {
593
+ if (typeof value !== "object" || value === null) {
594
+ return false;
595
+ }
596
+ const candidate = value;
597
+ return Array.isArray(candidate.resources);
598
+ }
599
+ function isStashedFileSnapshot(value) {
600
+ if (typeof value !== "object" || value === null) {
601
+ return false;
602
+ }
603
+ const candidate = value;
604
+ return typeof candidate.path === "string" && typeof candidate.content === "string";
605
+ }
606
+ function hydrateStashEntry(raw) {
607
+ if (typeof raw !== "object" || raw === null) {
608
+ return null;
609
+ }
610
+ const entry = raw;
611
+ if (typeof entry.id !== "string" || typeof entry.profile_name !== "string" || typeof entry.created_at !== "string") {
612
+ return null;
613
+ }
614
+ const contents = isProfileContents(entry.contents) ? entry.contents : buildProfileContents(entry.profile_name) ?? emptyProfileContents();
615
+ const fileChanges = Array.isArray(entry.file_changes) ? entry.file_changes.filter(
616
+ (change) => typeof change === "object" && change !== null && typeof change.path === "string" && typeof change.type === "string"
617
+ ) : [];
618
+ const stashedFiles = Array.isArray(entry.stashed_files) ? entry.stashed_files.filter(isStashedFileSnapshot) : [];
619
+ return {
620
+ id: entry.id,
621
+ profile_name: entry.profile_name,
622
+ created_at: entry.created_at,
623
+ contents,
624
+ file_changes: fileChanges,
625
+ stashed_files: stashedFiles
626
+ };
627
+ }
628
+ function readProfileStashFile() {
629
+ const filePath = getProfileStashPath();
630
+ if (!existsSync3(filePath)) {
631
+ return { entries: [] };
632
+ }
633
+ try {
634
+ const parsed = JSON.parse(readFileSync2(filePath, "utf-8"));
635
+ if (!Array.isArray(parsed.entries)) {
636
+ return { entries: [] };
637
+ }
638
+ const entries = parsed.entries.map((entry) => hydrateStashEntry(entry)).filter((entry) => entry !== null);
639
+ return { entries };
640
+ } catch {
641
+ return { entries: [] };
642
+ }
643
+ }
644
+ function writeProfileStashFile(file) {
645
+ const home = getHarnesstapDir();
646
+ mkdirSync(home, { recursive: true });
647
+ writeFileSync(
648
+ getProfileStashPath(),
649
+ `${JSON.stringify(file, null, 2)}
650
+ `,
651
+ "utf-8"
652
+ );
653
+ }
654
+ function listProfileStashEntries() {
655
+ return readProfileStashFile().entries;
656
+ }
657
+ function pushProfileStashEntry(input) {
658
+ const file = readProfileStashFile();
659
+ const entry = {
660
+ id: ulid(),
661
+ profile_name: input.profile_name,
662
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
663
+ contents: input.contents,
664
+ file_changes: input.file_changes,
665
+ stashed_files: input.stashed_files
666
+ };
667
+ file.entries.unshift(entry);
668
+ writeProfileStashFile(file);
669
+ return entry;
670
+ }
671
+ function popProfileStashEntry() {
672
+ const file = readProfileStashFile();
673
+ const entry = file.entries.shift();
674
+ if (entry) {
675
+ writeProfileStashFile(file);
676
+ }
677
+ return entry;
678
+ }
679
+ function peekProfileStashEntry() {
680
+ return readProfileStashFile().entries[0];
681
+ }
682
+ function resolveStashableActiveProfile() {
683
+ const activeProfile = getActiveProfileName();
684
+ if (!activeProfile) {
685
+ throw new ProfileStashError(
686
+ "No active profile to stash. Set one with profile use <name> first."
687
+ );
688
+ }
689
+ if (isEmptyBuiltinProfile(activeProfile)) {
690
+ throw new ProfileStashError(
691
+ 'Legacy active profile "empty" has no stashable state. Run profile use <name>, then profile stash.'
692
+ );
693
+ }
694
+ return activeProfile;
695
+ }
696
+ function readHomeFile(homeRoot, relativePath) {
697
+ const fullPath = resolve2(homeRoot, relativePath);
698
+ if (!existsSync3(fullPath)) {
699
+ return null;
700
+ }
701
+ try {
702
+ return readFileSync2(fullPath, "utf-8");
703
+ } catch {
704
+ return null;
705
+ }
706
+ }
707
+ function lastWrittenContent(profileName, relativePath) {
708
+ const snapshot = getLatestGlobalApplySnapshotForProfile(profileName);
709
+ if (!snapshot?.state) {
710
+ return void 0;
711
+ }
712
+ return flattenLiveRestoreFiles(snapshot.state).find((file) => file.path === relativePath)?.content;
713
+ }
714
+ async function stashManagedDriftChanges(input) {
715
+ return withProfileApplyLock(async () => {
716
+ const profileName = resolveStashableActiveProfile();
717
+ const homeRoot = resolveHomeRoot();
718
+ const files = [];
719
+ for (const change of input.changes) {
720
+ const current = readHomeFile(homeRoot, change.path);
721
+ if (current === null) {
722
+ continue;
723
+ }
724
+ files.push({ path: change.path, content: current });
725
+ }
726
+ if (files.length === 0) {
727
+ throw new ProfileStashError("No unsaved changes to stash.");
728
+ }
729
+ const contents = buildProfileContents(profileName) ?? emptyProfileContents();
730
+ const fileChanges = stashedFilesToDriftChanges(files);
731
+ if (!input.dryRun) {
732
+ for (const file of files) {
733
+ const previous = lastWrittenContent(profileName, file.path);
734
+ if (previous === void 0) {
735
+ continue;
736
+ }
737
+ const fullPath = resolve2(homeRoot, file.path);
738
+ mkdirSync(dirname(fullPath), { recursive: true });
739
+ writeFileSync(fullPath, previous, "utf-8");
740
+ }
741
+ }
742
+ if (input.dryRun) {
743
+ return {
744
+ entry: {
745
+ id: "dry-run",
746
+ profile_name: profileName,
747
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
748
+ contents,
749
+ file_changes: fileChanges,
750
+ stashed_files: files
751
+ },
752
+ cleared: {
753
+ dry_run: true,
754
+ profile_name: profileName,
755
+ removed_files: []
756
+ }
757
+ };
758
+ }
759
+ const entry = pushProfileStashEntry({
760
+ profile_name: profileName,
761
+ contents,
762
+ file_changes: fileChanges,
763
+ stashed_files: files
764
+ });
765
+ return {
766
+ entry,
767
+ cleared: {
768
+ dry_run: false,
769
+ profile_name: profileName,
770
+ removed_files: []
771
+ }
772
+ };
773
+ });
774
+ }
775
+ async function stashProfileCommand(options) {
776
+ return withProfileApplyLock(async () => {
777
+ const profileName = resolveStashableActiveProfile();
778
+ let capture;
779
+ try {
780
+ capture = await captureUntrackedResourcesForStash({
781
+ profileSelector: profileName,
782
+ harness: options.harness
783
+ });
784
+ } catch (error) {
785
+ throw new ProfileStashError(
786
+ error instanceof Error ? error.message : String(error)
787
+ );
788
+ }
789
+ const homeRoot = resolveHomeRoot();
790
+ const contents = buildContentsFromResources(capture.resources);
791
+ const fileChanges = stashedFilesToDriftChanges(capture.files);
792
+ const removedFiles = removeUntrackedStashFiles(
793
+ homeRoot,
794
+ capture.files,
795
+ options.dryRun
796
+ );
797
+ if (options.dryRun) {
798
+ return {
799
+ entry: {
800
+ id: "dry-run",
801
+ profile_name: profileName,
802
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
803
+ contents,
804
+ file_changes: fileChanges,
805
+ stashed_files: capture.files
806
+ },
807
+ cleared: {
808
+ dry_run: true,
809
+ profile_name: profileName,
810
+ removed_files: removedFiles
811
+ }
812
+ };
813
+ }
814
+ const entry = pushProfileStashEntry({
815
+ profile_name: profileName,
816
+ contents,
817
+ file_changes: fileChanges,
818
+ stashed_files: capture.files
819
+ });
820
+ return {
821
+ entry,
822
+ cleared: {
823
+ dry_run: false,
824
+ profile_name: profileName,
825
+ removed_files: removedFiles
826
+ }
827
+ };
828
+ });
829
+ }
830
+ async function popProfileStashCommand(options) {
831
+ return withProfileApplyLock(async () => {
832
+ const entry = popProfileStashEntry();
833
+ if (!entry) {
834
+ throw new ProfileStashError("No stashed profile to restore.");
835
+ }
836
+ const homeRoot = resolveHomeRoot();
837
+ const restoredFiles = restoreUntrackedStashFiles(
838
+ homeRoot,
839
+ entry.stashed_files,
840
+ options.dryRun
841
+ );
842
+ return {
843
+ entry,
844
+ restored: {
845
+ dry_run: options.dryRun === true,
846
+ profile_name: entry.profile_name,
847
+ restored_files: restoredFiles,
848
+ cancelled: false
849
+ },
850
+ removed: true
851
+ };
852
+ });
853
+ }
854
+ async function applyProfileStashCommand(options) {
855
+ return withProfileApplyLock(async () => {
856
+ const entry = peekProfileStashEntry();
857
+ if (!entry) {
858
+ throw new ProfileStashError("No stashed profile to restore.");
859
+ }
860
+ const homeRoot = resolveHomeRoot();
861
+ const restoredFiles = restoreUntrackedStashFiles(
862
+ homeRoot,
863
+ entry.stashed_files,
864
+ options.dryRun
865
+ );
866
+ return {
867
+ entry,
868
+ restored: {
869
+ dry_run: options.dryRun === true,
870
+ profile_name: entry.profile_name,
871
+ restored_files: restoredFiles,
872
+ cancelled: false
873
+ },
874
+ removed: false
875
+ };
876
+ });
877
+ }
878
+
879
+ // src/services/profile-switch-prompt.ts
880
+ function parseSwitchChanges(raw) {
881
+ if (raw === void 0 || raw === "") {
882
+ return void 0;
883
+ }
884
+ if (SWITCH_CHANGES_VALUES.includes(raw)) {
885
+ return raw;
886
+ }
887
+ return "invalid";
888
+ }
889
+ async function maybeSyncActiveProfileBeforeSwitch(input) {
890
+ const format = input.format ?? "human";
891
+ let status;
892
+ try {
893
+ status = await detectGlobalProfileStatus({
894
+ harness: input.harness,
895
+ depth: "full"
896
+ });
897
+ } catch (error) {
898
+ ui.warn(error instanceof Error ? error.message : String(error));
899
+ return "continue";
900
+ }
901
+ if (!status.active_profile || status.active_profile === input.targetProfileName) {
902
+ return "continue";
903
+ }
904
+ if (status.changes.length === 0) {
905
+ return "continue";
906
+ }
907
+ const count = status.changes.length;
908
+ const parsedChanges = parseSwitchChanges(input.changes);
909
+ if (parsedChanges === "invalid") {
910
+ ui.danger("Error: Invalid --changes. Use save, stash or discard.");
911
+ return "abort";
912
+ }
913
+ const interactive = !input.yes && shouldUseBrowsePicker({
914
+ noInteractive: input.noInteractive,
915
+ format
916
+ });
917
+ let action;
918
+ if (parsedChanges) {
919
+ action = parsedChanges;
920
+ } else if (!interactive) {
921
+ ui.danger(`Error: ${unsavedChangesLine(status.active_profile, count)}`);
922
+ ui.hint(unsavedChangesFlagHint());
923
+ return "abort";
924
+ } else {
925
+ ui.warn(unsavedChangesLine(status.active_profile, count));
926
+ action = await promptForChoice({
927
+ message: "What should HarnessTap do with them?",
928
+ choices: [
929
+ { name: `Save them to "${status.active_profile}"`, value: "save" },
930
+ { name: "Stash them", value: "stash" },
931
+ { name: "Discard them", value: "discard" },
932
+ { name: "Cancel", value: "cancel" }
933
+ ]
934
+ });
935
+ }
936
+ switch (action) {
937
+ case "cancel":
938
+ return "abort";
939
+ case "save": {
940
+ for (const change of status.changes) {
941
+ try {
942
+ await commitManagedPathFromLive({
943
+ profileSelector: status.active_profile,
944
+ path: change.path,
945
+ scope: "home",
946
+ ...input.harness ? { harness: input.harness } : {}
947
+ });
948
+ } catch {
949
+ }
950
+ }
951
+ ui.success(savedChangesLine(status.active_profile, count));
952
+ return "continue";
953
+ }
954
+ case "stash": {
955
+ await stashManagedDriftChanges({
956
+ changes: status.changes
957
+ });
958
+ ui.success(stashedChangesLine(count, "ht profile stash pop"));
959
+ return "continue";
960
+ }
961
+ case "discard": {
962
+ if (interactive && parsedChanges !== "discard") {
963
+ const confirmed = await promptForConfirmation({
964
+ message: discardConfirm(count),
965
+ default: false
966
+ });
967
+ if (!confirmed) {
968
+ return "abort";
969
+ }
970
+ }
971
+ ui.success(discardedChangesLine(count));
972
+ return "continue";
973
+ }
974
+ default: {
975
+ const unhandled = action;
976
+ throw new Error(`Unhandled switch changes action: ${String(unhandled)}`);
977
+ }
978
+ }
979
+ }
980
+
981
+ // src/services/wizards/project-use.ts
982
+ function formatProfilePluginHint(entry) {
983
+ switch (entry.source) {
984
+ case "catalog":
985
+ case "local":
986
+ return entry.selector ?? entry.name;
987
+ case "inline":
988
+ return entry.plugin ?? entry.name;
989
+ default: {
990
+ const unhandledSource = entry.source;
991
+ throw new Error(`Unhandled profile source: ${unhandledSource}`);
992
+ }
993
+ }
994
+ }
995
+ function formatProjectProfileChoiceName(config, entry) {
996
+ const parts = [entry.name, entry.source, formatProfilePluginHint(entry)];
997
+ const environment = resolveProfileEnvironment(config, entry);
998
+ if (environment) {
999
+ parts.push(`env ${environment}`);
1000
+ }
1001
+ return parts.join(" \xB7 ");
1002
+ }
1003
+ function buildProjectProfileChoices(config) {
1004
+ return config.profiles.map((entry) => ({
1005
+ name: formatProjectProfileChoiceName(config, entry),
1006
+ value: entry.name
1007
+ }));
1008
+ }
1009
+ function resolveDefaultProfileKey(config) {
1010
+ const defaultProfile = config.default_profile;
1011
+ if (!defaultProfile) {
1012
+ return void 0;
1013
+ }
1014
+ return config.profiles.some((profile) => profile.name === defaultProfile) ? defaultProfile : void 0;
1015
+ }
1016
+ async function promptForProjectProfile(config) {
1017
+ const choices = buildProjectProfileChoices(config);
1018
+ const defaultProfile = resolveDefaultProfileKey(config);
1019
+ const message = "Which project profile should be used?";
1020
+ if (choices.length >= 5) {
1021
+ return promptForSearchableChoice({
1022
+ message,
1023
+ choices,
1024
+ default: defaultProfile
1025
+ });
1026
+ }
1027
+ return promptForChoice({
1028
+ message,
1029
+ choices,
1030
+ default: defaultProfile
1031
+ });
1032
+ }
1033
+
1034
+ // src/services/project-config-use.ts
1035
+ function assertProfilePlugin(plugin, context) {
1036
+ if (!isProfilePlugin(plugin)) {
1037
+ throw new Error(`Plugin "${plugin.name}" is not tagged as a profile (${context})`);
1038
+ }
1039
+ }
1040
+ function resolvePluginNameFromSelector(selector) {
1041
+ const existing = resolvePluginSelector(selector);
1042
+ if (existing) {
1043
+ return existing.name;
1044
+ }
1045
+ return parsePluginSelector(selector).name;
1046
+ }
1047
+ function resolveExpectedPluginName(config, entry) {
1048
+ switch (entry.source) {
1049
+ case "catalog":
1050
+ case "local": {
1051
+ const selector = entry.selector;
1052
+ if (!selector) {
1053
+ throw new Error(`Profile ${entry.name} is missing a plugin selector.`);
1054
+ }
1055
+ return resolvePluginNameFromSelector(selector);
1056
+ }
1057
+ case "inline": {
1058
+ const pluginKey = entry.plugin;
1059
+ if (!pluginKey) {
1060
+ throw new Error(`Inline profile ${entry.name} is missing a plugin reference.`);
1061
+ }
1062
+ const inlinePlugin = config.plugins.find((plugin) => plugin.name === pluginKey);
1063
+ return inlinePlugin?.name ?? pluginKey;
1064
+ }
1065
+ default: {
1066
+ const unhandledSource = entry.source;
1067
+ throw new Error(`Unhandled profile source: ${unhandledSource}`);
1068
+ }
1069
+ }
1070
+ }
1071
+ function resolvePreviewPluginName(config, entry) {
1072
+ return resolveExpectedPluginName(config, entry);
1073
+ }
1074
+ function findInlinePluginTable(config, pluginKey) {
1075
+ const plugin = config.plugins.find((entry) => entry.name === pluginKey);
1076
+ if (!plugin) {
1077
+ throw new Error(`Inline profile references unknown plugin: ${pluginKey}`);
1078
+ }
1079
+ return plugin;
1080
+ }
1081
+ function isRecord(value) {
1082
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1083
+ }
1084
+ function importInlinePluginTable(pluginTable) {
1085
+ const resourcesRaw = Array.isArray(pluginTable.resources) ? pluginTable.resources : [];
1086
+ const plugin = createPlugin({
1087
+ name: pluginTable.name,
1088
+ version: typeof pluginTable.version === "string" ? pluginTable.version : "1.0.0",
1089
+ description: typeof pluginTable.description === "string" ? pluginTable.description : "",
1090
+ tags: Array.isArray(pluginTable.tags) ? pluginTable.tags.map(String) : [],
1091
+ ...isRecord(pluginTable.claude) ? { claude: pluginTable.claude } : {}
1092
+ });
1093
+ for (const raw of resourcesRaw) {
1094
+ if (!isRecord(raw)) continue;
1095
+ const metadata = isRecord(raw.metadata) ? raw.metadata : typeof raw.metadata_json === "string" ? JSON.parse(raw.metadata_json) : {};
1096
+ const upserted = upsertResource(
1097
+ normalizeResourceInput({
1098
+ type: String(raw.type ?? ""),
1099
+ name: String(raw.name ?? ""),
1100
+ description: String(raw.description ?? ""),
1101
+ content: String(raw.content ?? ""),
1102
+ metadata,
1103
+ source: `project-inline:${pluginTable.name}`,
1104
+ namespace: String(raw.namespace ?? ""),
1105
+ origin_kind: raw.origin_kind ?? "manual",
1106
+ origin_ref: String(raw.origin_ref ?? "")
1107
+ }),
1108
+ { policy: "overwrite" }
1109
+ );
1110
+ if (upserted.action === "skipped") {
1111
+ throw new Error(`Failed to import inline resource: ${String(raw.type)}:${String(raw.name)}`);
1112
+ }
1113
+ addResourceToPlugin(plugin.id, upserted.resource.id);
1114
+ }
1115
+ return plugin;
1116
+ }
1117
+ async function resolveProjectProfileKey(config, options) {
1118
+ if (options.profile) {
1119
+ getProfileEntry(config, options.profile);
1120
+ return options.profile;
1121
+ }
1122
+ if (config.profiles.length === 0) {
1123
+ throw new Error("Project config has no profiles");
1124
+ }
1125
+ if (config.profiles.length === 1) {
1126
+ const [onlyProfile] = config.profiles;
1127
+ if (!onlyProfile) {
1128
+ throw new Error("Project config has no profiles");
1129
+ }
1130
+ return onlyProfile.name;
1131
+ }
1132
+ if (shouldUseWizard({
1133
+ interactive: options.interactive,
1134
+ noInteractive: options.noInteractive,
1135
+ format: options.format,
1136
+ missingRequiredArgs: !options.profile
1137
+ })) {
1138
+ return promptForProjectProfile(config);
1139
+ }
1140
+ throw new Error("multiple profiles configured; pass --profile <name>");
1141
+ }
1142
+ async function resolveProjectProfilePluginName(config, entry, options) {
1143
+ const pull = options.pull ?? true;
1144
+ switch (entry.source) {
1145
+ case "catalog": {
1146
+ const selector = entry.selector;
1147
+ if (!selector) {
1148
+ throw new Error(`Catalog profile ${entry.name} is missing a plugin selector.`);
1149
+ }
1150
+ const existing = resolvePluginSelector(selector);
1151
+ if (existing) {
1152
+ assertProfilePlugin(existing, `catalog profile ${entry.name}`);
1153
+ return existing.name;
1154
+ }
1155
+ if (!pull) {
1156
+ throw new Error(
1157
+ `Profile plugin not found locally: ${selector}. Re-run with pull enabled or install the plugin first.`
1158
+ );
1159
+ }
1160
+ const parsed = parsePluginSelector(selector);
1161
+ if (parsed.scope === "published") {
1162
+ const remote = resolveRemotePluginSelector(selector, {});
1163
+ const installed = await installPluginFromCatalog(remote, {
1164
+ account: options.account,
1165
+ baseUrl: options.baseUrl
1166
+ });
1167
+ const plugin = resolvePluginSelector(installed.pluginName);
1168
+ if (!plugin) {
1169
+ throw new Error(`Plugin not found after catalog install: ${installed.pluginName}`);
1170
+ }
1171
+ assertProfilePlugin(plugin, `catalog profile ${entry.name}`);
1172
+ return plugin.name;
1173
+ }
1174
+ throw new Error(`Profile plugin not found locally: ${selector}`);
1175
+ }
1176
+ case "local": {
1177
+ const selector = entry.selector;
1178
+ if (!selector) {
1179
+ throw new Error(`Local profile ${entry.name} is missing a plugin selector.`);
1180
+ }
1181
+ const plugin = resolvePluginSelector(selector);
1182
+ if (!plugin) {
1183
+ throw new Error(`Profile plugin not found locally: ${selector}`);
1184
+ }
1185
+ assertProfilePlugin(plugin, `local profile ${entry.name}`);
1186
+ return plugin.name;
1187
+ }
1188
+ case "inline": {
1189
+ const pluginKey = entry.plugin;
1190
+ if (!pluginKey) {
1191
+ throw new Error(`Inline profile ${entry.name} is missing a plugin reference.`);
1192
+ }
1193
+ const pluginTable = findInlinePluginTable(config, pluginKey);
1194
+ const imported = importInlinePluginTable(pluginTable);
1195
+ assertProfilePlugin(imported, `inline profile ${entry.name}`);
1196
+ return imported.name;
1197
+ }
1198
+ default: {
1199
+ const unhandledSource = entry.source;
1200
+ throw new Error(`Unhandled profile source: ${unhandledSource}`);
1201
+ }
1202
+ }
1203
+ }
1204
+ async function importProjectConfigEnvironments(config) {
1205
+ for (const environment of config.environments) {
1206
+ importEnvironmentToml(formatEnvironmentToml(environment), {
1207
+ createIfMissing: true
1208
+ });
1209
+ }
1210
+ }
1211
+ async function shouldSkipProjectUse(input) {
1212
+ if (input.force) {
1213
+ return false;
1214
+ }
1215
+ const activeProfile = getActiveProfileName();
1216
+ if (activeProfile !== input.pluginName) {
1217
+ return false;
1218
+ }
1219
+ const activeEnvironment = getGlobalActiveEnvironmentName();
1220
+ const environmentMatches = input.environmentName === void 0 ? activeEnvironment === void 0 : activeEnvironment === input.environmentName;
1221
+ if (!environmentMatches) {
1222
+ return false;
1223
+ }
1224
+ const status = await detectGlobalProfileStatus({ harness: input.harness });
1225
+ return !status.has_drift && status.stack_in_sync || status.applied && !status.has_drift;
1226
+ }
1227
+ async function executeProjectUse(options = {}) {
1228
+ if (options.profile && isEmptyBuiltinProfile(options.profile)) {
1229
+ const conflictPolicy2 = resolveApplyConflictPolicy({
1230
+ onConflict: options.onConflict,
1231
+ noInteractive: options.noInteractive ?? options.format === "json"
1232
+ });
1233
+ let stashed;
1234
+ try {
1235
+ stashed = await stashProfileCommand({
1236
+ harness: options.harness,
1237
+ dryRun: options.dryRun,
1238
+ conflictPolicy: conflictPolicy2,
1239
+ pull: false,
1240
+ ...conflictPolicy2 === "prompt" ? { conflictResolver: promptMaterializationConflict } : {}
1241
+ });
1242
+ } catch (error) {
1243
+ if (!(error instanceof ProfileStashError)) {
1244
+ throw error;
1245
+ }
1246
+ }
1247
+ const cleared = await clearGlobalProfileApply({
1248
+ harness: options.harness,
1249
+ dryRun: options.dryRun,
1250
+ conflictPolicy: conflictPolicy2,
1251
+ pull: false,
1252
+ ...conflictPolicy2 === "prompt" ? { conflictResolver: promptMaterializationConflict } : {}
1253
+ });
1254
+ if (!options.dryRun) {
1255
+ clearActiveProfileName();
1256
+ }
1257
+ return {
1258
+ skipped: false,
1259
+ profile_key: stashed?.entry.profile_name ?? getActiveProfileName() ?? "empty",
1260
+ plugin_name: cleared.profile_name,
1261
+ stashed: Boolean(stashed),
1262
+ ...stashed ? { stash_id: stashed.entry.id } : {},
1263
+ ...cleared
1264
+ };
1265
+ }
1266
+ const config = findProjectConfig(options.project ?? process.cwd());
1267
+ if (!config) {
1268
+ throw new Error(MISSING_PROJECT_CONFIG_MESSAGE);
1269
+ }
1270
+ const profileKey = await resolveProjectProfileKey(config, {
1271
+ profile: options.profile,
1272
+ format: options.format,
1273
+ interactive: options.interactive,
1274
+ noInteractive: options.noInteractive
1275
+ });
1276
+ const entry = getProfileEntry(config, profileKey);
1277
+ const environmentName = resolveProfileEnvironment(config, entry);
1278
+ const expectedPluginName = resolveExpectedPluginName(config, entry);
1279
+ const dryRun = options.dryRun === true;
1280
+ if (await shouldSkipProjectUse({
1281
+ pluginName: expectedPluginName,
1282
+ environmentName,
1283
+ force: options.force,
1284
+ harness: options.harness
1285
+ })) {
1286
+ return {
1287
+ skipped: true,
1288
+ profile_key: profileKey,
1289
+ plugin_name: expectedPluginName,
1290
+ ...environmentName ? { environment_name: environmentName } : {}
1291
+ };
1292
+ }
1293
+ if (!dryRun) {
1294
+ await importProjectConfigEnvironments(config);
1295
+ }
1296
+ const pluginName = dryRun ? resolvePreviewPluginName(config, entry) : await resolveProjectProfilePluginName(config, entry, {
1297
+ pull: options.pull ?? true,
1298
+ account: options.account,
1299
+ baseUrl: options.baseUrl
1300
+ });
1301
+ if (environmentName && !dryRun) {
1302
+ useEnvironmentCommand(environmentName);
1303
+ }
1304
+ if (!dryRun) {
1305
+ const sync = await maybeSyncActiveProfileBeforeSwitch({
1306
+ targetProfileName: pluginName,
1307
+ harness: options.harness,
1308
+ yes: options.yes,
1309
+ format: options.format
1310
+ });
1311
+ if (sync === "abort") {
1312
+ throw new Error("Profile switch cancelled.");
1313
+ }
1314
+ }
1315
+ const conflictPolicy = resolveApplyConflictPolicy({
1316
+ onConflict: options.onConflict,
1317
+ noInteractive: options.noInteractive ?? options.format === "json"
1318
+ });
1319
+ const applied = await useProfileCommand(pluginName, {
1320
+ harness: options.harness,
1321
+ dryRun: options.dryRun,
1322
+ pull: options.pull ?? true,
1323
+ account: options.account,
1324
+ baseUrl: options.baseUrl,
1325
+ conflictPolicy,
1326
+ ...conflictPolicy === "prompt" ? { conflictResolver: promptMaterializationConflict } : {}
1327
+ });
1328
+ return {
1329
+ skipped: false,
1330
+ profile_key: profileKey,
1331
+ plugin_name: pluginName,
1332
+ ...environmentName ? { environment_name: environmentName } : {},
1333
+ ...applied
1334
+ };
1335
+ }
1336
+
1337
+ export {
1338
+ resolveUserPath,
1339
+ resolveApplyConflictPolicy,
1340
+ promptMaterializationConflict,
1341
+ printApplyPayload,
1342
+ printApplyDryRun,
1343
+ printApplySuccess,
1344
+ removalSkipReason,
1345
+ detectGlobalProfileStatus,
1346
+ buildProjectProfileChoices,
1347
+ listProfileStashEntries,
1348
+ stashProfileCommand,
1349
+ popProfileStashCommand,
1350
+ applyProfileStashCommand,
1351
+ maybeSyncActiveProfileBeforeSwitch,
1352
+ resolveExpectedPluginName,
1353
+ resolveProjectProfilePluginName,
1354
+ importProjectConfigEnvironments,
1355
+ executeProjectUse
1356
+ };
1357
+ //# sourceMappingURL=chunk-AOUDSNRK.js.map