@buaa_smat/hometrans 26.0.0-devecocli.3 → 26.0.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 (717) hide show
  1. package/README.md +433 -0
  2. package/agents/build-fixer.md +1 -2
  3. package/agents/code-reviewer.md +31 -15
  4. package/agents/model-render-worker.md +9 -5
  5. package/dist/cli/config-store.js +128 -0
  6. package/dist/cli/config.js +48 -0
  7. package/dist/cli/editors.json +114 -0
  8. package/dist/cli/env-vars.js +127 -0
  9. package/dist/cli/index.js +73 -0
  10. package/dist/cli/init.js +2513 -0
  11. package/dist/cli/uninstall.js +406 -0
  12. package/dist/platform/compose.js +228 -0
  13. package/dist/platform/frontmatter.js +151 -0
  14. package/dist/platform/installer.js +417 -0
  15. package/dist/platform/registry.js +337 -0
  16. package/dist/platform/transform.js +363 -0
  17. package/dist/platform/types.js +9 -0
  18. package/dist/platform/validate.js +152 -0
  19. package/dist/utils/regex.js +7 -0
  20. package/env-requirements.json +511 -0
  21. package/package.json +240 -11
  22. package/platforms/deveco/agents/code-reviewer.frontmatter.md +1 -1
  23. package/platforms/opencode/agents/code-reviewer.frontmatter.md +1 -1
  24. package/resource/choose_editor.png +0 -0
  25. package/resource/convert_pipeline_process.svg +114 -0
  26. package/resource/project_architecture.svg +120 -0
  27. package/resource/set_environment.png +0 -0
  28. package/resource/set_multimodel.png +0 -0
  29. package/resource/set_sdk.png +0 -0
  30. package/resource/title_dark.png +0 -0
  31. package/skills/a2h-app-migrate/SKILL.md +17 -11
  32. package/skills/a2h-app-migrate/references/stage-map.md +22 -7
  33. package/skills/a2h-app-migrate/references/workflow.yaml +276 -209
  34. package/skills/a2h-app-migrate/scripts/android_index.mjs +34 -16
  35. package/skills/a2h-app-migrate/scripts/check_arch_done.mjs +12 -12
  36. package/skills/a2h-app-migrate/scripts/check_module_docs_done.mjs +12 -12
  37. package/skills/a2h-app-migrate/scripts/check_signing.mjs +16 -16
  38. package/skills/a2h-app-migrate/scripts/check_spec_gen_done.mjs +17 -16
  39. package/skills/a2h-app-migrate/scripts/check_spec_pipeline_done.mjs +141 -62
  40. package/skills/a2h-app-migrate/scripts/check_ui_batch_done.mjs +12 -12
  41. package/skills/a2h-app-migrate/scripts/check_utg_static_done.mjs +26 -26
  42. package/skills/a2h-app-migrate/scripts/cli_values.mjs +7 -7
  43. package/skills/a2h-app-migrate/scripts/ensure_utg_snapshot.mjs +144 -0
  44. package/skills/a2h-app-migrate/scripts/env_preflight.mjs +474 -365
  45. package/skills/a2h-app-migrate/scripts/human_review_gate.mjs +115 -108
  46. package/skills/a2h-app-migrate/scripts/i18n-term.d.mts +5 -0
  47. package/skills/a2h-app-migrate/scripts/i18n-term.mjs +54 -0
  48. package/skills/a2h-app-migrate/scripts/infer_android_root.mjs +6 -6
  49. package/skills/a2h-app-migrate/scripts/json_io.mjs +1 -1
  50. package/skills/a2h-app-migrate/scripts/ledger.mjs +15 -15
  51. package/skills/a2h-app-migrate/scripts/paths_preflight.mjs +99 -99
  52. package/skills/a2h-app-migrate/scripts/resume_plan.mjs +25 -25
  53. package/skills/a2h-app-migrate/scripts/reuse_static_utg.mjs +9 -9
  54. package/skills/a2h-app-migrate/scripts/run_dir.mjs +33 -33
  55. package/skills/a2h-app-migrate/scripts/spec_layout.mjs +13 -11
  56. package/skills/a2h-app-migrate/scripts/validate_workflow.mjs +128 -80
  57. package/skills/a2h-app-migrate/scripts/write_resume_summary.mjs +349 -0
  58. package/skills/a2h-arch-generate/scripts/cleanup_intermediates.mjs +21 -21
  59. package/skills/a2h-arch-generate/scripts/create_project.mjs +23 -23
  60. package/skills/a2h-arch-generate/scripts/generate_source_baseline.mjs +48 -40
  61. package/skills/a2h-arch-generate/scripts/generate_state.mjs +7 -7
  62. package/skills/a2h-arch-generate/scripts/i18n-term.d.mts +5 -0
  63. package/skills/a2h-arch-generate/scripts/i18n-term.mjs +54 -0
  64. package/skills/a2h-arch-generate/scripts/inspect_android_project.mjs +10 -1
  65. package/skills/a2h-arch-generate/scripts/inspect_harmony_target.mjs +41 -36
  66. package/skills/a2h-arch-generate/scripts/lib/contract_terms.mjs +40 -0
  67. package/skills/a2h-arch-generate/scripts/lib/py_compat.mjs +1 -1
  68. package/skills/a2h-arch-generate/scripts/module_create/create.mjs +17 -17
  69. package/skills/a2h-arch-generate/scripts/module_create/generate.mjs +54 -50
  70. package/skills/a2h-arch-generate/scripts/scaffold_project.mjs +42 -42
  71. package/skills/a2h-arch-generate/scripts/validate_architecture_docs.mjs +69 -44
  72. package/skills/a2h-arch-generate/scripts/validate_data_docs.mjs +62 -17
  73. package/skills/a2h-arch-generate/scripts/validate_incremental_docs.mjs +5 -4
  74. package/skills/a2h-arkts-logic-coder/SKILL.md +39 -8
  75. package/skills/a2h-arkts-logic-coder/references/ISSUES.md +2 -0
  76. package/skills/a2h-arkts-logic-coder/references/code-generation.md +28 -17
  77. package/skills/{a2h-spec-design/SKILL.md → a2h-arkts-logic-coder/references/spec-design.md} +45 -78
  78. package/skills/a2h-arkts-logic-coder/scripts/check_mvvm.ts +1 -1
  79. package/skills/a2h-arkts-logic-coder/scripts/check_units.ts +448 -0
  80. package/skills/a2h-arkts-logic-coder/scripts/design/i18n-term.d.mts +5 -0
  81. package/skills/a2h-arkts-logic-coder/scripts/design/i18n-term.mjs +54 -0
  82. package/skills/{a2h-spec-design/scripts → a2h-arkts-logic-coder/scripts/design}/inspect_spec_design_inputs.mjs +18 -12
  83. package/skills/{a2h-spec-design/scripts → a2h-arkts-logic-coder/scripts/design}/lib/py_compat.mjs +1 -1
  84. package/skills/{a2h-spec-design/scripts → a2h-arkts-logic-coder/scripts/design}/move_spec_technical_reference.mjs +10 -7
  85. package/skills/{a2h-spec-design/scripts → a2h-arkts-logic-coder/scripts/design}/resolve_module_design.mjs +13 -7
  86. package/skills/{a2h-spec-design/scripts → a2h-arkts-logic-coder/scripts/design}/validate_spec_design_output.mjs +57 -41
  87. package/skills/a2h-arkts-logic-coder/scripts/stop_check_hook.ts +66 -323
  88. package/skills/a2h-arkts-logic-coder/scripts/test_check_scripts.ts +66 -108
  89. package/skills/a2h-arkts-logic-coder/scripts/test_check_units.ts +149 -0
  90. package/skills/a2h-arkts-logic-coder/scripts/test_worktree_compat.ts +5 -18
  91. package/skills/a2h-batch-ui-align/SKILL.md +39 -39
  92. package/skills/a2h-batch-ui-align/references/cards/alignment.md +31 -0
  93. package/skills/a2h-batch-ui-align/references/cards/build.md +13 -0
  94. package/skills/a2h-batch-ui-align/references/cards/canvas.md +17 -0
  95. package/skills/a2h-batch-ui-align/references/cards/dynamics.md +27 -0
  96. package/skills/a2h-batch-ui-align/references/cards/geometry.md +80 -0
  97. package/skills/a2h-batch-ui-align/references/cards/interaction.md +22 -0
  98. package/skills/a2h-batch-ui-align/references/cards/resources.md +83 -0
  99. package/skills/a2h-batch-ui-align/references/cards/state-v1.md +29 -0
  100. package/skills/a2h-batch-ui-align/references/cards/state.md +14 -0
  101. package/skills/a2h-batch-ui-align/references/cards/widgets.md +38 -0
  102. package/skills/a2h-batch-ui-align/references/cards/window.md +29 -0
  103. package/skills/a2h-batch-ui-align/references/checker-rules.md +642 -0
  104. package/skills/a2h-batch-ui-align/references/conversion-procedure.md +69 -260
  105. package/skills/a2h-batch-ui-align/references/host-dispatch.md +34 -0
  106. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-atomic-component-mapping-reference.md +16 -4
  107. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-interaction-mapping-reference.md +3 -1
  108. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-layout-mapping-reference.md +32 -1
  109. package/skills/a2h-batch-ui-align/references/source-only-tier.md +7 -1
  110. package/skills/a2h-batch-ui-align/references/state-mgmt/_/350/214/203/345/274/217/351/200/211/346/213/251/350/257/264/346/230/216.md +28 -0
  111. package/skills/a2h-batch-ui-align/references/state-mgmt/_/350/243/205/351/245/260/345/231/250/351/200/237/346/237/245.md +220 -0
  112. package/skills/a2h-batch-ui-align/references/step3-capture.md +11 -9
  113. package/skills/a2h-batch-ui-align/references/step4-prepare.md +13 -8
  114. package/skills/a2h-batch-ui-align/references/step5-convert.md +21 -18
  115. package/skills/a2h-batch-ui-align/scripts/agent_cli.mjs +44 -44
  116. package/skills/a2h-batch-ui-align/scripts/android_parse_fast.ts +237 -236
  117. package/skills/a2h-batch-ui-align/scripts/arkts_static_check.ts +42 -3834
  118. package/skills/a2h-batch-ui-align/scripts/build_conversion_set.mjs +34 -32
  119. package/skills/a2h-batch-ui-align/scripts/detach.mjs +1 -1
  120. package/skills/a2h-batch-ui-align/scripts/detect_paradigm.mjs +240 -0
  121. package/skills/a2h-batch-ui-align/scripts/export_ui_info.mjs +139 -33
  122. package/skills/a2h-batch-ui-align/scripts/gen_rule_docs.mjs +100 -0
  123. package/skills/a2h-batch-ui-align/scripts/generate_pages_json.mjs +26 -25
  124. package/skills/a2h-batch-ui-align/scripts/group_commit.mjs +1 -1
  125. package/skills/a2h-batch-ui-align/scripts/group_pack.mjs +159 -12
  126. package/skills/a2h-batch-ui-align/scripts/group_queue.mjs +145 -21
  127. package/skills/a2h-batch-ui-align/scripts/group_watch.mjs +8 -8
  128. package/skills/a2h-batch-ui-align/scripts/host_env.mjs +1 -1
  129. package/skills/a2h-batch-ui-align/scripts/i18n-term.d.mts +5 -0
  130. package/skills/a2h-batch-ui-align/scripts/i18n-term.mjs +54 -0
  131. package/skills/a2h-batch-ui-align/scripts/image_probe.mjs +228 -0
  132. package/skills/a2h-batch-ui-align/scripts/measure_pack.ts +444 -266
  133. package/skills/a2h-batch-ui-align/scripts/phase5_check.mjs +66 -32
  134. package/skills/a2h-batch-ui-align/scripts/shell_contract.mjs +141 -57
  135. package/skills/a2h-batch-ui-align/scripts/state_doc.mjs +410 -0
  136. package/skills/a2h-batch-ui-align/scripts/static_check/core/android.ts +80 -0
  137. package/skills/a2h-batch-ui-align/scripts/static_check/core/cli.ts +134 -0
  138. package/skills/a2h-batch-ui-align/scripts/static_check/core/findings.ts +21 -0
  139. package/skills/a2h-batch-ui-align/scripts/static_check/core/i18n.ts +22 -0
  140. package/skills/a2h-batch-ui-align/scripts/static_check/core/meta.ts +34 -0
  141. package/skills/a2h-batch-ui-align/scripts/static_check/core/parse.ts +668 -0
  142. package/skills/a2h-batch-ui-align/scripts/static_check/core/scan.ts +392 -0
  143. package/skills/a2h-batch-ui-align/scripts/static_check/main.ts +167 -0
  144. package/skills/a2h-batch-ui-align/scripts/static_check/package.json +3 -0
  145. package/skills/a2h-batch-ui-align/scripts/static_check/registry.ts +101 -0
  146. package/skills/a2h-batch-ui-align/scripts/static_check/rules/a11y.ts +629 -0
  147. package/skills/a2h-batch-ui-align/scripts/static_check/rules/android_immersive.ts +125 -0
  148. package/skills/a2h-batch-ui-align/scripts/static_check/rules/attr_chain.ts +67 -0
  149. package/skills/a2h-batch-ui-align/scripts/static_check/rules/block_comment_break.ts +64 -0
  150. package/skills/a2h-batch-ui-align/scripts/static_check/rules/blur_mirrored.ts +134 -0
  151. package/skills/a2h-batch-ui-align/scripts/static_check/rules/builder_call_sites.ts +242 -0
  152. package/skills/a2h-batch-ui-align/scripts/static_check/rules/builder_invokes_callback.ts +71 -0
  153. package/skills/a2h-batch-ui-align/scripts/static_check/rules/canvas.ts +255 -0
  154. package/skills/a2h-batch-ui-align/scripts/static_check/rules/color_string.ts +102 -0
  155. package/skills/a2h-batch-ui-align/scripts/static_check/rules/column_shrink.ts +154 -0
  156. package/skills/a2h-batch-ui-align/scripts/static_check/rules/constant_coordinate.ts +39 -0
  157. package/skills/a2h-batch-ui-align/scripts/static_check/rules/container_align.ts +140 -0
  158. package/skills/a2h-batch-ui-align/scripts/static_check/rules/entry_root_builtin.ts +69 -0
  159. package/skills/a2h-batch-ui-align/scripts/static_check/rules/entry_route.ts +114 -0
  160. package/skills/a2h-batch-ui-align/scripts/static_check/rules/fixed_size_safe_area.ts +103 -0
  161. package/skills/a2h-batch-ui-align/scripts/static_check/rules/format_string.ts +157 -0
  162. package/skills/a2h-batch-ui-align/scripts/static_check/rules/framework_picker.ts +115 -0
  163. package/skills/a2h-batch-ui-align/scripts/static_check/rules/layout_placement.ts +551 -0
  164. package/skills/a2h-batch-ui-align/scripts/static_check/rules/media_content.ts +138 -0
  165. package/skills/a2h-batch-ui-align/scripts/static_check/rules/media_tint.ts +310 -0
  166. package/skills/a2h-batch-ui-align/scripts/static_check/rules/offset_in_scroll.ts +163 -0
  167. package/skills/a2h-batch-ui-align/scripts/static_check/rules/orphan_component.ts +119 -0
  168. package/skills/a2h-batch-ui-align/scripts/static_check/rules/page_reachability.ts +94 -0
  169. package/skills/a2h-batch-ui-align/scripts/static_check/rules/path_commands_vp.ts +50 -0
  170. package/skills/a2h-batch-ui-align/scripts/static_check/rules/percent_height_in_scroll.ts +80 -0
  171. package/skills/a2h-batch-ui-align/scripts/static_check/rules/popup_menu.ts +64 -0
  172. package/skills/a2h-batch-ui-align/scripts/static_check/rules/r_template_string.ts +37 -0
  173. package/skills/a2h-batch-ui-align/scripts/static_check/rules/request_permission.ts +98 -0
  174. package/skills/a2h-batch-ui-align/scripts/static_check/rules/resource_as_string.ts +68 -0
  175. package/skills/a2h-batch-ui-align/scripts/static_check/rules/root_weight.ts +97 -0
  176. package/skills/a2h-batch-ui-align/scripts/static_check/rules/safe_area_clipping.ts +168 -0
  177. package/skills/a2h-batch-ui-align/scripts/static_check/rules/scroll_align.ts +75 -0
  178. package/skills/a2h-batch-ui-align/scripts/static_check/rules/sdk_api.ts +195 -0
  179. package/skills/a2h-batch-ui-align/scripts/static_check/rules/shared_chrome.ts +73 -0
  180. package/skills/a2h-batch-ui-align/scripts/static_check/rules/sheet_blur.ts +95 -0
  181. package/skills/a2h-batch-ui-align/scripts/static_check/rules/shell_content.ts +198 -0
  182. package/skills/a2h-batch-ui-align/scripts/static_check/rules/stack_occluding.ts +118 -0
  183. package/skills/a2h-batch-ui-align/scripts/static_check/rules/state_decorators.ts +73 -0
  184. package/skills/a2h-batch-ui-align/scripts/static_check/rules/state_name_shadows.ts +93 -0
  185. package/skills/a2h-batch-ui-align/scripts/static_check/rules/string_quote_leak.ts +73 -0
  186. package/skills/a2h-batch-ui-align/scripts/static_check/rules/surface_stroke.ts +50 -0
  187. package/skills/a2h-batch-ui-align/scripts/static_check/rules/track_getter.ts +132 -0
  188. package/skills/a2h-batch-ui-align/scripts/static_check/rules/wide_constant_width.ts +53 -0
  189. package/skills/a2h-batch-ui-align/scripts/static_check/rules/window_mode.ts +68 -0
  190. package/skills/a2h-batch-ui-align/scripts/static_check/scan_file.ts +153 -0
  191. package/skills/a2h-batch-ui-align/scripts/text_color_diff.mjs +65 -65
  192. package/skills/a2h-coldstart-smoke-gate/SKILL.md +8 -6
  193. package/skills/a2h-dashboard-render/SKILL.md +15 -7
  194. package/skills/a2h-dashboard-render/references/artifact-contract.jsonc +5 -35
  195. package/skills/a2h-dashboard-render/references/artifact-registry-spec.md +4 -4
  196. package/skills/a2h-dashboard-render/references/dashboard-guide.md +91 -0
  197. package/skills/a2h-dashboard-render/scripts/check-registry.mjs +17 -17
  198. package/skills/a2h-dashboard-render/scripts/dashboard.css +3546 -0
  199. package/skills/a2h-dashboard-render/scripts/dashboard.mjs +1021 -941
  200. package/skills/a2h-dashboard-render/scripts/device_capture.mjs +104 -65
  201. package/skills/a2h-dashboard-render/scripts/i18n-term.d.mts +5 -0
  202. package/skills/a2h-dashboard-render/scripts/i18n-term.mjs +54 -0
  203. package/skills/a2h-dashboard-render/scripts/page_capture.mjs +8 -8
  204. package/skills/a2h-dashboard-render/scripts/usage_readers.mjs +67 -37
  205. package/skills/a2h-dashboard-render/scripts/usage_worker.mjs +4 -4
  206. package/skills/a2h-fix-build-errors/SKILL.md +1 -2
  207. package/skills/a2h-resource-convert/SKILL.md +1 -3
  208. package/skills/a2h-resource-convert/references/step7-report-template.md +2 -2
  209. package/skills/a2h-resource-convert/scripts/a2h_resource_convert.ts +366 -361
  210. package/skills/a2h-resource-convert/scripts/a2h_resource_incremental.ts +170 -170
  211. package/skills/a2h-resource-convert/scripts/app_identity.ts +162 -162
  212. package/skills/a2h-resource-convert/scripts/code_vector_icons.ts +95 -95
  213. package/skills/a2h-resource-convert/scripts/extract_page_resources.ts +132 -132
  214. package/skills/a2h-resource-convert/scripts/extract_project_resources.ts +220 -220
  215. package/skills/a2h-resource-convert/scripts/i18n-term.d.mts +5 -0
  216. package/skills/a2h-resource-convert/scripts/i18n-term.mjs +54 -0
  217. package/skills/a2h-resource-convert/scripts/svg_fidelity_check.ts +74 -74
  218. package/skills/a2h-spec-design-pipeline/SKILL.md +113 -63
  219. package/skills/a2h-spec-design-pipeline/references/coding-loop.md +226 -56
  220. package/skills/a2h-spec-design-pipeline/references/execution-model.md +315 -62
  221. package/skills/a2h-spec-design-pipeline/references/final-report-template.md +4 -2
  222. package/skills/a2h-spec-design-pipeline/references/initialization.md +12 -9
  223. package/skills/a2h-spec-design-pipeline/references/legacy-cleanup.md +18 -0
  224. package/skills/a2h-spec-design-pipeline/references/merge-queue.md +109 -8
  225. package/skills/a2h-spec-design-pipeline/references/scripts.md +29 -16
  226. package/skills/a2h-spec-design-pipeline/references/state-and-resume.md +116 -8
  227. package/skills/a2h-spec-design-pipeline/references/static-defect-gate.md +179 -0
  228. package/skills/a2h-spec-design-pipeline/scripts/audit_claims.ts +33 -5
  229. package/skills/a2h-spec-design-pipeline/scripts/branch_landed.ts +36 -16
  230. package/skills/a2h-spec-design-pipeline/scripts/dispatch/evidence.mjs +93 -0
  231. package/skills/a2h-spec-design-pipeline/scripts/dispatch/fold.mjs +915 -0
  232. package/skills/a2h-spec-design-pipeline/scripts/dispatch/ledger.mjs +234 -0
  233. package/skills/a2h-spec-design-pipeline/scripts/dispatch/plan.mjs +33 -0
  234. package/skills/a2h-spec-design-pipeline/scripts/dispatch/progress.mjs +31 -0
  235. package/skills/a2h-spec-design-pipeline/scripts/dispatch/reconcile.mjs +94 -0
  236. package/skills/a2h-spec-design-pipeline/scripts/dispatch/state-mirror.mjs +55 -0
  237. package/skills/a2h-spec-design-pipeline/scripts/dispatch/timeouts.mjs +34 -0
  238. package/skills/a2h-spec-design-pipeline/scripts/dispatch/wait.mjs +92 -0
  239. package/skills/a2h-spec-design-pipeline/scripts/dispatch/waker.mjs +60 -0
  240. package/skills/a2h-spec-design-pipeline/scripts/dispatch/worktree.mjs +89 -0
  241. package/skills/a2h-spec-design-pipeline/scripts/dispatch.mjs +551 -0
  242. package/skills/a2h-spec-design-pipeline/scripts/ensure_wt_index.ts +267 -33
  243. package/skills/a2h-spec-design-pipeline/scripts/git_baseline.ts +30 -10
  244. package/skills/a2h-spec-design-pipeline/scripts/homecheck_scan.ts +634 -0
  245. package/skills/a2h-spec-design-pipeline/scripts/i18n-term.d.mts +5 -0
  246. package/skills/a2h-spec-design-pipeline/scripts/i18n-term.mjs +54 -0
  247. package/skills/a2h-spec-design-pipeline/scripts/lib/io.mjs +33 -0
  248. package/skills/a2h-spec-design-pipeline/scripts/plan_groups.ts +107 -19
  249. package/skills/a2h-spec-design-pipeline/scripts/stage_design_inputs.ts +79 -0
  250. package/skills/a2h-spec-design-pipeline/scripts/test_atomic_write.ts +4 -4
  251. package/skills/a2h-spec-design-pipeline/scripts/test_audit_claims.ts +121 -38
  252. package/skills/a2h-spec-design-pipeline/scripts/test_branch_landed.ts +58 -11
  253. package/skills/a2h-spec-design-pipeline/scripts/test_deps_ready.ts +31 -31
  254. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_commands.mjs +564 -0
  255. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_e2e.mjs +339 -0
  256. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_evidence.mjs +161 -0
  257. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_fold.mjs +1024 -0
  258. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_ledger.mjs +178 -0
  259. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_plan.mjs +60 -0
  260. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_progress.mjs +58 -0
  261. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_reconcile.mjs +91 -0
  262. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_wait.mjs +60 -0
  263. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_waker.mjs +95 -0
  264. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_worktree.mjs +81 -0
  265. package/skills/a2h-spec-design-pipeline/scripts/test_ensure_wt_index.ts +183 -2
  266. package/skills/a2h-spec-design-pipeline/scripts/test_git_baseline.ts +29 -2
  267. package/skills/a2h-spec-design-pipeline/scripts/test_homecheck_scan.ts +294 -0
  268. package/skills/a2h-spec-design-pipeline/scripts/test_i18n_term.ts +70 -0
  269. package/skills/a2h-spec-design-pipeline/scripts/test_plan_groups.ts +157 -30
  270. package/skills/a2h-spec-design-pipeline/scripts/test_plan_waves.ts +2 -2
  271. package/skills/a2h-spec-design-pipeline/scripts/test_stage_design_inputs.ts +72 -0
  272. package/skills/a2h-spec-generate/SKILL.md +34 -10
  273. package/skills/a2h-spec-generate/references/batch-mode.md +4 -1
  274. package/skills/a2h-spec-generate/references/fusion-task-contract.md +90 -21
  275. package/skills/a2h-spec-generate/references/recall-guide.md +1 -0
  276. package/skills/a2h-spec-generate/references/requirement-scope.md +1 -1
  277. package/skills/a2h-spec-generate/references/specs.schema.json +6 -0
  278. package/skills/a2h-spec-generate/references/worker-rules.md +2 -1
  279. package/skills/a2h-spec-generate/scripts/check-fused-spec.mjs +305 -116
  280. package/skills/a2h-spec-generate/scripts/check_spec.ts +136 -114
  281. package/skills/a2h-spec-generate/scripts/collect-specs.mjs +19 -4
  282. package/skills/a2h-spec-generate/scripts/ensure-index.mjs +74 -14
  283. package/skills/a2h-spec-generate/scripts/feature-stem.mjs +4 -2
  284. package/skills/a2h-spec-generate/scripts/i18n-term.d.mts +5 -0
  285. package/skills/a2h-spec-generate/scripts/i18n-term.mjs +54 -0
  286. package/skills/a2h-spec-generate/scripts/parse_requirements.ts +65 -65
  287. package/skills/a2h-spec-generate/scripts/prepare-facts.mjs +8 -2
  288. package/skills/a2h-spec-generate/scripts/publication-verdict.mjs +8 -2
  289. package/skills/a2h-spec-generate/scripts/publish-specs.mjs +80 -5
  290. package/skills/a2h-spec-generate/scripts/regroup-by-page.mjs +670 -0
  291. package/skills/a2h-spec-generate/scripts/render-tasks.mjs +37 -30
  292. package/skills/a2h-spec-generate/scripts/report.mjs +7 -3
  293. package/skills/a2h-spec-generate/scripts/reqgen/assets/dashboard.html +26 -26
  294. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-api.js +2 -2
  295. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-code-view.js +2 -2
  296. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-format.js +4 -4
  297. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-handoff.js +6 -6
  298. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz-tree.js +3 -3
  299. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz.html +23 -23
  300. package/skills/a2h-spec-generate/scripts/reqgen/assets/viz.js +16 -16
  301. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/graph/build.ts +27 -26
  302. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/graph/component-variants.ts +7 -4
  303. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/names/policy.ts +32 -31
  304. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/names/traceability.ts +3 -2
  305. package/skills/a2h-spec-generate/scripts/reqgen/src/analysis/req-model/build.ts +26 -20
  306. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/area-facts.ts +92 -69
  307. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/area-output.ts +7 -3
  308. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/behavior-seed.ts +545 -0
  309. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/library-evidence.ts +545 -0
  310. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/schema.ts +177 -2
  311. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/selfcheck.ts +424 -29
  312. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/spec-bindings.ts +133 -7
  313. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/task-contract.ts +302 -103
  314. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/zip.ts +99 -0
  315. package/skills/a2h-spec-generate/scripts/reqgen/src/i18n-term.d.mts +5 -0
  316. package/skills/a2h-spec-generate/scripts/reqgen/src/i18n-term.mjs +54 -0
  317. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/contracts.ts +8 -0
  318. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/schema.ts +5 -1
  319. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/task-contract.ts +39 -33
  320. package/skills/a2h-spec-generate/scripts/reqgen/src/interaction-analysis/tree-sitter-adapter.ts +4 -3
  321. package/skills/a2h-spec-generate/scripts/reqgen/src/model/contracts.ts +4 -0
  322. package/skills/a2h-spec-generate/scripts/reqgen/src/model/finalize.ts +48 -6
  323. package/skills/a2h-spec-generate/scripts/reqgen/src/model/prepare.ts +366 -5
  324. package/skills/a2h-spec-generate/scripts/reqgen/src/model/query.ts +102 -3
  325. package/skills/a2h-spec-generate/scripts/reqgen/src/model/task.ts +81 -52
  326. package/skills/a2h-spec-generate/scripts/reqgen/src/requirement-scope.ts +21 -11
  327. package/skills/a2h-spec-generate/scripts/reqgen/src/source-index/homegraph.ts +2 -1
  328. package/skills/a2h-spec-generate/scripts/reqgen/src/validation/req-text.ts +13 -4
  329. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-api.ts +2 -2
  330. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-code-view.ts +2 -2
  331. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-format.ts +4 -4
  332. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-handoff.ts +6 -6
  333. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz-tree.ts +3 -3
  334. package/skills/a2h-spec-generate/scripts/reqgen/src/viz/client/viz.ts +16 -16
  335. package/skills/a2h-utg-explorer/assets/final_viewer.html +21 -21
  336. package/skills/a2h-utg-explorer/references/architecture.md +7 -2
  337. package/skills/a2h-utg-explorer/scripts/compile_tasks.mjs +108 -9
  338. package/skills/a2h-utg-explorer/scripts/d_prereqs.mjs +21 -3
  339. package/skills/a2h-utg-explorer/scripts/hint_check.mjs +4 -1
  340. package/skills/a2h-utg-explorer/scripts/i18n-term.d.mts +5 -0
  341. package/skills/a2h-utg-explorer/scripts/i18n-term.mjs +54 -0
  342. package/skills/a2h-utg-explorer/scripts/panel_routes.mjs +229 -0
  343. package/skills/a2h-utg-explorer/scripts/plan.mjs +45 -2
  344. package/skills/a2h-utg-explorer/scripts/recover_b.mjs +2 -1
  345. package/skills/a2h-utg-explorer/scripts/recover_d.mjs +17 -6
  346. package/skills/a2h-utg-explorer/scripts/report.mjs +38 -18
  347. package/skills/a2h-utg-explorer/scripts/run_cycle.mjs +16 -6
  348. package/skills/a2h-utg-explorer/scripts/utg_explorer/adapters.mjs +179 -18
  349. package/skills/a2h-utg-explorer/scripts/utg_explorer/semantics.mjs +21 -4
  350. package/skills/a2h-utg-explorer/scripts/utg_explorer/task_runner.mjs +454 -43
  351. package/skills/a2h-utg-static/SKILL.md +7 -0
  352. package/skills/a2h-utg-static/scripts/assemble.mjs +29 -2
  353. package/skills/a2h-utg-static/scripts/click_paths.mjs +42 -26
  354. package/skills/a2h-utg-static/scripts/compose_body_text.mjs +6 -0
  355. package/skills/a2h-utg-static/scripts/fragment_nav.mjs +4 -2
  356. package/skills/a2h-utg-static/scripts/i18n-term.d.mts +5 -0
  357. package/skills/a2h-utg-static/scripts/i18n-term.mjs +54 -0
  358. package/skills/a2h-utg-static/scripts/manifest.mjs +91 -10
  359. package/skills/a2h-utg-static/scripts/nl_hints.mjs +68 -3
  360. package/skills/a2h-utg-static/scripts/presenter_nav.mjs +2 -1
  361. package/skills/a2h-utg-static/scripts/route_interceptor.mjs +374 -0
  362. package/skills/a2h-utg-static/scripts/static_prior.mjs +87 -33
  363. package/skills/a2h-utg-static/scripts/uniapp_nav.mjs +240 -8
  364. package/skills/a2h-utg-static/scripts/utg_html.mjs +51 -51
  365. package/skills/a2h-utg-static/tools/convert_static_utg_to_ui_elements.ts +100 -100
  366. package/devecocli-plugin/common.ts +0 -2203
  367. package/devecocli-plugin/install.ts +0 -61
  368. package/devecocli-plugin/uninstall.ts +0 -26
  369. package/devecocli-plugin/update.ts +0 -66
  370. package/index.js +0 -1418
  371. package/plugin.jsonc +0 -12
  372. package/skills/a2h-app-migrate/test/test_android_index.mjs +0 -80
  373. package/skills/a2h-app-migrate/test/test_apk_preflight.mjs +0 -63
  374. package/skills/a2h-app-migrate/test/test_arch_done.mjs +0 -54
  375. package/skills/a2h-app-migrate/test/test_build_fixer_contract.mjs +0 -92
  376. package/skills/a2h-app-migrate/test/test_config_example.mjs +0 -42
  377. package/skills/a2h-app-migrate/test/test_entry_guards.mjs +0 -93
  378. package/skills/a2h-app-migrate/test/test_env_requirements.mjs +0 -544
  379. package/skills/a2h-app-migrate/test/test_finalize.mjs +0 -89
  380. package/skills/a2h-app-migrate/test/test_gate_checkpoint.mjs +0 -146
  381. package/skills/a2h-app-migrate/test/test_hmos_fingerprint.mjs +0 -68
  382. package/skills/a2h-app-migrate/test/test_infer_android_root.mjs +0 -91
  383. package/skills/a2h-app-migrate/test/test_interaction.mjs +0 -122
  384. package/skills/a2h-app-migrate/test/test_json_io.mjs +0 -32
  385. package/skills/a2h-app-migrate/test/test_leaf_questions.mjs +0 -109
  386. package/skills/a2h-app-migrate/test/test_module_docs_done.mjs +0 -53
  387. package/skills/a2h-app-migrate/test/test_parse_args.mjs +0 -69
  388. package/skills/a2h-app-migrate/test/test_preflight_report.mjs +0 -93
  389. package/skills/a2h-app-migrate/test/test_resume_plan.mjs +0 -144
  390. package/skills/a2h-app-migrate/test/test_reuse_static_utg.mjs +0 -100
  391. package/skills/a2h-app-migrate/test/test_run_dir.mjs +0 -315
  392. package/skills/a2h-app-migrate/test/test_skill_doc.mjs +0 -133
  393. package/skills/a2h-app-migrate/test/test_spec_gen_done.mjs +0 -133
  394. package/skills/a2h-app-migrate/test/test_spec_gen_gate.mjs +0 -158
  395. package/skills/a2h-app-migrate/test/test_spec_pipeline_done.mjs +0 -181
  396. package/skills/a2h-app-migrate/test/test_specs_json_preflight.mjs +0 -76
  397. package/skills/a2h-app-migrate/test/test_ui_batch_done.mjs +0 -53
  398. package/skills/a2h-app-migrate/test/test_ui_batch_gate.mjs +0 -226
  399. package/skills/a2h-app-migrate/test/test_uniapp_preflight.mjs +0 -83
  400. package/skills/a2h-app-migrate/test/test_utg_dirs.mjs +0 -39
  401. package/skills/a2h-app-migrate/test/test_utg_static_done.mjs +0 -168
  402. package/skills/a2h-app-migrate/test/test_validate_races.mjs +0 -50
  403. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/build.gradle +0 -11
  404. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/AndroidManifest.xml +0 -12
  405. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/java/com/example/notes/MainActivity.kt +0 -8
  406. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/java/com/example/notes/NotesStore.kt +0 -17
  407. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/build.gradle +0 -3
  408. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/settings.gradle +0 -1
  409. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/AppScope/app.json5 +0 -8
  410. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/build-profile.json5 +0 -14
  411. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/build-profile.json5 +0 -7
  412. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/oh-package.json5 +0 -1
  413. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/src/main/ets/utils/Format.ets +0 -3
  414. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/build-profile.json5 +0 -7
  415. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/oh-package.json5 +0 -1
  416. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/src/main/ets/pages/Home.ets +0 -3
  417. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/build-profile.json5 +0 -7
  418. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/oh-package.json5 +0 -1
  419. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/src/main/ets/engine/SyncEngine.ets +0 -3
  420. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/hvigorfile.ts +0 -1
  421. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/oh-package.json5 +0 -1
  422. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/build-profile.json5 +0 -7
  423. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/oh-package.json5 +0 -9
  424. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/src/main/ets/pages/Index.ets +0 -7
  425. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/App.vue +0 -10
  426. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/manifest.json +0 -6
  427. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/pages/index/index.vue +0 -16
  428. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/pages.json +0 -5
  429. package/skills/a2h-arch-generate/scripts/tests/e2e/run_e2e.mjs +0 -548
  430. package/skills/a2h-arch-generate/scripts/tests/run_tests.mjs +0 -1122
  431. package/skills/a2h-arch-generate/scripts/tests/test_cleanup.mjs +0 -191
  432. package/skills/a2h-arch-generate/scripts/tests/test_console_encoding.mjs +0 -52
  433. package/skills/a2h-arch-generate/scripts/tests/test_git_root.mjs +0 -34
  434. package/skills/a2h-arch-generate/scripts/tests/test_router.mjs +0 -138
  435. package/skills/a2h-arkts-logic-coder/scripts/check_module_scope.ts +0 -224
  436. package/skills/a2h-batch-ui-align/flowchart.html +0 -271
  437. package/skills/a2h-batch-ui-align/references/mvvm/@Link/350/243/205/351/245/260/345/231/250/357/274/232/347/210/266/345/255/220/345/217/214/345/220/221/345/220/214/346/255/245.md +0 -648
  438. package/skills/a2h-batch-ui-align/references/mvvm/@Observed/350/243/205/351/245/260/345/231/250/345/222/214@ObjectLink/350/243/205/351/245/260/345/231/250/357/274/232/345/265/214/345/245/227/347/261/273/345/257/271/350/261/241/345/261/236/346/200/247/345/217/230/345/214/226.md +0 -2089
  439. package/skills/a2h-batch-ui-align/references/mvvm/@Prop/350/243/205/351/245/260/345/231/250/357/274/232/347/210/266/345/255/220/345/215/225/345/220/221/345/220/214/346/255/245.md +0 -1033
  440. package/skills/a2h-batch-ui-align/references/mvvm/@Provide/350/243/205/351/245/260/345/231/250/345/222/214@Consume/350/243/205/351/245/260/345/231/250/357/274/232/344/270/216/345/220/216/344/273/243/347/273/204/344/273/266/345/217/214/345/220/221/345/220/214/346/255/245.md +0 -1183
  441. package/skills/a2h-batch-ui-align/references/mvvm/@State/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/206/205/347/212/266/346/200/201.md +0 -576
  442. package/skills/a2h-batch-ui-align/references/mvvm/@Track/350/243/205/351/245/260/345/231/250/357/274/232class/345/257/271/350/261/241/345/261/236/346/200/247/347/272/247/346/233/264/346/226/260.md +0 -297
  443. package/skills/a2h-batch-ui-align/references/mvvm/@Watch/350/243/205/351/245/260/345/231/250/357/274/232/347/212/266/346/200/201/345/217/230/351/207/217/346/233/264/346/224/271/351/200/232/347/237/245.md +0 -395
  444. package/skills/a2h-batch-ui-align/references/mvvm/AppStorage/357/274/232/345/272/224/347/224/250/345/205/250/345/261/200/347/232/204UI/347/212/266/346/200/201/345/255/230/345/202/250.md +0 -903
  445. package/skills/a2h-batch-ui-align/references/mvvm/Environment/357/274/232/350/256/276/345/244/207/347/216/257/345/242/203/346/237/245/350/257/242.md +0 -106
  446. package/skills/a2h-batch-ui-align/references/mvvm/LocalStorage/357/274/232/351/241/265/351/235/242/347/272/247UI/347/212/266/346/200/201/345/255/230/345/202/250.md +0 -1178
  447. package/skills/a2h-batch-ui-align/references/mvvm/MVVM/346/250/241/345/274/217/357/274/210V1/357/274/211.md +0 -911
  448. package/skills/a2h-batch-ui-align/references/mvvm/PersistentStorage/357/274/232/346/214/201/344/271/205/345/214/226/345/255/230/345/202/250UI/347/212/266/346/200/201.md +0 -355
  449. package/skills/a2h-batch-ui-align/references/mvvm//347/256/241/347/220/206/345/272/224/347/224/250/346/213/245/346/234/211/347/232/204/347/212/266/346/200/201/346/246/202/350/277/260.md +0 -11
  450. package/skills/a2h-batch-ui-align/references/mvvm-v2/!!/350/257/255/346/263/225/357/274/232/345/217/214/345/220/221/347/273/221/345/256/232.md +0 -206
  451. package/skills/a2h-batch-ui-align/references/mvvm-v2/@Computed/350/243/205/351/245/260/345/231/250/357/274/232/350/256/241/347/256/227/345/261/236/346/200/247.md +0 -373
  452. package/skills/a2h-batch-ui-align/references/mvvm-v2/@Event/350/243/205/351/245/260/345/231/250/357/274/232/350/247/204/350/214/203/347/273/204/344/273/266/350/276/223/345/207/272.md +0 -158
  453. package/skills/a2h-batch-ui-align/references/mvvm-v2/@Local/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/206/205/351/203/250/347/212/266/346/200/201.md +0 -750
  454. package/skills/a2h-batch-ui-align/references/mvvm-v2/@Monitor/350/243/205/351/245/260/345/231/250/357/274/232/347/212/266/346/200/201/345/217/230/351/207/217/344/277/256/346/224/271/345/274/202/346/255/245/347/233/221/345/220/254.md +0 -1704
  455. package/skills/a2h-batch-ui-align/references/mvvm-v2/@ObservedV2/350/243/205/351/245/260/345/231/250/345/222/214@Trace/350/243/205/351/245/260/345/231/250/357/274/232/347/261/273/345/261/236/346/200/247/345/217/230/345/214/226/350/247/202/346/265/213.md +0 -1012
  456. package/skills/a2h-batch-ui-align/references/mvvm-v2/@Once/350/243/205/351/245/260/345/231/250/357/274/232/345/210/235/345/247/213/345/214/226/345/220/214/346/255/245/344/270/200/346/254/241.md +0 -164
  457. package/skills/a2h-batch-ui-align/references/mvvm-v2/@Param/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/244/226/351/203/250/350/276/223/345/205/245.md +0 -840
  458. package/skills/a2h-batch-ui-align/references/mvvm-v2/@Provider/350/243/205/351/245/260/345/231/250/345/222/214@Consumer/350/243/205/351/245/260/345/231/250/357/274/232/350/267/250/347/273/204/344/273/266/345/261/202/347/272/247/345/217/214/345/220/221/345/220/214/346/255/245.md +0 -856
  459. package/skills/a2h-batch-ui-align/references/mvvm-v2/@Type/350/243/205/351/245/260/345/231/250/357/274/232/346/240/207/350/256/260/347/261/273/345/261/236/346/200/247/347/232/204/347/261/273/345/236/213.md +0 -83
  460. package/skills/a2h-batch-ui-align/references/mvvm-v2/AppStorageV2/357/274/232/345/272/224/347/224/250/345/205/250/345/261/200UI/347/212/266/346/200/201/345/255/230/345/202/250.md +0 -294
  461. package/skills/a2h-batch-ui-align/references/mvvm-v2/MVVM/346/250/241/345/274/217/357/274/210V2/357/274/211.md +0 -1407
  462. package/skills/a2h-batch-ui-align/references/mvvm-v2/PersistenceV2/357/274/232/346/214/201/344/271/205/345/214/226/345/255/230/345/202/250UI/347/212/266/346/200/201.md +0 -1220
  463. package/skills/a2h-batch-ui-align/references/mvvm-v2/_/350/214/203/345/274/217/351/200/211/346/213/251/350/257/264/346/230/216.md +0 -47
  464. package/skills/a2h-batch-ui-align/references/mvvm-v2/_/350/243/205/351/245/260/345/231/250/351/200/237/346/237/245.md +0 -133
  465. package/skills/a2h-batch-ui-align/references/mvvm-v2//347/212/266/346/200/201/347/256/241/347/220/206V1/345/220/221V2/350/277/201/347/247/273/344/270/216/346/267/267/347/224/250/346/214/207/345/257/274.md +0 -840
  466. package/skills/a2h-batch-ui-align/scripts/tests/agent_cli.test.mjs +0 -217
  467. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_align_tint.test.mjs +0 -253
  468. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_canvas_pct.test.mjs +0 -312
  469. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_fidelity.test.mjs +0 -241
  470. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_layout_placement.test.mjs +0 -341
  471. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_review_fixes.test.mjs +0 -298
  472. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_rules.test.mjs +0 -365
  473. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_shell.test.mjs +0 -91
  474. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_weight_color.test.mjs +0 -445
  475. package/skills/a2h-batch-ui-align/scripts/tests/build_conversion_set.test.mjs +0 -356
  476. package/skills/a2h-batch-ui-align/scripts/tests/build_conversion_set_scope.test.mjs +0 -290
  477. package/skills/a2h-batch-ui-align/scripts/tests/color_utils_asset.test.mjs +0 -74
  478. package/skills/a2h-batch-ui-align/scripts/tests/export_scroll_states.test.mjs +0 -31
  479. package/skills/a2h-batch-ui-align/scripts/tests/export_ui_info.test.mjs +0 -564
  480. package/skills/a2h-batch-ui-align/scripts/tests/generate_pages_json.test.mjs +0 -123
  481. package/skills/a2h-batch-ui-align/scripts/tests/group_commit.test.mjs +0 -126
  482. package/skills/a2h-batch-ui-align/scripts/tests/group_pack.test.mjs +0 -241
  483. package/skills/a2h-batch-ui-align/scripts/tests/group_queue.test.mjs +0 -1451
  484. package/skills/a2h-batch-ui-align/scripts/tests/group_watch.test.mjs +0 -215
  485. package/skills/a2h-batch-ui-align/scripts/tests/harmony_index.test.mjs +0 -95
  486. package/skills/a2h-batch-ui-align/scripts/tests/host_env.test.mjs +0 -115
  487. package/skills/a2h-batch-ui-align/scripts/tests/measure_pack.test.mjs +0 -170
  488. package/skills/a2h-batch-ui-align/scripts/tests/occlusion.test.mjs +0 -102
  489. package/skills/a2h-batch-ui-align/scripts/tests/phase5_check.test.mjs +0 -244
  490. package/skills/a2h-batch-ui-align/scripts/tests/shell_contract.test.mjs +0 -166
  491. package/skills/a2h-batch-ui-align/scripts/tests/test_bfs_exit.ts +0 -49
  492. package/skills/a2h-batch-ui-align/scripts/tests/text_color_diff.test.mjs +0 -219
  493. package/skills/a2h-dashboard-render/references//347/234/213/346/235/277/350/257/264/346/230/216.md +0 -83
  494. package/skills/a2h-dashboard-render/test/fixtures/page_capture/broken.xml +0 -1
  495. package/skills/a2h-dashboard-render/test/fixtures/page_capture/expected.json +0 -156
  496. package/skills/a2h-dashboard-render/test/fixtures/page_capture/hmos.json +0 -1
  497. package/skills/a2h-dashboard-render/test/fixtures/page_capture/list.xml +0 -1
  498. package/skills/a2h-dashboard-render/test/fixtures/page_capture/nested_scroll.xml +0 -1
  499. package/skills/a2h-dashboard-render/test/test_artifact_contract.mjs +0 -170
  500. package/skills/a2h-dashboard-render/test/test_cli_check_registry.mjs +0 -99
  501. package/skills/a2h-dashboard-render/test/test_dashboard_architecture.mjs +0 -182
  502. package/skills/a2h-dashboard-render/test/test_dashboard_build.mjs +0 -64
  503. package/skills/a2h-dashboard-render/test/test_dashboard_node.mjs +0 -1172
  504. package/skills/a2h-dashboard-render/test/test_dashboard_spec_pipeline.mjs +0 -251
  505. package/skills/a2h-dashboard-render/test/test_dashboard_ui_pipeline.mjs +0 -81
  506. package/skills/a2h-dashboard-render/test/test_device_capture_env.mjs +0 -115
  507. package/skills/a2h-dashboard-render/test/test_device_capture_policy.mjs +0 -303
  508. package/skills/a2h-dashboard-render/test/test_page_capture.mjs +0 -147
  509. package/skills/a2h-dashboard-render/test/test_usage_readers.mjs +0 -444
  510. package/skills/a2h-module-semantic-docs/test/golden/module_structure.json +0 -187
  511. package/skills/a2h-module-semantic-docs/test/golden/module_understanding.json +0 -351
  512. package/skills/a2h-module-semantic-docs/test/golden/module_update_plan.json +0 -495
  513. package/skills/a2h-module-semantic-docs/test/golden/project_directory_structure.json +0 -157
  514. package/skills/a2h-module-semantic-docs/test/test_scan_and_commit.mjs +0 -388
  515. package/skills/a2h-resource-convert/scripts/tests/adaptive_icon.test.mjs +0 -182
  516. package/skills/a2h-resource-convert/scripts/tests/app_identity.test.mjs +0 -206
  517. package/skills/a2h-spec-design/test/golden/inspect_happy.json +0 -20
  518. package/skills/a2h-spec-design/test/golden/move_design.md +0 -18
  519. package/skills/a2h-spec-design/test/golden/move_design_crlf.md +0 -18
  520. package/skills/a2h-spec-design/test/golden/move_spec.md +0 -7
  521. package/skills/a2h-spec-design/test/golden/resolve_cases.json +0 -36
  522. package/skills/a2h-spec-design/test/golden/validate_issue_file.md +0 -12
  523. package/skills/a2h-spec-design/test/golden/validate_issues.json +0 -57
  524. package/skills/a2h-spec-design/test/test_spec_design_scripts.mjs +0 -381
  525. package/skills/a2h-spec-design-pipeline/scripts/inflight.mjs +0 -944
  526. package/skills/a2h-spec-design-pipeline/scripts/lib/bgcli.mjs +0 -95
  527. package/skills/a2h-spec-design-pipeline/scripts/reconcile.mjs +0 -218
  528. package/skills/a2h-spec-design-pipeline/scripts/test_bgcli.mjs +0 -64
  529. package/skills/a2h-spec-design-pipeline/scripts/test_inflight.mjs +0 -452
  530. package/skills/a2h-spec-design-pipeline/scripts/test_reconcile.mjs +0 -182
  531. package/skills/a2h-spec-design-pipeline/scripts/test_watchdog.mjs +0 -289
  532. package/skills/a2h-spec-design-pipeline/scripts/watchdog.mjs +0 -441
  533. package/skills/a2h-spec-generate/scripts/reqgen/test/control-fact-join.test.ts +0 -50
  534. package/skills/a2h-spec-generate/scripts/reqgen/test/control-name-uniapp.test.ts +0 -75
  535. package/skills/a2h-spec-generate/scripts/reqgen/test/cross-area-anchor.test.ts +0 -256
  536. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-area-facts.test.ts +0 -576
  537. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-contract.test.ts +0 -290
  538. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-finalize.test.ts +0 -1323
  539. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-prepare.test.ts +0 -574
  540. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-scope.test.ts +0 -339
  541. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-selfcheck.test.ts +0 -831
  542. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-spec.test.ts +0 -548
  543. package/skills/a2h-spec-generate/scripts/reqgen/test/model-cli-blockers.test.ts +0 -117
  544. package/skills/a2h-spec-generate/scripts/reqgen/test/model-scope.test.ts +0 -396
  545. package/skills/a2h-spec-generate/scripts/reqgen/test/model-seeds.test.ts +0 -175
  546. package/skills/a2h-spec-generate/scripts/reqgen/test/model-task-contract.test.ts +0 -298
  547. package/skills/a2h-spec-generate/scripts/reqgen/test/model-v4.test.ts +0 -1061
  548. package/skills/a2h-spec-generate/scripts/reqgen/test/specgen-completeness.test.ts +0 -286
  549. package/skills/a2h-spec-generate/scripts/reqgen/test/stagem-stored-path.test.ts +0 -25
  550. package/skills/a2h-spec-generate/scripts/reqgen/test/uniapp-scanner.test.ts +0 -159
  551. package/skills/a2h-spec-generate/test/check-fused-spec.test.mjs +0 -632
  552. package/skills/a2h-spec-generate/test/check-spec.test.ts +0 -200
  553. package/skills/a2h-spec-generate/test/collect-specs.test.mjs +0 -538
  554. package/skills/a2h-spec-generate/test/detect-project.test.mjs +0 -37
  555. package/skills/a2h-spec-generate/test/ensure-index.test.mjs +0 -45
  556. package/skills/a2h-spec-generate/test/feature-stem.test.mjs +0 -147
  557. package/skills/a2h-spec-generate/test/fixtures/android/app/src/main/AndroidManifest.xml +0 -3
  558. package/skills/a2h-spec-generate/test/fixtures/android/build.gradle +0 -3
  559. package/skills/a2h-spec-generate/test/fixtures/android/settings.gradle +0 -3
  560. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/package.json +0 -9
  561. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/App.vue +0 -8
  562. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/components/MyCard.vue +0 -9
  563. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/feature/editor/index.vue +0 -1
  564. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/main.ts +0 -6
  565. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/manifest.json +0 -4
  566. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/detail/index.vue +0 -1
  567. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/home/index.vue +0 -33
  568. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/settings/index.vue +0 -1
  569. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages.json +0 -23
  570. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/services/items.ts +0 -3
  571. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/tsconfig.json +0 -8
  572. package/skills/a2h-spec-generate/test/fixtures/unknown/README.txt +0 -1
  573. package/skills/a2h-spec-generate/test/inspect-uniapp.test.mjs +0 -54
  574. package/skills/a2h-spec-generate/test/publication-verdict.test.mjs +0 -157
  575. package/skills/a2h-spec-generate/test/publish-specs.test.mjs +0 -282
  576. package/skills/a2h-spec-generate/test/render-tasks.test.mjs +0 -593
  577. package/skills/a2h-utg-explorer/scripts/tests/attest.test.mjs +0 -66
  578. package/skills/a2h-utg-explorer/scripts/tests/chain.test.mjs +0 -45
  579. package/skills/a2h-utg-explorer/scripts/tests/compose_identity.test.mjs +0 -243
  580. package/skills/a2h-utg-explorer/scripts/tests/coverage_rules.test.mjs +0 -104
  581. package/skills/a2h-utg-explorer/scripts/tests/d_prereqs.test.mjs +0 -223
  582. package/skills/a2h-utg-explorer/scripts/tests/device_health.test.mjs +0 -88
  583. package/skills/a2h-utg-explorer/scripts/tests/device_lock_retry.test.mjs +0 -187
  584. package/skills/a2h-utg-explorer/scripts/tests/direct_launch.test.mjs +0 -130
  585. package/skills/a2h-utg-explorer/scripts/tests/explorer_review_fixes.test.mjs +0 -136
  586. package/skills/a2h-utg-explorer/scripts/tests/final_utg.test.mjs +0 -135
  587. package/skills/a2h-utg-explorer/scripts/tests/first_round_phases.test.mjs +0 -16
  588. package/skills/a2h-utg-explorer/scripts/tests/generalization_fixes.test.mjs +0 -251
  589. package/skills/a2h-utg-explorer/scripts/tests/hint_check.test.mjs +0 -42
  590. package/skills/a2h-utg-explorer/scripts/tests/interruptions.test.mjs +0 -162
  591. package/skills/a2h-utg-explorer/scripts/tests/node_coverage.test.mjs +0 -193
  592. package/skills/a2h-utg-explorer/scripts/tests/overflow_prefix.test.mjs +0 -204
  593. package/skills/a2h-utg-explorer/scripts/tests/page_identity_tiers.test.mjs +0 -355
  594. package/skills/a2h-utg-explorer/scripts/tests/pipeline.test.mjs +0 -240
  595. package/skills/a2h-utg-explorer/scripts/tests/recover.test.mjs +0 -212
  596. package/skills/a2h-utg-explorer/scripts/tests/recover_b.test.mjs +0 -173
  597. package/skills/a2h-utg-explorer/scripts/tests/recover_d.test.mjs +0 -267
  598. package/skills/a2h-utg-explorer/scripts/tests/review_fixes.test.mjs +0 -213
  599. package/skills/a2h-utg-explorer/scripts/tests/robustness_fixes.test.mjs +0 -345
  600. package/skills/a2h-utg-explorer/scripts/tests/run_cycle.test.mjs +0 -453
  601. package/skills/a2h-utg-explorer/scripts/tests/runner_capabilities.test.mjs +0 -131
  602. package/skills/a2h-utg-explorer/scripts/tests/scope.test.mjs +0 -229
  603. package/skills/a2h-utg-explorer/scripts/tests/scroll_sweep.test.mjs +0 -336
  604. package/skills/a2h-utg-explorer/scripts/tests/semantics.test.mjs +0 -102
  605. package/skills/a2h-utg-explorer/scripts/tests/state_ambiguity.test.mjs +0 -92
  606. package/skills/a2h-utg-explorer/scripts/tests/twin_opener.test.mjs +0 -119
  607. package/skills/a2h-utg-explorer/scripts/tests/u2_backend.test.mjs +0 -346
  608. package/skills/a2h-utg-explorer/scripts/tests/ui_state_anchors.test.mjs +0 -112
  609. package/skills/a2h-utg-explorer/scripts/tests/variant_strings.test.mjs +0 -63
  610. package/skills/a2h-utg-explorer/scripts/tests/worklist_parts.test.mjs +0 -24
  611. package/skills/a2h-utg-static/scripts/tests/_zipw.mjs +0 -28
  612. package/skills/a2h-utg-static/scripts/tests/probe_autoload.mjs +0 -108
  613. package/skills/a2h-utg-static/scripts/tests/probe_layout_fragments.mjs +0 -90
  614. package/skills/a2h-utg-static/scripts/tests/probe_unknown_scope.mjs +0 -61
  615. package/skills/a2h-utg-static/scripts/tests/regression_matrix.mjs +0 -1261
  616. package/skills/a2h-utg-static/scripts/tests/test_activity_alias_launcher.mjs +0 -90
  617. package/skills/a2h-utg-static/scripts/tests/test_activity_supertype_chain.mjs +0 -106
  618. package/skills/a2h-utg-static/scripts/tests/test_bottom_sheet_container.mjs +0 -58
  619. package/skills/a2h-utg-static/scripts/tests/test_branch_guard.mjs +0 -19
  620. package/skills/a2h-utg-static/scripts/tests/test_callee_string_default.mjs +0 -30
  621. package/skills/a2h-utg-static/scripts/tests/test_carry_answers.mjs +0 -103
  622. package/skills/a2h-utg-static/scripts/tests/test_chrome_tokens.mjs +0 -60
  623. package/skills/a2h-utg-static/scripts/tests/test_commented_out_trigger.mjs +0 -111
  624. package/skills/a2h-utg-static/scripts/tests/test_commit_scope.mjs +0 -113
  625. package/skills/a2h-utg-static/scripts/tests/test_compose_file_private_route.mjs +0 -117
  626. package/skills/a2h-utg-static/scripts/tests/test_compose_nested_graph.mjs +0 -166
  627. package/skills/a2h-utg-static/scripts/tests/test_compose_route_holder_collision.mjs +0 -112
  628. package/skills/a2h-utg-static/scripts/tests/test_compose_vm_nav.mjs +0 -284
  629. package/skills/a2h-utg-static/scripts/tests/test_custom_source_root.mjs +0 -71
  630. package/skills/a2h-utg-static/scripts/tests/test_defensive_null_guard.mjs +0 -77
  631. package/skills/a2h-utg-static/scripts/tests/test_dialog_orphan_entries.mjs +0 -99
  632. package/skills/a2h-utg-static/scripts/tests/test_dialog_page_owner.mjs +0 -69
  633. package/skills/a2h-utg-static/scripts/tests/test_dialogshow_builder_forms.mjs +0 -96
  634. package/skills/a2h-utg-static/scripts/tests/test_dialogshow_java_factory.mjs +0 -37
  635. package/skills/a2h-utg-static/scripts/tests/test_disabled_guard.mjs +0 -42
  636. package/skills/a2h-utg-static/scripts/tests/test_drawer_panel_gesture.mjs +0 -140
  637. package/skills/a2h-utg-static/scripts/tests/test_edge_dedupe_by_gesture.mjs +0 -111
  638. package/skills/a2h-utg-static/scripts/tests/test_edge_provenance_lint.mjs +0 -70
  639. package/skills/a2h-utg-static/scripts/tests/test_enclosing_gesture.mjs +0 -69
  640. package/skills/a2h-utg-static/scripts/tests/test_external_surface_roots.mjs +0 -43
  641. package/skills/a2h-utg-static/scripts/tests/test_find_package_indirect.mjs +0 -67
  642. package/skills/a2h-utg-static/scripts/tests/test_forwarding_wrapper.mjs +0 -38
  643. package/skills/a2h-utg-static/scripts/tests/test_fragment_containment.mjs +0 -85
  644. package/skills/a2h-utg-static/scripts/tests/test_fragment_helper_trigger.mjs +0 -92
  645. package/skills/a2h-utg-static/scripts/tests/test_graph.mjs +0 -55
  646. package/skills/a2h-utg-static/scripts/tests/test_guard_clause.mjs +0 -86
  647. package/skills/a2h-utg-static/scripts/tests/test_hint_language.mjs +0 -119
  648. package/skills/a2h-utg-static/scripts/tests/test_host_kind_by_chain.mjs +0 -68
  649. package/skills/a2h-utg-static/scripts/tests/test_hybrid_bundle_attribution.mjs +0 -74
  650. package/skills/a2h-utg-static/scripts/tests/test_hybrid_bundled_pages.mjs +0 -181
  651. package/skills/a2h-utg-static/scripts/tests/test_hybrid_scope.mjs +0 -293
  652. package/skills/a2h-utg-static/scripts/tests/test_hybrid_title_renders.mjs +0 -118
  653. package/skills/a2h-utg-static/scripts/tests/test_interaction_sites.mjs +0 -272
  654. package/skills/a2h-utg-static/scripts/tests/test_item_data_instance.mjs +0 -51
  655. package/skills/a2h-utg-static/scripts/tests/test_kotlin_fn_spans.mjs +0 -69
  656. package/skills/a2h-utg-static/scripts/tests/test_label_accessor_forms.mjs +0 -187
  657. package/skills/a2h-utg-static/scripts/tests/test_label_source.mjs +0 -70
  658. package/skills/a2h-utg-static/scripts/tests/test_launch_intent_guard.mjs +0 -67
  659. package/skills/a2h-utg-static/scripts/tests/test_layout_declared_fragment.mjs +0 -103
  660. package/skills/a2h-utg-static/scripts/tests/test_listener_call_forms.mjs +0 -79
  661. package/skills/a2h-utg-static/scripts/tests/test_listener_receiver_binding.mjs +0 -47
  662. package/skills/a2h-utg-static/scripts/tests/test_manifest_exported_default.mjs +0 -40
  663. package/skills/a2h-utg-static/scripts/tests/test_manifest_filters_modules.mjs +0 -84
  664. package/skills/a2h-utg-static/scripts/tests/test_manifest_srcfile.mjs +0 -68
  665. package/skills/a2h-utg-static/scripts/tests/test_mode_and_cb_param.mjs +0 -172
  666. package/skills/a2h-utg-static/scripts/tests/test_module_namespace.mjs +0 -33
  667. package/skills/a2h-utg-static/scripts/tests/test_module_strings.mjs +0 -44
  668. package/skills/a2h-utg-static/scripts/tests/test_multiple_entry_contracts.mjs +0 -80
  669. package/skills/a2h-utg-static/scripts/tests/test_nav_graph_xml.mjs +0 -35
  670. package/skills/a2h-utg-static/scripts/tests/test_nl_hint_grammar.mjs +0 -42
  671. package/skills/a2h-utg-static/scripts/tests/test_nl_hints_gate.mjs +0 -85
  672. package/skills/a2h-utg-static/scripts/tests/test_node_id_collision.mjs +0 -57
  673. package/skills/a2h-utg-static/scripts/tests/test_non_gesture_step_flag.mjs +0 -62
  674. package/skills/a2h-utg-static/scripts/tests/test_out_of_scope_and_settings.mjs +0 -72
  675. package/skills/a2h-utg-static/scripts/tests/test_overload_and_climb.mjs +0 -86
  676. package/skills/a2h-utg-static/scripts/tests/test_pager_page_source.mjs +0 -78
  677. package/skills/a2h-utg-static/scripts/tests/test_pager_position_zero.mjs +0 -65
  678. package/skills/a2h-utg-static/scripts/tests/test_pager_variant_guard.mjs +0 -172
  679. package/skills/a2h-utg-static/scripts/tests/test_pipeline_llm_phases.mjs +0 -107
  680. package/skills/a2h-utg-static/scripts/tests/test_plain_dialog_nodes.mjs +0 -167
  681. package/skills/a2h-utg-static/scripts/tests/test_plaindialog_shared_anchor.mjs +0 -117
  682. package/skills/a2h-utg-static/scripts/tests/test_preference_click_nav.mjs +0 -98
  683. package/skills/a2h-utg-static/scripts/tests/test_preference_host_binding.mjs +0 -87
  684. package/skills/a2h-utg-static/scripts/tests/test_preference_nesting.mjs +0 -183
  685. package/skills/a2h-utg-static/scripts/tests/test_preference_widgets.mjs +0 -48
  686. package/skills/a2h-utg-static/scripts/tests/test_read_text_crlf.mjs +0 -41
  687. package/skills/a2h-utg-static/scripts/tests/test_resolver_tier_parity.mjs +0 -126
  688. package/skills/a2h-utg-static/scripts/tests/test_result_launcher.mjs +0 -142
  689. package/skills/a2h-utg-static/scripts/tests/test_review_fixes.mjs +0 -135
  690. package/skills/a2h-utg-static/scripts/tests/test_route_token_words.mjs +0 -66
  691. package/skills/a2h-utg-static/scripts/tests/test_same_name_decl_scope.mjs +0 -236
  692. package/skills/a2h-utg-static/scripts/tests/test_scope_utils.mjs +0 -85
  693. package/skills/a2h-utg-static/scripts/tests/test_sealed_dialog_state.mjs +0 -148
  694. package/skills/a2h-utg-static/scripts/tests/test_shared_overlay_split.mjs +0 -63
  695. package/skills/a2h-utg-static/scripts/tests/test_slug_parity.mjs +0 -58
  696. package/skills/a2h-utg-static/scripts/tests/test_starter_node_id.mjs +0 -41
  697. package/skills/a2h-utg-static/scripts/tests/test_state_guard_arity.mjs +0 -109
  698. package/skills/a2h-utg-static/scripts/tests/test_state_guard_commented_candidates.mjs +0 -68
  699. package/skills/a2h-utg-static/scripts/tests/test_state_guard_model_gates.mjs +0 -127
  700. package/skills/a2h-utg-static/scripts/tests/test_state_specific_hop.mjs +0 -130
  701. package/skills/a2h-utg-static/scripts/tests/test_synthetic_label_identity.mjs +0 -51
  702. package/skills/a2h-utg-static/scripts/tests/test_template_method_layout.mjs +0 -81
  703. package/skills/a2h-utg-static/scripts/tests/test_template_title.mjs +0 -58
  704. package/skills/a2h-utg-static/scripts/tests/test_trigger_id_spelling.mjs +0 -68
  705. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_action_override.mjs +0 -91
  706. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_flow_filter.mjs +0 -110
  707. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_nl_hint_key.mjs +0 -89
  708. package/skills/a2h-utg-static/scripts/tests/test_uiless_host_fold.mjs +0 -98
  709. package/skills/a2h-utg-static/scripts/tests/test_uniapp_source.mjs +0 -231
  710. package/skills/a2h-utg-static/scripts/tests/test_view_click_refs.mjs +0 -104
  711. package/skills/a2h-utg-static/scripts/tests/test_view_id_label.mjs +0 -69
  712. package/skills/a2h-utg-static/scripts/tests/test_view_interactions.mjs +0 -346
  713. package/skills/a2h-utg-static/scripts/tests/test_viewpage_nav.mjs +0 -340
  714. package/skills/a2h-utg-static/scripts/tests/test_vm_nav_helper_navigate.mjs +0 -98
  715. package/skills/a2h-utg-static/scripts/tests/test_widget_class_scope.mjs +0 -92
  716. package/skills/a2h-utg-static/scripts/tests/test_window_nav_kotlin.mjs +0 -158
  717. package/skills/a2h-utg-static/scripts/tests/test_worklist_parts.mjs +0 -65
