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 @@
1
+ {"version":3,"sources":["../src/utils/user-path.ts","../src/services/materialization-conflicts.ts","../src/cli/print-apply-summary.ts","../src/services/global-profile-drift.ts","../src/services/profile-stash.ts","../src/services/profile-switch-prompt.ts","../src/services/wizards/project-use.ts","../src/services/project-config-use.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport { resolveHomeRoot } from \"./home-root.js\";\n\nexport class UserPathError extends Error {\n readonly input: string;\n\n constructor(input: string, resolved: string) {\n super(`Directory not found: ${input}.`);\n this.name = \"UserPathError\";\n this.input = input;\n this.resolved = resolved;\n }\n\n readonly resolved: string;\n}\n\nexport function expandUserPath(arg: string, home = resolveHomeRoot()): string {\n const trimmed = arg.trim();\n if (trimmed === \"~\") {\n return home;\n }\n if (trimmed.startsWith(\"~/\") || trimmed.startsWith(\"~\\\\\")) {\n return join(home, trimmed.slice(2));\n }\n return isAbsolute(trimmed) ? trimmed : resolve(trimmed);\n}\n\nexport function resolveUserPath(\n arg: string,\n opts?: { mustExist?: boolean; home?: string },\n): string {\n const resolved = resolve(expandUserPath(arg, opts?.home ?? resolveHomeRoot()));\n if (opts?.mustExist && !existsSync(resolved)) {\n throw new UserPathError(arg, resolved);\n }\n return resolved;\n}\n","import { ON_CONFLICT_VALUE_HELP, parseOnConflict } from \"../cli/on-conflict.js\";\nimport { ui } from \"../ui/index.js\";\nimport type {\n ConflictPolicy,\n ConflictResolution,\n MaterializationConflict,\n} from \"./applier.js\";\nimport { promptForChoice } from \"./wizards/shared.js\";\n\nexport function resolveApplyConflictPolicy(opts: {\n onConflict?: string;\n noInteractive?: boolean;\n}): ConflictPolicy {\n const parsed = opts.onConflict ? parseOnConflict(opts.onConflict) : undefined;\n if (\n parsed === \"replace\" ||\n parsed === \"skip\" ||\n parsed === \"prompt\" ||\n parsed === \"cancel\"\n ) {\n return parsed;\n }\n if (\n opts.noInteractive ||\n process.env.CI === \"true\" ||\n process.env.HARNESSTAP_NO_INTERACTIVE === \"1\" ||\n !process.stdin.isTTY ||\n !process.stdout.isTTY\n ) {\n return \"cancel\";\n }\n return \"prompt\";\n}\n\nexport async function promptMaterializationConflict(\n conflict: MaterializationConflict,\n): Promise<ConflictResolution> {\n const ownerSummary =\n conflict.owners.length > 0\n ? conflict.owners\n .map((owner) => `${owner.plugin_name}@${owner.plugin_version ?? \"?\"}`)\n .join(\", \")\n : \"another plugin or manual edit\";\n\n ui.warn(`File already exists: ${conflict.path}`);\n ui.dim(` Previously written by: ${ownerSummary}`);\n\n return promptForChoice({\n message: `How should HarnessTap handle ${conflict.path}?`,\n choices: [\n { name: ON_CONFLICT_VALUE_HELP.replace, value: \"replace\" as const },\n { name: ON_CONFLICT_VALUE_HELP.skip, value: \"skip\" as const },\n { name: ON_CONFLICT_VALUE_HELP.cancel, value: \"cancel\" as const },\n ],\n });\n}\n","import {\n applyHeaderLine,\n applyWroteLine,\n CLI_COPY,\n dryRunSectionHeader,\n dryRunWouldLine,\n keptFilesHeader,\n keptReasonLabel,\n snapshotSavedUndoLine,\n} from \"../copy/cli.js\";\nimport { ui } from \"../ui/index.js\";\n\nexport interface ApplyKeptFile {\n path: string;\n reason: \"modified\" | \"unmanaged\";\n}\n\nexport function keptFromSkippedRemovals(\n skipped: readonly { path: string; reason: string }[] | undefined,\n): ApplyKeptFile[] {\n return (skipped ?? []).flatMap((entry) => {\n const reason = removalSkipReason(entry.reason);\n return reason ? [{ path: entry.path, reason }] : [];\n });\n}\n\nexport function printApplyPayload(payload: {\n profile_name: string;\n harnesses: readonly string[];\n files: readonly unknown[];\n written_files: readonly string[];\n removed_files?: readonly string[];\n skipped_removals?: readonly { path: string; reason: string; message?: string }[];\n snapshot_id?: string;\n dry_run?: boolean;\n removal_backup?: string;\n}): void {\n const kept = keptFromSkippedRemovals(payload.skipped_removals);\n const unchanged = Math.max(0, payload.files.length - payload.written_files.length);\n if (payload.dry_run) {\n printApplyDryRun({\n wouldWrite: payload.written_files,\n wouldRemove: payload.removed_files ?? [],\n wouldKeep: kept,\n unchanged,\n });\n } else {\n printApplySuccess({\n name: payload.profile_name,\n harnessCount: payload.harnesses.length,\n wrote: payload.written_files.length,\n removed: payload.removed_files?.length ?? 0,\n kept,\n unchanged,\n snapshotId: payload.snapshot_id,\n });\n }\n for (const skipped of payload.skipped_removals ?? []) {\n if (skipped.reason === \"missing\") {\n continue;\n }\n if (skipped.message) {\n ui.warn(skipped.message);\n }\n }\n if (!payload.dry_run && payload.removal_backup && (payload.removed_files?.length ?? 0) > 0) {\n ui.info(`Backup: ${payload.removal_backup}`);\n }\n}\n\nexport function printApplyDryRun(input: {\n wouldWrite: readonly string[];\n wouldRemove: readonly string[];\n wouldKeep: readonly ApplyKeptFile[];\n unchanged: number;\n header?: string | false;\n}): void {\n if (input.header !== false) {\n console.log(input.header ?? CLI_COPY.dryRunNothingChanged);\n console.log(\"\");\n }\n if (input.wouldWrite.length > 0) {\n console.log(dryRunSectionHeader(\"write\", input.wouldWrite.length));\n for (const path of input.wouldWrite) {\n console.log(` ${path}`);\n }\n }\n if (input.wouldRemove.length > 0) {\n console.log(dryRunSectionHeader(\"remove\", input.wouldRemove.length));\n for (const path of input.wouldRemove) {\n console.log(` ${path}`);\n }\n }\n if (input.wouldKeep.length > 0) {\n console.log(dryRunSectionHeader(\"keep\", input.wouldKeep.length));\n for (const entry of input.wouldKeep) {\n console.log(` ${entry.path} ${keptReasonLabel(entry.reason)}`);\n }\n }\n console.log(\"\");\n console.log(\n dryRunWouldLine({\n write: input.wouldWrite.length,\n remove: input.wouldRemove.length,\n keep: input.wouldKeep.length,\n unchanged: input.unchanged,\n }),\n );\n}\n\nexport function printKeptFiles(kept: readonly ApplyKeptFile[]): void {\n if (kept.length === 0) {\n return;\n }\n console.log(keptFilesHeader(kept.length));\n for (const entry of kept) {\n console.log(` ${entry.path} ${keptReasonLabel(entry.reason)}`);\n }\n console.log(`${CLI_COPY.forceRemoveHint} ht apply --force-remove`);\n}\n\nexport function printApplySuccess(input: {\n name: string;\n harnessCount: number;\n wrote: number;\n removed: number;\n kept: readonly ApplyKeptFile[];\n unchanged: number;\n snapshotId?: string;\n}): void {\n console.log(applyHeaderLine(input.name, input.harnessCount));\n console.log(\n applyWroteLine({\n wrote: input.wrote,\n removed: input.removed,\n kept: input.kept.length,\n unchanged: input.unchanged,\n }),\n );\n if (input.wrote > 0 || input.removed > 0) {\n printKeptFiles(input.kept);\n }\n if (input.snapshotId) {\n console.log(snapshotSavedUndoLine(`ht revert ${input.snapshotId}`));\n }\n}\n\nexport function removalSkipReason(\n reason: string,\n): \"modified\" | \"unmanaged\" | undefined {\n if (reason === \"modified\") {\n return \"modified\";\n }\n if (reason === \"unmanaged\" || reason === \"preexisting\") {\n return \"unmanaged\";\n }\n return undefined;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { listMaterializationsForRootPath } from \"../models/resource-materialization.js\";\nimport { hashOnDiskFile } from \"./safe-file-removal.js\";\nimport { isEmptyBuiltinProfile, isProfilePlugin } from \"../constants/profile.js\";\nimport { getLatestGlobalApplySnapshotForProfile } from \"../models/global-apply-snapshot.js\";\nimport { resolvePluginSelector } from \"../models/plugin-model.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport { getActiveProfileName } from \"./active-profile.js\";\nimport {\n applyProfilePlugin,\n clearGlobalProfileApply,\n collectProfilePluginIds,\n type ApplyProfilePluginResult,\n} from \"./profile-apply.js\";\nimport { mergePluginsForApply } from \"./plugin-apply-merge.js\";\nimport { fileContentsEquivalentForDrift } from \"./file-contents-drift.js\";\nimport { withAffectedResources } from \"./scoped-file-content-delta.js\";\nimport type { DriftFileChange } from \"./project-drift.js\";\nimport { detectNotStagedProfileResources } from \"./profile-untracked-resources.js\";\nimport {\n buildProfileContents,\n type ProfileContents,\n} from \"./profile-contents.js\";\nimport {\n buildHostManagedStatus,\n profileSkillNameMap,\n type HostManagedStatus,\n} from \"./cursor-host-managed-skills.js\";\nimport {\n buildHarnessLiveStatusMap,\n classifyGlobalDriftChanges,\n collectOwnedGlobalProfileFiles,\n computeGlobalProfilePanelStatus,\n countMissingHarnessRows,\n declaredMcpFromExpectedFiles,\n resolveProjectDriftSummary,\n type GlobalProfileDriftSummary,\n type GlobalProfilePanelStatus,\n type GlobalProfileStatusDepth,\n type HarnessLiveStatus,\n} from \"./global-profile-status-panel.js\";\n\nexport interface GlobalProfileStatus {\n active_profile: string | null;\n profile_exists: boolean;\n applied: boolean;\n snapshot_id: string | null;\n snapshot_at: string | null;\n stack_in_sync: boolean;\n has_drift: boolean;\n changes: DriftFileChange[];\n warning?: string;\n depth: GlobalProfileStatusDepth;\n as_of: string;\n panel: GlobalProfilePanelStatus;\n harnesses: Record<string, HarnessLiveStatus>;\n drift_summary: GlobalProfileDriftSummary;\n contents?: ProfileContents | null;\n untracked_resource_count?: number;\n /** Alias for untracked_resource_count (not-staged working-tree resources). */\n not_staged_count?: number;\n /** App-managed inventory (full depth only); never applied or persisted. */\n host_managed?: HostManagedStatus;\n}\n\nfunction readGlobalFile(homeRoot: string, relativePath: string): string | null {\n const fullPath = join(homeRoot, relativePath);\n if (!existsSync(fullPath)) {\n return null;\n }\n try {\n return readFileSync(fullPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nfunction pluginIdsMatch(left: string[], right: string[]): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((pluginId, index) => pluginId === right[index]);\n}\n\nfunction declaredMcpFromExpectedApply(expectedApply: ApplyProfilePluginResult) {\n return declaredMcpFromExpectedFiles(\n expectedApply.harnesses,\n expectedApply.expected_files ?? [],\n );\n}\n\nfunction declaredMcpNamesFromMergedPlugins(pluginIds: string[]): Record<string, string[]> {\n const merged = mergePluginsForApply(pluginIds);\n const names = merged.resources\n .filter((resource) => resource.type === \"mcp_server\")\n .map((resource) => resource.name);\n return {\n \"claude-code\": names,\n cursor: names,\n };\n}\n\nfunction buildBaseStatusFields(input: {\n depth: GlobalProfileStatusDepth;\n activeProfile: string | null;\n profileExists: boolean;\n applied: boolean;\n snapshotId: string | null;\n snapshotAt: string | null;\n stackInSync: boolean;\n hasDrift: boolean;\n changes: DriftFileChange[];\n warning?: string;\n projectPath?: string;\n expectedApply?: ApplyProfilePluginResult;\n pluginIds?: string[];\n}): GlobalProfileStatus {\n const asOf = new Date().toISOString();\n const homeRoot = resolveHomeRoot();\n const ownedFiles = collectOwnedGlobalProfileFiles(input.snapshotId);\n const { owned, nonOwned } = classifyGlobalDriftChanges(input.changes, ownedFiles);\n\n const declaredPins =\n input.pluginIds && input.pluginIds.length > 0\n ? mergePluginsForApply(input.pluginIds).pluginPins\n : [];\n const declaredFromExpected = input.expectedApply\n ? declaredMcpFromExpectedApply(input.expectedApply)\n : null;\n const declaredMcpByHarness =\n declaredFromExpected?.namesByHarness\n ?? (input.pluginIds\n ? declaredMcpNamesFromMergedPlugins(input.pluginIds)\n : { \"claude-code\": [], cursor: [] });\n\n const harnesses = buildHarnessLiveStatusMap({\n depth: input.depth,\n homeRoot,\n declaredPins,\n declaredMcpByHarness,\n ...(declaredFromExpected\n ? { expectedMcpConfigsByHarness: declaredFromExpected.configsByHarness }\n : {}),\n });\n const { missingPlugins, missingMcp } =\n input.depth === \"full\"\n ? countMissingHarnessRows(harnesses)\n : { missingPlugins: 0, missingMcp: 0 };\n\n const contents = input.activeProfile\n ? buildProfileContents(input.activeProfile)\n : null;\n const hostManaged =\n input.depth === \"full\"\n ? buildHostManagedStatus({\n homeRoot,\n profileSkills: profileSkillNameMap(contents?.resources ?? []),\n })\n : undefined;\n\n const projectDrift = resolveProjectDriftSummary(input.projectPath);\n const panel = computeGlobalProfilePanelStatus({\n depth: input.depth,\n applied: input.applied,\n activeProfile: input.activeProfile,\n stackInSync: input.stackInSync,\n ownedDriftCount: owned.length,\n nonOwnedDriftCount: nonOwned.length,\n missingPluginCount: missingPlugins,\n missingMcpCount: missingMcp,\n projectDrift,\n warning: input.warning,\n hostManagedCollisionCount: hostManaged?.cursor?.collisions.length ?? 0,\n });\n\n const driftSummary: GlobalProfileDriftSummary = {\n global: {\n status: !input.applied\n ? \"pending\"\n : input.hasDrift\n ? \"drifted\"\n : \"clean\",\n owned_changes: owned.length,\n non_owned_changes: nonOwned.length,\n },\n ...(projectDrift ? { project: projectDrift } : {}),\n };\n\n return {\n active_profile: input.activeProfile,\n profile_exists: input.profileExists,\n applied: input.applied,\n snapshot_id: input.snapshotId,\n snapshot_at: input.snapshotAt,\n stack_in_sync: input.stackInSync,\n has_drift: input.hasDrift,\n changes: input.changes,\n ...(input.warning ? { warning: input.warning } : {}),\n depth: input.depth,\n as_of: asOf,\n panel,\n harnesses,\n drift_summary: driftSummary,\n contents,\n ...(hostManaged ? { host_managed: hostManaged } : {}),\n };\n}\n\nasync function finalizeGlobalProfileStatus(\n fields: Parameters<typeof buildBaseStatusFields>[0],\n harness?: string,\n): Promise<GlobalProfileStatus> {\n const status = buildBaseStatusFields(fields);\n if (\n fields.depth !== \"full\"\n || !status.active_profile\n || isEmptyBuiltinProfile(status.active_profile)\n ) {\n return status;\n }\n try {\n const notStaged = await detectNotStagedProfileResources({\n profileSelector: status.active_profile,\n scope: \"home\",\n ...(harness ? { harness } : {}),\n });\n return {\n ...status,\n untracked_resource_count: notStaged.length,\n not_staged_count: notStaged.length,\n };\n } catch {\n return status;\n }\n}\n\nexport async function detectGlobalProfileStatus(input: {\n harness?: string;\n depth?: GlobalProfileStatusDepth;\n projectPath?: string;\n} = {}): Promise<GlobalProfileStatus> {\n const depth = input.depth ?? \"full\";\n const activeProfile = getActiveProfileName() ?? null;\n if (!activeProfile) {\n return finalizeGlobalProfileStatus(\n {\n depth,\n activeProfile: null,\n profileExists: false,\n applied: false,\n snapshotId: null,\n snapshotAt: null,\n stackInSync: false,\n hasDrift: false,\n changes: [],\n projectPath: input.projectPath,\n },\n input.harness,\n );\n }\n\n const plugin = resolvePluginSelector(activeProfile);\n if (!plugin) {\n if (isEmptyBuiltinProfile(activeProfile)) {\n const latestSnapshot = getLatestGlobalApplySnapshotForProfile(activeProfile);\n let expectedApply: ApplyProfilePluginResult;\n try {\n expectedApply = await clearGlobalProfileApply({\n dryRun: true,\n harness: input.harness,\n conflictPolicy: \"replace\",\n pull: false,\n });\n } catch (error) {\n return finalizeGlobalProfileStatus({\n depth,\n activeProfile,\n profileExists: true,\n applied: Boolean(latestSnapshot),\n snapshotId: latestSnapshot?.id ?? null,\n snapshotAt: latestSnapshot?.created_at ?? null,\n stackInSync: false,\n hasDrift: true,\n changes: [],\n warning: error instanceof Error ? error.message : String(error),\n projectPath: input.projectPath,\n pluginIds: [],\n });\n }\n\n const stackInSync = latestSnapshot\n ? pluginIdsMatch(latestSnapshot.plugin_ids, expectedApply.configured_plugin_ids)\n : false;\n const applied = Boolean(latestSnapshot);\n const hasDrift = !applied || !stackInSync;\n\n return finalizeGlobalProfileStatus({\n depth,\n activeProfile,\n profileExists: true,\n applied,\n snapshotId: latestSnapshot?.id ?? null,\n snapshotAt: latestSnapshot?.created_at ?? null,\n stackInSync,\n hasDrift,\n changes: [],\n projectPath: input.projectPath,\n expectedApply,\n pluginIds: [],\n });\n }\n\n return finalizeGlobalProfileStatus({\n depth,\n activeProfile,\n profileExists: false,\n applied: false,\n snapshotId: null,\n snapshotAt: null,\n stackInSync: false,\n hasDrift: true,\n changes: [],\n warning: `missing plugin \"${activeProfile}\"`,\n projectPath: input.projectPath,\n });\n }\n\n if (!isProfilePlugin(plugin)) {\n return finalizeGlobalProfileStatus({\n depth,\n activeProfile,\n profileExists: true,\n applied: false,\n snapshotId: null,\n snapshotAt: null,\n stackInSync: false,\n hasDrift: true,\n changes: [],\n warning: `plugin \"${plugin.name}\" is not tagged as a profile`,\n projectPath: input.projectPath,\n });\n }\n\n const latestSnapshot = getLatestGlobalApplySnapshotForProfile(activeProfile);\n const homeRoot = resolveHomeRoot();\n const pluginIds = collectProfilePluginIds(plugin);\n let expectedApply: ApplyProfilePluginResult;\n try {\n expectedApply = await applyProfilePlugin(activeProfile, {\n dryRun: true,\n harness: input.harness,\n conflictPolicy: \"replace\",\n pull: false,\n pinSkillEmits: false,\n mergeLiveSkillMarkdown: false,\n });\n } catch (error) {\n return finalizeGlobalProfileStatus({\n depth,\n activeProfile,\n profileExists: true,\n applied: Boolean(latestSnapshot),\n snapshotId: latestSnapshot?.id ?? null,\n snapshotAt: latestSnapshot?.created_at ?? null,\n stackInSync: false,\n hasDrift: true,\n changes: [],\n warning: error instanceof Error ? error.message : String(error),\n projectPath: input.projectPath,\n pluginIds,\n });\n }\n\n const stackInSync = latestSnapshot\n ? pluginIdsMatch(latestSnapshot.plugin_ids, expectedApply.configured_plugin_ids)\n : false;\n\n const changes: DriftFileChange[] = [];\n for (const file of expectedApply.expected_files ?? []) {\n const current = readGlobalFile(homeRoot, file.path);\n const owned = listMaterializationsForRootPath(homeRoot, file.path);\n if (current === null) {\n if (owned.length === 0) {\n continue;\n }\n changes.push(\n withAffectedResources({ path: file.path, type: \"deleted\" }, file.content, null),\n );\n continue;\n }\n if (owned.length > 0) {\n const diskHash = hashOnDiskFile(join(homeRoot, file.path));\n if (owned.some((row) => row.generated_hash === diskHash)) {\n continue;\n }\n if (fileContentsEquivalentForDrift(file.path, current, file.content)) {\n continue;\n }\n changes.push(\n withAffectedResources(\n { path: file.path, type: \"modified\" },\n file.content,\n current,\n ),\n );\n continue;\n }\n if (!fileContentsEquivalentForDrift(file.path, current, file.content)) {\n changes.push(\n withAffectedResources(\n { path: file.path, type: \"modified\" },\n file.content,\n current,\n ),\n );\n }\n }\n\n const applied = Boolean(latestSnapshot);\n const hasDrift = !applied || !stackInSync || changes.length > 0;\n\n return finalizeGlobalProfileStatus(\n {\n depth,\n activeProfile,\n profileExists: true,\n applied,\n snapshotId: latestSnapshot?.id ?? null,\n snapshotAt: latestSnapshot?.created_at ?? null,\n stackInSync,\n hasDrift,\n changes,\n projectPath: input.projectPath,\n expectedApply,\n pluginIds,\n },\n input.harness,\n );\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { ulid } from \"ulid\";\nimport { isEmptyBuiltinProfile } from \"../constants/profile.js\";\nimport { getHarnesstapDir } from \"../db/connection.js\";\nimport { getLatestGlobalApplySnapshotForProfile } from \"../models/global-apply-snapshot.js\";\nimport { getActiveProfileName } from \"./active-profile.js\";\nimport type { ApplyProfilePluginOptions } from \"./profile-apply.js\";\nimport { withProfileApplyLock } from \"./profile-apply-lock.js\";\nimport { flattenLiveRestoreFiles } from \"./snapshot-capture.js\";\nimport {\n buildProfileContents,\n type ProfileContents,\n} from \"./profile-contents.js\";\nimport type { DriftFileChange } from \"./project-drift.js\";\nimport {\n buildContentsFromResources,\n captureUntrackedResourcesForStash,\n removeUntrackedStashFiles,\n restoreUntrackedStashFiles,\n stashedFilesToDriftChanges,\n type StashedFileSnapshot,\n} from \"./profile-untracked-resources.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\n\nexport interface ProfileStashEntry {\n id: string;\n profile_name: string;\n created_at: string;\n contents: ProfileContents;\n file_changes: DriftFileChange[];\n stashed_files: StashedFileSnapshot[];\n}\n\ninterface ProfileStashFile {\n entries: ProfileStashEntry[];\n}\n\nexport class ProfileStashError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ProfileStashError\";\n }\n}\n\nfunction emptyProfileContents(): ProfileContents {\n return {\n plugins: [],\n stack_resource_count: 0,\n stack_summary: null,\n type_counts: {},\n resources: [],\n plugin_pins: [],\n mcp_servers: [],\n };\n}\n\nfunction getProfileStashPath(): string {\n return join(getHarnesstapDir(), \"profile-stash.json\");\n}\n\nfunction isProfileContents(value: unknown): value is ProfileContents {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const candidate = value as Partial<ProfileContents>;\n return Array.isArray(candidate.resources);\n}\n\nfunction isStashedFileSnapshot(value: unknown): value is StashedFileSnapshot {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const candidate = value as Partial<StashedFileSnapshot>;\n return typeof candidate.path === \"string\" && typeof candidate.content === \"string\";\n}\n\nfunction hydrateStashEntry(raw: unknown): ProfileStashEntry | null {\n if (typeof raw !== \"object\" || raw === null) {\n return null;\n }\n const entry = raw as Partial<ProfileStashEntry>;\n if (\n typeof entry.id !== \"string\"\n || typeof entry.profile_name !== \"string\"\n || typeof entry.created_at !== \"string\"\n ) {\n return null;\n }\n\n const contents = isProfileContents(entry.contents)\n ? entry.contents\n : buildProfileContents(entry.profile_name) ?? emptyProfileContents();\n const fileChanges = Array.isArray(entry.file_changes)\n ? entry.file_changes.filter(\n (change): change is DriftFileChange =>\n typeof change === \"object\"\n && change !== null\n && typeof (change as DriftFileChange).path === \"string\"\n && typeof (change as DriftFileChange).type === \"string\",\n )\n : [];\n const stashedFiles = Array.isArray(entry.stashed_files)\n ? entry.stashed_files.filter(isStashedFileSnapshot)\n : [];\n\n return {\n id: entry.id,\n profile_name: entry.profile_name,\n created_at: entry.created_at,\n contents,\n file_changes: fileChanges,\n stashed_files: stashedFiles,\n };\n}\n\nfunction readProfileStashFile(): ProfileStashFile {\n const filePath = getProfileStashPath();\n if (!existsSync(filePath)) {\n return { entries: [] };\n }\n try {\n const parsed = JSON.parse(readFileSync(filePath, \"utf-8\")) as Partial<ProfileStashFile>;\n if (!Array.isArray(parsed.entries)) {\n return { entries: [] };\n }\n const entries = parsed.entries\n .map((entry) => hydrateStashEntry(entry))\n .filter((entry): entry is ProfileStashEntry => entry !== null);\n return { entries };\n } catch {\n return { entries: [] };\n }\n}\n\nfunction writeProfileStashFile(file: ProfileStashFile): void {\n const home = getHarnesstapDir();\n mkdirSync(home, { recursive: true });\n writeFileSync(\n getProfileStashPath(),\n `${JSON.stringify(file, null, 2)}\\n`,\n \"utf-8\",\n );\n}\n\nexport function listProfileStashEntries(): ProfileStashEntry[] {\n return readProfileStashFile().entries;\n}\n\nfunction pushProfileStashEntry(input: {\n profile_name: string;\n contents: ProfileContents;\n file_changes: DriftFileChange[];\n stashed_files: StashedFileSnapshot[];\n}): ProfileStashEntry {\n const file = readProfileStashFile();\n const entry: ProfileStashEntry = {\n id: ulid(),\n profile_name: input.profile_name,\n created_at: new Date().toISOString(),\n contents: input.contents,\n file_changes: input.file_changes,\n stashed_files: input.stashed_files,\n };\n file.entries.unshift(entry);\n writeProfileStashFile(file);\n return entry;\n}\n\nfunction popProfileStashEntry(): ProfileStashEntry | undefined {\n const file = readProfileStashFile();\n const entry = file.entries.shift();\n if (entry) {\n writeProfileStashFile(file);\n }\n return entry;\n}\n\nfunction peekProfileStashEntry(): ProfileStashEntry | undefined {\n return readProfileStashFile().entries[0];\n}\n\nfunction resolveStashableActiveProfile(): string {\n const activeProfile = getActiveProfileName();\n if (!activeProfile) {\n throw new ProfileStashError(\n \"No active profile to stash. Set one with profile use <name> first.\",\n );\n }\n if (isEmptyBuiltinProfile(activeProfile)) {\n throw new ProfileStashError(\n 'Legacy active profile \"empty\" has no stashable state. Run profile use <name>, then profile stash.',\n );\n }\n return activeProfile;\n}\n\nexport interface StashClearedUntrackedResult {\n dry_run: boolean;\n profile_name: string;\n removed_files: string[];\n}\n\nexport interface StashProfileResult {\n entry: ProfileStashEntry;\n cleared: StashClearedUntrackedResult;\n}\n\nfunction readHomeFile(homeRoot: string, relativePath: string): string | null {\n const fullPath = resolve(homeRoot, relativePath);\n if (!existsSync(fullPath)) {\n return null;\n }\n try {\n return readFileSync(fullPath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nfunction lastWrittenContent(profileName: string, relativePath: string): string | undefined {\n const snapshot = getLatestGlobalApplySnapshotForProfile(profileName);\n if (!snapshot?.state) {\n return undefined;\n }\n return flattenLiveRestoreFiles(snapshot.state).find((file) => file.path === relativePath)?.content;\n}\n\n/**\n * Stash modified managed files (the same set `--changes save` walks) and restore\n * last-apply bytes when known. Never deletes the path.\n */\nexport async function stashManagedDriftChanges(input: {\n changes: DriftFileChange[];\n dryRun?: boolean;\n}): Promise<StashProfileResult> {\n return withProfileApplyLock(async () => {\n const profileName = resolveStashableActiveProfile();\n const homeRoot = resolveHomeRoot();\n const files: StashedFileSnapshot[] = [];\n for (const change of input.changes) {\n const current = readHomeFile(homeRoot, change.path);\n if (current === null) {\n continue;\n }\n files.push({ path: change.path, content: current });\n }\n if (files.length === 0) {\n throw new ProfileStashError(\"No unsaved changes to stash.\");\n }\n\n const contents = buildProfileContents(profileName) ?? emptyProfileContents();\n const fileChanges = stashedFilesToDriftChanges(files);\n\n if (!input.dryRun) {\n for (const file of files) {\n const previous = lastWrittenContent(profileName, file.path);\n if (previous === undefined) {\n continue;\n }\n const fullPath = resolve(homeRoot, file.path);\n mkdirSync(dirname(fullPath), { recursive: true });\n writeFileSync(fullPath, previous, \"utf-8\");\n }\n }\n\n if (input.dryRun) {\n return {\n entry: {\n id: \"dry-run\",\n profile_name: profileName,\n created_at: new Date().toISOString(),\n contents,\n file_changes: fileChanges,\n stashed_files: files,\n },\n cleared: {\n dry_run: true,\n profile_name: profileName,\n removed_files: [],\n },\n };\n }\n\n const entry = pushProfileStashEntry({\n profile_name: profileName,\n contents,\n file_changes: fileChanges,\n stashed_files: files,\n });\n return {\n entry,\n cleared: {\n dry_run: false,\n profile_name: profileName,\n removed_files: [],\n },\n };\n });\n}\n\nexport async function stashProfileCommand(\n options: ApplyProfilePluginOptions,\n): Promise<StashProfileResult> {\n return withProfileApplyLock(async () => {\n const profileName = resolveStashableActiveProfile();\n let capture: Awaited<ReturnType<typeof captureUntrackedResourcesForStash>>;\n try {\n capture = await captureUntrackedResourcesForStash({\n profileSelector: profileName,\n harness: options.harness,\n });\n } catch (error) {\n throw new ProfileStashError(\n error instanceof Error ? error.message : String(error),\n );\n }\n\n const homeRoot = resolveHomeRoot();\n const contents = buildContentsFromResources(capture.resources);\n const fileChanges = stashedFilesToDriftChanges(capture.files);\n const removedFiles = removeUntrackedStashFiles(\n homeRoot,\n capture.files,\n options.dryRun,\n );\n\n if (options.dryRun) {\n return {\n entry: {\n id: \"dry-run\",\n profile_name: profileName,\n created_at: new Date().toISOString(),\n contents,\n file_changes: fileChanges,\n stashed_files: capture.files,\n },\n cleared: {\n dry_run: true,\n profile_name: profileName,\n removed_files: removedFiles,\n },\n };\n }\n\n const entry = pushProfileStashEntry({\n profile_name: profileName,\n contents,\n file_changes: fileChanges,\n stashed_files: capture.files,\n });\n\n return {\n entry,\n cleared: {\n dry_run: false,\n profile_name: profileName,\n removed_files: removedFiles,\n },\n };\n });\n}\n\nexport interface RestoreStashedUntrackedResult {\n dry_run: boolean;\n profile_name: string;\n restored_files: string[];\n cancelled: boolean;\n}\n\nexport interface RestoreProfileStashResult {\n entry: ProfileStashEntry;\n restored: RestoreStashedUntrackedResult;\n removed: boolean;\n}\n\nexport async function popProfileStashCommand(\n options: ApplyProfilePluginOptions,\n): Promise<RestoreProfileStashResult> {\n return withProfileApplyLock(async () => {\n const entry = popProfileStashEntry();\n if (!entry) {\n throw new ProfileStashError(\"No stashed profile to restore.\");\n }\n const homeRoot = resolveHomeRoot();\n const restoredFiles = restoreUntrackedStashFiles(\n homeRoot,\n entry.stashed_files,\n options.dryRun,\n );\n return {\n entry,\n restored: {\n dry_run: options.dryRun === true,\n profile_name: entry.profile_name,\n restored_files: restoredFiles,\n cancelled: false,\n },\n removed: true,\n };\n });\n}\n\nexport async function applyProfileStashCommand(\n options: ApplyProfilePluginOptions,\n): Promise<RestoreProfileStashResult> {\n return withProfileApplyLock(async () => {\n const entry = peekProfileStashEntry();\n if (!entry) {\n throw new ProfileStashError(\"No stashed profile to restore.\");\n }\n const homeRoot = resolveHomeRoot();\n const restoredFiles = restoreUntrackedStashFiles(\n homeRoot,\n entry.stashed_files,\n options.dryRun,\n );\n return {\n entry,\n restored: {\n dry_run: options.dryRun === true,\n profile_name: entry.profile_name,\n restored_files: restoredFiles,\n cancelled: false,\n },\n removed: false,\n };\n });\n}\n","import {\n discardConfirm,\n discardedChangesLine,\n SWITCH_CHANGES_VALUES,\n type SwitchChangesValue,\n savedChangesLine,\n stashedChangesLine,\n unsavedChangesFlagHint,\n unsavedChangesLine,\n} from \"../copy/cli.js\";\nimport { ui } from \"../ui/index.js\";\nimport {\n detectGlobalProfileStatus,\n type GlobalProfileStatus,\n} from \"./global-profile-drift.js\";\nimport { commitManagedPathFromLive } from \"./profile-commit-resource.js\";\nimport { stashManagedDriftChanges } from \"./profile-stash.js\";\nimport {\n promptForChoice,\n promptForConfirmation,\n shouldUseBrowsePicker,\n} from \"./wizards/shared.js\";\n\nexport type SwitchChangesDecision = \"continue\" | \"abort\";\n\nexport function parseSwitchChanges(\n raw: string | undefined,\n): SwitchChangesValue | \"invalid\" | undefined {\n if (raw === undefined || raw === \"\") {\n return undefined;\n }\n if ((SWITCH_CHANGES_VALUES as readonly string[]).includes(raw)) {\n return raw as SwitchChangesValue;\n }\n return \"invalid\";\n}\n\nexport async function maybeSyncActiveProfileBeforeSwitch(input: {\n targetProfileName: string;\n harness?: string;\n yes?: boolean;\n format?: string;\n changes?: string;\n noInteractive?: boolean;\n}): Promise<SwitchChangesDecision> {\n const format = input.format ?? \"human\";\n\n let status: GlobalProfileStatus;\n try {\n status = await detectGlobalProfileStatus({\n harness: input.harness,\n depth: \"full\",\n });\n } catch (error) {\n ui.warn(error instanceof Error ? error.message : String(error));\n return \"continue\";\n }\n\n if (!status.active_profile || status.active_profile === input.targetProfileName) {\n return \"continue\";\n }\n if (status.changes.length === 0) {\n return \"continue\";\n }\n\n const count = status.changes.length;\n const parsedChanges = parseSwitchChanges(input.changes);\n if (parsedChanges === \"invalid\") {\n ui.danger('Error: Invalid --changes. Use save, stash or discard.');\n return \"abort\";\n }\n\n const interactive =\n !input.yes\n && shouldUseBrowsePicker({\n noInteractive: input.noInteractive,\n format,\n });\n\n let action: SwitchChangesValue | \"cancel\";\n if (parsedChanges) {\n action = parsedChanges;\n } else if (!interactive) {\n ui.danger(`Error: ${unsavedChangesLine(status.active_profile, count)}`);\n ui.hint(unsavedChangesFlagHint());\n return \"abort\";\n } else {\n ui.warn(unsavedChangesLine(status.active_profile, count));\n action = await promptForChoice({\n message: \"What should HarnessTap do with them?\",\n choices: [\n { name: `Save them to \"${status.active_profile}\"`, value: \"save\" as const },\n { name: \"Stash them\", value: \"stash\" as const },\n { name: \"Discard them\", value: \"discard\" as const },\n { name: \"Cancel\", value: \"cancel\" as const },\n ],\n });\n }\n\n switch (action) {\n case \"cancel\":\n return \"abort\";\n case \"save\": {\n for (const change of status.changes) {\n try {\n await commitManagedPathFromLive({\n profileSelector: status.active_profile,\n path: change.path,\n scope: \"home\",\n ...(input.harness ? { harness: input.harness } : {}),\n });\n } catch {\n // Aggregate paths or unmapped files stay on disk; switch still proceeds.\n }\n }\n ui.success(savedChangesLine(status.active_profile, count));\n return \"continue\";\n }\n case \"stash\": {\n await stashManagedDriftChanges({\n changes: status.changes,\n });\n ui.success(stashedChangesLine(count, \"ht profile stash pop\"));\n return \"continue\";\n }\n case \"discard\": {\n if (interactive && parsedChanges !== \"discard\") {\n const confirmed = await promptForConfirmation({\n message: discardConfirm(count),\n default: false,\n });\n if (!confirmed) {\n return \"abort\";\n }\n }\n ui.success(discardedChangesLine(count));\n return \"continue\";\n }\n default: {\n const unhandled: never = action;\n throw new Error(`Unhandled switch changes action: ${String(unhandled)}`);\n }\n }\n}\n","import {\n resolveProfileEnvironment,\n type ProjectProfileEntry,\n type ResolvedProjectConfig,\n} from \"../project-config.js\";\nimport {\n promptForChoice,\n promptForSearchableChoice,\n type PromptChoice,\n} from \"./shared.js\";\n\nfunction formatProfilePluginHint(entry: ProjectProfileEntry): string {\n switch (entry.source) {\n case \"catalog\":\n case \"local\":\n return entry.selector ?? entry.name;\n case \"inline\":\n return entry.plugin ?? entry.name;\n default: {\n const unhandledSource: never = entry.source;\n throw new Error(`Unhandled profile source: ${unhandledSource}`);\n }\n }\n}\n\nfunction formatProjectProfileChoiceName(\n config: ResolvedProjectConfig,\n entry: ProjectProfileEntry,\n): string {\n const parts = [entry.name, entry.source, formatProfilePluginHint(entry)];\n const environment = resolveProfileEnvironment(config, entry);\n if (environment) {\n parts.push(`env ${environment}`);\n }\n return parts.join(\" · \");\n}\n\nexport function buildProjectProfileChoices(\n config: ResolvedProjectConfig,\n): PromptChoice<string>[] {\n return config.profiles.map((entry) => ({\n name: formatProjectProfileChoiceName(config, entry),\n value: entry.name,\n }));\n}\n\nfunction resolveDefaultProfileKey(config: ResolvedProjectConfig): string | undefined {\n const defaultProfile = config.default_profile;\n if (!defaultProfile) {\n return undefined;\n }\n return config.profiles.some((profile) => profile.name === defaultProfile)\n ? defaultProfile\n : undefined;\n}\n\nexport async function promptForProjectProfile(\n config: ResolvedProjectConfig,\n): Promise<string> {\n const choices = buildProjectProfileChoices(config);\n const defaultProfile = resolveDefaultProfileKey(config);\n const message = \"Which project profile should be used?\";\n\n if (choices.length >= 5) {\n return promptForSearchableChoice({\n message,\n choices,\n default: defaultProfile,\n });\n }\n\n return promptForChoice({\n message,\n choices,\n default: defaultProfile,\n });\n}\n","import {\n isEmptyBuiltinProfile,\n isProfilePlugin,\n} from \"../constants/profile.js\";\nimport {\n addResourceToPlugin,\n createPlugin,\n resolvePluginSelector,\n} from \"../models/plugin-model.js\";\nimport {\n normalizeResourceInput,\n upsertResource,\n} from \"../models/resource.js\";\nimport type { ClaudePluginConfig, ResourceType } from \"../types.js\";\nimport { useEnvironmentCommand } from \"./environment-commands.js\";\nimport {\n formatEnvironmentToml,\n importEnvironmentToml,\n} from \"./environment-import-export.js\";\nimport { detectGlobalProfileStatus } from \"./global-profile-drift.js\";\nimport { installPluginFromCatalog } from \"./plugin-catalog-install.js\";\nimport { parsePluginSelector, resolveRemotePluginSelector } from \"./plugin-selector.js\";\nimport {\n promptMaterializationConflict,\n resolveApplyConflictPolicy,\n} from \"./materialization-conflicts.js\";\nimport {\n findProjectConfig,\n getProfileEntry,\n resolveProfileEnvironment,\n type ProjectProfileEntry,\n type ProjectPluginTable,\n type ResolvedProjectConfig,\n} from \"./project-config.js\";\nimport { MISSING_PROJECT_CONFIG_MESSAGE } from \"./project-config-messages.js\";\nimport { promptForProjectProfile } from \"./wizards/project-use.js\";\nimport { shouldUseWizard } from \"./wizards/shared.js\";\nimport { useProfileCommand } from \"./profile-commands.js\";\nimport { stashProfileCommand, ProfileStashError } from \"./profile-stash.js\";\nimport { maybeSyncActiveProfileBeforeSwitch } from \"./profile-switch-prompt.js\";\nimport { clearGlobalProfileApply, type ApplyProfilePluginResult } from \"./profile-apply.js\";\nimport { clearActiveProfileName, getActiveProfileName } from \"./active-profile.js\";\nimport { getGlobalActiveEnvironmentName } from \"./environment-session.js\";\n\nexport interface ProjectUseOptions {\n profile?: string;\n project?: string;\n dryRun?: boolean;\n force?: boolean;\n pull?: boolean;\n harness?: string;\n account?: string;\n baseUrl?: string;\n onConflict?: string;\n format?: string;\n yes?: boolean;\n interactive?: boolean;\n noInteractive?: boolean;\n}\n\nexport type ProjectUseResult =\n | {\n skipped: true;\n profile_key: string;\n plugin_name: string;\n environment_name?: string;\n }\n | ({\n skipped: false;\n profile_key: string;\n plugin_name: string;\n environment_name?: string;\n stashed?: boolean;\n stash_id?: string;\n } & ApplyProfilePluginResult);\n\nfunction assertProfilePlugin(plugin: { name: string; tags: string[] }, context: string): void {\n if (!isProfilePlugin(plugin)) {\n throw new Error(`Plugin \"${plugin.name}\" is not tagged as a profile (${context})`);\n }\n}\n\nfunction resolvePluginNameFromSelector(selector: string): string {\n const existing = resolvePluginSelector(selector);\n if (existing) {\n return existing.name;\n }\n return parsePluginSelector(selector).name;\n}\n\nexport function resolveExpectedPluginName(\n config: ResolvedProjectConfig,\n entry: ProjectProfileEntry,\n): string {\n switch (entry.source) {\n case \"catalog\":\n case \"local\": {\n const selector = entry.selector;\n if (!selector) {\n throw new Error(`Profile ${entry.name} is missing a plugin selector.`);\n }\n return resolvePluginNameFromSelector(selector);\n }\n case \"inline\": {\n const pluginKey = entry.plugin;\n if (!pluginKey) {\n throw new Error(`Inline profile ${entry.name} is missing a plugin reference.`);\n }\n const inlinePlugin = config.plugins.find((plugin) => plugin.name === pluginKey);\n return inlinePlugin?.name ?? pluginKey;\n }\n default: {\n const unhandledSource: never = entry.source;\n throw new Error(`Unhandled profile source: ${unhandledSource}`);\n }\n }\n}\n\nfunction resolvePreviewPluginName(\n config: ResolvedProjectConfig,\n entry: ProjectProfileEntry,\n): string {\n return resolveExpectedPluginName(config, entry);\n}\n\nfunction findInlinePluginTable(\n config: ResolvedProjectConfig,\n pluginKey: string,\n): ProjectPluginTable {\n const plugin = config.plugins.find((entry) => entry.name === pluginKey);\n if (!plugin) {\n throw new Error(`Inline profile references unknown plugin: ${pluginKey}`);\n }\n return plugin;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction importInlinePluginTable(pluginTable: ProjectPluginTable) {\n const resourcesRaw = Array.isArray(pluginTable.resources) ? pluginTable.resources : [];\n const plugin = createPlugin({\n name: pluginTable.name,\n version: typeof pluginTable.version === \"string\" ? pluginTable.version : \"1.0.0\",\n description: typeof pluginTable.description === \"string\" ? pluginTable.description : \"\",\n tags: Array.isArray(pluginTable.tags) ? pluginTable.tags.map(String) : [],\n ...(isRecord(pluginTable.claude)\n ? { claude: pluginTable.claude as ClaudePluginConfig }\n : {}),\n });\n\n for (const raw of resourcesRaw) {\n if (!isRecord(raw)) continue;\n const metadata = isRecord(raw.metadata)\n ? raw.metadata\n : typeof raw.metadata_json === \"string\"\n ? (JSON.parse(raw.metadata_json) as Record<string, unknown>)\n : {};\n const upserted = upsertResource(\n normalizeResourceInput({\n type: String(raw.type ?? \"\") as ResourceType,\n name: String(raw.name ?? \"\"),\n description: String(raw.description ?? \"\"),\n content: String(raw.content ?? \"\"),\n metadata,\n source: `project-inline:${pluginTable.name}`,\n namespace: String(raw.namespace ?? \"\"),\n origin_kind: (raw.origin_kind ?? \"manual\") as \"manual\",\n origin_ref: String(raw.origin_ref ?? \"\"),\n }),\n { policy: \"overwrite\" },\n );\n if (upserted.action === \"skipped\") {\n throw new Error(`Failed to import inline resource: ${String(raw.type)}:${String(raw.name)}`);\n }\n addResourceToPlugin(plugin.id, upserted.resource.id);\n }\n\n return plugin;\n}\n\nexport async function resolveProjectProfileKey(\n config: ResolvedProjectConfig,\n options: Pick<ProjectUseOptions, \"profile\" | \"format\" | \"interactive\" | \"noInteractive\">,\n): Promise<string> {\n if (options.profile) {\n getProfileEntry(config, options.profile);\n return options.profile;\n }\n\n if (config.profiles.length === 0) {\n throw new Error(\"Project config has no profiles\");\n }\n\n if (config.profiles.length === 1) {\n const [onlyProfile] = config.profiles;\n if (!onlyProfile) {\n throw new Error(\"Project config has no profiles\");\n }\n return onlyProfile.name;\n }\n\n if (\n shouldUseWizard({\n interactive: options.interactive,\n noInteractive: options.noInteractive,\n format: options.format,\n missingRequiredArgs: !options.profile,\n })\n ) {\n return promptForProjectProfile(config);\n }\n\n throw new Error(\"multiple profiles configured; pass --profile <name>\");\n}\n\nexport async function resolveProjectProfilePluginName(\n config: ResolvedProjectConfig,\n entry: ProjectProfileEntry,\n options: Pick<ProjectUseOptions, \"pull\" | \"account\" | \"baseUrl\">,\n): Promise<string> {\n const pull = options.pull ?? true;\n\n switch (entry.source) {\n case \"catalog\": {\n const selector = entry.selector;\n if (!selector) {\n throw new Error(`Catalog profile ${entry.name} is missing a plugin selector.`);\n }\n const existing = resolvePluginSelector(selector);\n if (existing) {\n assertProfilePlugin(existing, `catalog profile ${entry.name}`);\n return existing.name;\n }\n if (!pull) {\n throw new Error(\n `Profile plugin not found locally: ${selector}. Re-run with pull enabled or install the plugin first.`,\n );\n }\n\n const parsed = parsePluginSelector(selector);\n if (parsed.scope === \"published\") {\n const remote = resolveRemotePluginSelector(selector, {});\n const installed = await installPluginFromCatalog(remote, {\n account: options.account,\n baseUrl: options.baseUrl,\n });\n const plugin = resolvePluginSelector(installed.pluginName);\n if (!plugin) {\n throw new Error(`Plugin not found after catalog install: ${installed.pluginName}`);\n }\n assertProfilePlugin(plugin, `catalog profile ${entry.name}`);\n return plugin.name;\n }\n\n throw new Error(`Profile plugin not found locally: ${selector}`);\n }\n case \"local\": {\n const selector = entry.selector;\n if (!selector) {\n throw new Error(`Local profile ${entry.name} is missing a plugin selector.`);\n }\n const plugin = resolvePluginSelector(selector);\n if (!plugin) {\n throw new Error(`Profile plugin not found locally: ${selector}`);\n }\n assertProfilePlugin(plugin, `local profile ${entry.name}`);\n return plugin.name;\n }\n case \"inline\": {\n const pluginKey = entry.plugin;\n if (!pluginKey) {\n throw new Error(`Inline profile ${entry.name} is missing a plugin reference.`);\n }\n const pluginTable = findInlinePluginTable(config, pluginKey);\n const imported = importInlinePluginTable(pluginTable);\n assertProfilePlugin(imported, `inline profile ${entry.name}`);\n return imported.name;\n }\n default: {\n const unhandledSource: never = entry.source;\n throw new Error(`Unhandled profile source: ${unhandledSource}`);\n }\n }\n}\n\nexport async function importProjectConfigEnvironments(\n config: ResolvedProjectConfig,\n): Promise<void> {\n for (const environment of config.environments) {\n importEnvironmentToml(formatEnvironmentToml(environment), {\n createIfMissing: true,\n });\n }\n}\n\nexport async function shouldSkipProjectUse(input: {\n pluginName: string;\n environmentName?: string;\n force?: boolean;\n harness?: string;\n}): Promise<boolean> {\n if (input.force) {\n return false;\n }\n\n const activeProfile = getActiveProfileName();\n if (activeProfile !== input.pluginName) {\n return false;\n }\n\n const activeEnvironment = getGlobalActiveEnvironmentName();\n const environmentMatches =\n input.environmentName === undefined\n ? activeEnvironment === undefined\n : activeEnvironment === input.environmentName;\n if (!environmentMatches) {\n return false;\n }\n\n const status = await detectGlobalProfileStatus({ harness: input.harness });\n return (\n (!status.has_drift && status.stack_in_sync) ||\n (status.applied && !status.has_drift)\n );\n}\n\nexport async function executeProjectUse(\n options: ProjectUseOptions = {},\n): Promise<ProjectUseResult> {\n if (options.profile && isEmptyBuiltinProfile(options.profile)) {\n const conflictPolicy = resolveApplyConflictPolicy({\n onConflict: options.onConflict,\n noInteractive: options.noInteractive ?? options.format === \"json\",\n });\n let stashed: Awaited<ReturnType<typeof stashProfileCommand>> | undefined;\n try {\n stashed = await stashProfileCommand({\n harness: options.harness,\n dryRun: options.dryRun,\n conflictPolicy,\n pull: false,\n ...(conflictPolicy === \"prompt\"\n ? { conflictResolver: promptMaterializationConflict }\n : {}),\n });\n } catch (error) {\n if (!(error instanceof ProfileStashError)) {\n throw error;\n }\n }\n const cleared = await clearGlobalProfileApply({\n harness: options.harness,\n dryRun: options.dryRun,\n conflictPolicy,\n pull: false,\n ...(conflictPolicy === \"prompt\"\n ? { conflictResolver: promptMaterializationConflict }\n : {}),\n });\n if (!options.dryRun) {\n clearActiveProfileName();\n }\n return {\n skipped: false,\n profile_key: stashed?.entry.profile_name ?? getActiveProfileName() ?? \"empty\",\n plugin_name: cleared.profile_name,\n stashed: Boolean(stashed),\n ...(stashed ? { stash_id: stashed.entry.id } : {}),\n ...cleared,\n };\n }\n\n const config = findProjectConfig(options.project ?? process.cwd());\n if (!config) {\n throw new Error(MISSING_PROJECT_CONFIG_MESSAGE);\n }\n\n const profileKey = await resolveProjectProfileKey(config, {\n profile: options.profile,\n format: options.format,\n interactive: options.interactive,\n noInteractive: options.noInteractive,\n });\n const entry = getProfileEntry(config, profileKey);\n const environmentName = resolveProfileEnvironment(config, entry);\n const expectedPluginName = resolveExpectedPluginName(config, entry);\n const dryRun = options.dryRun === true;\n\n if (\n await shouldSkipProjectUse({\n pluginName: expectedPluginName,\n environmentName,\n force: options.force,\n harness: options.harness,\n })\n ) {\n return {\n skipped: true,\n profile_key: profileKey,\n plugin_name: expectedPluginName,\n ...(environmentName ? { environment_name: environmentName } : {}),\n };\n }\n\n if (!dryRun) {\n await importProjectConfigEnvironments(config);\n }\n\n const pluginName = dryRun\n ? resolvePreviewPluginName(config, entry)\n : await resolveProjectProfilePluginName(config, entry, {\n pull: options.pull ?? true,\n account: options.account,\n baseUrl: options.baseUrl,\n });\n\n if (environmentName && !dryRun) {\n useEnvironmentCommand(environmentName);\n }\n\n if (!dryRun) {\n const sync = await maybeSyncActiveProfileBeforeSwitch({\n targetProfileName: pluginName,\n harness: options.harness,\n yes: options.yes,\n format: options.format,\n });\n if (sync === \"abort\") {\n throw new Error(\"Profile switch cancelled.\");\n }\n }\n\n const conflictPolicy = resolveApplyConflictPolicy({\n onConflict: options.onConflict,\n noInteractive: options.noInteractive ?? options.format === \"json\",\n });\n const applied = await useProfileCommand(pluginName, {\n harness: options.harness,\n dryRun: options.dryRun,\n pull: options.pull ?? true,\n account: options.account,\n baseUrl: options.baseUrl,\n conflictPolicy,\n ...(conflictPolicy === \"prompt\"\n ? { conflictResolver: promptMaterializationConflict }\n : {}),\n });\n\n return {\n skipped: false,\n profile_key: profileKey,\n plugin_name: pluginName,\n ...(environmentName ? { environment_name: environmentName } : {}),\n ...applied,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,MAAM,eAAe;AAGnC,IAAM,gBAAN,cAA4B,MAAM;AAAA,EAC9B;AAAA,EAET,YAAY,OAAe,UAAkB;AAC3C,UAAM,wBAAwB,KAAK,GAAG;AACtC,SAAK,OAAO;AACZ,SAAK,QAAQ;AACb,SAAK,WAAW;AAAA,EAClB;AAAA,EAES;AACX;AAEO,SAAS,eAAe,KAAa,OAAO,gBAAgB,GAAW;AAC5E,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,YAAY,KAAK;AACnB,WAAO;AAAA,EACT;AACA,MAAI,QAAQ,WAAW,IAAI,KAAK,QAAQ,WAAW,KAAK,GAAG;AACzD,WAAO,KAAK,MAAM,QAAQ,MAAM,CAAC,CAAC;AAAA,EACpC;AACA,SAAO,WAAW,OAAO,IAAI,UAAU,QAAQ,OAAO;AACxD;AAEO,SAAS,gBACd,KACA,MACQ;AACR,QAAM,WAAW,QAAQ,eAAe,KAAK,MAAM,QAAQ,gBAAgB,CAAC,CAAC;AAC7E,MAAI,MAAM,aAAa,CAAC,WAAW,QAAQ,GAAG;AAC5C,UAAM,IAAI,cAAc,KAAK,QAAQ;AAAA,EACvC;AACA,SAAO;AACT;;;AC5BO,SAAS,2BAA2B,MAGxB;AACjB,QAAM,SAAS,KAAK,aAAa,gBAAgB,KAAK,UAAU,IAAI;AACpE,MACE,WAAW,aACX,WAAW,UACX,WAAW,YACX,WAAW,UACX;AACA,WAAO;AAAA,EACT;AACA,MACE,KAAK,iBACL,QAAQ,IAAI,OAAO,UACnB,QAAQ,IAAI,8BAA8B,OAC1C,CAAC,QAAQ,MAAM,SACf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,eAAe;AAAA,EACvC;AAEA,MAAI,CAAC,QAAQ;AACX,UAAM,OAAO,MAAM,mCAAmC;AAAA,MACpD,mBAAmB;AAAA,MACnB,SAAS,QAAQ;AAAA,MACjB,KAAK,QAAQ;AAAA,MACb,QAAQ,QAAQ;AAAA,IAClB,CAAC;AACD,QAAI,SAAS,SAAS;AACpB,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AAAA,EACF;AAEA,QAAM,iBAAiB,2BAA2B;AAAA,IAChD,YAAY,QAAQ;AAAA,IACpB,eAAe,QAAQ,iBAAiB,QAAQ,WAAW;AAAA,EAC7D,CAAC;AACD,QAAM,UAAU,MAAM,kBAAkB,YAAY;AAAA,IAClD,SAAS,QAAQ;AAAA,IACjB,QAAQ,QAAQ;AAAA,IAChB,MAAM,QAAQ,QAAQ;AAAA,IACtB,SAAS,QAAQ;AAAA,IACjB,SAAS,QAAQ;AAAA,IACjB;AAAA,IACA,GAAI,mBAAmB,WACnB,EAAE,kBAAkB,8BAA8B,IAClD,CAAC;AAAA,EACP,CAAC;AAED,SAAO;AAAA,IACL,SAAS;AAAA,IACT,aAAa;AAAA,IACb,aAAa;AAAA,IACb,GAAI,kBAAkB,EAAE,kBAAkB,gBAAgB,IAAI,CAAC;AAAA,IAC/D,GAAG;AAAA,EACL;AACF;","names":["existsSync","join","join","existsSync","latestSnapshot","expectedApply","stackInSync","applied","hasDrift","existsSync","readFileSync","join","resolve","join","existsSync","readFileSync","resolve","conflictPolicy"]}
@@ -0,0 +1,311 @@
1
+ import {
2
+ detectHomePlatforms,
3
+ detectPlatforms,
4
+ scanAndPersist,
5
+ scanAndPersistHomeDefaults
6
+ } from "./chunk-WRX7CB2M.js";
7
+ import {
8
+ getAllPlatforms,
9
+ listResources,
10
+ resolveHomeRoot
11
+ } from "./chunk-TKBMHZTS.js";
12
+ import {
13
+ getHarnesstapDir
14
+ } from "./chunk-KLR2DURP.js";
15
+
16
+ // src/services/resource-tracked-directories.ts
17
+ import {
18
+ existsSync,
19
+ lstatSync,
20
+ mkdirSync,
21
+ readFileSync,
22
+ writeFileSync
23
+ } from "fs";
24
+ import { basename, dirname, join, relative, resolve } from "path";
25
+ var TRACKED_DIRECTORIES_FILE = "resource-tracked-directories.json";
26
+ var ResourceTrackedDirectoryError = class extends Error {
27
+ constructor(message) {
28
+ super(message);
29
+ this.name = "ResourceTrackedDirectoryError";
30
+ }
31
+ };
32
+ function trackedDirectoriesPath() {
33
+ return resolve(getHarnesstapDir(), TRACKED_DIRECTORIES_FILE);
34
+ }
35
+ function readCustomDirectories() {
36
+ const filePath = trackedDirectoriesPath();
37
+ if (!existsSync(filePath)) {
38
+ return [];
39
+ }
40
+ try {
41
+ const parsed = JSON.parse(
42
+ readFileSync(filePath, "utf-8")
43
+ );
44
+ if (!Array.isArray(parsed.directories)) {
45
+ return [];
46
+ }
47
+ return parsed.directories.filter(
48
+ (entry) => typeof entry === "string" && entry.trim().length > 0
49
+ );
50
+ } catch {
51
+ return [];
52
+ }
53
+ }
54
+ function writeCustomDirectories(directories) {
55
+ const home = getHarnesstapDir();
56
+ mkdirSync(home, { recursive: true });
57
+ const normalized = [...new Set(directories.map((entry) => resolve(entry)))].sort();
58
+ writeFileSync(
59
+ trackedDirectoriesPath(),
60
+ `${JSON.stringify({ directories: normalized }, null, 2)}
61
+ `,
62
+ "utf-8"
63
+ );
64
+ }
65
+ function countResourcesByOriginRef() {
66
+ const counts = /* @__PURE__ */ new Map();
67
+ for (const resource of listResources()) {
68
+ const originRef = resource.origin_ref?.trim();
69
+ if (!originRef) {
70
+ continue;
71
+ }
72
+ counts.set(originRef, (counts.get(originRef) ?? 0) + 1);
73
+ }
74
+ return counts;
75
+ }
76
+ function resolveConfiguredPath(rootPath, configuredPath) {
77
+ return configuredPath.startsWith("~/") ? join(rootPath, configuredPath.slice(2)) : join(rootPath, configuredPath);
78
+ }
79
+ function configuredPathValues(paths) {
80
+ const result = [];
81
+ for (const [key, value] of Object.entries(paths)) {
82
+ if (key === "pathAlternates" || typeof value !== "string" || !value) {
83
+ continue;
84
+ }
85
+ result.push(value);
86
+ }
87
+ for (const alternates of Object.values(paths.pathAlternates ?? {})) {
88
+ if (alternates) {
89
+ result.push(...alternates);
90
+ }
91
+ }
92
+ return result;
93
+ }
94
+ function topLevelFolderUnderRoot(rootPath, absolutePath) {
95
+ const rel = relative(rootPath, absolutePath);
96
+ if (!rel || rel === "." || rel.startsWith("..")) {
97
+ return null;
98
+ }
99
+ const first = rel.split(/[/\\]/)[0];
100
+ if (!first) {
101
+ return null;
102
+ }
103
+ return join(rootPath, first);
104
+ }
105
+ function foldersFromConfiguredPaths(rootPath, configured) {
106
+ const folders = /* @__PURE__ */ new Map();
107
+ for (const entry of configured) {
108
+ const absolute = resolveConfiguredPath(rootPath, entry.path);
109
+ if (!existsSync(absolute)) {
110
+ continue;
111
+ }
112
+ let target = absolute;
113
+ try {
114
+ if (!lstatSync(absolute).isDirectory()) {
115
+ target = dirname(absolute);
116
+ }
117
+ } catch {
118
+ continue;
119
+ }
120
+ const top = topLevelFolderUnderRoot(rootPath, target);
121
+ if (!top) {
122
+ continue;
123
+ }
124
+ const existing = folders.get(top);
125
+ if (existing) {
126
+ if (!existing.platform_ids.includes(entry.platformId)) {
127
+ existing.platform_ids.push(entry.platformId);
128
+ }
129
+ continue;
130
+ }
131
+ folders.set(top, {
132
+ path: top,
133
+ label: basename(top) || top,
134
+ platform_ids: [entry.platformId]
135
+ });
136
+ }
137
+ return [...folders.values()].sort((a, b) => a.label.localeCompare(b.label));
138
+ }
139
+ function homeResourceFolders(homeRoot) {
140
+ return foldersFromConfiguredPaths(
141
+ homeRoot,
142
+ detectHomePlatforms(homeRoot).flatMap(
143
+ (result) => result.discoveredPaths.map((path) => ({
144
+ path,
145
+ platformId: result.platformId
146
+ }))
147
+ )
148
+ );
149
+ }
150
+ function projectResourceFolders(projectRoot) {
151
+ const configured = [];
152
+ for (const platform of getAllPlatforms()) {
153
+ for (const path of configuredPathValues(platform.projectPaths)) {
154
+ configured.push({ path, platformId: platform.id });
155
+ }
156
+ }
157
+ return foldersFromConfiguredPaths(projectRoot, configured);
158
+ }
159
+ function entryForCustomDirectory(path, resourceCounts) {
160
+ const resolved = resolve(path);
161
+ return {
162
+ path: resolved,
163
+ kind: "custom",
164
+ label: basename(resolved) || resolved,
165
+ platform_ids: detectPlatforms(resolved),
166
+ resource_count: resourceCounts.get(resolved) ?? 0,
167
+ removable: true,
168
+ folders: projectResourceFolders(resolved),
169
+ display_path: resolved
170
+ };
171
+ }
172
+ function listResourceTrackedDirectories() {
173
+ const homeRoot = resolve(homeRootPath());
174
+ const detected = detectHomePlatforms(homeRoot);
175
+ const resourceCounts = countResourcesByOriginRef();
176
+ const entries = [
177
+ {
178
+ path: homeRoot,
179
+ kind: "home_default",
180
+ label: "Home harness defaults",
181
+ platform_ids: detected.map((result) => result.platformId),
182
+ resource_count: resourceCounts.get(homeRoot) ?? 0,
183
+ removable: false,
184
+ folders: homeResourceFolders(homeRoot),
185
+ display_path: "~"
186
+ }
187
+ ];
188
+ for (const directory of readCustomDirectories()) {
189
+ const resolved = resolve(directory);
190
+ if (resolved === homeRoot) {
191
+ continue;
192
+ }
193
+ entries.push(entryForCustomDirectory(resolved, resourceCounts));
194
+ }
195
+ return entries;
196
+ }
197
+ function homeRootPath() {
198
+ return resolveHomeRoot();
199
+ }
200
+ async function addResourceTrackedDirectory(inputPath) {
201
+ const resolved = resolve(inputPath.trim());
202
+ if (!existsSync(resolved)) {
203
+ throw new ResourceTrackedDirectoryError(`Directory not found: ${resolved}`);
204
+ }
205
+ const homeRoot = resolve(homeRootPath());
206
+ if (resolved === homeRoot) {
207
+ throw new ResourceTrackedDirectoryError(
208
+ "Home directory is already tracked as harness defaults."
209
+ );
210
+ }
211
+ const custom = readCustomDirectories();
212
+ if (custom.some((entry) => resolve(entry) === resolved)) {
213
+ throw new ResourceTrackedDirectoryError(`Directory already tracked: ${resolved}`);
214
+ }
215
+ custom.push(resolved);
216
+ writeCustomDirectories(custom);
217
+ const imported = await scanAndPersist(resolved, void 0, {
218
+ conflictPolicy: "skip",
219
+ originRef: resolved,
220
+ namespace: "project"
221
+ });
222
+ const resourceCounts = countResourcesByOriginRef();
223
+ return {
224
+ directory: entryForCustomDirectory(resolved, resourceCounts),
225
+ imported_count: imported.length
226
+ };
227
+ }
228
+ function removeResourceTrackedDirectory(inputPath) {
229
+ const resolved = resolve(inputPath.trim());
230
+ const homeRoot = resolve(homeRootPath());
231
+ if (resolved === homeRoot) {
232
+ throw new ResourceTrackedDirectoryError("Cannot remove home harness defaults.");
233
+ }
234
+ const custom = readCustomDirectories();
235
+ const next = custom.filter((entry) => resolve(entry) !== resolved);
236
+ if (next.length === custom.length) {
237
+ throw new ResourceTrackedDirectoryError(`Directory not tracked: ${resolved}`);
238
+ }
239
+ writeCustomDirectories(next);
240
+ }
241
+ async function rescanResourceTrackedDirectories() {
242
+ const homeRoot = resolve(homeRootPath());
243
+ const rescanned = [];
244
+ let importedCount = 0;
245
+ const homeDefaults = await scanAndPersistHomeDefaults(void 0, homeRoot);
246
+ const homeImported = homeDefaults.resources.length;
247
+ importedCount += homeImported;
248
+ rescanned.push({
249
+ path: homeRoot,
250
+ kind: "home_default",
251
+ imported_count: homeImported,
252
+ skipped: false
253
+ });
254
+ for (const directory of readCustomDirectories()) {
255
+ const resolved = resolve(directory);
256
+ if (resolved === homeRoot) {
257
+ continue;
258
+ }
259
+ if (!existsSync(resolved)) {
260
+ rescanned.push({
261
+ path: resolved,
262
+ kind: "custom",
263
+ imported_count: 0,
264
+ skipped: true,
265
+ error: `Directory not found: ${resolved}`
266
+ });
267
+ continue;
268
+ }
269
+ try {
270
+ const beforeIds = new Set(
271
+ listResources().map((resource) => resource.id)
272
+ );
273
+ const resolvedResources = await scanAndPersist(resolved, void 0, {
274
+ conflictPolicy: "skip",
275
+ originRef: resolved,
276
+ namespace: "project"
277
+ });
278
+ const imported = resolvedResources.filter(
279
+ (resource) => !beforeIds.has(resource.id)
280
+ ).length;
281
+ importedCount += imported;
282
+ rescanned.push({
283
+ path: resolved,
284
+ kind: "custom",
285
+ imported_count: imported,
286
+ skipped: false
287
+ });
288
+ } catch (error) {
289
+ rescanned.push({
290
+ path: resolved,
291
+ kind: "custom",
292
+ imported_count: 0,
293
+ skipped: true,
294
+ error: error instanceof Error ? error.message : String(error)
295
+ });
296
+ }
297
+ }
298
+ return {
299
+ directories: listResourceTrackedDirectories(),
300
+ rescanned,
301
+ imported_count: importedCount
302
+ };
303
+ }
304
+
305
+ export {
306
+ listResourceTrackedDirectories,
307
+ addResourceTrackedDirectory,
308
+ removeResourceTrackedDirectory,
309
+ rescanResourceTrackedDirectories
310
+ };
311
+ //# sourceMappingURL=chunk-BNDJJAEI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/services/resource-tracked-directories.ts"],"sourcesContent":["import {\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { getHarnesstapDir } from \"../db/connection.js\";\nimport { listResources } from \"../models/resource.js\";\nimport { getAllPlatforms } from \"../platforms/registry.js\";\nimport type { PlatformPaths } from \"../types.js\";\nimport { resolveHomeRoot } from \"../utils/home-root.js\";\nimport {\n detectHomePlatforms,\n detectPlatforms,\n scanAndPersist,\n scanAndPersistHomeDefaults,\n} from \"./scanner.js\";\n\nconst TRACKED_DIRECTORIES_FILE = \"resource-tracked-directories.json\";\n\nexport class ResourceTrackedDirectoryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ResourceTrackedDirectoryError\";\n }\n}\n\ninterface TrackedDirectoriesFile {\n directories: string[];\n}\n\nexport interface ResourceTrackedFolderEntry {\n path: string;\n label: string;\n platform_ids: string[];\n}\n\nexport interface ResourceTrackedDirectoryEntry {\n path: string;\n kind: \"home_default\" | \"custom\";\n label: string;\n platform_ids: string[];\n resource_count: number;\n removable: boolean;\n folders: ResourceTrackedFolderEntry[];\n display_path?: string;\n}\n\nfunction trackedDirectoriesPath(): string {\n return resolve(getHarnesstapDir(), TRACKED_DIRECTORIES_FILE);\n}\n\nfunction readCustomDirectories(): string[] {\n const filePath = trackedDirectoriesPath();\n if (!existsSync(filePath)) {\n return [];\n }\n try {\n const parsed = JSON.parse(\n readFileSync(filePath, \"utf-8\"),\n ) as Partial<TrackedDirectoriesFile>;\n if (!Array.isArray(parsed.directories)) {\n return [];\n }\n return parsed.directories.filter(\n (entry): entry is string => typeof entry === \"string\" && entry.trim().length > 0,\n );\n } catch {\n return [];\n }\n}\n\nfunction writeCustomDirectories(directories: string[]): void {\n const home = getHarnesstapDir();\n mkdirSync(home, { recursive: true });\n const normalized = [...new Set(directories.map((entry) => resolve(entry)))].sort();\n writeFileSync(\n trackedDirectoriesPath(),\n `${JSON.stringify({ directories: normalized } satisfies TrackedDirectoriesFile, null, 2)}\\n`,\n \"utf-8\",\n );\n}\n\nfunction countResourcesByOriginRef(): Map<string, number> {\n const counts = new Map<string, number>();\n for (const resource of listResources()) {\n const originRef = resource.origin_ref?.trim();\n if (!originRef) {\n continue;\n }\n counts.set(originRef, (counts.get(originRef) ?? 0) + 1);\n }\n return counts;\n}\n\nfunction resolveConfiguredPath(rootPath: string, configuredPath: string): string {\n return configuredPath.startsWith(\"~/\")\n ? join(rootPath, configuredPath.slice(2))\n : join(rootPath, configuredPath);\n}\n\nfunction configuredPathValues(paths: PlatformPaths): string[] {\n const result: string[] = [];\n for (const [key, value] of Object.entries(paths)) {\n if (key === \"pathAlternates\" || typeof value !== \"string\" || !value) {\n continue;\n }\n result.push(value);\n }\n for (const alternates of Object.values(paths.pathAlternates ?? {})) {\n if (alternates) {\n result.push(...alternates);\n }\n }\n return result;\n}\n\nfunction topLevelFolderUnderRoot(\n rootPath: string,\n absolutePath: string,\n): string | null {\n const rel = relative(rootPath, absolutePath);\n if (!rel || rel === \".\" || rel.startsWith(\"..\")) {\n return null;\n }\n const first = rel.split(/[/\\\\]/)[0];\n if (!first) {\n return null;\n }\n return join(rootPath, first);\n}\n\nfunction foldersFromConfiguredPaths(\n rootPath: string,\n configured: Array<{ path: string; platformId: string }>,\n): ResourceTrackedFolderEntry[] {\n const folders = new Map<string, ResourceTrackedFolderEntry>();\n\n for (const entry of configured) {\n const absolute = resolveConfiguredPath(rootPath, entry.path);\n if (!existsSync(absolute)) {\n continue;\n }\n let target = absolute;\n try {\n if (!lstatSync(absolute).isDirectory()) {\n target = dirname(absolute);\n }\n } catch {\n continue;\n }\n const top = topLevelFolderUnderRoot(rootPath, target);\n if (!top) {\n continue;\n }\n const existing = folders.get(top);\n if (existing) {\n if (!existing.platform_ids.includes(entry.platformId)) {\n existing.platform_ids.push(entry.platformId);\n }\n continue;\n }\n folders.set(top, {\n path: top,\n label: basename(top) || top,\n platform_ids: [entry.platformId],\n });\n }\n\n return [...folders.values()].sort((a, b) => a.label.localeCompare(b.label));\n}\n\nfunction homeResourceFolders(homeRoot: string): ResourceTrackedFolderEntry[] {\n return foldersFromConfiguredPaths(\n homeRoot,\n detectHomePlatforms(homeRoot).flatMap((result) =>\n result.discoveredPaths.map((path) => ({\n path,\n platformId: result.platformId,\n })),\n ),\n );\n}\n\nfunction projectResourceFolders(projectRoot: string): ResourceTrackedFolderEntry[] {\n const configured: Array<{ path: string; platformId: string }> = [];\n for (const platform of getAllPlatforms()) {\n for (const path of configuredPathValues(platform.projectPaths)) {\n configured.push({ path, platformId: platform.id });\n }\n }\n return foldersFromConfiguredPaths(projectRoot, configured);\n}\n\nfunction entryForCustomDirectory(\n path: string,\n resourceCounts: Map<string, number>,\n): ResourceTrackedDirectoryEntry {\n const resolved = resolve(path);\n return {\n path: resolved,\n kind: \"custom\",\n label: basename(resolved) || resolved,\n platform_ids: detectPlatforms(resolved),\n resource_count: resourceCounts.get(resolved) ?? 0,\n removable: true,\n folders: projectResourceFolders(resolved),\n display_path: resolved,\n };\n}\n\nexport function listResourceTrackedDirectories(): ResourceTrackedDirectoryEntry[] {\n const homeRoot = resolve(homeRootPath());\n const detected = detectHomePlatforms(homeRoot);\n const resourceCounts = countResourcesByOriginRef();\n\n const entries: ResourceTrackedDirectoryEntry[] = [\n {\n path: homeRoot,\n kind: \"home_default\",\n label: \"Home harness defaults\",\n platform_ids: detected.map((result) => result.platformId),\n resource_count: resourceCounts.get(homeRoot) ?? 0,\n removable: false,\n folders: homeResourceFolders(homeRoot),\n display_path: \"~\",\n },\n ];\n\n for (const directory of readCustomDirectories()) {\n const resolved = resolve(directory);\n if (resolved === homeRoot) {\n continue;\n }\n entries.push(entryForCustomDirectory(resolved, resourceCounts));\n }\n\n return entries;\n}\n\nfunction homeRootPath(): string {\n return resolveHomeRoot();\n}\n\nexport async function addResourceTrackedDirectory(inputPath: string): Promise<{\n directory: ResourceTrackedDirectoryEntry;\n imported_count: number;\n}> {\n const resolved = resolve(inputPath.trim());\n if (!existsSync(resolved)) {\n throw new ResourceTrackedDirectoryError(`Directory not found: ${resolved}`);\n }\n\n const homeRoot = resolve(homeRootPath());\n if (resolved === homeRoot) {\n throw new ResourceTrackedDirectoryError(\n \"Home directory is already tracked as harness defaults.\",\n );\n }\n\n const custom = readCustomDirectories();\n if (custom.some((entry) => resolve(entry) === resolved)) {\n throw new ResourceTrackedDirectoryError(`Directory already tracked: ${resolved}`);\n }\n\n custom.push(resolved);\n writeCustomDirectories(custom);\n\n const imported = await scanAndPersist(resolved, undefined, {\n conflictPolicy: \"skip\",\n originRef: resolved,\n namespace: \"project\",\n });\n\n const resourceCounts = countResourcesByOriginRef();\n return {\n directory: entryForCustomDirectory(resolved, resourceCounts),\n imported_count: imported.length,\n };\n}\n\nexport function removeResourceTrackedDirectory(inputPath: string): void {\n const resolved = resolve(inputPath.trim());\n const homeRoot = resolve(homeRootPath());\n if (resolved === homeRoot) {\n throw new ResourceTrackedDirectoryError(\"Cannot remove home harness defaults.\");\n }\n\n const custom = readCustomDirectories();\n const next = custom.filter((entry) => resolve(entry) !== resolved);\n if (next.length === custom.length) {\n throw new ResourceTrackedDirectoryError(`Directory not tracked: ${resolved}`);\n }\n writeCustomDirectories(next);\n}\n\nexport interface ResourceTrackedDirectoryRescanEntry {\n path: string;\n kind: \"home_default\" | \"custom\";\n imported_count: number;\n skipped: boolean;\n error?: string;\n}\n\nexport interface ResourceTrackedDirectoriesRescanResult {\n directories: ResourceTrackedDirectoryEntry[];\n rescanned: ResourceTrackedDirectoryRescanEntry[];\n imported_count: number;\n}\n\n/**\n * Re-scan home harness defaults and every custom tracked directory into the library.\n * Uses skip conflict policy so existing library rows are not overwritten.\n */\nexport async function rescanResourceTrackedDirectories(): Promise<ResourceTrackedDirectoriesRescanResult> {\n const homeRoot = resolve(homeRootPath());\n const rescanned: ResourceTrackedDirectoryRescanEntry[] = [];\n let importedCount = 0;\n\n const homeDefaults = await scanAndPersistHomeDefaults(undefined, homeRoot);\n const homeImported = homeDefaults.resources.length;\n importedCount += homeImported;\n rescanned.push({\n path: homeRoot,\n kind: \"home_default\",\n imported_count: homeImported,\n skipped: false,\n });\n\n for (const directory of readCustomDirectories()) {\n const resolved = resolve(directory);\n if (resolved === homeRoot) {\n continue;\n }\n if (!existsSync(resolved)) {\n rescanned.push({\n path: resolved,\n kind: \"custom\",\n imported_count: 0,\n skipped: true,\n error: `Directory not found: ${resolved}`,\n });\n continue;\n }\n try {\n const beforeIds = new Set(\n listResources().map((resource) => resource.id),\n );\n const resolvedResources = await scanAndPersist(resolved, undefined, {\n conflictPolicy: \"skip\",\n originRef: resolved,\n namespace: \"project\",\n });\n const imported = resolvedResources.filter(\n (resource) => !beforeIds.has(resource.id),\n ).length;\n importedCount += imported;\n rescanned.push({\n path: resolved,\n kind: \"custom\",\n imported_count: imported,\n skipped: false,\n });\n } catch (error) {\n rescanned.push({\n path: resolved,\n kind: \"custom\",\n imported_count: 0,\n skipped: true,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return {\n directories: listResourceTrackedDirectories(),\n rescanned,\n imported_count: importedCount,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AA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