harnesstap 1.2.0 → 1.3.1

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-2GRNKR5H.js +67 -0
  3. package/dist/apply-2GRNKR5H.js.map +1 -0
  4. package/dist/approve-KQNCNH2R.js +181 -0
  5. package/dist/approve-KQNCNH2R.js.map +1 -0
  6. package/dist/audit-SLYOZCMI.js +434 -0
  7. package/dist/audit-SLYOZCMI.js.map +1 -0
  8. package/dist/auth-3IEVICFT.js +220 -0
  9. package/dist/auth-3IEVICFT.js.map +1 -0
  10. package/dist/bin.js +166 -0
  11. package/dist/bin.js.map +1 -0
  12. package/dist/chunk-2EIJYDNI.js +10945 -0
  13. package/dist/chunk-2EIJYDNI.js.map +1 -0
  14. package/dist/chunk-2H7UOFLK.js +11 -0
  15. package/dist/chunk-2H7UOFLK.js.map +1 -0
  16. package/dist/chunk-37E5M4JX.js +34 -0
  17. package/dist/chunk-37E5M4JX.js.map +1 -0
  18. package/dist/chunk-3FIWOI3H.js +98 -0
  19. package/dist/chunk-3FIWOI3H.js.map +1 -0
  20. package/dist/chunk-3IWTJCPA.js +6448 -0
  21. package/dist/chunk-3IWTJCPA.js.map +1 -0
  22. package/dist/chunk-3IZ7SEGT.js +346 -0
  23. package/dist/chunk-3IZ7SEGT.js.map +1 -0
  24. package/dist/chunk-3RBYT7QN.js +540 -0
  25. package/dist/chunk-3RBYT7QN.js.map +1 -0
  26. package/dist/chunk-4KNQZDZC.js +115 -0
  27. package/dist/chunk-4KNQZDZC.js.map +1 -0
  28. package/dist/chunk-5F3LNDZG.js +9 -0
  29. package/dist/chunk-5F3LNDZG.js.map +1 -0
  30. package/dist/chunk-63U7QWNY.js +364 -0
  31. package/dist/chunk-63U7QWNY.js.map +1 -0
  32. package/dist/chunk-6BY4BV5G.js +998 -0
  33. package/dist/chunk-6BY4BV5G.js.map +1 -0
  34. package/dist/chunk-7L2K4N25.js +610 -0
  35. package/dist/chunk-7L2K4N25.js.map +1 -0
  36. package/dist/chunk-7LWH5SWH.js +18 -0
  37. package/dist/chunk-7LWH5SWH.js.map +1 -0
  38. package/dist/chunk-BIBUCC2E.js +696 -0
  39. package/dist/chunk-BIBUCC2E.js.map +1 -0
  40. package/dist/chunk-BSOBXLYI.js +172 -0
  41. package/dist/chunk-BSOBXLYI.js.map +1 -0
  42. package/dist/chunk-C4QBVVEH.js +32 -0
  43. package/dist/chunk-C4QBVVEH.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-DV74UZJI.js +87 -0
  47. package/dist/chunk-DV74UZJI.js.map +1 -0
  48. package/dist/chunk-DWVAR4BP.js +656 -0
  49. package/dist/chunk-DWVAR4BP.js.map +1 -0
  50. package/dist/chunk-DXKAKKLP.js +302 -0
  51. package/dist/chunk-DXKAKKLP.js.map +1 -0
  52. package/dist/chunk-EIWXS4RM.js +235 -0
  53. package/dist/chunk-EIWXS4RM.js.map +1 -0
  54. package/dist/chunk-EWBCFAF3.js +681 -0
  55. package/dist/chunk-EWBCFAF3.js.map +1 -0
  56. package/dist/chunk-F2L4VNQK.js +1759 -0
  57. package/dist/chunk-F2L4VNQK.js.map +1 -0
  58. package/dist/chunk-G26HZZDJ.js +1359 -0
  59. package/dist/chunk-G26HZZDJ.js.map +1 -0
  60. package/dist/chunk-GQKKX7OE.js +818 -0
  61. package/dist/chunk-GQKKX7OE.js.map +1 -0
  62. package/dist/chunk-GRJY22U6.js +691 -0
  63. package/dist/chunk-GRJY22U6.js.map +1 -0
  64. package/dist/chunk-H6DVP2SI.js +682 -0
  65. package/dist/chunk-H6DVP2SI.js.map +1 -0
  66. package/dist/chunk-HVVPTCKR.js +1173 -0
  67. package/dist/chunk-HVVPTCKR.js.map +1 -0
  68. package/dist/chunk-I6XFZLTJ.js +9 -0
  69. package/dist/chunk-I6XFZLTJ.js.map +1 -0
  70. package/dist/chunk-IBOABSIA.js +17 -0
  71. package/dist/chunk-IBOABSIA.js.map +1 -0
  72. package/dist/chunk-IK524ZDW.js +691 -0
  73. package/dist/chunk-IK524ZDW.js.map +1 -0
  74. package/dist/chunk-IRU7NBOT.js +141 -0
  75. package/dist/chunk-IRU7NBOT.js.map +1 -0
  76. package/dist/chunk-J4CKQXQ6.js +806 -0
  77. package/dist/chunk-J4CKQXQ6.js.map +1 -0
  78. package/dist/chunk-JKGSJGCC.js +311 -0
  79. package/dist/chunk-JKGSJGCC.js.map +1 -0
  80. package/dist/chunk-JQOKQKQT.js +158 -0
  81. package/dist/chunk-JQOKQKQT.js.map +1 -0
  82. package/dist/chunk-JRFUTIEH.js +426 -0
  83. package/dist/chunk-JRFUTIEH.js.map +1 -0
  84. package/dist/chunk-K2BPYEH5.js +491 -0
  85. package/dist/chunk-K2BPYEH5.js.map +1 -0
  86. package/dist/chunk-KCQC7YBK.js +7795 -0
  87. package/dist/chunk-KCQC7YBK.js.map +1 -0
  88. package/dist/chunk-KDAV2GUT.js +1357 -0
  89. package/dist/chunk-KDAV2GUT.js.map +1 -0
  90. package/dist/chunk-KDDXZBMC.js +583 -0
  91. package/dist/chunk-KDDXZBMC.js.map +1 -0
  92. package/dist/chunk-KMWHZSEG.js +41 -0
  93. package/dist/chunk-KMWHZSEG.js.map +1 -0
  94. package/dist/chunk-KRI4R7EM.js +25 -0
  95. package/dist/chunk-KRI4R7EM.js.map +1 -0
  96. package/dist/chunk-LNJ3WZZX.js +186 -0
  97. package/dist/chunk-LNJ3WZZX.js.map +1 -0
  98. package/dist/chunk-MWXA4PFE.js +103 -0
  99. package/dist/chunk-MWXA4PFE.js.map +1 -0
  100. package/dist/chunk-MY62SSKC.js +183 -0
  101. package/dist/chunk-MY62SSKC.js.map +1 -0
  102. package/dist/chunk-NAGAJ5UM.js +145 -0
  103. package/dist/chunk-NAGAJ5UM.js.map +1 -0
  104. package/dist/chunk-NJ7WRKIQ.js +532 -0
  105. package/dist/chunk-NJ7WRKIQ.js.map +1 -0
  106. package/dist/chunk-OS6NUIBJ.js +38 -0
  107. package/dist/chunk-OS6NUIBJ.js.map +1 -0
  108. package/dist/chunk-PXU2OS26.js +238 -0
  109. package/dist/chunk-PXU2OS26.js.map +1 -0
  110. package/dist/chunk-QO4LBDVI.js +496 -0
  111. package/dist/chunk-QO4LBDVI.js.map +1 -0
  112. package/dist/chunk-QRZPQNLX.js +65 -0
  113. package/dist/chunk-QRZPQNLX.js.map +1 -0
  114. package/dist/chunk-SNVAMWB7.js +40 -0
  115. package/dist/chunk-SNVAMWB7.js.map +1 -0
  116. package/dist/chunk-SPRVUATR.js +430 -0
  117. package/dist/chunk-SPRVUATR.js.map +1 -0
  118. package/dist/chunk-SY7G5QEI.js +35 -0
  119. package/dist/chunk-SY7G5QEI.js.map +1 -0
  120. package/dist/chunk-SZNBUIDR.js +6438 -0
  121. package/dist/chunk-SZNBUIDR.js.map +1 -0
  122. package/dist/chunk-TQ2NA4Z4.js +24 -0
  123. package/dist/chunk-TQ2NA4Z4.js.map +1 -0
  124. package/dist/chunk-TYULB6ZY.js +2959 -0
  125. package/dist/chunk-TYULB6ZY.js.map +1 -0
  126. package/dist/chunk-UJYFTXHV.js +296 -0
  127. package/dist/chunk-UJYFTXHV.js.map +1 -0
  128. package/dist/chunk-VC6OKCJF.js +184 -0
  129. package/dist/chunk-VC6OKCJF.js.map +1 -0
  130. package/dist/chunk-VL2NWCZV.js +118 -0
  131. package/dist/chunk-VL2NWCZV.js.map +1 -0
  132. package/dist/chunk-VL7BGD47.js +514 -0
  133. package/dist/chunk-VL7BGD47.js.map +1 -0
  134. package/dist/chunk-VQVUJYYY.js +244 -0
  135. package/dist/chunk-VQVUJYYY.js.map +1 -0
  136. package/dist/chunk-VZQG2JDV.js +9 -0
  137. package/dist/chunk-VZQG2JDV.js.map +1 -0
  138. package/dist/chunk-XFZQVYIN.js +115 -0
  139. package/dist/chunk-XFZQVYIN.js.map +1 -0
  140. package/dist/chunk-XGTTOO4R.js +84 -0
  141. package/dist/chunk-XGTTOO4R.js.map +1 -0
  142. package/dist/chunk-XQFT4PEP.js +60 -0
  143. package/dist/chunk-XQFT4PEP.js.map +1 -0
  144. package/dist/chunk-YDD3ES2K.js +571 -0
  145. package/dist/chunk-YDD3ES2K.js.map +1 -0
  146. package/dist/chunk-ZY2MZ2KQ.js +1140 -0
  147. package/dist/chunk-ZY2MZ2KQ.js.map +1 -0
  148. package/dist/compile-57EEIUMB.js +161 -0
  149. package/dist/compile-57EEIUMB.js.map +1 -0
  150. package/dist/config-4EJ3D7QJ.js +438 -0
  151. package/dist/config-4EJ3D7QJ.js.map +1 -0
  152. package/dist/doctor-EEV6P5CH.js +111 -0
  153. package/dist/doctor-EEV6P5CH.js.map +1 -0
  154. package/dist/environment-WFEG4DAT.js +2745 -0
  155. package/dist/environment-WFEG4DAT.js.map +1 -0
  156. package/dist/github-BSMQD72A.js +114 -0
  157. package/dist/github-BSMQD72A.js.map +1 -0
  158. package/dist/harness-VX3PNVQW.js +746 -0
  159. package/dist/harness-VX3PNVQW.js.map +1 -0
  160. package/dist/help-AW2HKX63.js +2079 -0
  161. package/dist/help-AW2HKX63.js.map +1 -0
  162. package/dist/help-BVFOZD7E.js +1892 -0
  163. package/dist/help-BVFOZD7E.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-SPN2GEZ4.js +873 -0
  168. package/dist/init-SPN2GEZ4.js.map +1 -0
  169. package/dist/lock-K2LLUU7H.js +455 -0
  170. package/dist/lock-K2LLUU7H.js.map +1 -0
  171. package/dist/marketplace-VEKSWGX3.js +495 -0
  172. package/dist/marketplace-VEKSWGX3.js.map +1 -0
  173. package/dist/mcp-T6DKIKSF.js +202 -0
  174. package/dist/mcp-T6DKIKSF.js.map +1 -0
  175. package/dist/migrate-OO37WSB2.js +1043 -0
  176. package/dist/migrate-OO37WSB2.js.map +1 -0
  177. package/dist/open-3V3QK5RK.js +32 -0
  178. package/dist/open-3V3QK5RK.js.map +1 -0
  179. package/dist/pack-V32UPC7W.js +99 -0
  180. package/dist/pack-V32UPC7W.js.map +1 -0
  181. package/dist/plugin-KOBNQ7GT.js +64 -0
  182. package/dist/plugin-KOBNQ7GT.js.map +1 -0
  183. package/dist/plugin-from-project-X3VO3MB6.js +16 -0
  184. package/dist/plugin-from-project-X3VO3MB6.js.map +1 -0
  185. package/dist/policy-F5MKZNOC.js +105 -0
  186. package/dist/policy-F5MKZNOC.js.map +1 -0
  187. package/dist/profile-H4PMH4XT.js +1886 -0
  188. package/dist/profile-H4PMH4XT.js.map +1 -0
  189. package/dist/project-QVNEJJGH.js +1392 -0
  190. package/dist/project-QVNEJJGH.js.map +1 -0
  191. package/dist/resource-GL4RLSGI.js +555 -0
  192. package/dist/resource-GL4RLSGI.js.map +1 -0
  193. package/dist/version-PBHZK44K.js +17 -0
  194. package/dist/version-PBHZK44K.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,1392 @@