@@ -0,0 +1,2513 @@
1
+ /**
2
+ * `ht init` — interactive initialization for HomeTrans.
3
+ *
4
+ * Displays the HomeTrans banner, lets the user select which editors to
5
+ * configure, then copies bundled skills/agents/commands into the chosen editors.
6
+ */
7
+ import fs from 'node:fs/promises';
8
+ import fsSync from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import crypto from 'node:crypto';
12
+ import { execFileSync, spawnSync } from 'node:child_process';
13
+ import { fileURLToPath } from 'node:url';
14
+ import chalk from 'chalk';
15
+ import figlet from 'figlet';
16
+ import inquirer from 'inquirer';
17
+ import { defaultEditors, deriveSdkPaths, ENV_KEYS, envFromProcess, SHARED_AGENTS_FALLBACK, } from './config-store.js';
18
+ import { persistEnvVars } from './env-vars.js';
19
+ import { installTo, listBundledAgents, listBundledCommands, listBundledSkills, } from '../platform/installer.js';
20
+ import { pathExists } from '../platform/compose.js';
21
+ import { editorDisplayName, platformForEditor } from '../platform/registry.js';
22
+ import { mapAgentColorToHex } from '../platform/transform.js';
23
+ function ensureChalkColor() {
24
+ if (process.stdout.isTTY && chalk.level === 0) {
25
+ chalk.level = 1;
26
+ }
27
+ }
28
+ /**
29
+ * Did the user abort an inquirer prompt with Ctrl-C / Esc?
30
+ * inquirer v14 (@inquirer/core) rejects with an `ExitPromptError` in that case.
31
+ * We must distinguish this from a genuine non-interactive failure (no TTY),
32
+ * otherwise Ctrl-C silently gets swallowed and the install proceeds anyway.
33
+ */
34
+ export function isPromptAbort(err) {
35
+ return err instanceof Error && err.name === 'ExitPromptError';
36
+ }
37
+ /** Print a cancellation notice and exit with the conventional SIGINT code. */
38
+ function abortInit() {
39
+ console.log(chalk.yellow('\n Cancelled. No changes were made beyond this point.\n'));
40
+ process.exit(130);
41
+ }
42
+ const __filename = fileURLToPath(import.meta.url);
43
+ const __dirname = path.dirname(__filename);
44
+ /**
45
+ * Whether `ht init` should exit non-zero. Per-target failures are collected
46
+ * instead of thrown (one broken target must not abort the rest), and every
47
+ * selected target being skipped means nothing was deployed — both are failures
48
+ * for scripts and CI. The shared ~/.agents fallback (no editors selected) is
49
+ * not a failure on its own.
50
+ */
51
+ export function initFailed(result, noEditorsSelected) {
52
+ if (result.errors.length > 0)
53
+ return true;
54
+ return !noEditorsSelected && result.configured.length === 0;
55
+ }
56
+ export async function dirExists(dirPath) {
57
+ try {
58
+ const stat = await fs.stat(dirPath);
59
+ return stat.isDirectory();
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ function resolveSkillsRoot() {
66
+ return path.resolve(__dirname, '..', '..', 'skills');
67
+ }
68
+ function resolveAgentsRoot() {
69
+ return path.resolve(__dirname, '..', '..', 'agents');
70
+ }
71
+ function resolveCommandsRoot() {
72
+ return path.resolve(__dirname, '..', '..', 'commands');
73
+ }
74
+ /**
75
+ * Install the bundled skills/agents/commands into one editor's target dirs.
76
+ *
77
+ * The real work lives in `src/platform/installer.ts`, which composes each
78
+ * document from the platform table (`editors.json`) plus the optional
79
+ * `platforms/` overlays — the same pipeline `devecocli plugin install` uses.
80
+ */
81
+ export async function installForEditor(editor, skillsRoot, agentsRoot, commandsRoot, result, options = {}) {
82
+ const platform = platformForEditor(editor);
83
+ // Output label (`Claude Code`), not the canonical id (`claude-code`) — the id
84
+ // stays the config key / selection value everywhere.
85
+ const label = editorDisplayName(editor.name);
86
+ const marker = platform.markerDir;
87
+ if (marker && !(await dirExists(marker))) {
88
+ result.skipped.push(`${label} (not installed)`);
89
+ return;
90
+ }
91
+ const roots = {
92
+ skillsRoot,
93
+ agentsRoot,
94
+ commandsRoot,
95
+ platformsRoot: resolvePlatformsRoot(),
96
+ };
97
+ const skillsDir = platform.skillsDir;
98
+ const agentsDir = platform.agentsDir;
99
+ // Same-name items already in the editor's dirs → ask before overwriting.
100
+ const skillConflicts = [];
101
+ if (skillsDir) {
102
+ for (const name of await listBundledSkills(skillsRoot)) {
103
+ if (await pathExists(path.join(skillsDir, name)))
104
+ skillConflicts.push(name);
105
+ }
106
+ }
107
+ const agentConflicts = [];
108
+ if (agentsDir) {
109
+ for (const name of await listBundledAgents(agentsRoot)) {
110
+ if (await pathExists(path.join(agentsDir, name)))
111
+ agentConflicts.push(name);
112
+ }
113
+ }
114
+ const commandConflicts = [];
115
+ const commandTargetDir = platform.commandsAsSkills && platform.skillsDir ? platform.skillsDir : platform.commandsDir;
116
+ if (commandTargetDir) {
117
+ for (const name of await listBundledCommands(commandsRoot)) {
118
+ // commandsAsSkills platforms store each command as skills/<name>/SKILL.md
119
+ const targetName = platform.commandsAsSkills && platform.skillsDir ? name.replace(/\.md$/, '') : name;
120
+ if (await pathExists(path.join(commandTargetDir, targetName)))
121
+ commandConflicts.push(name);
122
+ }
123
+ }
124
+ let overwrite = true;
125
+ const hasConflicts = skillConflicts.length > 0 || agentConflicts.length > 0 || commandConflicts.length > 0;
126
+ if (hasConflicts && !options.force) {
127
+ overwrite = await confirmOverwrite(label, skillConflicts, agentConflicts, commandConflicts);
128
+ }
129
+ // N = incremental install: keep the conflicting items untouched, still copy
130
+ // everything that doesn't exist in the target dirs yet.
131
+ const skip = (names) => (overwrite ? new Set() : new Set(names));
132
+ const skipSkills = skip(skillConflicts);
133
+ const skipAgents = skip(agentConflicts);
134
+ const skipCommands = skip(commandConflicts);
135
+ try {
136
+ const r = await installTo(platform, roots, {
137
+ force: options.force,
138
+ skipSkills,
139
+ skipAgents,
140
+ skipCommands,
141
+ });
142
+ if (r.skills > 0 && skillsDir) {
143
+ result.configured.push(`${label} skills (${r.skills} -> ${prettyHome(skillsDir)})`);
144
+ }
145
+ if (r.agents > 0 && agentsDir) {
146
+ result.configured.push(`${label} agents (${r.agents} -> ${prettyHome(agentsDir)})`);
147
+ }
148
+ if (r.commands > 0) {
149
+ const shown = platform.commandsAsSkills && platform.skillsDir
150
+ ? platform.skillsDir
151
+ : platform.commandsDir ?? platform.skillsDir ?? '';
152
+ result.configured.push(`${label} commands (${r.commands} -> ${prettyHome(shown)})`);
153
+ }
154
+ if (!overwrite) {
155
+ result.skipped.push(`${label} existing kept: ${skipSkills.size} skills, ${skipAgents.size} agents, ${skipCommands.size} commands (new items installed)`);
156
+ }
157
+ for (const note of r.skipped)
158
+ result.skipped.push(note);
159
+ for (const issue of r.issues) {
160
+ const line = `[${issue.level}] ${label}: ${issue.message}`;
161
+ if (issue.level === 'error')
162
+ result.errors.push(line);
163
+ else
164
+ result.skipped.push(line);
165
+ }
166
+ }
167
+ catch (err) {
168
+ result.errors.push(`${label}: ${err.message}`);
169
+ }
170
+ }
171
+ /** Optional overlay root (`<packageRoot>/platforms`); absent in published builds. */
172
+ export function resolvePlatformsRoot() {
173
+ return path.resolve(__dirname, '..', '..', 'platforms');
174
+ }
175
+ /** Backwards-compatible export; the implementation moved to the platform layer. */
176
+ export const mapAgentMarkdownColorToHex = mapAgentColorToHex;
177
+ /**
178
+ * Ask whether same-name skills/agents/commands already present in the editor's target
179
+ * dirs may be overwritten. Returns true (overwrite) when the user confirms or
180
+ * the shell is non-interactive (legacy behavior); false keeps existing files —
181
+ * the caller then only refreshes the API-key config files. Ctrl-C aborts init.
182
+ */
183
+ async function confirmOverwrite(editorName, skillConflicts, agentConflicts, commandConflicts) {
184
+ console.log(chalk.yellow(` ! ${editorName}: the following already exist and would be overwritten:`));
185
+ if (skillConflicts.length > 0) {
186
+ console.log(chalk.yellow(` skills: ${skillConflicts.join(', ')}`));
187
+ }
188
+ if (agentConflicts.length > 0) {
189
+ console.log(chalk.yellow(` agents: ${agentConflicts.join(', ')}`));
190
+ }
191
+ if (commandConflicts.length > 0) {
192
+ console.log(chalk.yellow(` commands: ${commandConflicts.join(', ')}`));
193
+ }
194
+ try {
195
+ const answers = await inquirer.prompt([
196
+ {
197
+ type: 'confirm',
198
+ name: 'overwrite',
199
+ message: `Overwrite them in ${editorName}? (N = keep existing files; new items are still installed and API-key configs refreshed)`,
200
+ default: true,
201
+ },
202
+ ]);
203
+ return answers.overwrite;
204
+ }
205
+ catch (err) {
206
+ if (isPromptAbort(err))
207
+ abortInit();
208
+ console.log(chalk.yellow(' Non-interactive: overwriting by default.'));
209
+ return true;
210
+ }
211
+ }
212
+ /**
213
+ * Display paths as full absolute OS-native paths (e.g. on Windows:
214
+ * `C:\Users\<you>\.claude\skills`) — no `~` abbreviation, no separator
215
+ * rewriting, so output matches what the user can copy into their shell.
216
+ */
217
+ export function prettyHome(p) {
218
+ return p;
219
+ }
220
+ /** Bundled at the package root, alongside skills/ and agents/. */
221
+ function resolveEnvRequirementsPath() {
222
+ return path.resolve(__dirname, '..', '..', 'env-requirements.json');
223
+ }
224
+ /**
225
+ * Load env-requirements.json. The leading `$`-prefixed keys are documentation
226
+ * and ignored. Returns null (with a warning) if the file is missing or invalid
227
+ * so `ht init` degrades gracefully instead of crashing.
228
+ */
229
+ export async function loadEnvRequirements() {
230
+ const p = resolveEnvRequirementsPath();
231
+ let raw;
232
+ try {
233
+ raw = await fs.readFile(p, 'utf-8');
234
+ }
235
+ catch {
236
+ console.log(chalk.yellow(` ! env-requirements.json not found at ${p} — skipping impact check.`));
237
+ return null;
238
+ }
239
+ try {
240
+ const parsed = JSON.parse(raw);
241
+ if (!parsed.tools || !Array.isArray(parsed.requirements)) {
242
+ throw new Error('expected { tools: {...}, requirements: [...] }');
243
+ }
244
+ return parsed;
245
+ }
246
+ catch (err) {
247
+ console.log(chalk.yellow(` ! env-requirements.json is invalid (${err.message}) — skipping impact check.`));
248
+ return null;
249
+ }
250
+ }
251
+ /** Locate a command on PATH (`where` on Windows, `which` elsewhere). */
252
+ function whichSync(cmd) {
253
+ const isWin = process.platform === 'win32';
254
+ try {
255
+ const out = execFileSync(isWin ? 'where' : 'which', [cmd], {
256
+ encoding: 'utf-8',
257
+ timeout: 5000,
258
+ stdio: ['ignore', 'pipe', 'ignore'],
259
+ });
260
+ const lines = out.split('\n').map((l) => l.trim()).filter(Boolean);
261
+ return lines[0] || null;
262
+ }
263
+ catch {
264
+ return null;
265
+ }
266
+ }
267
+ /**
268
+ * Run a tool's verify command and return its first non-empty output line.
269
+ * Reads the configured stream first (stdout by default; stderr for `java
270
+ * -version`), falling back to the combined output if that stream is empty.
271
+ */
272
+ function captureVerify(cmd, args, stream) {
273
+ const r = spawnSync(cmd, args, { encoding: 'utf-8', timeout: 5000 });
274
+ if (r.error)
275
+ return null;
276
+ const primary = stream === 'stderr' ? r.stderr : r.stdout;
277
+ const text = primary && primary.trim() ? primary : `${r.stdout ?? ''}\n${r.stderr ?? ''}`;
278
+ const line = (text ?? '').split('\n').map((l) => l.trim()).filter(Boolean)[0];
279
+ return line || null;
280
+ }
281
+ async function fileExists(p) {
282
+ try {
283
+ await fs.access(p);
284
+ return true;
285
+ }
286
+ catch {
287
+ return false;
288
+ }
289
+ }
290
+ /** Parse the first dotted-number sequence into [major, minor, patch]. */
291
+ export function parseVersion(s) {
292
+ const m = s.match(/(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
293
+ if (!m)
294
+ return null;
295
+ return [Number(m[1] || 0), Number(m[2] || 0), Number(m[3] || 0)];
296
+ }
297
+ function cmpVersion(a, b) {
298
+ for (let i = 0; i < 3; i++) {
299
+ const d = a[i] - b[i];
300
+ if (d !== 0)
301
+ return d < 0 ? -1 : 1;
302
+ }
303
+ return 0;
304
+ }
305
+ /**
306
+ * Is `version` inside the [min, max) window? Unparseable versions or an absent
307
+ * range are treated as satisfied (we never block on what we can't measure).
308
+ */
309
+ export function versionInRange(version, range) {
310
+ if (!range || (!range.min && !range.max))
311
+ return true;
312
+ const pv = parseVersion(version);
313
+ if (!pv)
314
+ return true;
315
+ if (range.min) {
316
+ const pm = parseVersion(range.min);
317
+ if (pm && cmpVersion(pv, pm) < 0)
318
+ return false;
319
+ }
320
+ if (range.max) {
321
+ const px = parseVersion(range.max);
322
+ if (px && cmpVersion(pv, px) >= 0)
323
+ return false;
324
+ }
325
+ return true;
326
+ }
327
+ /** Human-readable form of a range, e.g. ">= 3.10", "< 2.0", "[1.0, 2.0)". */
328
+ function describeRange(range) {
329
+ if (!range)
330
+ return '';
331
+ if (range.min && range.max)
332
+ return `[${range.min}, ${range.max})`;
333
+ if (range.min)
334
+ return `>= ${range.min}`;
335
+ if (range.max)
336
+ return `< ${range.max}`;
337
+ return '';
338
+ }
339
+ /**
340
+ * Detect every tool declared in env-requirements.json. `source: 'env-dir'`
341
+ * tools are a directory check; `source: 'path'` tools are located by trying
342
+ * each alias on PATH, then the optional DevEco fallback path. When a `verify`
343
+ * command is present we also capture and parse the tool's version.
344
+ */
345
+ async function detectEnvironment(spec, env) {
346
+ const status = new Map();
347
+ const isWin = process.platform === 'win32';
348
+ const baseDir = (key) => key === 'DEVECO_SDK_HOME'
349
+ ? env.DEVECO_SDK_HOME
350
+ : key === 'DEVECO_HOME'
351
+ ? env.DEVECO_HOME
352
+ : '';
353
+ for (const [id, tool] of Object.entries(spec.tools)) {
354
+ if (tool.source === 'env-dir') {
355
+ const dir = tool.envVar ? baseDir(tool.envVar) : '';
356
+ const ok = dir ? await dirExists(dir) : false;
357
+ status.set(id, { found: ok, path: ok ? dir : undefined });
358
+ continue;
359
+ }
360
+ // source 'python-import': probe a pip package by importing it with the
361
+ // first Python interpreter found on PATH. Same alias resolution as the
362
+ // python tool itself, and no shell — keeps `-c` code quoting-proof.
363
+ if (tool.source === 'python-import') {
364
+ const aliases = tool.aliases?.length ? tool.aliases : ['python', 'python3', 'py'];
365
+ const code = `import ${(tool.imports ?? [id]).join(', ')}`;
366
+ let found = false;
367
+ let resolved;
368
+ for (const alias of aliases) {
369
+ const p = whichSync(alias);
370
+ if (!p)
371
+ continue;
372
+ resolved = p;
373
+ const r = spawnSync(p, ['-c', code], { encoding: 'utf-8', timeout: 30_000 });
374
+ if (r.status === 0) {
375
+ found = true;
376
+ break;
377
+ }
378
+ }
379
+ status.set(id, { found, path: resolved });
380
+ continue;
381
+ }
382
+ // source 'path': try each alias on PATH, then the fallback path.
383
+ const aliases = tool.aliases?.length ? tool.aliases : [id];
384
+ let resolvedPath = null;
385
+ let cmdToRun = null;
386
+ for (const alias of aliases) {
387
+ const p = whichSync(alias);
388
+ if (p) {
389
+ resolvedPath = p;
390
+ cmdToRun = alias;
391
+ break;
392
+ }
393
+ }
394
+ let viaFallback = false;
395
+ if (!resolvedPath && tool.fallback) {
396
+ const base = baseDir(tool.fallback.base);
397
+ if (base) {
398
+ const exe = isWin ? `${tool.fallback.exe}.exe` : tool.fallback.exe;
399
+ const cand = path.join(base, ...tool.fallback.segments, exe);
400
+ if (await fileExists(cand)) {
401
+ resolvedPath = cand;
402
+ cmdToRun = cand;
403
+ viaFallback = true;
404
+ }
405
+ }
406
+ }
407
+ const st = { found: !!resolvedPath, path: resolvedPath ?? undefined };
408
+ if (resolvedPath && cmdToRun && tool.verify) {
409
+ const raw = captureVerify(cmdToRun, tool.verify, tool.versionStream === 'stderr' ? 'stderr' : 'stdout');
410
+ if (raw) {
411
+ st.note = viaFallback ? `${raw} (via ${tool.fallback.base} fallback)` : raw;
412
+ if (tool.versionRegex) {
413
+ const m = raw.match(new RegExp(tool.versionRegex));
414
+ if (m && m[1])
415
+ st.version = m[1];
416
+ }
417
+ }
418
+ else if (viaFallback) {
419
+ st.note = `via ${tool.fallback.base} fallback`;
420
+ }
421
+ }
422
+ else if (viaFallback) {
423
+ st.note = `via ${tool.fallback.base} fallback`;
424
+ }
425
+ status.set(id, st);
426
+ }
427
+ return status;
428
+ }
429
+ /**
430
+ * A dependency is satisfied when its tool is present AND its detected version
431
+ * (if known) falls in the required range (dependency range overrides the tool
432
+ * default). Returns the reason token shown in the impact table when not.
433
+ */
434
+ function evaluateDependency(dep, spec, tools) {
435
+ const st = tools.get(dep.tool);
436
+ const range = dep.version ?? spec.tools[dep.tool]?.version ?? null;
437
+ if (!st || !st.found) {
438
+ return { satisfied: false, reason: dep.tool };
439
+ }
440
+ if (st.version && !versionInRange(st.version, range)) {
441
+ return {
442
+ satisfied: false,
443
+ reason: `${dep.tool} ${st.version} (need ${describeRange(range)})`,
444
+ };
445
+ }
446
+ return { satisfied: true, reason: '' };
447
+ }
448
+ /** Print detected tools + the per-skill/agent impact table. */
449
+ export async function runEnvironmentCheck(env) {
450
+ console.log('');
451
+ console.log(chalk.cyan(' Environment Check'));
452
+ const spec = await loadEnvRequirements();
453
+ if (!spec)
454
+ return;
455
+ const tools = await detectEnvironment(spec, env);
456
+ const order = Object.keys(spec.tools);
457
+ for (const name of order) {
458
+ const st = tools.get(name);
459
+ const tool = spec.tools[name];
460
+ const label = (tool.label ?? name).padEnd(12);
461
+ if (st.found) {
462
+ let note = st.note ?? '';
463
+ if (st.version && tool.version && !versionInRange(st.version, tool.version)) {
464
+ note += ` (requires ${describeRange(tool.version)})`;
465
+ }
466
+ const noteStr = note ? chalk.gray(` (${note})`) : '';
467
+ console.log(` ${chalk.green('+')} ${label} ${st.path ?? ''}${noteStr}`);
468
+ }
469
+ else {
470
+ console.log(` ${chalk.yellow('!')} ${label} ${chalk.yellow('not found')} ${chalk.gray(tool.hint ?? '')}`);
471
+ }
472
+ }
473
+ console.log('');
474
+ console.log(chalk.cyan(' Impact on skills/agents:'));
475
+ const nameW = 28;
476
+ console.log(chalk.gray(` ${'Name'.padEnd(nameW)} ${'Kind'.padEnd(6)} ${'Status'.padEnd(8)} Missing`));
477
+ let allOk = true;
478
+ for (const row of spec.requirements) {
479
+ const unmetReq = [];
480
+ const unmetOpt = [];
481
+ for (const dep of row.dependencies) {
482
+ const { satisfied, reason } = evaluateDependency(dep, spec, tools);
483
+ if (satisfied)
484
+ continue;
485
+ if (dep.level === 'required')
486
+ unmetReq.push(reason);
487
+ else
488
+ unmetOpt.push(`${reason}(optional)`);
489
+ }
490
+ let plain;
491
+ let color;
492
+ let parts;
493
+ if (unmetReq.length > 0) {
494
+ plain = 'BLOCKED';
495
+ color = chalk.red;
496
+ parts = [...unmetReq, ...unmetOpt];
497
+ allOk = false;
498
+ }
499
+ else if (unmetOpt.length > 0) {
500
+ plain = 'LIMITED';
501
+ color = chalk.yellow;
502
+ parts = unmetOpt;
503
+ allOk = false;
504
+ }
505
+ else {
506
+ plain = 'OK';
507
+ color = chalk.green;
508
+ parts = [];
509
+ }
510
+ const noteStr = parts.length > 0 && row.note ? chalk.gray(` — ${row.note}`) : '';
511
+ console.log(` ${row.name.padEnd(nameW)} ${row.kind.padEnd(6)} ${color(plain.padEnd(8))} ${parts.join(', ')}${noteStr}`);
512
+ }
513
+ if (!allOk) {
514
+ console.log('');
515
+ console.log(chalk.gray(' Install the missing tools above and re-run `ht init` to clear the impact list.'));
516
+ }
517
+ }
518
+ export async function detectInstalledEditors(editors) {
519
+ const status = new Map();
520
+ const errors = [];
521
+ for (const editor of editors) {
522
+ // Resolve through the platform table so $CODEX_HOME-style roots are honored.
523
+ let marker;
524
+ try {
525
+ marker = platformForEditor(editor).markerDir;
526
+ }
527
+ catch (err) {
528
+ // A hand-edited config entry with no editors.json row cannot be installed
529
+ // anywhere. Report it once here (the caller also drops it from the
530
+ // selection list) instead of aborting the whole init.
531
+ errors.push(`${editorDisplayName(editor.name)}: ${err.message}`);
532
+ continue;
533
+ }
534
+ if (!marker) {
535
+ status.set(editor.name, true);
536
+ }
537
+ else {
538
+ status.set(editor.name, await dirExists(marker));
539
+ }
540
+ }
541
+ return { status, errors };
542
+ }
543
+ /**
544
+ * SDK path variables `ht init` writes as real OS environment variables — the
545
+ * only place they are kept (there is no config file). PATH entries for
546
+ * node/java/hdc are not included here — those are documented as manual PATH
547
+ * setup. Empty values are never exported.
548
+ */
549
+ export const MACHINE_ENV_KEYS = ENV_KEYS;
550
+ /** Mask API-key values for display; show paths in full. */
551
+ function maskEnvValue(name, value) {
552
+ if (/_API_KEY$/.test(name) && value.length > 0) {
553
+ return value.length <= 8 ? '***' : `${value.slice(0, 4)}***${value.slice(-4)}`;
554
+ }
555
+ return value;
556
+ }
557
+ /**
558
+ * Show the resolved SDK values that would become machine environment
559
+ * variables, then ask Y/N before writing them (Windows: setx; macOS/Linux:
560
+ * shell rc block). Variables already present in the OS environment with the
561
+ * exact same value are skipped — they are neither shown nor re-written, and if
562
+ * nothing needs updating the prompt is skipped entirely. Non-interactive shells
563
+ * skip without changing anything. Re-throws ExitPromptError so the caller can
564
+ * abort init on Ctrl-C.
565
+ */
566
+ async function maybePersistMachineEnv(env) {
567
+ const allVars = MACHINE_ENV_KEYS.map((k) => [k, (env[k] ?? '').trim()]).filter(([, value]) => value.length > 0);
568
+ if (allVars.length === 0)
569
+ return;
570
+ // Skip variables already set in the OS environment with the same value — no
571
+ // need to re-write them or re-ask. process.env reflects the environment this
572
+ // process launched with, so a prior `ht init` (seen from a fresh terminal)
573
+ // already shows up here.
574
+ const sameValue = ([name, value]) => (process.env[name] ?? '').trim() === value;
575
+ const alreadySet = allVars.filter(sameValue);
576
+ const vars = allVars.filter((v) => !sameValue(v));
577
+ if (vars.length === 0) {
578
+ console.log('');
579
+ console.log(chalk.green(' + Machine environment variables already set with the current values — nothing to add.'));
580
+ return;
581
+ }
582
+ console.log('');
583
+ console.log(chalk.blue(' Add these to your machine environment variables? Skills and MCP tools read these from the OS environment at runtime.'));
584
+ for (const [name, value] of vars) {
585
+ console.log(` ${chalk.cyan(name)} = ${maskEnvValue(name, value)}`);
586
+ }
587
+ if (alreadySet.length > 0) {
588
+ console.log(chalk.gray(` (${alreadySet.length} already set with the same value — skipped: ${alreadySet
589
+ .map(([name]) => name)
590
+ .join(', ')})`));
591
+ }
592
+ let confirmed;
593
+ try {
594
+ const answers = await inquirer.prompt([
595
+ {
596
+ type: 'confirm',
597
+ name: 'persist',
598
+ message: 'Write these environment variables to this machine?',
599
+ default: true,
600
+ },
601
+ ]);
602
+ confirmed = answers.persist;
603
+ }
604
+ catch (err) {
605
+ if (isPromptAbort(err))
606
+ throw err;
607
+ console.log(chalk.yellow(' Non-interactive: skipped (set them manually if needed).'));
608
+ return;
609
+ }
610
+ if (!confirmed) {
611
+ console.log(chalk.yellow(' Skipped — no system environment variables were set.'));
612
+ console.log(chalk.gray(' Skills that build or check HarmonyOS code will not find the SDK automatically:\n' +
613
+ ' set these variables yourself, or re-run `ht init` and answer Y.'));
614
+ return;
615
+ }
616
+ // The environment is now the only store for these values. On macOS/Linux the
617
+ // managed rc block is replaced as a whole, so it must carry every value —
618
+ // writing only the changed ones would drop the unchanged ones from the block.
619
+ // Windows `setx` sets each name independently, so the changed ones suffice.
620
+ const note = await persistEnvVars(process.platform === 'win32' ? vars : allVars);
621
+ console.log(chalk.green(` + Environment variables ${note}`));
622
+ }
623
+ /**
624
+ * Run `git --version`. Returns the trimmed first output line on success (exit 0),
625
+ * or null when git is missing / exits non-zero. Used by `installGit` for
626
+ * idempotent detection before and after auto-provisioning.
627
+ */
628
+ function gitVersion() {
629
+ try {
630
+ const out = execFileSync('git', ['--version'], {
631
+ encoding: 'utf-8',
632
+ timeout: 15000,
633
+ stdio: ['ignore', 'pipe', 'ignore'],
634
+ shell: process.platform === 'win32',
635
+ });
636
+ return (out ?? '').split('\n').map((l) => l.trim()).filter(Boolean)[0] ?? '';
637
+ }
638
+ catch {
639
+ return null;
640
+ }
641
+ }
642
+ /**
643
+ * Git part of the Dependency Installation step — git is required for the
644
+ * diff-based agent precheck runs and generally assumed by npm and the skills.
645
+ * Idempotent: `git --version` returning normally skips the install. Per-OS auto
646
+ * provisioning:
647
+ * - Windows: `winget install --id Git.Git -e --source winget` when winget is
648
+ * on PATH; otherwise print the manual download URL.
649
+ * - macOS: `brew install git` when Homebrew is on PATH; otherwise offer to
650
+ * install Homebrew first via its official installer, then `brew install git`.
651
+ * MacPorts / `xcode-select --install` are shown as fallbacks.
652
+ * - Linux: print the common package-manager commands (apt / dnf / pacman)
653
+ * — auto-install would need sudo, which we don't want to grab silently.
654
+ * Never throws — failures are reported and `ht init` continues. The
655
+ * "Dependency Installation" section header is printed once by the caller.
656
+ */
657
+ async function installGit(offline) {
658
+ console.log(chalk.gray(' git'));
659
+ const existing = gitVersion();
660
+ if (existing !== null) {
661
+ console.log(chalk.green(` + git already installed (${existing || 'version unknown'}) — skipping.`));
662
+ return;
663
+ }
664
+ // Offline mode: winget/brew need the network — print the manual path instead.
665
+ if (offline) {
666
+ console.log(chalk.yellow(' ! git not found. Offline mode cannot auto-install it — use your offline medium:'));
667
+ console.log(chalk.gray(' Windows: offline Git for Windows installer — https://git-scm.com/download/win'));
668
+ console.log(chalk.gray(' macOS: xcode-select --install, or Homebrew from an offline mirror'));
669
+ console.log(chalk.gray(' Linux: distro package (apt/dnf/pacman) from an offline repo'));
670
+ console.log(chalk.gray(' Then re-run `ht init`.'));
671
+ return;
672
+ }
673
+ const platform = process.platform;
674
+ if (platform === 'win32') {
675
+ await installGitWindows();
676
+ return;
677
+ }
678
+ if (platform === 'darwin') {
679
+ await installGitMacOS();
680
+ return;
681
+ }
682
+ // Linux / other Unix: print instructions only.
683
+ console.log(chalk.yellow(' ! git not found. Install it with your distro package manager:'));
684
+ console.log(chalk.gray(' Debian/Ubuntu: sudo apt-get install -y git'));
685
+ console.log(chalk.gray(' Fedora/RHEL: sudo dnf install -y git'));
686
+ console.log(chalk.gray(' Arch: sudo pacman -S --noconfirm git'));
687
+ console.log(chalk.gray(' Docs: https://git-scm.com/download/linux'));
688
+ }
689
+ /** Windows branch of installGit — uses winget when available, prints download URL otherwise. */
690
+ async function installGitWindows() {
691
+ if (!whichSync('winget')) {
692
+ console.log(chalk.yellow(' ! git not found and winget is unavailable on this Windows host.'));
693
+ console.log(chalk.gray(' Install Git for Windows manually: https://git-scm.com/download/win'));
694
+ console.log(chalk.gray(' Then re-run `ht init`.'));
695
+ return;
696
+ }
697
+ const cmdText = 'winget install --id Git.Git -e --source winget';
698
+ let proceed = true;
699
+ try {
700
+ const answers = await inquirer.prompt([
701
+ {
702
+ type: 'confirm',
703
+ name: 'install',
704
+ message: `git not found. Install it now via winget?\n ${cmdText}`,
705
+ default: true,
706
+ },
707
+ ]);
708
+ proceed = answers.install;
709
+ }
710
+ catch (err) {
711
+ if (isPromptAbort(err))
712
+ abortInit();
713
+ console.log(chalk.yellow(' Non-interactive: proceeding with install.'));
714
+ }
715
+ if (!proceed) {
716
+ console.log(chalk.yellow(' Skipped — install later with:'));
717
+ console.log(chalk.gray(` ${cmdText}`));
718
+ return;
719
+ }
720
+ console.log(chalk.gray(` Running: ${cmdText} ...`));
721
+ try {
722
+ execFileSync('winget', ['install', '--id', 'Git.Git', '-e', '--source', 'winget'], { stdio: 'inherit', timeout: 10 * 60 * 1000, shell: true });
723
+ }
724
+ catch (err) {
725
+ console.log(chalk.red(` ! winget install failed: ${err.message}`));
726
+ console.log(chalk.gray(` Re-run manually: ${cmdText}`));
727
+ console.log(chalk.gray(' Or download the installer: https://git-scm.com/download/win'));
728
+ return;
729
+ }
730
+ const version = gitVersion();
731
+ if (version !== null) {
732
+ console.log(chalk.green(` + git installed & verified (${version || 'version unknown'}).`));
733
+ }
734
+ else {
735
+ console.log(chalk.yellow(' ! Installed, but `git --version` did not return successfully.'));
736
+ console.log(chalk.gray(' Open a new terminal (PATH refresh), then verify: git --version'));
737
+ }
738
+ }
739
+ /** macOS branch of installGit — prefers Homebrew, offers to install Homebrew first if missing. */
740
+ async function installGitMacOS() {
741
+ // Homebrew present → straight `brew install git`.
742
+ if (whichSync('brew')) {
743
+ await runBrewInstallGit();
744
+ return;
745
+ }
746
+ // No Homebrew: offer to install it via the official installer, then brew install git.
747
+ const brewInstallCmd = '/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"';
748
+ console.log(chalk.yellow(' ! git not found and Homebrew is unavailable on this macOS host.'));
749
+ console.log(chalk.gray(' HomeTrans can install Homebrew via the official installer, then run `brew install git`.'));
750
+ console.log(chalk.gray(` ${brewInstallCmd}`));
751
+ console.log(chalk.gray(' Alternatives:'));
752
+ console.log(chalk.gray(' MacPorts: sudo port install git (requires MacPorts already installed)'));
753
+ console.log(chalk.gray(' Xcode CLT: xcode-select --install (ships Apple\'s git build)'));
754
+ let proceed = true;
755
+ try {
756
+ const answers = await inquirer.prompt([
757
+ {
758
+ type: 'confirm',
759
+ name: 'install',
760
+ message: 'Install Homebrew now, then install git via brew?',
761
+ default: true,
762
+ },
763
+ ]);
764
+ proceed = answers.install;
765
+ }
766
+ catch (err) {
767
+ if (isPromptAbort(err))
768
+ abortInit();
769
+ console.log(chalk.yellow(' Non-interactive: proceeding with install.'));
770
+ }
771
+ if (!proceed) {
772
+ console.log(chalk.yellow(' Skipped — install git later using one of the options above.'));
773
+ return;
774
+ }
775
+ console.log(chalk.gray(` Running: ${brewInstallCmd} ...`));
776
+ try {
777
+ execFileSync('/bin/bash', ['-c', `$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)`], {
778
+ stdio: 'inherit',
779
+ timeout: 15 * 60 * 1000,
780
+ });
781
+ }
782
+ catch (err) {
783
+ console.log(chalk.red(` ! Homebrew install failed: ${err.message}`));
784
+ console.log(chalk.gray(' Fallback: xcode-select --install (ships Apple\'s git build)'));
785
+ return;
786
+ }
787
+ if (!whichSync('brew')) {
788
+ console.log(chalk.yellow(' ! Homebrew installed, but `brew` is not on PATH in this shell.'));
789
+ console.log(chalk.gray(' Open a new terminal and run: brew install git'));
790
+ return;
791
+ }
792
+ await runBrewInstallGit();
793
+ }
794
+ /** `brew install git` + verification helper, shared by both Homebrew branches on macOS. */
795
+ async function runBrewInstallGit() {
796
+ const cmdText = 'brew install git';
797
+ console.log(chalk.gray(` Running: ${cmdText} ...`));
798
+ try {
799
+ execFileSync('brew', ['install', 'git'], {
800
+ stdio: 'inherit',
801
+ timeout: 15 * 60 * 1000,
802
+ });
803
+ }
804
+ catch (err) {
805
+ console.log(chalk.red(` ! brew install git failed: ${err.message}`));
806
+ console.log(chalk.gray(' Fallback: xcode-select --install (ships Apple\'s git build)'));
807
+ return;
808
+ }
809
+ const version = gitVersion();
810
+ if (version !== null) {
811
+ console.log(chalk.green(` + git installed & verified (${version || 'version unknown'}).`));
812
+ }
813
+ else {
814
+ console.log(chalk.yellow(' ! Installed, but `git --version` did not return successfully.'));
815
+ console.log(chalk.gray(' Open a new terminal (PATH refresh), then verify: git --version'));
816
+ }
817
+ }
818
+ /**
819
+ * Global npm packages the skills need at runtime: CLI tools first, then the
820
+ * libraries reqgen resolves through its npm-linked node_modules.
821
+ *
822
+ * The tree-sitter pair is pinned as a coupled unit. reqgen's Model contracts
823
+ * hard-code exactly `web-tree-sitter@0.20.8` + `tree-sitter-wasms@0.1.13`
824
+ * (reqgen model/prepare.ts fingerprint + contracts.ts), and the pair only
825
+ * works together: tree-sitter-wasms@0.1.13 ships grammars in the old WASM
826
+ * dynamic-linking format that web-tree-sitter >= 0.26 cannot load
827
+ * (tree-sitter#5171), while web-tree-sitter 0.20.x supports parser ABI 13-14
828
+ * only. Never let either side float to latest independently.
829
+ */
830
+ const GLOBAL_NPM_PACKAGES = [
831
+ 'a2h-resource',
832
+ 'homegraph',
833
+ 'arkanalyzer',
834
+ '@deveco/deveco-cli',
835
+ 'commander',
836
+ 'zod',
837
+ 'web-tree-sitter@0.20.8',
838
+ 'tree-sitter-wasms@0.1.13',
839
+ ];
840
+ /**
841
+ * reqgen's runtime dependencies. `ht init` links these from the global
842
+ * install into each installed copy's node_modules: bare-specifier ESM
843
+ * imports ignore NODE_PATH, so junctions/symlinks are the only bridge that
844
+ * makes the copied scripts resolve the GLOBAL packages (homegraph's version
845
+ * therefore follows the global install, where the tree-sitter pair is pinned
846
+ * to web-tree-sitter@0.20.8 + tree-sitter-wasms@0.1.13).
847
+ */
848
+ const REQGEN_LINKED_PACKAGES = [
849
+ 'commander',
850
+ 'homegraph',
851
+ 'tree-sitter-wasms',
852
+ 'web-tree-sitter',
853
+ 'zod',
854
+ ];
855
+ /** Absolute path of the global node_modules dir, or null when npm is unusable. */
856
+ function npmGlobalRoot() {
857
+ try {
858
+ const out = execFileSync('npm', ['root', '-g'], {
859
+ encoding: 'utf-8',
860
+ timeout: 30_000,
861
+ shell: process.platform === 'win32',
862
+ stdio: ['ignore', 'pipe', 'ignore'],
863
+ });
864
+ const line = out.split('\n').map((l) => l.trim()).filter(Boolean)[0];
865
+ return line || null;
866
+ }
867
+ catch {
868
+ return null;
869
+ }
870
+ }
871
+ /**
872
+ * The effective npm registry this machine's npm resolves packages from
873
+ * (`npm config get registry`), or null when npm is unusable. npm's cache is
874
+ * keyed by exact request URL, so offline installs only hit entries seeded
875
+ * from the SAME registry the consuming machine is configured with.
876
+ */
877
+ function npmConfigRegistry() {
878
+ try {
879
+ const out = execFileSync('npm', ['config', 'get', 'registry'], {
880
+ encoding: 'utf-8',
881
+ timeout: 30_000,
882
+ shell: process.platform === 'win32',
883
+ stdio: ['ignore', 'pipe', 'ignore'],
884
+ });
885
+ const line = out.split('\n').map((l) => l.trim()).filter(Boolean)[0];
886
+ return line || null;
887
+ }
888
+ catch {
889
+ return null;
890
+ }
891
+ }
892
+ /** Split an npm spec (`pkg`, `pkg@1.2.3`, `@scope/pkg`, `@scope/pkg@1.2.3`)
893
+ * into its name and optional explicit version. */
894
+ function parseNpmSpec(spec) {
895
+ const at = spec.startsWith('@') ? spec.indexOf('@', 1) : spec.indexOf('@');
896
+ return at === -1
897
+ ? { name: spec }
898
+ : { name: spec.slice(0, at), version: spec.slice(at + 1) };
899
+ }
900
+ /** Installed version of a global npm package, or null when absent/unreadable. */
901
+ async function installedGlobalVersion(root, name) {
902
+ try {
903
+ const raw = await fs.readFile(path.join(root, name, 'package.json'), 'utf-8');
904
+ const version = JSON.parse(raw).version;
905
+ return typeof version === 'string' && version ? version : null;
906
+ }
907
+ catch {
908
+ return null;
909
+ }
910
+ }
911
+ /**
912
+ * Map a package spec to its pinned spec from the bundle manifest
913
+ * (`homegraph` → `homegraph@<version resolved at bundle time>`), so offline
914
+ * installs reproduce the exact versions the cache was seeded with. Falls back
915
+ * to the incoming spec. A spec that already carries an explicit version (the
916
+ * pinned tree-sitter pair in GLOBAL_NPM_PACKAGES) is authoritative and passes
917
+ * through unchanged.
918
+ */
919
+ function pinnedNpmSpec(bundle, pkg) {
920
+ const parsed = parseNpmSpec(pkg);
921
+ if (parsed.version)
922
+ return pkg;
923
+ const hit = bundle.manifest.npmPackages.find((spec) => parseNpmSpec(spec).name === parsed.name);
924
+ return hit ?? pkg;
925
+ }
926
+ /**
927
+ * Global npm part of the Dependency Installation step. Idempotent: every
928
+ * package already present at the pinned version in `npm root -g` is skipped;
929
+ * missing or version-mismatched packages are passed to one `npm install -g`
930
+ * (pinned specs reinstall their exact version). With a bundle, installs run
931
+ * strictly offline against the bundle's seeded cache using manifest-pinned
932
+ * versions. Never throws — failures print the manual command and `ht init`
933
+ * continues.
934
+ */
935
+ async function installGlobalNpmClis(bundle) {
936
+ console.log(chalk.gray(bundle
937
+ ? ' npm globals — offline (from bundle cache)'
938
+ : ' npm globals (homegraph, arkanalyzer, a2h-resource, devecocli, reqgen libs)'));
939
+ const root = npmGlobalRoot();
940
+ if (!root) {
941
+ console.log(chalk.yellow(' ! npm not usable (`npm root -g` failed). Install manually:'));
942
+ console.log(chalk.gray(` npm install -g ${GLOBAL_NPM_PACKAGES.join(' ')}`));
943
+ return;
944
+ }
945
+ const missing = [];
946
+ for (const spec of GLOBAL_NPM_PACKAGES) {
947
+ const { name, version } = parseNpmSpec(spec);
948
+ const installed = await installedGlobalVersion(root, name);
949
+ if (installed === null) {
950
+ missing.push(spec);
951
+ continue;
952
+ }
953
+ // A pinned spec must match exactly: an existing-but-different global
954
+ // version is precisely the silent incompatible pair this pin prevents.
955
+ if (version && installed !== version) {
956
+ console.log(chalk.yellow(` ! ${name}@${installed} is installed but ${spec} is required — reinstalling.`));
957
+ missing.push(spec);
958
+ }
959
+ }
960
+ if (missing.length === 0) {
961
+ console.log(chalk.green(' + npm global packages already installed — skipping.'));
962
+ return;
963
+ }
964
+ if (bundle) {
965
+ const specs = missing.map((p) => pinnedNpmSpec(bundle, p));
966
+ const args = [
967
+ 'install',
968
+ '-g',
969
+ '--offline',
970
+ '--no-audit',
971
+ '--no-fund',
972
+ '--cache',
973
+ shellArg(bundle.npmCacheDir),
974
+ ...specs,
975
+ ];
976
+ const cmdText = `npm ${args.join(' ')}`;
977
+ console.log(chalk.gray(` Running: ${cmdText} ...`));
978
+ const r = spawnSync('npm', args, {
979
+ stdio: 'inherit',
980
+ shell: process.platform === 'win32',
981
+ timeout: 20 * 60 * 1000,
982
+ });
983
+ if (r.status !== 0) {
984
+ console.log(chalk.yellow(' ! offline npm install failed — the bundle cache may be incomplete, seeded from a different npm registry, or predate the accept-variant fix (caches seeded by npm ≥ 10.8 do not serve npm ≤ 10.7).'));
985
+ console.log(chalk.gray(' Check `npm config get registry` against the registry recorded in the bundle\'s manifest.json, and `npm -v` against the creating machine\'s npm; or recreate the bundle: ht offline-bundle <dir>'));
986
+ return;
987
+ }
988
+ console.log(chalk.green(` + installed ${missing.length} npm package(s) from the offline bundle.`));
989
+ return;
990
+ }
991
+ const cmdText = `npm install -g ${missing.join(' ')}`;
992
+ console.log(chalk.gray(` Running: ${cmdText} ...`));
993
+ const r = spawnSync('npm', ['install', '-g', ...missing], {
994
+ stdio: 'inherit',
995
+ shell: process.platform === 'win32',
996
+ timeout: 10 * 60 * 1000,
997
+ });
998
+ if (r.status !== 0) {
999
+ console.log(chalk.yellow(' ! npm install -g failed. Install manually:'));
1000
+ console.log(chalk.gray(` ${cmdText}`));
1001
+ return;
1002
+ }
1003
+ console.log(chalk.green(` + installed ${missing.length} npm package(s).`));
1004
+ }
1005
+ /**
1006
+ * Link the reqgen runtime dependencies from the global install into the
1007
+ * installed skill copy's node_modules (`npm link` creates junctions/symlinks
1008
+ * there), so the copy's ESM imports resolve to the global packages. Guarded
1009
+ * by a stamp file listing the linked set: unchanged copies skip, and a
1010
+ * changed package list (or a stale node_modules from the old in-skill
1011
+ * `npm ci`) triggers a clean re-link. Never throws.
1012
+ */
1013
+ async function linkReqgenGlobalDeps(skillsDir, editorName) {
1014
+ const reqgenDir = path.join(skillsDir, 'a2h-spec-generate', 'scripts', 'reqgen');
1015
+ if (!(await fileExists(path.join(reqgenDir, 'package.json'))))
1016
+ return;
1017
+ const nodeModules = path.join(reqgenDir, 'node_modules');
1018
+ const stampPath = path.join(nodeModules, '.hometrans-npm-link');
1019
+ const stampBody = REQGEN_LINKED_PACKAGES.join('\n') + '\n';
1020
+ try {
1021
+ const existing = await fs.readFile(stampPath, 'utf-8');
1022
+ if (existing === stampBody)
1023
+ return; // already linked with this exact set
1024
+ }
1025
+ catch {
1026
+ // no stamp → first run, or a stale non-linked node_modules → re-link
1027
+ }
1028
+ // A pre-existing node_modules (e.g. from the old in-skill `npm ci`) would
1029
+ // keep shadowing the links with local package copies; remove it first.
1030
+ if (await dirExists(nodeModules)) {
1031
+ await fs.rm(nodeModules, { recursive: true, force: true });
1032
+ }
1033
+ const cmdText = `npm link ${REQGEN_LINKED_PACKAGES.join(' ')}`;
1034
+ console.log(chalk.gray(` reqgen deps (${editorName}): ${cmdText}`));
1035
+ const r = spawnSync('npm', ['link', ...REQGEN_LINKED_PACKAGES], {
1036
+ stdio: 'inherit',
1037
+ shell: process.platform === 'win32',
1038
+ timeout: 10 * 60 * 1000,
1039
+ cwd: reqgenDir,
1040
+ });
1041
+ if (r.status !== 0) {
1042
+ console.log(chalk.yellow(` ! reqgen dependency link failed for ${editorName}. Manual:`));
1043
+ console.log(chalk.gray(` cd "${reqgenDir}" && ${cmdText}`));
1044
+ return;
1045
+ }
1046
+ await fs.mkdir(nodeModules, { recursive: true });
1047
+ await fs.writeFile(stampPath, stampBody, 'utf-8');
1048
+ console.log(chalk.green(` + reqgen deps linked to global packages (${editorName}).`));
1049
+ }
1050
+ /**
1051
+ * The npm packages seeded into every bundle's cache — the runtime set only.
1052
+ * hometrans itself is NOT fetched from the registry: the bundle carries the
1053
+ * LOCAL build (see packLocalHometransAll) so an offline machine bootstraps the
1054
+ * exact feature set that created the bundle (e.g. `--offline-bundle` itself).
1055
+ *
1056
+ * Every skill ships Node-only scripts, so npm is the whole dependency story:
1057
+ * there is no Python/pip half of the bundle any more.
1058
+ */
1059
+ const OFFLINE_NPM_SEED_SET = [...GLOBAL_NPM_PACKAGES];
1060
+ /** Registry fallback for hometrans when the local `npm pack` fails. */
1061
+ const HOMETRANS_PACKAGE = '@buaa_smat/hometrans';
1062
+ /**
1063
+ * (os, cpu, libc) combos whose platform-native binaries are merged into the
1064
+ * packed tarball's bundled node_modules. The staging install only resolves
1065
+ * binaries for the CREATING machine (e.g. @img/sharp-win32-x64 on Windows),
1066
+ * which left `require('sharp')` broken on offline Macs / Linux. Covers the
1067
+ * realistic target set (HarmonyOS dev machines: Windows + macOS, plus glibc
1068
+ * Linux); extend with musl/other combos if a bundled package ever needs them.
1069
+ */
1070
+ const BUNDLED_NATIVE_PLATFORMS = [
1071
+ { os: 'win32', cpu: 'x64' },
1072
+ { os: 'darwin', cpu: 'arm64' },
1073
+ { os: 'darwin', cpu: 'x64' },
1074
+ { os: 'linux', cpu: 'x64', libc: 'glibc' },
1075
+ { os: 'linux', cpu: 'arm64', libc: 'glibc' },
1076
+ ];
1077
+ /**
1078
+ * Name shape of platform-native binary packages — the optional dependencies a
1079
+ * native host resolves per platform (sharp → `@img/sharp-darwin-arm64`,
1080
+ * esbuild → `@esbuild/win32-x64`, rollup → `@rollup/rollup-darwin-x64`, ...).
1081
+ */
1082
+ const PLATFORM_BINARY_NAME = /^(@[^/]+\/)?[a-z0-9._-]*?(win32|darwin|linux|android|freebsd|openbsd|sunos|aix)-(ia32|x86|x64|arm64|armv7|arm|riscv64|ppc64|s390x|loong64|mips64)(-(gnu|musl|msvc|gnueabihf))?$/;
1083
+ /**
1084
+ * Top-level packages in `nodeModulesDir` that declare platform-native
1085
+ * optional dependencies (e.g. sharp → @img/sharp-*). Defensively per-entry:
1086
+ * an unreadable package is skipped rather than failing the scan.
1087
+ */
1088
+ function findNativeBinaryHosts(nodeModulesDir) {
1089
+ const hosts = [];
1090
+ const consider = (pkgDirPath, name) => {
1091
+ let pkgJson;
1092
+ try {
1093
+ pkgJson = JSON.parse(fsSync.readFileSync(path.join(pkgDirPath, 'package.json'), 'utf-8'));
1094
+ }
1095
+ catch {
1096
+ return;
1097
+ }
1098
+ const hasBinaryDeps = Object.keys(pkgJson.optionalDependencies ?? {}).some((dep) => PLATFORM_BINARY_NAME.test(dep));
1099
+ if (hasBinaryDeps && typeof pkgJson.version === 'string') {
1100
+ hosts.push({ name, version: pkgJson.version });
1101
+ }
1102
+ };
1103
+ let entries = [];
1104
+ try {
1105
+ entries = fsSync.readdirSync(nodeModulesDir);
1106
+ }
1107
+ catch {
1108
+ return hosts;
1109
+ }
1110
+ for (const entry of entries) {
1111
+ let pkgPath = path.join(nodeModulesDir, entry);
1112
+ try {
1113
+ if (!fsSync.statSync(pkgPath).isDirectory())
1114
+ continue;
1115
+ if (entry.startsWith('@')) {
1116
+ for (const child of fsSync.readdirSync(pkgPath)) {
1117
+ const childPath = path.join(pkgPath, child);
1118
+ if (fsSync.statSync(childPath).isDirectory())
1119
+ consider(childPath, `${entry}/${child}`);
1120
+ }
1121
+ }
1122
+ else {
1123
+ consider(pkgPath, entry);
1124
+ }
1125
+ }
1126
+ catch {
1127
+ continue;
1128
+ }
1129
+ }
1130
+ return hosts;
1131
+ }
1132
+ /**
1133
+ * Package names reachable from `roots` through dependencies/optionalDependencies
1134
+ * edges of the installed packages in `nodeModulesDir` — the set npm pack will
1135
+ * actually bundle. dev/peer edges are not followed: packages reached only
1136
+ * through them sit in node_modules but are not carried by the tarball, so
1137
+ * their native binaries would be merged in vain.
1138
+ */
1139
+ function bundledClosureNames(nodeModulesDir, roots) {
1140
+ const seen = new Set();
1141
+ const readPkg = (name) => {
1142
+ try {
1143
+ const raw = fsSync.readFileSync(path.join(nodeModulesDir, ...name.split('/'), 'package.json'), 'utf-8');
1144
+ return JSON.parse(raw);
1145
+ }
1146
+ catch {
1147
+ return null;
1148
+ }
1149
+ };
1150
+ const queue = [...roots];
1151
+ while (queue.length > 0) {
1152
+ const name = queue.pop();
1153
+ if (seen.has(name))
1154
+ continue;
1155
+ seen.add(name);
1156
+ const pkg = readPkg(name);
1157
+ if (!pkg)
1158
+ continue;
1159
+ queue.push(...Object.keys(pkg.dependencies ?? {}));
1160
+ queue.push(...Object.keys(pkg.optionalDependencies ?? {}));
1161
+ }
1162
+ return seen;
1163
+ }
1164
+ /**
1165
+ * Cross-platform half of the bundled-native-binaries fix: for every combo in
1166
+ * BUNDLED_NATIVE_PLATFORMS and every host package found in the bundled tree,
1167
+ * a scratch install with npm's --os/--cpu/--libc overrides resolves that
1168
+ * platform's binary packages; ones missing from the tree are copied in, so
1169
+ * the tarball works on every target platform instead of only the creating
1170
+ * machine's. Existing dirs always win (the creating machine's own resolution
1171
+ * is authoritative); idempotent across re-runs. Never throws — a combo that
1172
+ * fails only warns, because the pack itself can proceed without it.
1173
+ */
1174
+ /** Platform map key for a combo (`win32-x64`, `linux-arm64`, ...). */
1175
+ function platformComboKey(combo) {
1176
+ return `${combo.os}-${combo.cpu}`;
1177
+ }
1178
+ /**
1179
+ * Top-level packages in `nodeModulesDir` whose NAME marks a platform-native
1180
+ * binary package (see PLATFORM_BINARY_NAME) — e.g. @img/sharp-darwin-arm64,
1181
+ * @rollup/rollup-linux-x64-gnu. Defensively per-entry: unreadable entries are
1182
+ * skipped.
1183
+ */
1184
+ function platformBinaryPackageNames(nodeModulesDir) {
1185
+ const names = [];
1186
+ let entries = [];
1187
+ try {
1188
+ entries = fsSync.readdirSync(nodeModulesDir);
1189
+ }
1190
+ catch {
1191
+ return names;
1192
+ }
1193
+ for (const entry of entries) {
1194
+ try {
1195
+ const pkgPath = path.join(nodeModulesDir, entry);
1196
+ if (!fsSync.statSync(pkgPath).isDirectory())
1197
+ continue;
1198
+ if (entry.startsWith('@')) {
1199
+ for (const child of fsSync.readdirSync(pkgPath)) {
1200
+ if (PLATFORM_BINARY_NAME.test(`${entry}/${child}`))
1201
+ names.push(`${entry}/${child}`);
1202
+ }
1203
+ }
1204
+ else if (PLATFORM_BINARY_NAME.test(entry)) {
1205
+ names.push(entry);
1206
+ }
1207
+ }
1208
+ catch {
1209
+ continue;
1210
+ }
1211
+ }
1212
+ return names;
1213
+ }
1214
+ /**
1215
+ * Remove every platform-binary package dir from `nodeModulesDir` and return
1216
+ * the removed names — the per-platform pack loop keeps the staging tree
1217
+ * NEUTRAL between rounds: acquire one combo's binaries, pack, strip them
1218
+ * again. Bundling two platforms' binaries in one tarball is not an option:
1219
+ * npm rejects the install of every binary foreign to the installing machine
1220
+ * with EBADPLATFORM.
1221
+ */
1222
+ function removePlatformBinaryPackages(nodeModulesDir) {
1223
+ const removed = platformBinaryPackageNames(nodeModulesDir);
1224
+ for (const name of removed) {
1225
+ fsSync.rmSync(path.join(nodeModulesDir, ...name.split('/')), { recursive: true, force: true });
1226
+ }
1227
+ return removed;
1228
+ }
1229
+ /**
1230
+ * Copy the platform-native binaries ONE combo needs into the staging
1231
+ * `nodeModulesDir`. A scratch `npm install --os/--cpu/--libc` of every
1232
+ * native-binary host resolves that combo's binary set — companions included,
1233
+ * no name parsing involved (sharp → @img/sharp-darwin-arm64 AND
1234
+ * @img/sharp-libvips-darwin-arm64) — and everything missing from the staging
1235
+ * tree is copied in. `--libc` matters on non-linux creating machines: without
1236
+ * it npm cannot detect a libc family and rejects every libc-gated linux
1237
+ * binary. Returns the copied package names (empty on failure — a failed
1238
+ * combo only warns; the pack can proceed without its binaries). Never throws.
1239
+ */
1240
+ function acquireComboBinaries(nodeModulesDir, hosts, combo, npmRun) {
1241
+ const copied = [];
1242
+ const scratch = fsSync.mkdtempSync(path.join(os.tmpdir(), 'hometrans-native-'));
1243
+ try {
1244
+ fsSync.writeFileSync(path.join(scratch, 'package.json'), JSON.stringify({ name: 'hometrans-native-bins', private: true, version: '0.0.0' }, null, 2), 'utf-8');
1245
+ for (const host of hosts) {
1246
+ const args = [
1247
+ 'install',
1248
+ '--no-save',
1249
+ '--ignore-scripts',
1250
+ '--no-audit',
1251
+ '--no-fund',
1252
+ '--os',
1253
+ combo.os,
1254
+ '--cpu',
1255
+ combo.cpu,
1256
+ ...(combo.libc ? ['--libc', combo.libc] : []),
1257
+ `${host.name}@${host.version}`,
1258
+ ];
1259
+ const r = npmRun(args, scratch);
1260
+ if (r.status !== 0) {
1261
+ console.log(chalk.yellow(` ! native binaries for ${host.name} @ ${platformComboKey(combo)} not bundled (install failed).`));
1262
+ continue;
1263
+ }
1264
+ const scratchNm = path.join(scratch, 'node_modules');
1265
+ let entries = [];
1266
+ try {
1267
+ entries = fsSync.readdirSync(scratchNm);
1268
+ }
1269
+ catch {
1270
+ continue;
1271
+ }
1272
+ for (const entry of entries) {
1273
+ try {
1274
+ const src = path.join(scratchNm, entry);
1275
+ if (!fsSync.statSync(src).isDirectory())
1276
+ continue;
1277
+ const merge = (srcDir, rel) => {
1278
+ const dest = path.join(nodeModulesDir, rel);
1279
+ if (fsSync.existsSync(dest))
1280
+ return;
1281
+ fsSync.cpSync(srcDir, dest, { recursive: true });
1282
+ copied.push(rel);
1283
+ };
1284
+ if (entry.startsWith('@')) {
1285
+ for (const child of fsSync.readdirSync(src)) {
1286
+ const childSrc = path.join(src, child);
1287
+ if (fsSync.statSync(childSrc).isDirectory())
1288
+ merge(childSrc, `${entry}/${child}`);
1289
+ }
1290
+ }
1291
+ else {
1292
+ merge(src, entry);
1293
+ }
1294
+ }
1295
+ catch {
1296
+ continue;
1297
+ }
1298
+ }
1299
+ }
1300
+ }
1301
+ finally {
1302
+ fsSync.rmSync(scratch, { recursive: true, force: true });
1303
+ }
1304
+ return copied;
1305
+ }
1306
+ /**
1307
+ * `npm pack` the hometrans package this CLI runs from into `bundleRoot` as a
1308
+ * SET of self-contained per-platform tarballs — one per combo in
1309
+ * BUNDLED_NATIVE_PLATFORMS (win32-x64, darwin-arm64, darwin-x64, linux-x64
1310
+ * glibc, linux-arm64 glibc). Returns the `<os>-<cpu>` → filename map (e.g.
1311
+ * `darwin-arm64` → `buaa_smat-hometrans-<version>-darwin-arm64.tgz`), or null
1312
+ * on failure — in which case the bundle falls back to registry hometrans
1313
+ * (printed as a warning).
1314
+ *
1315
+ * `file:` dependencies cannot be resolved when a package is installed
1316
+ * FROM A TARBALL — npm opens the file: path before extracting. The published
1317
+ * hometrans avoids this by rewriting the dep to a registry version at publish
1318
+ * time; we cannot (the local tgz may be newer). So the raw pack is re-packed
1319
+ * through a staging copy where EVERY runtime dependency is pre-installed into
1320
+ * node_modules and moved to `bundleDependencies` (file: deps additionally get
1321
+ * their spec rewritten to the local version, making it inert): the tarball
1322
+ * carries its whole runtime closure, and installs from it never touch the
1323
+ * registry — no packuments, no cache, any npm version.
1324
+ *
1325
+ * Native binaries are split PER PLATFORM only when the runtime closure
1326
+ * actually resolves them: npm hard-fails an install (EBADPLATFORM) whose
1327
+ * bundled node_modules contains binaries built for another os/cpu, so a single
1328
+ * tarball cannot serve every platform in that case. Today the closure is plain
1329
+ * JS/wasm, so ONE cross-platform tarball is packed and every `<os>-<cpu>` key
1330
+ * in the manifest points at it; if a native-binary host appears again, the
1331
+ * staging tree is kept NEUTRAL between rounds (for each combo the right
1332
+ * binaries are merged in via a scratch `npm install --os/--cpu/--libc`, the
1333
+ * tarball is packed, and the binaries are stripped again) and every combo is
1334
+ * packed as `buaa_smat-hometrans-<version>-<os>-<cpu>.tgz` — uniform
1335
+ * platform-suffixed naming. The creating machine's combo is packed first (a
1336
+ * partially successful run then still serves the machine that built the
1337
+ * bundle, and its entry doubles as the back-compat single-tarball
1338
+ * `hometransTarball` manifest field).
1339
+ */
1340
+ export function packLocalHometransAll(bundleRoot) {
1341
+ const repoRoot = path.resolve(__dirname, '..', '..');
1342
+ const npmRun = (args, cwd) => spawnSync('npm', args, {
1343
+ encoding: 'utf-8',
1344
+ shell: process.platform === 'win32',
1345
+ timeout: 20 * 60 * 1000,
1346
+ cwd,
1347
+ });
1348
+ const tgzFromStdout = (out) => out.split('\n').map((l) => l.trim()).filter((l) => l.endsWith('.tgz')).pop() ?? null;
1349
+ const staging = fsSync.mkdtempSync(path.join(os.tmpdir(), 'hometrans-pack-'));
1350
+ try {
1351
+ // 1. Raw pack from the repo (runs `prepare` → build; honors the files field).
1352
+ const raw = npmRun(['pack', '--pack-destination', shellArg(staging)], repoRoot);
1353
+ if (raw.status !== 0)
1354
+ return null;
1355
+ const rawName = tgzFromStdout(raw.stdout || '');
1356
+ if (!rawName)
1357
+ return null;
1358
+ // 2. Extract into a staging package dir.
1359
+ const pkgDir = path.join(staging, 'pkg');
1360
+ fsSync.mkdirSync(pkgDir, { recursive: true });
1361
+ const untar = spawnSync('tar', ['--strip-components=1', '-xf', path.join(staging, rawName), '-C', pkgDir], { timeout: 5 * 60 * 1000 });
1362
+ if (untar.status !== 0)
1363
+ return null;
1364
+ // 3. Find the file: dependencies declared by the package.
1365
+ const pkgJsonPath = path.join(pkgDir, 'package.json');
1366
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1367
+ const pkgJson = JSON.parse(fsSync.readFileSync(pkgJsonPath, 'utf-8'));
1368
+ const fileDeps = Object.entries(pkgJson.dependencies ?? {}).filter(([, spec]) => spec.startsWith('file:'));
1369
+ if (fileDeps.length > 0) {
1370
+ // 4. Install each file: dep (with its full dependency closure) into the
1371
+ // staging node_modules, then rewrite its spec to the LOCAL version
1372
+ // (e.g. "file:tools/.../pkg-1.2.3.tgz" → "1.2.3") and mark
1373
+ // it bundled. npm pack only bundles deps that stay in `dependencies`;
1374
+ // bundled deps are extracted from the tarball at install time and
1375
+ // never resolved from a registry, so the rewritten spec is inert.
1376
+ // `--ignore-scripts` — we only need the files; `--no-save` keeps the
1377
+ // rewritten manifest authoritative.
1378
+ for (const [name, spec] of fileDeps) {
1379
+ const inst = npmRun(['install', '--no-save', '--ignore-scripts', '--no-audit', '--no-fund', spec], pkgDir);
1380
+ if (inst.status !== 0)
1381
+ return null;
1382
+ const installedPkgPath = path.join(pkgDir, 'node_modules', ...name.split('/'), 'package.json');
1383
+ const installed = JSON.parse(fsSync.readFileSync(installedPkgPath, 'utf-8'));
1384
+ if (!installed.version)
1385
+ return null;
1386
+ pkgJson.dependencies[name] = installed.version;
1387
+ delete pkgJson.bundleDependencies;
1388
+ }
1389
+ }
1390
+ // 5. Install the FULL runtime closure (registry deps like chalk/commander/
1391
+ // figlet/inquirer land in node_modules next to the file: dep trees;
1392
+ // already-satisfied deps are kept in place without a fetch) and mark
1393
+ // every runtime dependency bundled, so the packed tarball installs
1394
+ // offline with zero registry lookups.
1395
+ const inst = npmRun(['install', '--omit=dev', '--no-save', '--ignore-scripts', '--no-audit', '--no-fund'], pkgDir);
1396
+ if (inst.status !== 0)
1397
+ return null;
1398
+ pkgJson.bundledDependencies = [
1399
+ ...new Set([...(pkgJson.bundledDependencies ?? []), ...Object.keys(pkgJson.dependencies ?? {})]),
1400
+ ];
1401
+ delete pkgJson.bundleDependencies;
1402
+ fsSync.rmSync(path.join(pkgDir, 'package-lock.json'), { force: true });
1403
+ // 6. Strip lifecycle scripts — `prepare` runs scripts/build.js, which the
1404
+ // files field excludes from the pack; dist/ is already built.
1405
+ pkgJson.scripts = {};
1406
+ fsSync.writeFileSync(pkgJsonPath, JSON.stringify(pkgJson, null, 2), 'utf-8');
1407
+ // 7. Per-platform packs. Neutralize the tree first (the staging install
1408
+ // resolved only the creating machine's binaries); every combo — the
1409
+ // creating machine's included — then acquires its binary set the same
1410
+ // way, packs, and strips it again.
1411
+ const nodeModulesDir = path.join(pkgDir, 'node_modules');
1412
+ const bundledRoots = pkgJson.bundledDependencies ?? [];
1413
+ const hosts = findNativeBinaryHosts(nodeModulesDir).filter((h) => bundledClosureNames(nodeModulesDir, bundledRoots).has(h.name));
1414
+ removePlatformBinaryPackages(nodeModulesDir);
1415
+ const stem = `${(pkgJson.name ?? 'hometrans').replace('@', '').replace('/', '-')}-${pkgJson.version ?? '0.0.0'}`;
1416
+ const creatingCombo = BUNDLED_NATIVE_PLATFORMS.find((c) => c.os === process.platform && c.cpu === process.arch && (!c.libc || c.libc === 'glibc'));
1417
+ const combos = creatingCombo
1418
+ ? [creatingCombo, ...BUNDLED_NATIVE_PLATFORMS.filter((c) => c !== creatingCombo)]
1419
+ : [...BUNDLED_NATIVE_PLATFORMS];
1420
+ const tarballs = {};
1421
+ const packInto = (destName) => {
1422
+ const tmpPacks = path.join(staging, 'packs');
1423
+ fsSync.mkdirSync(tmpPacks, { recursive: true });
1424
+ const final = npmRun(['pack', '--pack-destination', shellArg(tmpPacks)], pkgDir);
1425
+ if (final.status !== 0)
1426
+ return false;
1427
+ const natural = tgzFromStdout(final.stdout || '');
1428
+ if (!natural)
1429
+ return false;
1430
+ const dest = path.join(bundleRoot, destName);
1431
+ fsSync.rmSync(dest, { force: true });
1432
+ fsSync.cpSync(path.join(tmpPacks, natural), dest);
1433
+ return true;
1434
+ };
1435
+ // No bundled package resolves platform-native binaries (every runtime dep
1436
+ // is plain JS or wasm), so the tarball is byte-identical for every target:
1437
+ // pack it ONCE and point every platform key at that one file. The lookup
1438
+ // map keeps its shape, so the bootstrap scripts and `ht init
1439
+ // --offline-bundle` need no special case; only the bundle shrinks (one
1440
+ // ~25 MB file instead of five) and the four extra pack rounds disappear.
1441
+ // As soon as a runtime dependency ships native optional deps again,
1442
+ // `hosts` is non-empty and the per-platform split below takes over.
1443
+ if (hosts.length === 0) {
1444
+ const destName = `${stem}.tgz`;
1445
+ if (!packInto(destName))
1446
+ return null;
1447
+ for (const combo of BUNDLED_NATIVE_PLATFORMS) {
1448
+ tarballs[platformComboKey(combo)] = destName;
1449
+ }
1450
+ console.log(chalk.gray(` + packed local hometrans ${destName} (one cross-platform tarball — no native deps)`));
1451
+ return tarballs;
1452
+ }
1453
+ for (const combo of combos) {
1454
+ const key = platformComboKey(combo);
1455
+ try {
1456
+ acquireComboBinaries(nodeModulesDir, hosts, combo, npmRun);
1457
+ const destName = `${stem}-${key}.tgz`;
1458
+ if (!packInto(destName)) {
1459
+ console.log(chalk.yellow(` ! npm pack for ${key} failed — that platform's tarball is not bundled.`));
1460
+ continue;
1461
+ }
1462
+ tarballs[key] = destName;
1463
+ console.log(chalk.gray(` + packed local hometrans ${destName} (${key})`));
1464
+ }
1465
+ finally {
1466
+ removePlatformBinaryPackages(nodeModulesDir);
1467
+ }
1468
+ }
1469
+ return Object.keys(tarballs).length > 0 ? tarballs : null;
1470
+ }
1471
+ catch {
1472
+ return null;
1473
+ }
1474
+ finally {
1475
+ fsSync.rmSync(staging, { recursive: true, force: true });
1476
+ }
1477
+ }
1478
+ /**
1479
+ * Validate and load a bundle produced by `ht offline-bundle`. Throws a plain
1480
+ * Error with an actionable message when the directory is not a usable bundle.
1481
+ */
1482
+ export async function loadOfflineBundle(dir) {
1483
+ const abs = path.resolve(dir);
1484
+ const manifestPath = path.join(abs, 'manifest.json');
1485
+ let raw;
1486
+ try {
1487
+ raw = await fs.readFile(manifestPath, 'utf-8');
1488
+ }
1489
+ catch {
1490
+ throw new Error(`${abs} is not an offline bundle (missing manifest.json). Create one on a networked machine with: ht offline-bundle <dir>`);
1491
+ }
1492
+ let manifest;
1493
+ try {
1494
+ manifest = JSON.parse(raw);
1495
+ }
1496
+ catch (err) {
1497
+ throw new Error(`${manifestPath} is not valid JSON: ${err.message}`);
1498
+ }
1499
+ if (!Array.isArray(manifest.npmPackages)) {
1500
+ throw new Error(`${manifestPath} is missing npmPackages — recreate the bundle.`);
1501
+ }
1502
+ const npmCacheDir = path.join(abs, 'npm-cache');
1503
+ if (!(await dirExists(npmCacheDir))) {
1504
+ throw new Error(`offline bundle ${abs} is missing npm-cache/ — recreate the bundle.`);
1505
+ }
1506
+ if (manifest.hometransTarball && !(await fileExists(path.join(abs, manifest.hometransTarball)))) {
1507
+ throw new Error(`offline bundle ${abs} is missing ${manifest.hometransTarball} (listed in manifest.json) — recreate the bundle.`);
1508
+ }
1509
+ for (const [platform, file] of Object.entries(manifest.hometransTarballs ?? {})) {
1510
+ if (!(await fileExists(path.join(abs, file))) || typeof file !== 'string' || !file) {
1511
+ throw new Error(`offline bundle ${abs} is missing ${String(file)} (hometransTarballs.${platform} in manifest.json) — recreate the bundle.`);
1512
+ }
1513
+ }
1514
+ return {
1515
+ dir: abs,
1516
+ manifest,
1517
+ npmCacheDir,
1518
+ };
1519
+ }
1520
+ /** The accept header npm ≥ 10.8 sends for packuments (full metadata doc). */
1521
+ const PACKUMENT_ACCEPT_FULL = 'application/json';
1522
+ /** The accept header npm ≤ 10.7 (incl. 9.x) sends for packuments (corgi doc). */
1523
+ const PACKUMENT_ACCEPT_CORGI = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*';
1524
+ function sha1Hex(text) {
1525
+ return crypto.createHash('sha1').update(text).digest('hex');
1526
+ }
1527
+ /** cacache bucket file path for a key, relative to the npm cache dir. */
1528
+ function cacheBucketPath(npmCacheDir, key) {
1529
+ const hash = crypto.createHash('sha256').update(key).digest('hex');
1530
+ return path.join(npmCacheDir, '_cacache', 'index-v5', hash.slice(0, 2), hash.slice(2, 4), hash.slice(4));
1531
+ }
1532
+ /** Parse a cacache bucket file into its (sha1-validated) index entries. */
1533
+ function parseCacheIndexFile(bucket) {
1534
+ let raw;
1535
+ try {
1536
+ raw = fsSync.readFileSync(bucket, 'utf-8');
1537
+ }
1538
+ catch {
1539
+ return [];
1540
+ }
1541
+ const out = [];
1542
+ for (const line of raw.split('\n')) {
1543
+ if (!line)
1544
+ continue;
1545
+ const tab = line.indexOf('\t');
1546
+ if (tab <= 0)
1547
+ continue;
1548
+ const json = line.slice(tab + 1);
1549
+ if (sha1Hex(json) !== line.slice(0, tab))
1550
+ continue; // corrupt line — cacache skips it too
1551
+ try {
1552
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1553
+ const entry = JSON.parse(json);
1554
+ if (entry && typeof entry.key === 'string')
1555
+ out.push(entry);
1556
+ }
1557
+ catch {
1558
+ // skip
1559
+ }
1560
+ }
1561
+ return out;
1562
+ }
1563
+ /** Append an index entry to its bucket file (same layout cacache insert writes). */
1564
+ function appendCacheIndexEntry(npmCacheDir, entry) {
1565
+ const bucket = cacheBucketPath(npmCacheDir, entry.key);
1566
+ fsSync.mkdirSync(path.dirname(bucket), { recursive: true });
1567
+ const json = JSON.stringify(entry);
1568
+ fsSync.appendFileSync(bucket, `\n${sha1Hex(json)}\t${json}`, 'utf-8');
1569
+ }
1570
+ /** Rewrite a bucket file with exactly these entries (cacache compact layout). */
1571
+ function rewriteCacheIndexFile(bucket, entries) {
1572
+ const body = entries.map((entry) => {
1573
+ const json = JSON.stringify(entry);
1574
+ return `${sha1Hex(json)}\t${json}`;
1575
+ });
1576
+ fsSync.writeFileSync(bucket, `\n${body.join('\n')}`, 'utf-8');
1577
+ }
1578
+ /** All bucket files under the cache's index, recursively. */
1579
+ function cacheIndexFiles(npmCacheDir) {
1580
+ const root = path.join(npmCacheDir, '_cacache', 'index-v5');
1581
+ const files = [];
1582
+ try {
1583
+ for (const entry of fsSync.readdirSync(root, { recursive: true, withFileTypes: true })) {
1584
+ if (entry.isFile())
1585
+ files.push(path.join(entry.parentPath ?? entry.path, entry.name));
1586
+ }
1587
+ }
1588
+ catch {
1589
+ return files;
1590
+ }
1591
+ return files;
1592
+ }
1593
+ /** Content file path for a cacache integrity string, or null when unparseable. */
1594
+ function cacheContentPath(npmCacheDir, integrity) {
1595
+ const match = /^([a-z0-9-]+)-([A-Za-z0-9+/=]+)$/.exec(integrity);
1596
+ if (!match)
1597
+ return null;
1598
+ try {
1599
+ const hex = Buffer.from(match[2], 'base64').toString('hex');
1600
+ return path.join(npmCacheDir, '_cacache', 'content-v2', match[1], hex.slice(0, 2), hex.slice(2, 4), hex.slice(4));
1601
+ }
1602
+ catch {
1603
+ return null;
1604
+ }
1605
+ }
1606
+ /**
1607
+ * Fix 1 from the header comment: for every cached PACKUMENT (registry URL
1608
+ * without a `.tgz` tail) whose response varies on accept, append index
1609
+ * entries for the missing accept variant(s), pointing at the same content.
1610
+ * The body served to a corgi request is the full-metadata document — a
1611
+ * strict superset of the abbreviated one, parsed happily by old npm. A
1612
+ * variant counts as present only when its content file still exists on disk,
1613
+ * so this also repairs caches whose variant content was lost (e.g. pruned
1614
+ * by an older tool). Returns the number of appended entries.
1615
+ */
1616
+ export function clonePackumentAcceptVariants(npmCacheDir, registry) {
1617
+ const prefix = `make-fetch-happen:request-cache:${registry.replace(/\/+$/, '')}/`;
1618
+ let appended = 0;
1619
+ for (const bucket of cacheIndexFiles(npmCacheDir)) {
1620
+ const entries = parseCacheIndexFile(bucket);
1621
+ if (entries.length === 0)
1622
+ continue;
1623
+ const byKey = new Map();
1624
+ for (const entry of entries) {
1625
+ const list = byKey.get(entry.key) ?? [];
1626
+ list.push(entry);
1627
+ byKey.set(entry.key, list);
1628
+ }
1629
+ for (const [key, list] of byKey) {
1630
+ if (!key.startsWith(prefix) || key.endsWith('.tgz'))
1631
+ continue;
1632
+ // Variant is servable only when the content behind it exists on disk.
1633
+ const present = new Set();
1634
+ let source = null; // newest entry with live content
1635
+ for (const entry of list) {
1636
+ const accept = entry.metadata?.reqHeaders?.accept;
1637
+ if (!entry.integrity)
1638
+ continue;
1639
+ const contentPath = cacheContentPath(npmCacheDir, entry.integrity);
1640
+ if (!contentPath || !fsSync.existsSync(contentPath))
1641
+ continue;
1642
+ if (typeof accept === 'string')
1643
+ present.add(accept);
1644
+ source = entry;
1645
+ }
1646
+ if (!source || !source.integrity)
1647
+ continue;
1648
+ const meta = source.metadata;
1649
+ if (!meta?.resHeaders || !/\baccept\b/i.test(meta.resHeaders.vary ?? ''))
1650
+ continue;
1651
+ for (const accept of [PACKUMENT_ACCEPT_FULL, PACKUMENT_ACCEPT_CORGI]) {
1652
+ if (present.has(accept))
1653
+ continue;
1654
+ appendCacheIndexEntry(npmCacheDir, {
1655
+ key,
1656
+ integrity: source.integrity,
1657
+ time: Date.now(),
1658
+ size: source.size,
1659
+ metadata: {
1660
+ ...meta,
1661
+ reqHeaders: { ...(meta.reqHeaders ?? {}), accept },
1662
+ },
1663
+ });
1664
+ appended++;
1665
+ }
1666
+ }
1667
+ }
1668
+ return appended;
1669
+ }
1670
+ /**
1671
+ * Fix 2 from the header comment: drop every `pacote:tarball:file:` index
1672
+ * entry (cached copies of local tarballs installed during seeding) and
1673
+ * garbage-collect content files no index entry references anymore. Returns
1674
+ * the freed bytes.
1675
+ */
1676
+ function pruneNpmCacheLocalTarballs(npmCacheDir) {
1677
+ let freed = 0;
1678
+ for (const bucket of cacheIndexFiles(npmCacheDir)) {
1679
+ const entries = parseCacheIndexFile(bucket);
1680
+ if (entries.length === 0)
1681
+ continue;
1682
+ const local = entries.filter((e) => e.key.startsWith('pacote:tarball:file:'));
1683
+ if (local.length === 0)
1684
+ continue;
1685
+ if (local.length === entries.length) {
1686
+ // One key per bucket (sha256-keyed) — the whole file is this key's history.
1687
+ fsSync.rmSync(bucket, { force: true });
1688
+ }
1689
+ else {
1690
+ // Theoretical hash collision — rewrite without the local-tarball lines.
1691
+ rewriteCacheIndexFile(bucket, entries.filter((e) => !e.key.startsWith('pacote:tarball:file:')));
1692
+ }
1693
+ }
1694
+ // Conservative GC: a content file survives when ANY surviving index line
1695
+ // references its integrity.
1696
+ const referenced = new Set();
1697
+ for (const bucket of cacheIndexFiles(npmCacheDir)) {
1698
+ for (const entry of parseCacheIndexFile(bucket)) {
1699
+ if (entry.integrity)
1700
+ referenced.add(entry.integrity);
1701
+ }
1702
+ }
1703
+ const contentRoot = path.join(npmCacheDir, '_cacache', 'content-v2');
1704
+ let contentFiles = [];
1705
+ try {
1706
+ contentFiles = fsSync
1707
+ .readdirSync(contentRoot, { recursive: true, withFileTypes: true })
1708
+ .filter((e) => e.isFile())
1709
+ .map((e) => path.join(e.parentPath ?? e.path, e.name));
1710
+ }
1711
+ catch {
1712
+ return freed;
1713
+ }
1714
+ for (const file of contentFiles) {
1715
+ const rel = path.relative(contentRoot, file).split(path.sep);
1716
+ if (rel.length < 4)
1717
+ continue;
1718
+ const algo = rel[0];
1719
+ const hex = rel.slice(1).join('');
1720
+ if (!/^[0-9a-f]+$/.test(hex) || !/^[a-z0-9-]+$/.test(algo))
1721
+ continue;
1722
+ const integrity = `${algo}-${Buffer.from(hex, 'hex').toString('base64')}`;
1723
+ if (referenced.has(integrity))
1724
+ continue;
1725
+ try {
1726
+ freed += fsSync.statSync(file).size;
1727
+ fsSync.rmSync(file, { force: true });
1728
+ }
1729
+ catch {
1730
+ // skip
1731
+ }
1732
+ }
1733
+ return freed;
1734
+ }
1735
+ /** Registry URLs compare equal ignoring trailing slashes (`.../npm/` === `.../npm`). */
1736
+ function sameRegistryUrl(a, b) {
1737
+ return a.replace(/\/+$/, '') === b.replace(/\/+$/, '');
1738
+ }
1739
+ /**
1740
+ * Registry-mismatch precheck for `ht init --offline-bundle`. npm's offline
1741
+ * cache is keyed by exact registry URL, so a bundle seeded under registry X
1742
+ * is guaranteed to fail with ENOTCACHED on a machine whose registry is Y —
1743
+ * even though every package is in the cache. Detect that here and abort with
1744
+ * the fix before npm prints its wall of ENOTCACHED errors. Silently skipped
1745
+ * when npm is unusable or the bundle predates the check (no npmRegistry in
1746
+ * the manifest). Returns an actionable error message, or null when the check
1747
+ * passes or cannot run.
1748
+ */
1749
+ function bundleNpmRegistryMismatch(bundle) {
1750
+ const seeded = bundle.manifest.npmRegistry;
1751
+ if (!seeded)
1752
+ return null;
1753
+ const current = npmConfigRegistry();
1754
+ if (!current)
1755
+ return null;
1756
+ if (sameRegistryUrl(current, seeded))
1757
+ return null;
1758
+ return [
1759
+ `npm registry mismatch — this bundle's npm-cache was seeded from ${seeded},`,
1760
+ `but this machine's npm resolves packages from ${current}. npm offline installs`,
1761
+ `look up the cache by exact registry URL, so running now would fail with ENOTCACHED.`,
1762
+ `Fix (pick one), then re-run ht init --offline-bundle:`,
1763
+ ` 1. Point npm at the bundle's registry on this machine (offline-safe: the URL is`,
1764
+ ` only a cache key, nothing is fetched): npm config set registry ${seeded}`,
1765
+ ` or for the current shell only: PowerShell: $env:npm_config_registry="${seeded}" bash: export npm_config_registry=${seeded}`,
1766
+ ` 2. Recreate the bundle on a machine whose npm registry is ${current}:`,
1767
+ ` ht offline-bundle <dir>`,
1768
+ ].join('\n');
1769
+ }
1770
+ /**
1771
+ * POSIX bootstrap script written into every bundle root as install.sh — the
1772
+ * ONE-COMMAND offline entry point. It auto-selects the hometrans tarball for
1773
+ * the machine it runs on: platform/arch is detected through the NODE BINARY
1774
+ * (`node -p process.platform/arch`), because that is what npm installs for —
1775
+ * a Rosetta or emulated shell would otherwise pick the wrong file. The
1776
+ * tarball filename comes from manifest.json's hometransTarballs map
1777
+ * (pretty-printed, one field per line, so a sed extracts it without jq).
1778
+ * One step by design: after the tarball install it execs `ht init
1779
+ * --offline-bundle` in the same process — the registry override below must
1780
+ * cover init too, and a separate manual `ht init` would run outside it
1781
+ * against the machine's own registry config.
1782
+ *
1783
+ * Registry override: npm's offline cache is keyed by exact registry URL, so
1784
+ * the script exports npm_config_registry from manifest.json's npmRegistry
1785
+ * for itself and its children (npm, ht) — an offline machine whose registry
1786
+ * points elsewhere (corporate mirror) installs from the cache without its
1787
+ * npm config being touched (the override dies with the script process).
1788
+ *
1789
+ * Text constraints: String.raw keeps the sed backslashes verbatim, so the
1790
+ * script must contain NO backticks and NO ${...} — both would terminate or
1791
+ * interpolate inside the enclosing template literal.
1792
+ */
1793
+ const OFFLINE_INSTALL_SH = String.raw `#!/bin/sh
1794
+ # HomeTrans offline bootstrap - generated by 'ht offline-bundle'.
1795
+ # Auto-selects the hometrans tarball for this machine (the os/arch of the
1796
+ # node binary npm installs for - not the shell, so Rosetta and emulated
1797
+ # terminals still pick the right file) and installs it fully offline from
1798
+ # the bundle's npm cache, then runs 'ht init --offline-bundle' in this same
1799
+ # process - one step, so the registry override below covers init too.
1800
+
1801
+ set -e
1802
+
1803
+ DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
1804
+ MANIFEST="$DIR/manifest.json"
1805
+
1806
+ if ! command -v node >/dev/null 2>&1; then
1807
+ echo "error: node not found - install node (>= 22.18 recommended) first." >&2
1808
+ exit 1
1809
+ fi
1810
+ if ! command -v npm >/dev/null 2>&1; then
1811
+ echo "error: npm not found - it ships with node." >&2
1812
+ exit 1
1813
+ fi
1814
+
1815
+ OS=$(node -p process.platform)
1816
+ ARCH=$(node -p process.arch)
1817
+ KEY="$OS-$ARCH"
1818
+
1819
+ # manifest.json maps platform keys to tarball filenames, e.g.
1820
+ # "darwin-arm64": "buaa_smat-hometrans-<version>-darwin-arm64.tgz"
1821
+ TARBALL=""
1822
+ MATCH=$(sed -n 's/.*"'"$KEY"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$MANIFEST" 2>/dev/null | head -n 1)
1823
+ if [ -n "$MATCH" ] && [ -f "$DIR/$MATCH" ]; then
1824
+ TARBALL="$DIR/$MATCH"
1825
+ else
1826
+ for f in "$DIR"/*-"$KEY".tgz; do
1827
+ if [ -f "$f" ]; then
1828
+ TARBALL="$f"
1829
+ break
1830
+ fi
1831
+ done
1832
+ fi
1833
+ if [ -z "$TARBALL" ]; then
1834
+ echo "error: this bundle carries no hometrans tarball for $KEY." >&2
1835
+ ls -1 "$DIR"/*.tgz >&2 2>/dev/null || echo " (no *.tgz files in $DIR)" >&2
1836
+ echo " Recreate the bundle with a newer 'ht offline-bundle', or install" >&2
1837
+ echo " the matching tarball manually: npm install -g --offline --cache" >&2
1838
+ echo " <bundle>/npm-cache <bundle>/<tarball-for-your-platform>" >&2
1839
+ exit 1
1840
+ fi
1841
+
1842
+ echo "Detected platform : $KEY"
1843
+ echo "Tarball : $(basename "$TARBALL")"
1844
+
1845
+ # npm's offline cache is keyed by the exact registry URL each request would
1846
+ # hit. When this machine resolves packages from a different registry (a
1847
+ # corporate mirror, say), the cache would miss with ENOTCACHED even though
1848
+ # every package is inside it. Point npm at the registry the cache was seeded
1849
+ # from - the override is exported for THIS SCRIPT and its children only
1850
+ # (npm, ht): when the script exits, your npm config is exactly as before.
1851
+ BUNDLE_REGISTRY=$(sed -n 's/.*"npmRegistry"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$MANIFEST" 2>/dev/null | head -n 1)
1852
+ if [ -n "$BUNDLE_REGISTRY" ]; then
1853
+ echo "npm registry (cache key): $BUNDLE_REGISTRY - script-scoped, npm config untouched"
1854
+ export npm_config_registry="$BUNDLE_REGISTRY"
1855
+ fi
1856
+
1857
+ echo "Installing offline (no network needed) ..."
1858
+ npm install -g --offline --no-audit --no-fund --cache "$DIR/npm-cache" "$TARBALL"
1859
+
1860
+ echo ""
1861
+ echo "hometrans installed - initializing (ht init --offline-bundle) ..."
1862
+ exec ht init --offline-bundle "$DIR"
1863
+ `;
1864
+ /**
1865
+ * Windows counterpart of OFFLINE_INSTALL_SH, written as install.ps1.
1866
+ * PowerShell has ConvertFrom-Json built in, so the manifest lookup needs no
1867
+ * sed gymnastics. Same one-step flow (tarball install, then `ht init
1868
+ * --offline-bundle` in this same process), same registry override
1869
+ * (npm_config_registry from the manifest's npmRegistry, process-scoped, npm
1870
+ * config untouched), and same text rules as the sh script: no backticks,
1871
+ * no ${...}.
1872
+ */
1873
+ const OFFLINE_INSTALL_PS1 = String.raw `# HomeTrans offline bootstrap - generated by 'ht offline-bundle'.
1874
+ # Auto-selects the hometrans tarball for this machine (the os/arch of the
1875
+ # node binary npm installs for - not the shell) and installs it fully
1876
+ # offline from the bundle's npm cache, then runs 'ht init --offline-bundle'
1877
+ # in this same process - one step, so the registry override below covers
1878
+ # init too.
1879
+
1880
+ [CmdletBinding()]
1881
+ param()
1882
+ $ErrorActionPreference = 'Stop'
1883
+
1884
+ $Dir = $PSScriptRoot
1885
+ $ManifestPath = Join-Path $Dir 'manifest.json'
1886
+
1887
+ foreach ($cmd in @('node', 'npm')) {
1888
+ if (-not (Get-Command $cmd -ErrorAction SilentlyContinue)) {
1889
+ Write-Error ('{0} not found - install node (>= 22.18 recommended) first.' -f $cmd)
1890
+ }
1891
+ }
1892
+
1893
+ $os = (node -p process.platform).Trim()
1894
+ $arch = (node -p process.arch).Trim()
1895
+ $key = "$os-$arch"
1896
+
1897
+ $tgz = $null
1898
+ if (Test-Path $ManifestPath) {
1899
+ $manifest = Get-Content $ManifestPath -Raw | ConvertFrom-Json
1900
+ if ($manifest.hometransTarballs) {
1901
+ $tgz = $manifest.hometransTarballs.$key
1902
+ }
1903
+ }
1904
+ if (-not $tgz -or -not (Test-Path (Join-Path $Dir "$tgz"))) {
1905
+ $available = (Get-ChildItem -Path (Join-Path $Dir '*.tgz') -ErrorAction SilentlyContinue | ForEach-Object { $_.Name }) -join ', '
1906
+ Write-Error ('this bundle carries no hometrans tarball for {0} (available: {1}).' -f $key, $available)
1907
+ }
1908
+
1909
+ $Cache = Join-Path $Dir 'npm-cache'
1910
+ $Tarball = Join-Path $Dir "$tgz"
1911
+
1912
+ # npm's offline cache is keyed by the exact registry URL each request would
1913
+ # hit. When this machine resolves packages from a different registry (a
1914
+ # corporate mirror, say), the cache would miss with ENOTCACHED even though
1915
+ # every package is inside it. Point npm at the registry the cache was seeded
1916
+ # from - the override lives in THIS PROCESS only (npm and ht inherit it):
1917
+ # when the script exits, your npm config is exactly as before.
1918
+ if ($manifest -and $manifest.npmRegistry) {
1919
+ Write-Host ('npm registry (cache key): {0} - script-scoped, npm config untouched' -f $manifest.npmRegistry)
1920
+ $env:npm_config_registry = $manifest.npmRegistry
1921
+ }
1922
+
1923
+ Write-Host "Detected platform : $key"
1924
+ Write-Host "Tarball : $tgz"
1925
+ Write-Host 'Installing offline (no network needed) ...'
1926
+ npm install -g --offline --no-audit --no-fund --cache $Cache $Tarball
1927
+ if ($LASTEXITCODE -ne 0) {
1928
+ exit $LASTEXITCODE
1929
+ }
1930
+
1931
+ Write-Host ''
1932
+ Write-Host 'hometrans installed - initializing (ht init --offline-bundle) ...'
1933
+ & ht init --offline-bundle $Dir
1934
+ if ($LASTEXITCODE -ne 0) {
1935
+ exit $LASTEXITCODE
1936
+ }
1937
+ `;
1938
+ /**
1939
+ * Write the bootstrap scripts into a bundle root: install.sh with LF endings
1940
+ * (POSIX requirement) and the executable bit on non-Windows creators,
1941
+ * install.ps1 with CRLF endings. Exported so a bundle's scripts can be
1942
+ * regenerated in place (e.g. after a template fix) without re-running the
1943
+ * whole `ht offline-bundle` flow.
1944
+ */
1945
+ export function writeOfflineBootstrapScripts(bundleRoot) {
1946
+ fsSync.writeFileSync(path.join(bundleRoot, 'install.sh'), OFFLINE_INSTALL_SH.replace(/\r\n/g, '\n'), 'utf-8');
1947
+ fsSync.writeFileSync(path.join(bundleRoot, 'install.ps1'), OFFLINE_INSTALL_PS1.replace(/\r?\n/g, '\r\n'), 'utf-8');
1948
+ if (process.platform !== 'win32') {
1949
+ try {
1950
+ fsSync.chmodSync(path.join(bundleRoot, 'install.sh'), 0o755);
1951
+ }
1952
+ catch {
1953
+ // best effort — 'sh install.sh' works without the exec bit too
1954
+ }
1955
+ }
1956
+ }
1957
+ /**
1958
+ * Filename prefix of packed hometrans tarballs (e.g. 'buaa_smat-hometrans-'),
1959
+ * derived from the repo package name the same way packLocalHometransAll
1960
+ * derives its tarball stem — used to sweep stale tarballs from a previous
1961
+ * run of this command out of the bundle dir.
1962
+ */
1963
+ function hometransTarballPrefix() {
1964
+ try {
1965
+ const pkgPath = path.resolve(__dirname, '..', '..', 'package.json');
1966
+ const name = JSON.parse(fsSync.readFileSync(pkgPath, 'utf-8')).name ??
1967
+ '@buaa_smat/hometrans';
1968
+ return `${name.replace('@', '').replace('/', '-')}-`;
1969
+ }
1970
+ catch {
1971
+ return 'buaa_smat-hometrans-';
1972
+ }
1973
+ }
1974
+ /**
1975
+ * Create an offline bundle on this (networked) machine.
1976
+ *
1977
+ * npm only: a scratch project `npm install --cache <bundle>/npm-cache` pulls
1978
+ * the full transitive graph into a self-contained cache; the scratch
1979
+ * package-lock.json pins every top-level package to the exact resolved
1980
+ * version so the offline install is deterministic. hometrans itself ships as
1981
+ * a repacked LOCAL tarball (see packLocalHometransAll).
1982
+ *
1983
+ * There is no Python/pip half any more: every shipped skill and agent is
1984
+ * Node-only, so the bundle needs nothing but the npm cache and the
1985
+ * per-platform hometrans tarballs. Bundles created before that change may
1986
+ * still carry a pip-wheels/ directory; it is simply ignored.
1987
+ *
1988
+ * Never prompts; hard-fails only when the npm seeding fails.
1989
+ */
1990
+ export async function createOfflineBundle(dir) {
1991
+ const abs = path.resolve(dir);
1992
+ console.log(chalk.cyan(` Creating offline bundle: ${abs}`));
1993
+ const npmCacheDir = path.join(abs, 'npm-cache');
1994
+ await fs.mkdir(npmCacheDir, { recursive: true });
1995
+ // Sweep hometrans tarballs left by a previous run of this command in the
1996
+ // same dir — the packs below rewrite the current set, and stale versioned
1997
+ // files would otherwise linger and confuse the bootstrap scripts' lookup.
1998
+ const stalePrefix = hometransTarballPrefix();
1999
+ for (const entry of fsSync.readdirSync(abs)) {
2000
+ if (entry.startsWith(stalePrefix) && entry.endsWith('.tgz')) {
2001
+ fsSync.rmSync(path.join(abs, entry), { force: true });
2002
+ }
2003
+ }
2004
+ // --- hometrans itself: pack the LOCAL build into the bundle --------------
2005
+ // The offline machine bootstraps `ht` from one of these tarballs — one per
2006
+ // target platform, each fully self-contained (whole runtime closure + that
2007
+ // platform's native binaries) — so it gets the exact feature set that
2008
+ // created the bundle (registry versions may lag).
2009
+ const localVersion = hometransVersion();
2010
+ const tarballs = packLocalHometransAll(abs);
2011
+ let hometransSpec = null; // what the scratch install seeds
2012
+ if (tarballs) {
2013
+ const files = [...new Set(Object.values(tarballs))];
2014
+ console.log(chalk.gray(files.length === 1
2015
+ ? ` Packed local hometrans: ${files[0]} (one cross-platform tarball)`
2016
+ : ` Packed local hometrans for: ${Object.keys(tarballs).join(', ')}`));
2017
+ }
2018
+ else {
2019
+ console.log(chalk.yellow(' ! npm pack of the local hometrans failed — bundling the registry version instead.'));
2020
+ console.log(chalk.yellow(' The offline machine may lack this CLI\'s offline features. Prefer re-creating the bundle.'));
2021
+ hometransSpec = HOMETRANS_PACKAGE;
2022
+ }
2023
+ // --- npm: seed a self-contained cache via a scratch install -------------
2024
+ // Record the registry the cache is being seeded from: npm's cache is keyed
2025
+ // by exact registry URL, so offline machines must resolve from the same one
2026
+ // (init prechecks this against the manifest and aborts with a fix).
2027
+ const npmRegistry = npmConfigRegistry() ?? undefined;
2028
+ const scratch = path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'hometrans-offline-seed-')));
2029
+ let npmPins = [];
2030
+ // Platform-native optional deps in the seed closure are the only thing a
2031
+ // second `npm install --os/--cpu` round can add to the cache, so capture
2032
+ // whether any exist while the scratch tree is still on disk.
2033
+ let seedNativeHosts = [];
2034
+ try {
2035
+ await fs.writeFile(path.join(scratch, 'package.json'), JSON.stringify({ name: 'hometrans-offline-seed', private: true, version: '0.0.0' }, null, 2), 'utf-8');
2036
+ console.log(chalk.gray(` Seeding npm cache for ${OFFLINE_NPM_SEED_SET.length} packages (full dependency graph) ...`));
2037
+ // The packed tarballs carry hometrans' whole runtime closure, so they need
2038
+ // nothing from the cache — only the registry fallback (pack failed) is
2039
+ // seeded through the scratch install like any other package.
2040
+ const r = spawnSync('npm', [
2041
+ 'install',
2042
+ '--cache',
2043
+ shellArg(npmCacheDir),
2044
+ '--no-audit',
2045
+ '--no-fund',
2046
+ ...(hometransSpec ? [shellArg(hometransSpec)] : []),
2047
+ ...OFFLINE_NPM_SEED_SET,
2048
+ ], { stdio: 'inherit', shell: process.platform === 'win32', timeout: 20 * 60 * 1000, cwd: scratch });
2049
+ if (r.status !== 0) {
2050
+ throw new Error('npm seeding install failed — check the network and registry reachability.');
2051
+ }
2052
+ // Pin each runtime package to the exact resolved version from the lockfile.
2053
+ const lock = JSON.parse(await fs.readFile(path.join(scratch, 'package-lock.json'), 'utf-8'));
2054
+ npmPins = OFFLINE_NPM_SEED_SET.map((spec) => {
2055
+ const name = spec.startsWith('@') ? spec.split('@').slice(0, 2).join('@') : spec.split('@')[0];
2056
+ const version = lock.packages?.[`node_modules/${name}`]?.version;
2057
+ return version ? `${name}@${version}` : spec;
2058
+ });
2059
+ seedNativeHosts = findNativeBinaryHosts(path.join(scratch, 'node_modules'));
2060
+ }
2061
+ finally {
2062
+ await fs.rm(scratch, { recursive: true, force: true }).catch(() => { });
2063
+ }
2064
+ // --- npm: cross-platform cache rounds --------------------------------------
2065
+ // The seed set's platform-specific optional dependencies (e.g. fsevents on
2066
+ // macOS, @img binaries) are only resolved when npm installs FOR that
2067
+ // platform — one scratch round per target combo. `--libc` is required on
2068
+ // non-linux creators: without a detected libc family npm rejects every
2069
+ // libc-gated linux binary. A failed round only warns (the bundle stays
2070
+ // usable on the other platforms).
2071
+ //
2072
+ // With no platform-native dependency in the seed closure the cache is
2073
+ // identical for every target (tarballs and packuments do not vary by os/cpu),
2074
+ // so the creating machine's round above already covers all platforms and the
2075
+ // four extra installs are pure waiting. They come back automatically if a
2076
+ // native-binary host ever enters the seed set.
2077
+ if (seedNativeHosts.length === 0) {
2078
+ console.log(chalk.gray(' npm cache: no platform-native dependencies in the seed set — one round covers every target platform.'));
2079
+ }
2080
+ else {
2081
+ console.log(chalk.gray(` npm cache: native hosts to resolve per platform — ${seedNativeHosts.map((h) => h.name).join(', ')}`));
2082
+ const creatingCombo = BUNDLED_NATIVE_PLATFORMS.find((c) => c.os === process.platform && c.cpu === process.arch && (!c.libc || c.libc === 'glibc'));
2083
+ for (const combo of BUNDLED_NATIVE_PLATFORMS) {
2084
+ if (combo === creatingCombo)
2085
+ continue; // covered by the main seed round above
2086
+ const key = platformComboKey(combo);
2087
+ const platScratch = path.join(await fs.mkdtemp(path.join(os.tmpdir(), `hometrans-offline-seed-${key}-`)));
2088
+ try {
2089
+ await fs.writeFile(path.join(platScratch, 'package.json'), JSON.stringify({ name: 'hometrans-offline-seed', private: true, version: '0.0.0' }, null, 2), 'utf-8');
2090
+ const r = spawnSync('npm', [
2091
+ 'install',
2092
+ '--cache',
2093
+ shellArg(npmCacheDir),
2094
+ '--no-audit',
2095
+ '--no-fund',
2096
+ '--os',
2097
+ combo.os,
2098
+ '--cpu',
2099
+ combo.cpu,
2100
+ ...(combo.libc ? ['--libc', combo.libc] : []),
2101
+ ...OFFLINE_NPM_SEED_SET,
2102
+ ], { stdio: 'inherit', shell: process.platform === 'win32', timeout: 20 * 60 * 1000, cwd: platScratch });
2103
+ if (r.status !== 0) {
2104
+ console.log(chalk.yellow(` ! npm cache round for ${key} failed — that platform's optional deps may be missing offline.`));
2105
+ }
2106
+ }
2107
+ finally {
2108
+ await fs.rm(platScratch, { recursive: true, force: true }).catch(() => { });
2109
+ }
2110
+ }
2111
+ }
2112
+ // --- npm: cross-npm-version cache hardening --------------------------------
2113
+ // Clone every packument's missing accept variant so the cache serves BOTH
2114
+ // npm generations (≤ 10.7 corgi / ≥ 10.8 full — see
2115
+ // clonePackumentAcceptVariants), then drop the cached copies of local
2116
+ // tarballs the scratch installs left behind (~0.5 GB each) plus content
2117
+ // files nothing references anymore.
2118
+ const clonedEntries = clonePackumentAcceptVariants(npmCacheDir, npmRegistry ?? 'https://registry.npmjs.org/');
2119
+ console.log(chalk.gray(` npm cache: ${clonedEntries} packument accept-variant entries cloned (npm ≤ 10.7 and ≥ 10.8 compatible).`));
2120
+ const freedBytes = pruneNpmCacheLocalTarballs(npmCacheDir);
2121
+ console.log(chalk.gray(` npm cache: pruned local-tarball copies — ${(freedBytes / 1048576).toFixed(1)} MB freed.`));
2122
+ // --- manifest -------------------------------------------------------------
2123
+ const manifest = {
2124
+ createdBy: `@buaa_smat/hometrans@${localVersion}`,
2125
+ createdAt: new Date().toISOString(),
2126
+ platform: `${process.platform}-${process.arch}`,
2127
+ npmPackages: npmPins,
2128
+ npmRegistry,
2129
+ hometransVersion: localVersion,
2130
+ // Back-compat single-tarball field (only loadOfflineBundle's existence
2131
+ // check reads it): the creating machine's tarball when its platform is
2132
+ // bundled — combos are packed creating-machine first — else the first
2133
+ // packed combo.
2134
+ hometransTarball: tarballs ? Object.values(tarballs)[0] : undefined,
2135
+ hometransTarballs: tarballs ?? undefined,
2136
+ };
2137
+ await fs.writeFile(path.join(abs, 'manifest.json'), JSON.stringify(manifest, null, 2), 'utf-8');
2138
+ // --- bootstrap scripts: one-command offline entry with platform auto-select
2139
+ if (tarballs) {
2140
+ writeOfflineBootstrapScripts(abs);
2141
+ console.log(chalk.gray(' Bootstrap scripts: install.sh (macOS/Linux) / install.ps1 (Windows) — auto-select the tarball, install offline, then run ht init in the same process (one step).'));
2142
+ }
2143
+ // --- project README: readable copy at the bundle root ----------------------
2144
+ // The tarball embeds it under package/, but a top-level copy documents the
2145
+ // bundle (install flow, migration steps) without unpacking anything. Always
2146
+ // refreshed so the bundle documents the exact build it was created from.
2147
+ try {
2148
+ await fs.copyFile(path.resolve(__dirname, '..', '..', 'README.md'), path.join(abs, 'README.md'));
2149
+ console.log(chalk.gray(' README: copied from the project to the bundle root.'));
2150
+ }
2151
+ catch {
2152
+ console.log(chalk.yellow(' ! README.md not found in the project — bundle-root copy skipped.'));
2153
+ }
2154
+ console.log(chalk.green(' + Offline bundle created.'));
2155
+ // One cross-platform tarball lists every platform key against the same
2156
+ // file; collapse repeated filenames into one readable entry.
2157
+ const byFile = new Map();
2158
+ for (const [key, file] of Object.entries(tarballs ?? {})) {
2159
+ byFile.set(file, [...(byFile.get(file) ?? []), key]);
2160
+ }
2161
+ const forAllPlatforms = (keys) => keys.length === BUNDLED_NATIVE_PLATFORMS.length;
2162
+ const manual = [...byFile]
2163
+ .map(([file, keys]) => forAllPlatforms(keys) ? `${file} → every platform` : keys.map((key) => `${key} → ${file}`).join(' | '))
2164
+ .join(' | ');
2165
+ if (tarballs) {
2166
+ const listed = [...byFile]
2167
+ .map(([file, keys]) => forAllPlatforms(keys)
2168
+ ? `${file} (one cross-platform tarball)`
2169
+ : `${file} (${keys.join(', ')})`)
2170
+ .join(', ');
2171
+ console.log(chalk.gray(` ht: local build v${localVersion} — ${listed}`));
2172
+ }
2173
+ else {
2174
+ console.log(chalk.gray(` ht: registry version (pack failed!)`));
2175
+ }
2176
+ console.log(chalk.gray(` npm: ${manifest.npmPackages.join(', ')}`));
2177
+ if (manifest.npmRegistry) {
2178
+ console.log(chalk.gray(` npm registry: ${manifest.npmRegistry} — offline machines must resolve from the same one (the cache is keyed by registry URL)`));
2179
+ }
2180
+ console.log(chalk.gray(` platform: ${manifest.platform}`));
2181
+ console.log('');
2182
+ console.log(chalk.gray(' On the offline machine (adjust the bundle path to where you copy it):'));
2183
+ if (tarballs) {
2184
+ console.log(chalk.gray(` macOS / Linux: sh "${path.join(abs, 'install.sh')}"`));
2185
+ console.log(chalk.gray(` Windows: powershell -ExecutionPolicy Bypass -File "${path.join(abs, 'install.ps1')}"`));
2186
+ console.log(chalk.gray(' — one step: auto-detects the machine platform, installs the matching tarball offline, then runs'));
2187
+ console.log(chalk.gray(' ht init --offline-bundle in the same process (registry override included)'));
2188
+ console.log(chalk.gray(` manual equivalent: npm install -g --offline --cache "${path.join(abs, 'npm-cache')}" <tarball> — ${manual} — then ht init --offline-bundle "${abs}"`));
2189
+ }
2190
+ else {
2191
+ console.log(chalk.gray(` 1. npm install -g --offline --cache "${path.join(abs, 'npm-cache')}" ${HOMETRANS_PACKAGE}`));
2192
+ console.log(chalk.gray(` 2. ht init --offline-bundle "${abs}"`));
2193
+ }
2194
+ }
2195
+ /**
2196
+ * The running hometrans version (for manifest provenance). Resolved from the
2197
+ * package.json two levels above dist/cli — the same file the CLI --version uses.
2198
+ */
2199
+ function hometransVersion() {
2200
+ try {
2201
+ const pkgPath = path.resolve(__dirname, '..', '..', 'package.json');
2202
+ return JSON.parse(fsSync.readFileSync(pkgPath, 'utf-8')).version ?? 'unknown';
2203
+ }
2204
+ catch {
2205
+ return 'unknown';
2206
+ }
2207
+ }
2208
+ /**
2209
+ * Quote a single argv value for `spawnSync(..., { shell: true })` on Windows —
2210
+ * with a shell, Node joins the args array with spaces, so any value containing
2211
+ * spaces (e.g. bundle paths) must carry its own quotes. Non-Windows platforms
2212
+ * run without a shell and need no quoting.
2213
+ */
2214
+ function shellArg(v) {
2215
+ return process.platform === 'win32' && /\s/.test(v) ? `"${v}"` : v;
2216
+ }
2217
+ export async function initCommand(options = {}) {
2218
+ ensureChalkColor();
2219
+ // Resolve the offline bundle (if any) up front — invalid bundles abort with
2220
+ // an actionable message before anything is installed.
2221
+ let bundle;
2222
+ if (options.offlineBundle) {
2223
+ try {
2224
+ bundle = await loadOfflineBundle(options.offlineBundle);
2225
+ }
2226
+ catch (err) {
2227
+ console.error(chalk.red(` ! ${err.message}`));
2228
+ process.exitCode = 1;
2229
+ return;
2230
+ }
2231
+ console.log(chalk.blue(` Offline mode: using bundle ${bundle.dir}`));
2232
+ console.log(chalk.gray(` created by ${bundle.manifest.createdBy} on ${bundle.manifest.platform}` +
2233
+ ` at ${bundle.manifest.createdAt}` +
2234
+ (bundle.manifest.npmRegistry ? `, npm-cache seeded from ${bundle.manifest.npmRegistry}` : '')));
2235
+ const registryMismatch = bundleNpmRegistryMismatch(bundle);
2236
+ if (registryMismatch) {
2237
+ console.error(chalk.red(` ! ${registryMismatch}`));
2238
+ process.exitCode = 1;
2239
+ return;
2240
+ }
2241
+ if (bundle.manifest.hometransTarballs) {
2242
+ const current = `${process.platform}-${process.arch}`;
2243
+ if (!bundle.manifest.hometransTarballs[current]) {
2244
+ console.log(chalk.yellow(` ! this bundle has no hometrans tarball for ${current} (carries: ${Object.keys(bundle.manifest.hometransTarballs).join(', ')}).`));
2245
+ console.log(chalk.gray(' Fine if `ht` is already installed from another source; otherwise bootstrap it from a matching tarball.'));
2246
+ }
2247
+ }
2248
+ console.log('');
2249
+ }
2250
+ const banner = figlet.textSync('HomeTrans', { font: 'Standard' });
2251
+ console.log(chalk.cyan(`\n${banner.trimEnd()}`));
2252
+ console.log(chalk.gray('\n Android-to-HarmonyOS skill & agent installer for AI editors\n'));
2253
+ const skillsRoot = resolveSkillsRoot();
2254
+ const agentsRoot = resolveAgentsRoot();
2255
+ const commandsRoot = resolveCommandsRoot();
2256
+ const hasSkills = await dirExists(skillsRoot);
2257
+ const hasAgents = await dirExists(agentsRoot);
2258
+ if (!hasSkills && !hasAgents) {
2259
+ console.error(chalk.red(` ! Neither skills/ nor agents/ found at package root.`));
2260
+ console.error(chalk.gray(` Looked in: ${skillsRoot}`));
2261
+ console.error(chalk.gray(` ${agentsRoot}`));
2262
+ console.error(chalk.gray(' Reinstall hometrans or run `npm run build` from the package root.'));
2263
+ process.exitCode = 1;
2264
+ return;
2265
+ }
2266
+ // No config file: the editor list is the bundled editors.json table (same as
2267
+ // `devecocli plugin install`), and the SDK paths start from what the OS
2268
+ // environment already has. A ~/.hometrans/config.json left by an older
2269
+ // release is not read.
2270
+ const editors = defaultEditors();
2271
+ const env = envFromProcess();
2272
+ const detected = await detectInstalledEditors(editors);
2273
+ const installedStatus = detected.status;
2274
+ // Entries detectInstalledEditors could not resolve (no editors.json row) have
2275
+ // no install target: keep them out of the selection list. Their message is
2276
+ // reported under Errors at the end.
2277
+ const configurableEditors = editors.filter((e) => installedStatus.has(e.name));
2278
+ let selectedEditors;
2279
+ if (options.all) {
2280
+ selectedEditors = configurableEditors.map((e) => e.name);
2281
+ console.log(chalk.blue(' --all: selecting all editors.\n'));
2282
+ }
2283
+ else {
2284
+ const choices = configurableEditors.map((editor) => {
2285
+ const installed = installedStatus.get(editor.name);
2286
+ // Show the editors.json displayName (`Claude Code`); the value stays the
2287
+ // canonical id so the selection logic is unaffected.
2288
+ const title = editorDisplayName(editor.name);
2289
+ const label = installed
2290
+ ? `${title} ${chalk.green('(detected)')}`
2291
+ : `${title} ${chalk.gray('(not detected)')}`;
2292
+ return {
2293
+ name: label,
2294
+ value: editor.name,
2295
+ checked: installed,
2296
+ };
2297
+ });
2298
+ try {
2299
+ const answers = await inquirer.prompt([
2300
+ {
2301
+ type: 'checkbox',
2302
+ name: 'selectedEditors',
2303
+ message: 'Select editors to configure:',
2304
+ choices,
2305
+ // Do not wrap around at the ends: without this @inquirer/checkbox
2306
+ // (loop defaults to true) jumps from the last editor back to the
2307
+ // first, which looks like endless downward scrolling.
2308
+ loop: false,
2309
+ // Append a "ctrl-c cancel" entry to the built-in key help line, reusing
2310
+ // @inquirer/checkbox's default formatting (bold key · dim action · dim
2311
+ // " • " separator):
2312
+ // ↑↓ navigate • space select • a all • i invert • ⏎ submit • ctrl-c cancel
2313
+ theme: {
2314
+ style: {
2315
+ keysHelpTip: (keys) => [...keys, ['ctrl-c', 'cancel']]
2316
+ .map(([key, action]) => `${chalk.bold(key)} ${chalk.dim(action)}`)
2317
+ .join(chalk.dim(' • ')),
2318
+ },
2319
+ },
2320
+ },
2321
+ ]);
2322
+ selectedEditors = answers.selectedEditors;
2323
+ }
2324
+ catch (err) {
2325
+ if (isPromptAbort(err))
2326
+ abortInit();
2327
+ console.log(chalk.yellow('\n Interactive selection failed. Auto-selecting all detected editors.'));
2328
+ console.log(chalk.gray(' Tip: use --all to skip interactive selection.\n'));
2329
+ selectedEditors = configurableEditors
2330
+ .filter((e) => installedStatus.get(e.name))
2331
+ .map((e) => e.name);
2332
+ }
2333
+ }
2334
+ // No editors selected — do NOT abort. Every remaining init step still runs
2335
+ // (SDK / model configuration, dependency installation, environment check,
2336
+ // tools copy, machine env vars); only the install target changes: skills
2337
+ // and agents go to the shared ~/.agents location instead of editor dirs.
2338
+ const noEditorsSelected = selectedEditors.length === 0;
2339
+ if (noEditorsSelected) {
2340
+ console.log(chalk.yellow('\n No editors selected.'));
2341
+ console.log(chalk.gray(' Skills & agents will be installed into the shared ~/.agents location\n' +
2342
+ ' (~/.agents/skills + ~/.agents/agents). Re-run `ht init` later to install into an editor.'));
2343
+ }
2344
+ // --- User parameters (SDK paths) ---
2345
+ console.log('');
2346
+ console.log(chalk.blue(' Harmony SDK Configuration'));
2347
+ try {
2348
+ const answers = await inquirer.prompt([
2349
+ {
2350
+ type: 'input',
2351
+ name: 'DEVECO_SDK_HOME',
2352
+ message: 'DEVECO_SDK_HOME (DevEco Studio SDK dir):',
2353
+ default: env.DEVECO_SDK_HOME || undefined,
2354
+ },
2355
+ ]);
2356
+ const sdk = deriveSdkPaths(answers.DEVECO_SDK_HOME);
2357
+ Object.assign(env, sdk);
2358
+ // Echo the derived paths and validate each exists on disk; missing ones are
2359
+ // a strong signal of a typo'd DEVECO_SDK_HOME or a broken DevEco install.
2360
+ if (sdk.DEVECO_SDK_HOME) {
2361
+ const checks = [
2362
+ ['DEVECO_SDK_HOME', sdk.DEVECO_SDK_HOME],
2363
+ ['DEVECO_HOME', sdk.DEVECO_HOME],
2364
+ ['OHOS_SDK_PATH', sdk.OHOS_SDK_PATH],
2365
+ ['HMS_SDK_PATH', sdk.HMS_SDK_PATH],
2366
+ ];
2367
+ // Validate the derived paths on disk silently — the listing itself is not
2368
+ // printed; only a warning surfaces when one or more paths fail to resolve.
2369
+ let missingCount = 0;
2370
+ for (const [, p] of checks) {
2371
+ if (!(await dirExists(p)))
2372
+ missingCount++;
2373
+ }
2374
+ if (missingCount > 0) {
2375
+ console.log('');
2376
+ console.log(chalk.yellow(' ! Check DEVECO_SDK_HOME (it should be the "sdk" folder inside your DevEco Studio install)'));
2377
+ console.log(chalk.yellow(' and re-run `ht init` after fixing it. Skills that build or'));
2378
+ console.log(chalk.yellow(' review code will not work until these paths resolve.'));
2379
+ }
2380
+ }
2381
+ }
2382
+ catch (err) {
2383
+ if (isPromptAbort(err))
2384
+ abortInit();
2385
+ console.log(chalk.yellow(' Parameter prompts skipped (non-interactive mode).'));
2386
+ }
2387
+ // No model configuration: no shipped skill reads a multimodal model key (the
2388
+ // AutoGLM crawler that did is gone), so init neither asks for nor exports one.
2389
+ // Dependency Installation — `ht init` is the single provisioning point; no
2390
+ // skill ever self-installs. Provisioned here: git (diff-based agent
2391
+ // precheck) and the global npm packages (homegraph + arkanalyzer,
2392
+ // a2h-resource, @deveco/deveco-cli, and the reqgen runtime libraries).
2393
+ // Every shipped skill is Node-only, so there is no Python/pip step.
2394
+ // Runs before the Environment Check so the check reflects fresh installs.
2395
+ console.log('');
2396
+ console.log(chalk.cyan(' Dependency Installation'));
2397
+ // git first — required by the diff-based agent precheck and by some npm-install-g flows.
2398
+ try {
2399
+ await installGit(Boolean(bundle));
2400
+ }
2401
+ catch (err) {
2402
+ if (isPromptAbort(err))
2403
+ abortInit();
2404
+ console.log(chalk.yellow(` ! git install skipped: ${err.message}`));
2405
+ }
2406
+ // Global npm CLIs + libraries used by the skills.
2407
+ try {
2408
+ await installGlobalNpmClis(bundle);
2409
+ }
2410
+ catch (err) {
2411
+ if (isPromptAbort(err))
2412
+ abortInit();
2413
+ console.log(chalk.yellow(` ! npm global install skipped: ${err.message}`));
2414
+ }
2415
+ // Detect external tools (adb / hdc / java + DevEco) and report
2416
+ // which skills/agents are impacted by anything missing.
2417
+ try {
2418
+ await runEnvironmentCheck(env);
2419
+ }
2420
+ catch (err) {
2421
+ console.log(chalk.yellow(` ! environment check skipped: ${err.message}`));
2422
+ }
2423
+ // Persist the SDK paths as real OS environment variables (Windows: setx;
2424
+ // macOS/Linux: shell rc block) — the only place they are kept, and where every
2425
+ // skill reads them. Shows what will be written and asks Y/N first.
2426
+ try {
2427
+ await maybePersistMachineEnv(env);
2428
+ }
2429
+ catch (err) {
2430
+ if (isPromptAbort(err))
2431
+ abortInit();
2432
+ console.log(chalk.red(` ! environment variables: ${err.message}`));
2433
+ }
2434
+ console.log('');
2435
+ // Empty selection → install into the shared ~/.agents location instead of
2436
+ // aborting, so the skills/agents are still available on this machine.
2437
+ const editorsToSetup = noEditorsSelected
2438
+ ? [SHARED_AGENTS_FALLBACK]
2439
+ : configurableEditors.filter((e) => selectedEditors.includes(e.name));
2440
+ const result = {
2441
+ configured: [],
2442
+ skipped: [],
2443
+ errors: [...detected.errors],
2444
+ };
2445
+ for (const editor of editorsToSetup) {
2446
+ console.log(chalk.cyan(` Configuring ${editorDisplayName(editor.name)}...`));
2447
+ // One broken target must not abort the whole init (e.g. a hand-edited config
2448
+ // entry with no editors.json row): record it and keep going.
2449
+ try {
2450
+ await installForEditor(editor, skillsRoot, agentsRoot, commandsRoot, result, {
2451
+ force: options.force,
2452
+ });
2453
+ // reqgen resolves its npm runtime deps from the global install via
2454
+ // per-copy node_modules links (skills never self-install).
2455
+ const installedSkillsDir = platformForEditor(editor).skillsDir;
2456
+ if (!installedSkillsDir)
2457
+ continue;
2458
+ try {
2459
+ await linkReqgenGlobalDeps(installedSkillsDir, editorDisplayName(editor.name));
2460
+ }
2461
+ catch (err) {
2462
+ console.log(chalk.yellow(` ! reqgen dependency link: ${err.message}`));
2463
+ }
2464
+ }
2465
+ catch (err) {
2466
+ result.errors.push(`${editorDisplayName(editor.name)}: ${err.message}`);
2467
+ }
2468
+ }
2469
+ console.log('');
2470
+ if (result.configured.length > 0) {
2471
+ console.log(chalk.green(' Configured:'));
2472
+ for (const name of result.configured)
2473
+ console.log(chalk.green(` + ${name}`));
2474
+ }
2475
+ if (result.skipped.length > 0) {
2476
+ console.log('');
2477
+ console.log(chalk.yellow(' Skipped:'));
2478
+ for (const name of result.skipped)
2479
+ console.log(chalk.yellow(` - ${name}`));
2480
+ }
2481
+ if (result.errors.length > 0) {
2482
+ console.log('');
2483
+ console.log(chalk.red(' Errors:'));
2484
+ for (const err of result.errors)
2485
+ console.log(chalk.red(` ! ${err}`));
2486
+ }
2487
+ console.log('');
2488
+ console.log(chalk.gray(` Source skills: ${skillsRoot}`));
2489
+ console.log(chalk.gray(` Source agents: ${agentsRoot}`));
2490
+ console.log('');
2491
+ if (result.errors.length > 0) {
2492
+ console.log(chalk.yellow(' Finished with errors — see the list above.'));
2493
+ if (noEditorsSelected) {
2494
+ console.log(chalk.yellow(' The shared ~/.agents install may be incomplete; re-run `ht init`.'));
2495
+ }
2496
+ }
2497
+ else if (noEditorsSelected) {
2498
+ console.log(chalk.green(' Done. Skills, agents & commands installed into the shared ~/.agents location.'));
2499
+ }
2500
+ else if (result.configured.length === 0) {
2501
+ console.log(chalk.yellow(' No editors were configured. Make sure the selected editors are installed,'));
2502
+ console.log(chalk.yellow(' then re-run `ht init`.'));
2503
+ }
2504
+ else {
2505
+ console.log(chalk.green(' Done. Re-open your editor for the new skills/agents to be picked up.'));
2506
+ }
2507
+ // Errors were collected instead of thrown, so the exit code is the only
2508
+ // signal scripts and CI get. A run where every selected target was skipped
2509
+ // (nothing deployed) is a failure too.
2510
+ if (initFailed(result, noEditorsSelected))
2511
+ process.exitCode = 1;
2512
+ console.log('');
2513
+ }