1
+ import {
2
+ makeIdColumn
3
+ } from "./chunk-7LWH5SWH.js";
4
+ import {
5
+ handleUseCommand
6
+ } from "./chunk-BSOBXLYI.js";
7
+ import {
8
+ resolveUserPath
9
+ } from "./chunk-KDAV2GUT.js";
10
+ import "./chunk-J4CKQXQ6.js";
11
+ import "./chunk-IRU7NBOT.js";
12
+ import "./chunk-VZQG2JDV.js";
13
+ import {
14
+ applyImportedSnapshotToGlobal,
15
+ backupAndRewriteFile,
16
+ buildProjectStatusPayload,
17
+ captureManagedSnapshotState,
18
+ classifyManagedPathOwnership,
19
+ detectProjectDriftFromLatest,
20
+ executeSafeFileRemovals,
21
+ flattenLiveRestoreFiles,
22
+ formatDriftStatusLabel,
23
+ formatResourceTypeSummary,
24
+ generateFiles,
25
+ getGitOrigin,
26
+ getGlobalApplySnapshot,
27
+ hashGeneratedContent,
28
+ hashOnDiskFile,
29
+ listGlobalApplySnapshots,
30
+ materializeFiles,
31
+ normalizeGitUrl,
32
+ projectNameFromUrl,
33
+ restoreSafeRemovalBackup,
34
+ snapshotAbsentPaths,
35
+ writeFiles
36
+ } from "./chunk-KCQC7YBK.js";
37
+ import "./chunk-PXU2OS26.js";
38
+ import {
39
+ promptForChoice
40
+ } from "./chunk-NAGAJ5UM.js";
41
+ import {
42
+ initializeSchema
43
+ } from "./chunk-IK524ZDW.js";
44
+ import "./chunk-SY7G5QEI.js";
45
+ import {
46
+ createSnapshot,
47
+ findSnapshotById,
48
+ listSnapshots
49
+ } from "./chunk-XQFT4PEP.js";
50
+ import "./chunk-3IZ7SEGT.js";
51
+ import "./chunk-I6XFZLTJ.js";
52
+ import "./chunk-7L2K4N25.js";
53
+ import "./chunk-JRFUTIEH.js";
54
+ import {
55
+ getHarnessPreference,
56
+ getProject,
57
+ getProjectByOrigin,
58
+ getProjectHarnessConfig,
59
+ resolveScanGlobalHarnessTargets,
60
+ setProjectHarnessConfig,
61
+ uniqueHarnessTargets,
62
+ upsertProject
63
+ } from "./chunk-UJYFTXHV.js";
64
+ import {
65
+ applyScanConflicts,
66
+ detectPlatforms,
67
+ dropHarnessSkillsDuplicatingPluginSource,
68
+ hasPluginSourceLayout,
69
+ hasSharedProjectResourceFiles,
70
+ isPluginSourcePath,
71
+ listImportedSnapshots,
72
+ mainScanLacksPluginSkills,
73
+ mergeReferenceResourceInputs,
74
+ persistMergedProjectScan,
75
+ scanAndPersistPluginSource,
76
+ scanPlatform,
77
+ scanProjectWithPluginSource
78
+ } from "./chunk-3IWTJCPA.js";
79
+ import "./chunk-HVVPTCKR.js";
80
+ import "./chunk-SPRVUATR.js";
81
+ import "./chunk-EWBCFAF3.js";
82
+ import {
83
+ resolveHomeRoot,
84
+ scanPluginSource,
85
+ scanPluginSourceForMerge
86
+ } from "./chunk-2EIJYDNI.js";
87
+ import "./chunk-6BY4BV5G.js";
88
+ import "./chunk-GQKKX7OE.js";
89
+ import "./chunk-K2BPYEH5.js";
90
+ import {
91
+ parseOutputFormat,
92
+ printJson
93
+ } from "./chunk-TQ2NA4Z4.js";
94
+ import {
95
+ ON_CONFLICT_APPLY_HELP,
96
+ fail,
97
+ formatCommand,
98
+ reportNoGitOrigin
99
+ } from "./chunk-DXKAKKLP.js";
100
+ import {
101
+ createProgress,
102
+ formatCount,
103
+ formatRelativeTime,
104
+ kvBlock,
105
+ panel,
106
+ status,
107
+ subheader,
108
+ table,
109
+ theme,
110
+ ui
111
+ } from "./chunk-YDD3ES2K.js";
112
+ import "./chunk-ZY2MZ2KQ.js";
113
+ import "./chunk-VQVUJYYY.js";
114
+ import {
115
+ CLI_COPY,
116
+ getDb,
117
+ restoredRemovedLine
118
+ } from "./chunk-DWVAR4BP.js";
119
+
120
+ // src/cli/commands/project.ts
121
+ import { resolve as resolve2 } from "path";
122
+
123
+ // src/services/snapshot-revert.ts
124
+ import { existsSync, readFileSync } from "fs";
125
+ import { resolve } from "path";
126
+ var PREFIX_MIN = 8;
127
+ function parseStoredState(raw) {
128
+ if (typeof raw !== "object" || raw === null) {
129
+ return void 0;
130
+ }
131
+ const record = raw;
132
+ if (!record.platform_files || typeof record.platform_files !== "object") {
133
+ return void 0;
134
+ }
135
+ return record;
136
+ }
137
+ function capturedStateUseful(state) {
138
+ if (!state) {
139
+ return false;
140
+ }
141
+ return Object.keys(state.platform_files).length > 0 || Object.keys(state.disk_files ?? {}).length > 0 || (state.absent_paths?.length ?? 0) > 0 || Object.keys(state.harness_files ?? {}).length > 0;
142
+ }
143
+ function findGlobalByPrefix(prefix) {
144
+ const matches = listGlobalApplySnapshots().filter((row) => row.id.startsWith(prefix));
145
+ return matches.length === 1 ? matches[0] : void 0;
146
+ }
147
+ function resolveRevertPlan(snapshotId) {
148
+ const trimmed = snapshotId.trim();
149
+ if (!trimmed) {
150
+ return { error: "Error: Pass a snapshot id." };
151
+ }
152
+ const projectSnap = findSnapshotById(trimmed, PREFIX_MIN);
153
+ if (projectSnap) {
154
+ const project = getProject(projectSnap.project_id);
155
+ if (!project) {
156
+ return { error: "Error: Snapshot project not found." };
157
+ }
158
+ return {
159
+ kind: "project",
160
+ id: projectSnap.id,
161
+ rootPath: project.local_path,
162
+ label: projectSnap.label,
163
+ createdAt: projectSnap.created_at,
164
+ restoreFiles: flattenLiveRestoreFiles(projectSnap.state),
165
+ absentPaths: snapshotAbsentPaths(projectSnap.state),
166
+ hasCapturedState: capturedStateUseful(projectSnap.state)
167
+ };
168
+ }
169
+ const globalSnap = getGlobalApplySnapshot(trimmed) ?? (trimmed.length >= PREFIX_MIN ? findGlobalByPrefix(trimmed) : void 0);
170
+ if (!globalSnap) {
171
+ return { error: `Error: No snapshot named "${trimmed}".` };
172
+ }
173
+ const state = parseStoredState(globalSnap.state);
174
+ return {
175
+ kind: "global",
176
+ id: globalSnap.id,
177
+ rootPath: resolveHomeRoot(),
178
+ label: globalSnap.profile_name,
179
+ createdAt: globalSnap.created_at,
180
+ restoreFiles: state ? flattenLiveRestoreFiles(state) : [],
181
+ absentPaths: state ? snapshotAbsentPaths(state) : [],
182
+ hasCapturedState: capturedStateUseful(state)
183
+ };
184
+ }
185
+ function shouldRestorePath(rootPath, file) {
186
+ const fullPath = resolve(rootPath, file.path);
187
+ if (!existsSync(fullPath)) {
188
+ return "write";
189
+ }
190
+ const onDisk = readFileSync(fullPath, "utf-8");
191
+ if (onDisk === file.content) {
192
+ return "unchanged";
193
+ }
194
+ const ownership = classifyManagedPathOwnership(rootPath, file.path);
195
+ if (ownership === "unowned") {
196
+ return "skip-unmanaged";
197
+ }
198
+ if (ownership === "owned") {
199
+ return "write";
200
+ }
201
+ if (hashOnDiskFile(fullPath) === hashGeneratedContent(file.content)) {
202
+ return "unchanged";
203
+ }
204
+ return "skip-modified";
205
+ }
206
+ function executeRevert(plan, options = {}) {
207
+ const restored = [];
208
+ const skipped = [];
209
+ if (!plan.hasCapturedState && plan.kind === "global" && !options.dryRun) {
210
+ restored.push(
211
+ ...restoreSafeRemovalBackup({
212
+ snapshotId: plan.id,
213
+ rootPath: plan.rootPath
214
+ })
215
+ );
216
+ }
217
+ const toWrite = [];
218
+ for (const file of plan.restoreFiles) {
219
+ const decision = shouldRestorePath(plan.rootPath, file);
220
+ switch (decision) {
221
+ case "write":
222
+ toWrite.push(file);
223
+ restored.push(file.path);
224
+ break;
225
+ case "unchanged":
226
+ restored.push(file.path);
227
+ break;
228
+ case "skip-modified":
229
+ skipped.push({
230
+ path: file.path,
231
+ reason: "modified",
232
+ message: `Skipped restoring ${file.path} (modified since HarnessTap wrote it).`
233
+ });
234
+ break;
235
+ case "skip-unmanaged":
236
+ skipped.push({
237
+ path: file.path,
238
+ reason: "unmanaged",
239
+ message: `Skipped restoring ${file.path} (not managed by HarnessTap).`
240
+ });
241
+ break;
242
+ default: {
243
+ const _exhaustive = decision;
244
+ throw new Error(`Unhandled restore decision: ${_exhaustive}`);
245
+ }
246
+ }
247
+ }
248
+ if (!options.dryRun) {
249
+ for (const file of toWrite) {
250
+ backupAndRewriteFile({
251
+ rootPath: plan.rootPath,
252
+ relativePath: file.path,
253
+ nextContent: file.content,
254
+ applyId: options.applyId ?? plan.id,
255
+ snapshotId: plan.id
256
+ });
257
+ }
258
+ }
259
+ const removal = executeSafeFileRemovals(plan.rootPath, plan.absentPaths, {
260
+ dryRun: options.dryRun,
261
+ forceRemove: options.forceRemove,
262
+ applyId: options.applyId ?? plan.id,
263
+ snapshotId: plan.id
264
+ });
265
+ const warnings = [
266
+ ...skipped.filter((entry) => entry.reason !== "missing").map((entry) => entry.message),
267
+ ...removal.warnings
268
+ ];
269
+ return {
270
+ restored: [...new Set(restored)],
271
+ removed: removal.removed,
272
+ skipped: [...skipped, ...removal.skipped],
273
+ warnings
274
+ };
275
+ }
276
+
277
+ // src/services/project-sync.ts
278
+ import { existsSync as existsSync3, mkdirSync, symlinkSync, unlinkSync } from "fs";
279
+ import { dirname, join as join2, relative } from "path";
280
+
281
+ // src/services/harness-surface-gaps.ts
282
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2 } from "fs";
283
+ import { join } from "path";
284
+ function listFiles(dir) {
285
+ try {
286
+ return readdirSync(dir);
287
+ } catch {
288
+ return [];
289
+ }
290
+ }
291
+ function readJson(filePath) {
292
+ try {
293
+ return JSON.parse(readFileSync2(filePath, "utf-8"));
294
+ } catch {
295
+ return void 0;
296
+ }
297
+ }
298
+ function isOpencodeServerPluginFile(file) {
299
+ return file.endsWith(".mjs") || file.endsWith(".js");
300
+ }
301
+ function isOpencodePluginConfigEntry(entry) {
302
+ if (isOpencodeServerPluginFile(entry)) return true;
303
+ return entry.includes("@") || entry.includes("git+") || entry.startsWith(".");
304
+ }
305
+ function detectHarnessSurfaces(projectRoot) {
306
+ const surfaces = [];
307
+ const opencodePluginsDir = join(projectRoot, ".opencode", "plugins");
308
+ for (const file of listFiles(opencodePluginsDir)) {
309
+ if (!isOpencodeServerPluginFile(file)) continue;
310
+ surfaces.push({
311
+ harness: "opencode",
312
+ path: `.opencode/plugins/${file}`,
313
+ category: "opencode-server-plugin",
314
+ message: "OpenCode server plugins must stay registered in opencode.json on OpenCode."
315
+ });
316
+ }
317
+ const opencodeConfig = readJson(join(projectRoot, "opencode.json"));
318
+ const pluginEntries = opencodeConfig?.["plugin"];
319
+ if (Array.isArray(pluginEntries)) {
320
+ for (const entry of pluginEntries) {
321
+ if (typeof entry !== "string" || !isOpencodePluginConfigEntry(entry)) {
322
+ continue;
323
+ }
324
+ const normalized = entry.replace(/^\.\//, "");
325
+ if (surfaces.some((surface) => surface.path === normalized)) continue;
326
+ surfaces.push({
327
+ harness: "opencode",
328
+ path: normalized,
329
+ category: "opencode-server-plugin",
330
+ message: "OpenCode server plugins must stay registered in opencode.json on OpenCode."
331
+ });
332
+ }
333
+ }
334
+ if (existsSync2(join(projectRoot, "pi-extension"))) {
335
+ surfaces.push({
336
+ harness: "pi",
337
+ path: "pi-extension/",
338
+ category: "pi-extension",
339
+ message: "Pi extensions install through the Pi CLI, not mirror."
340
+ });
341
+ }
342
+ if (existsSync2(join(projectRoot, "gemini-extension.json"))) {
343
+ surfaces.push({
344
+ harness: "gemini-cli",
345
+ path: "gemini-extension.json",
346
+ category: "gemini-extension",
347
+ message: "Gemini extension manifests apply to Gemini CLI and Antigravity only."
348
+ });
349
+ }
350
+ const hooksDir = join(projectRoot, "hooks");
351
+ for (const file of listFiles(hooksDir)) {
352
+ if (!file.includes("statusline")) continue;
353
+ surfaces.push({
354
+ harness: "claude-code",
355
+ path: `hooks/${file}`,
356
+ category: "statusline-hook",
357
+ message: "Statusline hooks are host-specific terminal integrations."
358
+ });
359
+ }
360
+ return surfaces;
361
+ }
362
+ function mirrorSurfaceWarnings(surfaces, aliasHarnesses) {
363
+ const warnings = [];
364
+ for (const surface of surfaces) {
365
+ const missingAliases = aliasHarnesses.filter(
366
+ (alias) => alias !== surface.harness
367
+ );
368
+ if (missingAliases.length === 0) continue;
369
+ warnings.push({
370
+ harness: surface.harness,
371
+ path: surface.path,
372
+ category: surface.category,
373
+ message: surface.message,
374
+ alias_harnesses: missingAliases
375
+ });
376
+ }
377
+ return warnings;
378
+ }
379
+
380
+ // src/services/project-sync.ts
381
+ function resolveSyncHarnesses(projectId, projectRoot, fromHarness) {
382
+ const projectConfig = projectId ? getProjectHarnessConfig(projectId) : void 0;
383
+ const global = getHarnessPreference();
384
+ const detected = detectPlatforms(projectRoot);
385
+ const registered = uniqueHarnessTargets([
386
+ ...fromHarness ? [fromHarness] : [],
387
+ ...projectConfig?.registered_harnesses ?? global?.registered_harnesses ?? detected
388
+ ]);
389
+ const from = fromHarness ?? registered[0];
390
+ if (!from) {
391
+ throw new Error(
392
+ "No harnesses configured. Run ht harness project set or ht harness set."
393
+ );
394
+ }
395
+ return {
396
+ registered_harnesses: registered.length > 0 ? registered : [from],
397
+ from_harness: from,
398
+ materialization_strategy: projectConfig?.materialization_strategy ?? "symlink-preferred",
399
+ ...projectConfig?.cursor_skill_mode ? { cursor_skill_mode: projectConfig.cursor_skill_mode } : {}
400
+ };
401
+ }
402
+ function writeAliasFiles(files, projectRoot, strategy, mainFiles) {
403
+ const mainByContent = /* @__PURE__ */ new Map();
404
+ for (const file of mainFiles) {
405
+ mainByContent.set(file.content, file.path);
406
+ }
407
+ let written = 0;
408
+ for (const file of files) {
409
+ const fullPath = join2(projectRoot, file.path);
410
+ const parent = dirname(fullPath);
411
+ if (!existsSync3(parent)) {
412
+ mkdirSync(parent, { recursive: true });
413
+ }
414
+ const mainPathForContent = mainByContent.get(file.content);
415
+ const useSymlink = strategy === "symlink-preferred" && mainPathForContent !== void 0 && mainPathForContent !== file.path;
416
+ if (useSymlink) {
417
+ const target = join2(projectRoot, mainPathForContent);
418
+ if (existsSync3(fullPath)) {
419
+ try {
420
+ unlinkSync(fullPath);
421
+ } catch {
422
+ }
423
+ }
424
+ const relTarget = relative(dirname(fullPath), target);
425
+ symlinkSync(relTarget, fullPath);
426
+ written++;
427
+ continue;
428
+ }
429
+ writeFiles([file], projectRoot);
430
+ written++;
431
+ }
432
+ return written;
433
+ }
434
+ var AGENTS_REFERENCE_PLATFORMS = [
435
+ "codex",
436
+ "cursor",
437
+ "warp",
438
+ "opencode",
439
+ "copilot-cli",
440
+ "gemini-cli",
441
+ "cline",
442
+ "roo",
443
+ "continue",
444
+ "goose",
445
+ "trae",
446
+ "openhands",
447
+ "kiro",
448
+ "pi"
449
+ ];
450
+ function toSyncResources(inputs) {
451
+ return inputs.map((resource) => ({
452
+ ...resource,
453
+ id: `sync:${resource.type}:${resource.name}`,
454
+ namespace: resource.namespace ?? "",
455
+ origin_kind: resource.origin_kind ?? "manual",
456
+ origin_ref: resource.origin_ref ?? "",
457
+ content_hash: resource.content_hash ?? "",
458
+ content_blob_ref: resource.content_blob_ref ?? "",
459
+ created_at: "",
460
+ updated_at: ""
461
+ }));
462
+ }
463
+ async function scanPluginReferenceResources(projectRoot) {
464
+ if (!hasPluginSourceLayout(projectRoot)) {
465
+ return [];
466
+ }
467
+ const imports = await scanPluginSourceForMerge(projectRoot);
468
+ return imports.flatMap((entry) => entry.resources);
469
+ }
470
+ async function scanAgentsReferenceResources(projectRoot) {
471
+ const detected = new Set(detectPlatforms(projectRoot));
472
+ const resources = [];
473
+ const seen = /* @__PURE__ */ new Set();
474
+ for (const platformId of AGENTS_REFERENCE_PLATFORMS) {
475
+ if (!detected.has(platformId)) continue;
476
+ const scan = await scanPlatform(platformId, projectRoot);
477
+ for (const resource of scan.resources) {
478
+ const key = `${resource.type}:${resource.name}:${resource.namespace ?? ""}`;
479
+ if (seen.has(key)) continue;
480
+ seen.add(key);
481
+ resources.push(resource);
482
+ }
483
+ }
484
+ return resources;
485
+ }
486
+ function emptyReferenceError(fromHarness, projectRoot) {
487
+ return new Error(
488
+ `Harness "${fromHarness}" has no on-disk resources in ${projectRoot}. Try: ht mirror --reference plugin or ht scan . or ht harness project set --harnesses claude-code,cursor`
489
+ );
490
+ }
491
+ async function resolveReferenceResources(projectRoot, fromHarness, strategy) {
492
+ if (strategy === "plugin") {
493
+ const pluginResources2 = await scanPluginReferenceResources(projectRoot);
494
+ if (pluginResources2.length === 0) {
495
+ throw new Error(
496
+ `No plugin-source resources found in ${projectRoot}. Try: harnesstap scan .`
497
+ );
498
+ }
499
+ return toSyncResources(pluginResources2);
500
+ }
501
+ if (strategy === "agents") {
502
+ const agentResources2 = await scanAgentsReferenceResources(projectRoot);
503
+ if (agentResources2.length === 0) {
504
+ throw new Error(
505
+ `No AGENTS.md instruction resources found in ${projectRoot}.`
506
+ );
507
+ }
508
+ return toSyncResources(agentResources2);
509
+ }
510
+ const diskScan = await scanPlatform(fromHarness, projectRoot);
511
+ if (strategy === "main" || strategy === "disk") {
512
+ if (diskScan.resources.length === 0) {
513
+ throw emptyReferenceError(fromHarness, projectRoot);
514
+ }
515
+ return toSyncResources(diskScan.resources);
516
+ }
517
+ if (diskScan.resources.length > 0) {
518
+ if (strategy === "auto" && hasPluginSourceLayout(projectRoot)) {
519
+ const pluginResources2 = await scanPluginReferenceResources(projectRoot);
520
+ if (mainScanLacksPluginSkills(diskScan.resources, pluginResources2)) {
521
+ return toSyncResources(
522
+ mergeReferenceResourceInputs(diskScan.resources, pluginResources2)
523
+ );
524
+ }
525
+ }
526
+ return toSyncResources(diskScan.resources);
527
+ }
528
+ const pluginResources = await scanPluginReferenceResources(projectRoot);
529
+ if (pluginResources.length > 0) {
530
+ return toSyncResources(pluginResources);
531
+ }
532
+ const agentResources = await scanAgentsReferenceResources(projectRoot);
533
+ if (agentResources.length > 0) {
534
+ return toSyncResources(agentResources);
535
+ }
536
+ throw emptyReferenceError(fromHarness, projectRoot);
537
+ }
538
+ async function syncProject(options) {
539
+ const {
540
+ projectRoot,
541
+ dryRun,
542
+ forceShiftReference,
543
+ referenceStrategy = "disk"
544
+ } = options;
545
+ const gitOrigin = getGitOrigin(projectRoot);
546
+ let projectId;
547
+ if (gitOrigin) {
548
+ const project = upsertProject({
549
+ git_origin: normalizeGitUrl(gitOrigin),
550
+ name: projectNameFromUrl(gitOrigin),
551
+ local_path: projectRoot
552
+ });
553
+ projectId = project.id;
554
+ if (forceShiftReference) {
555
+ const current = getProjectHarnessConfig(project.id);
556
+ setProjectHarnessConfig({
557
+ project_id: project.id,
558
+ registered_harnesses: uniqueHarnessTargets([
559
+ forceShiftReference,
560
+ ...current?.registered_harnesses ?? []
561
+ ]),
562
+ materialization_strategy: current?.materialization_strategy,
563
+ cursor_skill_mode: current?.cursor_skill_mode
564
+ });
565
+ }
566
+ }
567
+ const harnesses = resolveSyncHarnesses(
568
+ projectId,
569
+ projectRoot,
570
+ forceShiftReference
571
+ );
572
+ const resources = await resolveReferenceResources(
573
+ projectRoot,
574
+ harnesses.from_harness,
575
+ referenceStrategy
576
+ );
577
+ const otherPlatforms = harnesses.registered_harnesses.filter(
578
+ (id) => id !== harnesses.from_harness
579
+ );
580
+ const aliasPlatforms = otherPlatforms.length > 0 ? otherPlatforms : detectPlatforms(projectRoot).filter((p) => p !== harnesses.from_harness);
581
+ const serializeOptions = harnesses.cursor_skill_mode ? { skillCursorMode: harnesses.cursor_skill_mode } : void 0;
582
+ const mainGenerated = await generateFiles(
583
+ resources,
584
+ [harnesses.from_harness],
585
+ projectRoot,
586
+ serializeOptions
587
+ );
588
+ const aliasGenerated = aliasPlatforms.length > 0 ? await generateFiles(resources, aliasPlatforms, projectRoot, serializeOptions) : [];
589
+ const allGenerated = [...mainGenerated, ...aliasGenerated];
590
+ const surfaceWarnings = mirrorSurfaceWarnings(
591
+ detectHarnessSurfaces(projectRoot),
592
+ aliasPlatforms
593
+ );
594
+ if (dryRun) {
595
+ return {
596
+ ...harnesses,
597
+ platforms_synced: allGenerated.map((r) => r.platformId),
598
+ files_written: allGenerated.reduce((n, r) => n + r.files.length, 0),
599
+ surface_warnings: surfaceWarnings
600
+ };
601
+ }
602
+ if (gitOrigin && projectId) {
603
+ createSnapshot({
604
+ project_id: projectId,
605
+ label: `Before mirror (${harnesses.from_harness})`,
606
+ state: captureManagedSnapshotState({
607
+ rootPath: projectRoot,
608
+ resources,
609
+ generated: allGenerated
610
+ })
611
+ });
612
+ }
613
+ const mainFiles = mainGenerated[0]?.files ?? [];
614
+ let filesWritten = 0;
615
+ for (const result of aliasGenerated) {
616
+ filesWritten += writeAliasFiles(
617
+ result.files,
618
+ projectRoot,
619
+ harnesses.materialization_strategy,
620
+ mainFiles
621
+ );
622
+ }
623
+ return {
624
+ ...harnesses,
625
+ platforms_synced: aliasGenerated.map((r) => r.platformId),
626
+ files_written: filesWritten,
627
+ surface_warnings: surfaceWarnings
628
+ };
629
+ }
630
+
631
+ // src/ui/project-status-render.ts
632
+ function formatPluginLabel(plugin) {
633
+ return `${plugin.name}@${plugin.version}`;
634
+ }
635
+ function formatResourceCountLine(count, summary) {
636
+ const head = formatCount(count, "resource");
637
+ if (count === 0 || summary.length === 0) {
638
+ return head;
639
+ }
640
+ return `${head} (${summary})`;
641
+ }
642
+ function formatScanStatusLabel(status2, payload) {
643
+ const { comparison } = payload.project_resources;
644
+ switch (status2) {
645
+ case "no_harness_files":
646
+ return "no harness files";
647
+ case "not_scanned":
648
+ return "not scanned";
649
+ case "up_to_date":
650
+ return "up to date";
651
+ case "stale": {
652
+ const parts = [];
653
+ if (comparison.new_count > 0) {
654
+ parts.push(`+${comparison.new_count} new`);
655
+ }
656
+ if (comparison.changed_count > 0) {
657
+ parts.push(`${comparison.changed_count} changed`);
658
+ }
659
+ if (comparison.removed_count > 0) {
660
+ parts.push(`${comparison.removed_count} removed`);
661
+ }
662
+ return parts.length > 0 ? `stale (${parts.join(", ")})` : "stale";
663
+ }
664
+ default: {
665
+ const exhaustive = status2;
666
+ return exhaustive;
667
+ }
668
+ }
669
+ }
670
+ function formatScanHint(payload) {
671
+ const { comparison } = payload.project_resources;
672
+ if (comparison.status === "no_harness_files") {
673
+ return "Scans project files on disk, not harness setup: see `ht harness status`";
674
+ }
675
+ if (comparison.status === "not_scanned" || comparison.status === "stale") {
676
+ return "run `ht scan` to import";
677
+ }
678
+ return void 0;
679
+ }
680
+ function renderProjectStatusHuman(payload) {
681
+ panel({
682
+ title: ["PROJECT"],
683
+ rows: [
684
+ ["Root", payload.project_root],
685
+ ["Git origin", payload.git_origin_raw ?? "(none)"],
686
+ ["Platforms", payload.platforms.join(", ") || "(none detected)"],
687
+ ["Drift", formatDriftStatusLabel(payload.project, payload.drift)]
688
+ ]
689
+ });
690
+ const profileRows = [["Active", payload.profile.active_profile ?? "(none)"]];
691
+ if (payload.profile.warning) {
692
+ profileRows.push(["Warning", payload.profile.warning]);
693
+ } else if (payload.profile.stack_summary) {
694
+ profileRows.push([
695
+ "Stack",
696
+ formatResourceCountLine(
697
+ payload.profile.stack_resource_count,
698
+ payload.profile.stack_summary
699
+ )
700
+ ]);
701
+ }
702
+ panel({ title: ["PROFILE"], rows: profileRows });
703
+ subheader("APPLIED PLUGINS");
704
+ if (payload.applied_plugins.length === 0) {
705
+ console.log(" (none applied)");
706
+ status.dim(" Run `ht apply <plugin>`");
707
+ } else {
708
+ for (const row of payload.applied_plugins) {
709
+ const summary = formatResourceCountLine(row.resource_count, row.resource_summary);
710
+ console.log(` ${theme.accent(formatPluginLabel(row.plugin))} ${summary}`);
711
+ const meta = [
712
+ row.platforms.join(", ") || "(no platforms)",
713
+ formatRelativeTime(row.applied_at)
714
+ ].join(" \xB7 ");
715
+ console.log(` ${theme.muted(meta)}`);
716
+ }
717
+ }
718
+ const resolvedRows = [
719
+ [
720
+ "Total",
721
+ formatResourceCountLine(payload.resolved.resource_count, payload.resolved.resource_summary)
722
+ ],
723
+ [
724
+ "Environment",
725
+ `${payload.resolved.environment_vars} vars \xB7 ${payload.resolved.environment_secrets} secrets`
726
+ ]
727
+ ];
728
+ if (payload.resolved.plugin_pins.length > 0) {
729
+ resolvedRows.splice(1, 0, [
730
+ "Plugin pins",
731
+ `${payload.resolved.plugin_pins.length} pinned`
732
+ ]);
733
+ }
734
+ panel({ title: ["RESOLVED"], rows: resolvedRows });
735
+ subheader("PROJECT RESOURCES");
736
+ const onDiskSummary = formatResourceTypeSummary(payload.project_resources.on_disk.resources);
737
+ const inLibraryCount = payload.project_resources.in_library.resources.length;
738
+ const inLibrarySummary = formatResourceTypeSummary(
739
+ payload.project_resources.in_library.resources
740
+ );
741
+ kvBlock([
742
+ {
743
+ key: "On disk",
744
+ value: formatResourceCountLine(
745
+ payload.project_resources.on_disk.resources.length,
746
+ onDiskSummary
747
+ )
748
+ },
749
+ {
750
+ key: "In library",
751
+ value: inLibraryCount === 0 ? "0 resources (not scanned)" : formatResourceCountLine(inLibraryCount, inLibrarySummary)
752
+ }
753
+ ], { keyWidth: 14 });
754
+ subheader("SCAN");
755
+ const scanStatus = formatScanStatusLabel(payload.project_resources.comparison.status, payload);
756
+ const scanHint = formatScanHint(payload);
757
+ kvBlock([
758
+ { key: "Status", value: scanStatus },
759
+ ...scanHint ? [{ key: "Hint", value: scanHint }] : []
760
+ ], { keyWidth: 14 });
761
+ if (payload.resolved.plugin_pins.length > 0) {
762
+ subheader("PLUGIN PINS");
763
+ table.print({
764
+ columns: [
765
+ { key: "ref", header: "REF", width: 28 },
766
+ { key: "constraint", header: "CONSTRAINT", width: 16 },
767
+ { key: "status", header: "STATUS", width: 14 }
768
+ ],
769
+ rows: payload.resolved.plugin_pins.map((pin) => ({
770
+ ref: pin.ref,
771
+ constraint: pin.version_constraint || ": ",
772
+ status: pin.status
773
+ }))
774
+ });
775
+ }
776
+ if (payload.lock?.drift) {
777
+ subheader("LOCKFILE");
778
+ for (const change of payload.lock.changes) {
779
+ console.log(` ${change.name} ${change.locked} \u2192 ${change.resolved}`);
780
+ }
781
+ for (const name of payload.lock.added) {
782
+ console.log(` ${name} (added)`);
783
+ }
784
+ for (const name of payload.lock.removed) {
785
+ console.log(` ${name} (removed)`);
786
+ }
787
+ status.dim(` hint: ht apply ${payload.lock.root} --update`);
788
+ }
789
+ }
790
+ function projectStatusPayloadToJson(payload) {
791
+ return {
792
+ project_root: payload.project_root,
793
+ git_origin: payload.git_origin,
794
+ platforms: payload.platforms,
795
+ environment_cascade: payload.environment_cascade,
796
+ drift: payload.drift,
797
+ profile: {
798
+ active_profile: payload.profile.active_profile,
799
+ stack_summary: payload.profile.stack_summary,
800
+ ...payload.profile.warning ? { warning: payload.profile.warning } : {}
801
+ },
802
+ applied_plugins: payload.applied_plugins.map((row) => ({
803
+ name: row.plugin.name,
804
+ version: row.plugin.version,
805
+ resource_count: row.resource_count,
806
+ resource_summary: row.resource_summary,
807
+ platforms: row.platforms,
808
+ applied_at: row.applied_at
809
+ })),
810
+ resolved: {
811
+ resource_count: payload.resolved.resource_count,
812
+ resource_summary: payload.resolved.resource_summary,
813
+ plugin_pins: payload.resolved.plugin_pins,
814
+ environment_vars: payload.resolved.environment_vars,
815
+ environment_secrets: payload.resolved.environment_secrets
816
+ },
817
+ project_resources: payload.project_resources,
818
+ ...payload.lock ? { lock: payload.lock } : {},
819
+ ...payload.project ? {
820
+ applied_plugins_count: payload.applied_plugins.length,
821
+ snapshots: payload.snapshots_count
822
+ } : {}
823
+ };
824
+ }
825
+
826
+ // src/cli/commands/project.ts
827
+ function resolveScanConflictPolicy(opts) {
828
+ if (opts.overwrite) return "overwrite";
829
+ if (opts.skipExisting) return "skip";
830
+ if (opts.noInteractive || !process.stdin.isTTY || !process.stdout.isTTY) {
831
+ return "fail";
832
+ }
833
+ return "prompt";
834
+ }
835
+ function parseReferenceStrategy(value) {
836
+ const strategy = value ?? "disk";
837
+ switch (strategy) {
838
+ case "main":
839
+ case "disk":
840
+ return "disk";
841
+ case "plugin":
842
+ case "agents":
843
+ case "auto":
844
+ return strategy;
845
+ default:
846
+ throw new Error(
847
+ `Invalid --reference value: ${value}. Expected disk, plugin, agents, auto, or main (deprecated).`
848
+ );
849
+ }
850
+ }
851
+ function printProjectScanResults(results, options = {}) {
852
+ for (const result of results) {
853
+ if (result.resources.length === 0) continue;
854
+ const count = options.dryRun ? result.resources.length : options.importedCounts?.get(result.platformId) ?? result.resources.length;
855
+ const prefix = options.dryRun ? ui.theme.muted("[dry run] ") : "";
856
+ const verdict = ui.theme.success(
857
+ `${ui.icons.success} ${result.platformId} ${ui.icons.bullet} ${formatCount(count, "resource")}`
858
+ );
859
+ console.log(prefix + verdict);
860
+ for (const resource of result.resources) {
861
+ console.log(ui.theme.muted(` ${ui.icons.bullet} ${resource.type} ${resource.name}`));
862
+ }
863
+ }
864
+ }
865
+ function printPluginScanDryRun(imports) {
866
+ for (const result of imports) {
867
+ const count = result.resources.length;
868
+ const dryTag = ui.theme.muted("[dry run] ");
869
+ const verdict = ui.theme.success(
870
+ `${ui.icons.success} ${result.plugin_name} ${ui.icons.bullet} ${formatCount(count, "resource")}`
871
+ );
872
+ console.log(dryTag + verdict);
873
+ for (const resource of result.resources) {
874
+ console.log(ui.theme.muted(` ${ui.icons.bullet} ${resource.type} ${resource.name}`));
875
+ }
876
+ }
877
+ }
878
+ async function promptScanConflicts(conflicts) {
879
+ if (conflicts.length === 0) return "skip";
880
+ ui.warn(
881
+ `${formatCount(conflicts.length, "resource")} ${conflicts.length === 1 ? "differs" : "differ"} from the library snapshot.`
882
+ );
883
+ for (const conflict of conflicts) {
884
+ ui.dim(
885
+ ` ${conflict.incoming.type}:${conflict.incoming.name} (${conflict.platformId})`
886
+ );
887
+ }
888
+ return promptForChoice({
889
+ message: "How should HarnessTap handle these conflicts?",
890
+ choices: [
891
+ { name: "Replace library copies", value: "overwrite" },
892
+ { name: "Keep existing library copies", value: "skip" },
893
+ { name: "Cancel scan", value: "cancel" }
894
+ ]
895
+ });
896
+ }
897
+ function listRelatedImportedSnapshotIds(snapshot) {
898
+ return listImportedSnapshots().filter(
899
+ (candidate) => candidate.id !== snapshot.id && candidate.source_kind === snapshot.source_kind && candidate.source_label === snapshot.source_label && candidate.plugin_name === snapshot.plugin_name
900
+ ).map((candidate) => candidate.id);
901
+ }
902
+ async function preflightImportedGlobalInstall(persisted, harnessTargets, homeRoot) {
903
+ const resourcesById = new Map(persisted.resources.map((resource) => [resource.id, resource]));
904
+ const plannedPaths = /* @__PURE__ */ new Map();
905
+ for (const snapshot of persisted.snapshots) {
906
+ const resources = snapshot.resource_ids.map((id) => resourcesById.get(id)).filter(
907
+ (resource) => Boolean(resource)
908
+ );
909
+ if (resources.length !== snapshot.resource_ids.length) {
910
+ throw new Error(`Imported snapshot ${snapshot.id} is missing one or more resources`);
911
+ }
912
+ const results = await generateFiles(resources, harnessTargets, homeRoot, {
913
+ target: "global"
914
+ });
915
+ const files = results.flatMap((result) => result.files);
916
+ for (const file of files) {
917
+ const existingSnapshotId = plannedPaths.get(file.path);
918
+ if (existingSnapshotId && existingSnapshotId !== snapshot.id) {
919
+ throw new Error(
920
+ `Global install cancelled for ${snapshot.plugin_name}; resolve conflicts and retry.`
921
+ );
922
+ }
923
+ plannedPaths.set(file.path, snapshot.id);
924
+ }
925
+ const preflight = await materializeFiles(files, homeRoot, {
926
+ conflictPolicy: "prompt",
927
+ currentSnapshotId: snapshot.id,
928
+ replaceOwnedSnapshotIds: listRelatedImportedSnapshotIds(snapshot),
929
+ dryRun: true
930
+ });
931
+ if (preflight.cancelled) {
932
+ throw new Error(
933
+ `Global install cancelled for ${snapshot.plugin_name}; resolve conflicts and retry.`
934
+ );
935
+ }
936
+ }
937
+ }
938
+ async function handleScanCommand(path, opts) {
939
+ const db = getDb();
940
+ initializeSchema(db);
941
+ const format = parseOutputFormat(opts.format);
942
+ let projectRoot;
943
+ try {
944
+ projectRoot = resolveUserPath(path, { mustExist: true });
945
+ } catch (error) {
946
+ fail(error instanceof Error ? error.message : String(error));
947
+ return;
948
+ }
949
+ const detected = detectPlatforms(projectRoot);
950
+ const hasHarnessSignals = detected.length > 0 || hasSharedProjectResourceFiles(projectRoot);
951
+ const pluginSourcePath = !hasHarnessSignals && isPluginSourcePath(projectRoot);
952
+ const scanHarnessFilter = opts.global ? void 0 : opts.harness;
953
+ if (pluginSourcePath && opts.harness && !opts.global) {
954
+ throw new Error("--harness without --global is not supported when scanning a plugin source");
955
+ }
956
+ if (pluginSourcePath) {
957
+ if (opts.dryRun) {
958
+ if (opts.global) {
959
+ ui.warn("--global is ignored with --dry-run");
960
+ }
961
+ const imports = await scanPluginSource(projectRoot);
962
+ if (format === "json") {
963
+ printJson({ dry_run: true, imports });
964
+ return;
965
+ }
966
+ for (const result of imports) {
967
+ const count = result.resources.length;
968
+ const dryTag = ui.theme.muted("[dry run] ");
969
+ const verdict = ui.theme.success(
970
+ `${ui.icons.success} ${result.plugin_name} ${ui.icons.bullet} ${formatCount(count, "resource")}`
971
+ );
972
+ console.log(dryTag + verdict);
973
+ for (const resource of result.resources) {
974
+ console.log(ui.theme.muted(` ${ui.icons.bullet} ${resource.type} ${resource.name}`));
975
+ }
976
+ }
977
+ return;
978
+ }
979
+ const spin2 = createProgress("Scanning...");
980
+ const persisted = await scanAndPersistPluginSource(projectRoot);
981
+ spin2.stop();
982
+ if (format === "json") {
983
+ printJson(persisted);
984
+ } else {
985
+ for (const result of persisted.imports) {
986
+ ui.success(`${result.plugin_name} ${ui.icons.bullet} ${formatCount(result.resources.length, "resource")}`);
987
+ for (const resource of result.resources) {
988
+ console.log(ui.theme.muted(` ${ui.icons.bullet} ${resource.type} ${resource.name}`));
989
+ }
990
+ }
991
+ }
992
+ if (!opts.global) {
993
+ return;
994
+ }
995
+ const homeRoot = resolveHomeRoot();
996
+ const harnessTargets = resolveScanGlobalHarnessTargets(opts.harness, homeRoot);
997
+ await preflightImportedGlobalInstall(persisted, harnessTargets, homeRoot);
998
+ for (const snapshot of persisted.snapshots) {
999
+ const install = await applyImportedSnapshotToGlobal(
1000
+ snapshot.id,
1001
+ harnessTargets,
1002
+ homeRoot
1003
+ );
1004
+ if (install.cancelled) {
1005
+ throw new Error(
1006
+ `Global install cancelled for ${snapshot.plugin_name}; resolve conflicts and retry.`
1007
+ );
1008
+ }
1009
+ ui.success(
1010
+ `Installed ${snapshot.plugin_name} globally to ${harnessTargets.join(", ")} ${ui.icons.bullet} ${formatCount(install.writtenFiles.length, "file")}`
1011
+ );
1012
+ }
1013
+ return;
1014
+ }
1015
+ if (opts.global) {
1016
+ throw new Error("--global is only supported when scanning a plugin source");
1017
+ }
1018
+ if (!hasHarnessSignals && !isPluginSourcePath(projectRoot)) {
1019
+ ui.warn(`No harness resources found in this directory (${projectRoot}).`);
1020
+ ui.hint(
1021
+ `If you need to scan your global harness configuration, use \`${formatCommand("init")}\`.`
1022
+ );
1023
+ return;
1024
+ }
1025
+ if (opts.dryRun) {
1026
+ const { harness: rawHarness, plugin } = await scanProjectWithPluginSource(
1027
+ projectRoot,
1028
+ scanHarnessFilter
1029
+ );
1030
+ const harness = dropHarnessSkillsDuplicatingPluginSource(rawHarness, plugin);
1031
+ if (format === "json") {
1032
+ printJson({ dry_run: true, harness, plugin });
1033
+ return;
1034
+ }
1035
+ printProjectScanResults(harness, { dryRun: true });
1036
+ if (plugin.length > 0) {
1037
+ printPluginScanDryRun(plugin);
1038
+ }
1039
+ return;
1040
+ }
1041
+ const spin = createProgress("Scanning...");
1042
+ const conflictPolicy = resolveScanConflictPolicy(opts);
1043
+ const merged = await persistMergedProjectScan(projectRoot, scanHarnessFilter, {
1044
+ conflictPolicy,
1045
+ namespace: opts.namespace ?? "project",
1046
+ originRef: projectRoot
1047
+ });
1048
+ spin.stop();
1049
+ let harnessPersisted = merged.harness;
1050
+ if (harnessPersisted.conflicts.length > 0 && conflictPolicy === "prompt") {
1051
+ const resolution = await promptScanConflicts(harnessPersisted.conflicts);
1052
+ if (resolution === "cancel") {
1053
+ throw new Error("Scan cancelled due to resource conflicts.");
1054
+ }
1055
+ const resolved = applyScanConflicts(harnessPersisted.conflicts, resolution);
1056
+ harnessPersisted = {
1057
+ ...harnessPersisted,
1058
+ resources: [...harnessPersisted.resources, ...resolved],
1059
+ conflicts: []
1060
+ };
1061
+ } else if (harnessPersisted.conflicts.length > 0) {
1062
+ throw new Error(
1063
+ `${formatCount(harnessPersisted.conflicts.length, "resource conflict")}. Use --overwrite or --skip-existing.`
1064
+ );
1065
+ }
1066
+ if (format === "json") {
1067
+ printJson({
1068
+ harness: harnessPersisted,
1069
+ plugin: merged.scan.plugin
1070
+ });
1071
+ return;
1072
+ }
1073
+ printProjectScanResults(merged.scan.harness, {
1074
+ importedCounts: harnessPersisted.importedCounts
1075
+ });
1076
+ if (merged.scan.plugin.length > 0) {
1077
+ for (const result of merged.scan.plugin) {
1078
+ ui.success(`${result.plugin_name} ${ui.icons.bullet} ${formatCount(result.resources.length, "resource")}`);
1079
+ for (const resource of result.resources) {
1080
+ console.log(ui.theme.muted(` ${ui.icons.bullet} ${resource.type} ${resource.name}`));
1081
+ }
1082
+ }
1083
+ }
1084
+ const gitOrigin = getGitOrigin(projectRoot);
1085
+ if (!gitOrigin) {
1086
+ return;
1087
+ }
1088
+ const normalized = normalizeGitUrl(gitOrigin);
1089
+ const name = projectNameFromUrl(gitOrigin);
1090
+ const existingProject = getProjectByOrigin(normalized);
1091
+ upsertProject({
1092
+ git_origin: normalized,
1093
+ name,
1094
+ local_path: projectRoot
1095
+ });
1096
+ if (!existingProject) {
1097
+ console.log("");
1098
+ ui.success(`Project linked: ${name}`);
1099
+ ui.hint(
1100
+ "Enables apply snapshots, drift checks (status --check), history, and revert for this repository."
1101
+ );
1102
+ } else if (resolve2(existingProject.local_path) !== resolve2(projectRoot)) {
1103
+ ui.hint(`Updated local path for ${name}.`);
1104
+ }
1105
+ }
1106
+ function handleHistoryCommand(path, opts) {
1107
+ const db = getDb();
1108
+ initializeSchema(db);
1109
+ const format = parseOutputFormat(opts.format);
1110
+ let projectRoot;
1111
+ try {
1112
+ projectRoot = resolveUserPath(path, { mustExist: true });
1113
+ } catch (error) {
1114
+ fail(error instanceof Error ? error.message : String(error));
1115
+ return;
1116
+ }
1117
+ const gitOrigin = getGitOrigin(projectRoot);
1118
+ if (!gitOrigin) {
1119
+ reportNoGitOrigin(formatCommand("history"));
1120
+ return;
1121
+ }
1122
+ const project = getProjectByOrigin(normalizeGitUrl(gitOrigin));
1123
+ if (!project) {
1124
+ if (format === "json") {
1125
+ printJson({ snapshots: [] });
1126
+ return;
1127
+ }
1128
+ ui.warn(`No project record found. Run \`${formatCommand("scan")}\` first.`);
1129
+ return;
1130
+ }
1131
+ const snapshots = listSnapshots(project.id);
1132
+ if (snapshots.length === 0) {
1133
+ if (format === "json") {
1134
+ printJson({ snapshots: [] });
1135
+ return;
1136
+ }
1137
+ ui.dim("No snapshots found.");
1138
+ return;
1139
+ }
1140
+ if (format === "json") {
1141
+ printJson(
1142
+ snapshots.map((snapshot) => ({
1143
+ id: snapshot.id,
1144
+ created_at: snapshot.created_at,
1145
+ label: snapshot.label
1146
+ }))
1147
+ );
1148
+ return;
1149
+ }
1150
+ const showId = Boolean(opts.showId);
1151
+ const rows = snapshots.map((s) => ({
1152
+ when: s.created_at,
1153
+ id: s.id,
1154
+ label: s.label ?? ""
1155
+ }));
1156
+ ui.table.print({
1157
+ columns: [
1158
+ { key: "when", header: "WHEN", width: 16, transform: (value) => ui.format.formatRelativeTime(String(value)) },
1159
+ ...makeIdColumn(showId, 14),
1160
+ { key: "label", header: "LABEL", width: showId ? 36 : 50 }
1161
+ ],
1162
+ rows,
1163
+ summary: `${rows.length} snapshots`
1164
+ });
1165
+ }
1166
+ function handleRevertCommand(snapshotId, opts) {
1167
+ const db = getDb();
1168
+ initializeSchema(db);
1169
+ const format = parseOutputFormat(opts.format);
1170
+ if (!snapshotId) {
1171
+ fail("Pass a snapshot id.", {
1172
+ hint: `Run ${formatCommand("history --show-id")} to see your snapshots.`
1173
+ });
1174
+ return;
1175
+ }
1176
+ const plan = resolveRevertPlan(snapshotId);
1177
+ if ("error" in plan) {
1178
+ fail(plan.error, {
1179
+ hint: `Run ${formatCommand("history --show-id")} to see your snapshots.`
1180
+ });
1181
+ return;
1182
+ }
1183
+ const result = executeRevert(plan, {
1184
+ dryRun: opts.dryRun,
1185
+ forceRemove: opts.forceRemove
1186
+ });
1187
+ if (format === "json") {
1188
+ printJson({
1189
+ dry_run: Boolean(opts.dryRun),
1190
+ snapshot_id: plan.id,
1191
+ kind: plan.kind,
1192
+ restored: result.restored,
1193
+ removed: result.removed,
1194
+ skipped: result.skipped
1195
+ });
1196
+ return;
1197
+ }
1198
+ if (opts.dryRun) {
1199
+ console.log(CLI_COPY.dryRunNothingChanged);
1200
+ console.log(
1201
+ restoredRemovedLine(result.restored.length, result.removed.length, {
1202
+ dryRun: true
1203
+ })
1204
+ );
1205
+ return;
1206
+ }
1207
+ for (const warning of result.warnings) {
1208
+ ui.warn(warning);
1209
+ }
1210
+ ui.success(restoredRemovedLine(result.restored.length, result.removed.length));
1211
+ }
1212
+ async function handleProjectStatusCommand(path, opts) {
1213
+ const db = getDb();
1214
+ initializeSchema(db);
1215
+ const format = parseOutputFormat(opts.format);
1216
+ let projectRoot;
1217
+ try {
1218
+ projectRoot = resolveUserPath(path, { mustExist: true });
1219
+ } catch (error) {
1220
+ fail(error instanceof Error ? error.message : String(error));
1221
+ return;
1222
+ }
1223
+ if (opts.check) {
1224
+ const gitOrigin = getGitOrigin(projectRoot);
1225
+ if (!gitOrigin) {
1226
+ reportNoGitOrigin(formatCommand("status --check"));
1227
+ return;
1228
+ }
1229
+ const normalizedOrigin = normalizeGitUrl(gitOrigin);
1230
+ const project = getProjectByOrigin(normalizedOrigin);
1231
+ if (!project) {
1232
+ if (format === "json") {
1233
+ printJson({
1234
+ project_root: projectRoot,
1235
+ snapshot_id: null,
1236
+ has_drift: false,
1237
+ changes: [],
1238
+ message: `No project record. Run ${formatCommand("apply")} first.`
1239
+ });
1240
+ return;
1241
+ }
1242
+ ui.warn(`No project record found. Run \`${formatCommand("apply")}\` first.`);
1243
+ return;
1244
+ }
1245
+ const report = detectProjectDriftFromLatest(projectRoot, project.id);
1246
+ if (!report) {
1247
+ return;
1248
+ }
1249
+ const statusPayload = await buildProjectStatusPayload(projectRoot);
1250
+ const lockDrift = statusPayload.lock?.drift === true;
1251
+ const hasDrift = report.has_drift || lockDrift;
1252
+ if (format === "json") {
1253
+ printJson({
1254
+ ...report,
1255
+ has_drift: hasDrift,
1256
+ ...statusPayload.lock ? { lock: statusPayload.lock } : {}
1257
+ });
1258
+ if (hasDrift) {
1259
+ process.exitCode = 1;
1260
+ }
1261
+ return;
1262
+ }
1263
+ if (!report.snapshot_id && !lockDrift) {
1264
+ ui.dim("No snapshots found. Drift detection requires a prior apply or mirror.");
1265
+ return;
1266
+ }
1267
+ if (!hasDrift) {
1268
+ ui.success("No drift detected since last snapshot.");
1269
+ return;
1270
+ }
1271
+ if (report.has_drift) {
1272
+ fail(
1273
+ `Drift detected: ${formatCount(report.changes.length, "change")} since snapshot ${report.snapshot_id}`
1274
+ );
1275
+ }
1276
+ if (lockDrift && statusPayload.lock) {
1277
+ fail(
1278
+ `Lock drift detected for root ${statusPayload.lock.root} (${formatCount(statusPayload.lock.changes.length, "version change")}).`
1279
+ );
1280
+ }
1281
+ process.exitCode = 1;
1282
+ return;
1283
+ }
1284
+ const payload = await buildProjectStatusPayload(projectRoot);
1285
+ if (format === "json") {
1286
+ printJson(projectStatusPayloadToJson(payload));
1287
+ return;
1288
+ }
1289
+ renderProjectStatusHuman(payload);
1290
+ }
1291
+ function printMirrorSurfaceWarnings(warnings) {
1292
+ for (const warning of warnings) {
1293
+ ui.warn(
1294
+ `${warning.harness} surface ${warning.path} is not rematerialized to ${warning.alias_harnesses.join(", ")}: ${warning.message}`
1295
+ );
1296
+ }
1297
+ }
1298
+ async function handleProjectSyncCommand(path, opts) {
1299
+ const db = getDb();
1300
+ initializeSchema(db);
1301
+ const format = parseOutputFormat(opts.format);
1302
+ let projectRoot;
1303
+ try {
1304
+ projectRoot = resolveUserPath(path, { mustExist: true });
1305
+ } catch (error) {
1306
+ fail(error instanceof Error ? error.message : String(error));
1307
+ return;
1308
+ }
1309
+ let referenceStrategy;
1310
+ try {
1311
+ referenceStrategy = parseReferenceStrategy(opts.reference);
1312
+ } catch (err) {
1313
+ fail(err instanceof Error ? err.message : String(err));
1314
+ process.exitCode = 1;
1315
+ return;
1316
+ }
1317
+ try {
1318
+ const result = await (async () => {
1319
+ if (format === "human" && !opts.dryRun) {
1320
+ const spin = createProgress("Syncing...");
1321
+ const r = await syncProject({
1322
+ projectRoot,
1323
+ dryRun: false,
1324
+ forceShiftReference: opts.from ?? opts.forceShiftReference,
1325
+ referenceStrategy
1326
+ });
1327
+ spin.succeed(
1328
+ `Synced ${r.platforms_synced.join(", ") || "(none)"} from ${r.from_harness} ${ui.icons.bullet} ${formatCount(r.files_written, "file")}`
1329
+ );
1330
+ printMirrorSurfaceWarnings(r.surface_warnings);
1331
+ return r;
1332
+ }
1333
+ return syncProject({
1334
+ projectRoot,
1335
+ dryRun: opts.dryRun,
1336
+ forceShiftReference: opts.from ?? opts.forceShiftReference,
1337
+ referenceStrategy
1338
+ });
1339
+ })();
1340
+ if (format === "json") {
1341
+ printJson(result);
1342
+ return;
1343
+ }
1344
+ printMirrorSurfaceWarnings(result.surface_warnings);
1345
+ if (opts.dryRun) {
1346
+ const dryTag = ui.theme.muted("[dry run] ");
1347
+ const verdict = ui.theme.success(
1348
+ `${ui.icons.success} Synced ${result.platforms_synced.join(", ") || "(none)"} from ${result.from_harness} ${ui.icons.bullet} ${formatCount(result.files_written, "file")}`
1349
+ );
1350
+ console.log(dryTag + verdict);
1351
+ }
1352
+ } catch (err) {
1353
+ fail(err instanceof Error ? err.message : String(err));
1354
+ }
1355
+ }
1356
+ function registerProjectCommandsBeforeConfig(root) {
1357
+ root.command("scan").argument("[path]", "Project directory or plugin source to scan", ".").option("--harness <slugs>", "Harness slug(s): scan filter, or install targets with --global").option("--dry-run", "Show what would be imported without writing to DB").option("--global", "Install imported plugin sources into global harness locations").option("--overwrite", "Overwrite library resources when scan content differs").option("--skip-existing", "Keep existing library resources when scan content differs").option("--namespace <name>", "Namespace for imported project resources").option("--format <mode>", "Output format: human or json", "human").description(
1358
+ "Scan a project directory or plugin source and import configurations into the database"
1359
+ ).action(handleScanCommand);
1360
+ root.command("use").description("Switch to a project-configured profile and environment").option("--profile <name>", "Profile key from apm.yml").option("--project <path>", "Project directory", ".").option("--list", "List profiles from project config without applying").option("--dry-run", "Show what would be written without applying").option("--force", "Apply even when the profile is already active and in sync").option("--no-pull", "Do not auto-pull missing published plugin dependencies").option(
1361
+ "--harness <slugs>",
1362
+ "Comma-separated harness slugs (defaults to global harness preference)"
1363
+ ).option("--account <name>", "Cloud account name for dependency pulls").option("--base-url <url>", "Cloud base URL for dependency pulls").option(
1364
+ "--on-conflict <policy>",
1365
+ ON_CONFLICT_APPLY_HELP
1366
+ ).option("--no-interactive", "Disable interactive prompts").option("--interactive", "Enable interactive prompts").option("--format <mode>", "Output format: human or json", "human").action(handleUseCommand);
1367
+ }
1368
+ function registerProjectCommandsAfterConfig(root) {
1369
+ root.command("mirror").argument("[path]", "Project directory", ".").option("--dry-run", "Show what would be written without writing files").option("--from <slug>", "On-disk harness to copy from (same as --force-shift-reference)").option(
1370
+ "--force-shift-reference <slug>",
1371
+ "Deprecated alias of --from"
1372
+ ).option(
1373
+ "--reference <strategy>",
1374
+ "Reference source: disk, plugin, agents, or auto (main is a deprecated alias of disk)",
1375
+ "disk"
1376
+ ).option("--format <mode>", "Output format: human or json", "human").description(
1377
+ "Rematerialize registered harness files from one on-disk harness (or plugin/AGENTS.md fallback)"
1378
+ ).action(handleProjectSyncCommand);
1379
+ root.command("history").argument("[path]", "Project directory", ".").option("--format <mode>", "Output format: human or json", "human").option("--show-id", "Show snapshot IDs in human-readable tables").description("List configuration snapshots for a project").action(handleHistoryCommand);
1380
+ root.command("revert").argument("[snapshot-id]", "Snapshot ID to revert to").option("--dry-run", "Show what would be restored without writing").option(
1381
+ "--force-remove",
1382
+ "Remove files even when they were changed or not made by HarnessTap"
1383
+ ).option("--format <mode>", "Output format: human or json", "human").description("Revert a project or global apply snapshot").action(handleRevertCommand);
1384
+ root.command("status").argument("[path]", "Project directory", ".").option("--format <mode>", "Output format: human or json", "human").option("--check", "Exit with code 1 when snapshot or lock drift exists").description("Show current project status and drift summary").action(async (path, opts) => {
1385
+ await handleProjectStatusCommand(path, opts);
1386
+ });
1387
+ }
1388
+ export {
1389
+ registerProjectCommandsAfterConfig,
1390
+ registerProjectCommandsBeforeConfig
1391
+ };
1392
+ //# sourceMappingURL=project-QVNEJJGH.js.map