@buaa_smat/hometrans 26.0.0-devecocli.2 → 26.0.0-devecocli.3

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 (497) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +1 -1
  3. package/plugin.jsonc +1 -1
  4. package/skills/a2h-app-migrate/references/specs.example.json +19 -19
  5. package/skills/a2h-app-migrate/scripts/env_preflight.mjs +38 -14
  6. package/skills/a2h-app-migrate/scripts/infer_android_root.mjs +3 -3
  7. package/skills/a2h-app-migrate/scripts/json_io.mjs +35 -35
  8. package/skills/a2h-app-migrate/scripts/lib-yaml-lite.mjs +288 -288
  9. package/skills/a2h-app-migrate/scripts/paths_preflight.mjs +183 -15
  10. package/skills/a2h-app-migrate/test/test_arch_done.mjs +54 -54
  11. package/skills/a2h-app-migrate/test/test_env_requirements.mjs +40 -1
  12. package/skills/a2h-app-migrate/test/test_gate_checkpoint.mjs +146 -146
  13. package/skills/a2h-app-migrate/test/test_hmos_fingerprint.mjs +68 -68
  14. package/skills/a2h-app-migrate/test/test_json_io.mjs +32 -32
  15. package/skills/a2h-app-migrate/test/test_module_docs_done.mjs +53 -53
  16. package/skills/a2h-app-migrate/test/test_parse_args.mjs +69 -69
  17. package/skills/a2h-app-migrate/test/test_preflight_report.mjs +11 -1
  18. package/skills/a2h-app-migrate/test/test_spec_pipeline_done.mjs +181 -181
  19. package/skills/a2h-app-migrate/test/test_ui_batch_done.mjs +53 -53
  20. package/skills/a2h-app-migrate/test/test_ui_batch_gate.mjs +226 -226
  21. package/skills/a2h-app-migrate/test/test_uniapp_preflight.mjs +83 -0
  22. package/skills/a2h-app-migrate/test/test_utg_dirs.mjs +39 -39
  23. package/skills/a2h-arch-generate/examples/reconcile-existing-project.md +107 -107
  24. package/skills/a2h-arch-generate/examples/simple-conversion-android.md +103 -103
  25. package/skills/a2h-arch-generate/examples/simple-conversion-backend.md +70 -70
  26. package/skills/a2h-arch-generate/examples/simple-conversion-uniapp.md +106 -106
  27. package/skills/a2h-arch-generate/references/arkts-mvvm-v2.md +1407 -1407
  28. package/skills/a2h-arch-generate/references/artifact-contracts.generate.md +120 -120
  29. package/skills/a2h-arch-generate/references/artifact-contracts.reconcile.md +123 -123
  30. package/skills/a2h-arch-generate/references/bpta-layered-architecture-design.md +87 -87
  31. package/skills/a2h-arch-generate/references/database-schema-recovery.md +107 -107
  32. package/skills/a2h-arch-generate/references/existing-target-annotation.md +68 -68
  33. package/skills/a2h-arch-generate/references/harmony-project-inspection.md +150 -150
  34. package/skills/a2h-arch-generate/references/harmony-target-architecture.md +94 -94
  35. package/skills/a2h-arch-generate/references/reconciliation-model.md +204 -204
  36. package/skills/a2h-arch-generate/references/scope-policy.md +28 -28
  37. package/skills/a2h-arch-generate/references/semantic-review.md +65 -65
  38. package/skills/a2h-arch-generate/references/source-ecosystems.md +54 -54
  39. package/skills/a2h-arch-generate/references/transformation-model.md +78 -78
  40. package/skills/a2h-arch-generate/scripts/create_project.mjs +149 -149
  41. package/skills/a2h-arch-generate/scripts/generate_state.mjs +60 -60
  42. package/skills/a2h-arch-generate/scripts/inspect_and_route.mjs +326 -326
  43. package/skills/a2h-arch-generate/scripts/inspect_uniapp_project.mjs +809 -809
  44. package/skills/a2h-arch-generate/scripts/lib/py_compat.mjs +1454 -1454
  45. package/skills/a2h-arch-generate/scripts/module_create/create.mjs +136 -136
  46. package/skills/a2h-arch-generate/scripts/module_create/generate.mjs +636 -636
  47. package/skills/a2h-arch-generate/scripts/module_create/hap/build-profile.json5 +32 -32
  48. package/skills/a2h-arch-generate/scripts/module_create/hap/hvigorfile.ts +5 -5
  49. package/skills/a2h-arch-generate/scripts/module_create/hap/obfuscation-rules.txt +22 -22
  50. package/skills/a2h-arch-generate/scripts/module_create/hap/oh-package.json5 +10 -10
  51. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/ets/applicationability/ApplicationAbility.ets +43 -43
  52. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/ets/pages/Index.ets +22 -22
  53. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/module.json5 +25 -25
  54. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/element/color.json +7 -7
  55. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/element/float.json +8 -8
  56. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/element/string.json +15 -15
  57. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/media/layered_image.json +6 -6
  58. package/skills/a2h-arch-generate/scripts/module_create/hap/src/main/resources/base/profile/main_pages.json +5 -5
  59. package/skills/a2h-arch-generate/scripts/module_create/hap/src/mock/mock-config.json5 +1 -1
  60. package/skills/a2h-arch-generate/scripts/module_create/hap/src/ohosTest/ets/test/Ability.test.ets +34 -34
  61. package/skills/a2h-arch-generate/scripts/module_create/hap/src/ohosTest/ets/test/List.test.ets +4 -4
  62. package/skills/a2h-arch-generate/scripts/module_create/hap/src/ohosTest/module.json5 +11 -11
  63. package/skills/a2h-arch-generate/scripts/module_create/hap/src/test/List.test.ets +4 -4
  64. package/skills/a2h-arch-generate/scripts/module_create/hap/src/test/LocalUnit.test.ets +32 -32
  65. package/skills/a2h-arch-generate/scripts/module_create/har/Index.ets +1 -1
  66. package/skills/a2h-arch-generate/scripts/module_create/har/build-profile.json5 +36 -36
  67. package/skills/a2h-arch-generate/scripts/module_create/har/hvigorfile.ts +5 -5
  68. package/skills/a2h-arch-generate/scripts/module_create/har/obfuscation-rules.txt +22 -22
  69. package/skills/a2h-arch-generate/scripts/module_create/har/oh-package.json5 +9 -9
  70. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/ets/components/MainPage.ets +19 -19
  71. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/module.json5 +9 -9
  72. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/resources/base/element/float.json +8 -8
  73. package/skills/a2h-arch-generate/scripts/module_create/har/src/main/resources/base/element/string.json +8 -8
  74. package/skills/a2h-arch-generate/scripts/module_create/har/src/ohosTest/ets/test/Ability.test.ets +34 -34
  75. package/skills/a2h-arch-generate/scripts/module_create/har/src/ohosTest/ets/test/List.test.ets +4 -4
  76. package/skills/a2h-arch-generate/scripts/module_create/har/src/ohosTest/module.json5 +11 -11
  77. package/skills/a2h-arch-generate/scripts/module_create/har/src/test/List.test.ets +4 -4
  78. package/skills/a2h-arch-generate/scripts/module_create/har/src/test/LocalUnit.test.ets +32 -32
  79. package/skills/a2h-arch-generate/scripts/module_create/hsp/build-profile.json5 +35 -35
  80. package/skills/a2h-arch-generate/scripts/module_create/hsp/hvigorfile.ts +5 -5
  81. package/skills/a2h-arch-generate/scripts/module_create/hsp/obfuscation-rules.txt +22 -22
  82. package/skills/a2h-arch-generate/scripts/module_create/hsp/oh-package.json5 +9 -9
  83. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/ets/pages/Index.ets +19 -19
  84. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/ets/utils/Calc.ets +2 -2
  85. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/module.json5 +11 -11
  86. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/resources/base/element/float.json +8 -8
  87. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/resources/base/element/string.json +7 -7
  88. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/main/resources/base/profile/main_pages.json +5 -5
  89. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/ohosTest/ets/test/Ability.test.ets +34 -34
  90. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/ohosTest/ets/test/List.test.ets +4 -4
  91. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/ohosTest/module.json5 +10 -10
  92. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/test/List.test.ets +4 -4
  93. package/skills/a2h-arch-generate/scripts/module_create/hsp/src/test/LocalUnit.test.ets +32 -32
  94. package/skills/a2h-arch-generate/scripts/module_create/testdata/reconcile-layer-PROJECT_DESIGN.md +47 -47
  95. package/skills/a2h-arch-generate/scripts/module_create/testdata/single-entry-PROJECT_DESIGN.md +15 -15
  96. package/skills/a2h-arch-generate/scripts/module_create/testdata/three-layer-PROJECT_DESIGN.md +36 -36
  97. package/skills/a2h-arch-generate/scripts/resolve_android_stores.mjs +529 -529
  98. package/skills/a2h-arch-generate/scripts/scaffold_project.mjs +230 -230
  99. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/build.gradle +11 -11
  100. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/AndroidManifest.xml +12 -12
  101. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/java/com/example/notes/MainActivity.kt +8 -8
  102. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/app/src/main/java/com/example/notes/NotesStore.kt +17 -17
  103. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/build.gradle +3 -3
  104. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/android_source/settings.gradle +1 -1
  105. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/AppScope/app.json5 +8 -8
  106. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/build-profile.json5 +14 -14
  107. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/build-profile.json5 +7 -7
  108. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/oh-package.json5 +1 -1
  109. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/common/utils/src/main/ets/utils/Format.ets +3 -3
  110. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/build-profile.json5 +7 -7
  111. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/oh-package.json5 +1 -1
  112. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/home/src/main/ets/pages/Home.ets +3 -3
  113. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/build-profile.json5 +7 -7
  114. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/oh-package.json5 +1 -1
  115. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/features/sync/src/main/ets/engine/SyncEngine.ets +3 -3
  116. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/hvigorfile.ts +1 -1
  117. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/oh-package.json5 +1 -1
  118. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/build-profile.json5 +7 -7
  119. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/oh-package.json5 +9 -9
  120. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/harmony_target/products/app/src/main/ets/pages/Index.ets +7 -7
  121. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/App.vue +10 -10
  122. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/manifest.json +6 -6
  123. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/pages/index/index.vue +16 -16
  124. package/skills/a2h-arch-generate/scripts/tests/e2e/fixtures/uniapp_source/pages.json +5 -5
  125. package/skills/a2h-arch-generate/scripts/tests/test_console_encoding.mjs +52 -52
  126. package/skills/a2h-arch-generate/scripts/tests/test_git_root.mjs +34 -34
  127. package/skills/a2h-arch-generate/scripts/tests/test_router.mjs +138 -138
  128. package/skills/a2h-arch-generate/scripts/validate_data_docs.mjs +937 -937
  129. package/skills/a2h-arch-generate/scripts/validate_homegraph_artifacts.mjs +542 -542
  130. package/skills/a2h-arch-generate/scripts/validate_incremental_docs.mjs +415 -415
  131. package/skills/a2h-arkts-logic-coder/references/ISSUES.md +6 -6
  132. package/skills/a2h-arkts-logic-coder/scripts/check_module_scope.ts +224 -224
  133. package/skills/a2h-arkts-logic-coder/scripts/check_mvvm.ts +377 -377
  134. package/skills/a2h-arkts-logic-coder/scripts/stop_check_hook.ts +443 -443
  135. package/skills/a2h-arkts-logic-coder/scripts/test_check_scripts.ts +211 -211
  136. package/skills/a2h-arkts-logic-coder/scripts/test_worktree_compat.ts +81 -81
  137. package/skills/a2h-batch-ui-align/SKILL.md +19 -7
  138. package/skills/a2h-batch-ui-align/flowchart.html +271 -271
  139. package/skills/a2h-batch-ui-align/references/conversion-procedure.md +57 -8
  140. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-atomic-component-mapping-reference.md +2535 -2533
  141. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-interaction-mapping-reference.md +558 -558
  142. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-layout-mapping-reference.md +117 -117
  143. 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 +648 -648
  144. 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 +2088 -2088
  145. 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 +1033 -1033
  146. 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 +1183 -1183
  147. 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 +576 -576
  148. 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 +297 -297
  149. 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 +395 -395
  150. 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 +902 -902
  151. 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 +106 -106
  152. 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 +1178 -1178
  153. package/skills/a2h-batch-ui-align/references/mvvm/MVVM/346/250/241/345/274/217/357/274/210V1/357/274/211.md +911 -911
  154. 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 +354 -354
  155. 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 +11 -11
  156. 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 +206 -206
  157. 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 +373 -373
  158. 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 +158 -158
  159. 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 +750 -750
  160. 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 +1704 -1704
  161. 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 +1012 -1012
  162. 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 +164 -164
  163. 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 +840 -840
  164. 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 +856 -856
  165. 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 +83 -83
  166. 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 +294 -294
  167. package/skills/a2h-batch-ui-align/references/mvvm-v2/MVVM/346/250/241/345/274/217/357/274/210V2/357/274/211.md +1407 -1407
  168. 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 +1220 -1220
  169. 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 +47 -47
  170. 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 +133 -133
  171. 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 +840 -840
  172. package/skills/a2h-batch-ui-align/references/step3-capture.md +4 -1
  173. package/skills/a2h-batch-ui-align/references/step4-prepare.md +7 -3
  174. package/skills/a2h-batch-ui-align/references/step5-convert.md +8 -5
  175. package/skills/a2h-batch-ui-align/scripts/answers_check.mjs +86 -86
  176. package/skills/a2h-batch-ui-align/scripts/arkts_static_check.ts +1171 -2
  177. package/skills/a2h-batch-ui-align/scripts/build_conversion_set.mjs +1675 -1656
  178. package/skills/a2h-batch-ui-align/scripts/databinding_analyzer_design.md +79 -79
  179. package/skills/a2h-batch-ui-align/scripts/detach.mjs +258 -258
  180. package/skills/a2h-batch-ui-align/scripts/export_ui_info.mjs +130 -10
  181. package/skills/a2h-batch-ui-align/scripts/generate_pages_json.mjs +612 -612
  182. package/skills/a2h-batch-ui-align/scripts/group_commit.mjs +166 -166
  183. package/skills/a2h-batch-ui-align/scripts/group_pack.mjs +1627 -1437
  184. package/skills/a2h-batch-ui-align/scripts/group_queue.mjs +1869 -1869
  185. package/skills/a2h-batch-ui-align/scripts/harmony_index.mjs +218 -218
  186. package/skills/a2h-batch-ui-align/scripts/host_env.mjs +208 -208
  187. package/skills/a2h-batch-ui-align/scripts/phase5_check.mjs +1179 -1124
  188. package/skills/a2h-batch-ui-align/scripts/shell_contract.mjs +1036 -996
  189. package/skills/a2h-batch-ui-align/scripts/tests/agent_cli.test.mjs +217 -217
  190. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_align_tint.test.mjs +253 -253
  191. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_canvas_pct.test.mjs +312 -0
  192. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_fidelity.test.mjs +241 -0
  193. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_layout_placement.test.mjs +341 -0
  194. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_review_fixes.test.mjs +298 -0
  195. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_rules.test.mjs +365 -365
  196. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_shell.test.mjs +91 -72
  197. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_weight_color.test.mjs +92 -0
  198. package/skills/a2h-batch-ui-align/scripts/tests/build_conversion_set.test.mjs +356 -345
  199. package/skills/a2h-batch-ui-align/scripts/tests/build_conversion_set_scope.test.mjs +290 -290
  200. package/skills/a2h-batch-ui-align/scripts/tests/export_scroll_states.test.mjs +31 -0
  201. package/skills/a2h-batch-ui-align/scripts/tests/export_ui_info.test.mjs +57 -0
  202. package/skills/a2h-batch-ui-align/scripts/tests/generate_pages_json.test.mjs +123 -123
  203. package/skills/a2h-batch-ui-align/scripts/tests/group_commit.test.mjs +126 -126
  204. package/skills/a2h-batch-ui-align/scripts/tests/group_pack.test.mjs +241 -189
  205. package/skills/a2h-batch-ui-align/scripts/tests/group_queue.test.mjs +1451 -1451
  206. package/skills/a2h-batch-ui-align/scripts/tests/group_watch.test.mjs +215 -215
  207. package/skills/a2h-batch-ui-align/scripts/tests/harmony_index.test.mjs +95 -95
  208. package/skills/a2h-batch-ui-align/scripts/tests/host_env.test.mjs +115 -115
  209. package/skills/a2h-batch-ui-align/scripts/tests/phase5_check.test.mjs +244 -244
  210. package/skills/a2h-batch-ui-align/scripts/tests/shell_contract.test.mjs +166 -130
  211. package/skills/a2h-batch-ui-align/scripts/tests/test_bfs_exit.ts +49 -49
  212. package/skills/a2h-batch-ui-align/scripts/tests/text_color_diff.test.mjs +219 -0
  213. package/skills/a2h-batch-ui-align/scripts/text_color_diff.mjs +470 -0
  214. package/skills/a2h-dashboard-render/references/artifact-registry-spec.md +67 -67
  215. package/skills/a2h-dashboard-render/references/dashboard.config.example.json +19 -19
  216. package/skills/a2h-dashboard-render/scripts/artifact_contract.mjs +138 -138
  217. package/skills/a2h-dashboard-render/scripts/check-registry.mjs +87 -87
  218. package/skills/a2h-dashboard-render/test/fixtures/page_capture/expected.json +155 -155
  219. package/skills/a2h-dashboard-render/test/fixtures/page_capture/hmos.json +1 -1
  220. package/skills/a2h-dashboard-render/test/fixtures/page_capture/list.xml +1 -1
  221. package/skills/a2h-dashboard-render/test/fixtures/page_capture/nested_scroll.xml +1 -1
  222. package/skills/a2h-dashboard-render/test/test_cli_check_registry.mjs +99 -99
  223. package/skills/a2h-dashboard-render/test/test_dashboard_build.mjs +64 -64
  224. package/skills/a2h-dashboard-render/test/test_page_capture.mjs +147 -147
  225. package/skills/a2h-fix-build-errors/references/arkts-strict-patterns.md +219 -219
  226. package/skills/a2h-fix-build-errors/references/known-patterns.md +157 -157
  227. package/skills/a2h-fix-build-errors/references/rdb-entity-pattern.md +131 -131
  228. package/skills/a2h-module-semantic-docs/scripts/commit_module_state.mjs +168 -168
  229. package/skills/a2h-module-semantic-docs/scripts/lib/py_compat.mjs +688 -688
  230. package/skills/a2h-module-semantic-docs/scripts/scan_modules.mjs +1021 -1021
  231. package/skills/a2h-module-semantic-docs/test/golden/module_structure.json +187 -187
  232. package/skills/a2h-module-semantic-docs/test/golden/module_understanding.json +351 -351
  233. package/skills/a2h-module-semantic-docs/test/golden/module_update_plan.json +495 -495
  234. package/skills/a2h-module-semantic-docs/test/golden/project_directory_structure.json +157 -157
  235. package/skills/a2h-module-semantic-docs/test/test_scan_and_commit.mjs +388 -388
  236. package/skills/a2h-resource-convert/references/code-vector-icon-rules.md +335 -335
  237. package/skills/a2h-resource-convert/references/conversion-rules.md +687 -687
  238. package/skills/a2h-resource-convert/references/dependency-analysis-rules.md +410 -410
  239. package/skills/a2h-resource-convert/references/incremental-page-migration.md +250 -250
  240. package/skills/a2h-resource-convert/references/lottie-conversion-rules.md +219 -219
  241. package/skills/a2h-resource-convert/references/resource-mapping-rules.md +493 -493
  242. package/skills/a2h-resource-convert/references/step3_5-dependency-filter.md +54 -54
  243. package/skills/a2h-resource-convert/references/step4-qualifiers-and-values.md +142 -142
  244. package/skills/a2h-resource-convert/references/step4-resource-types.md +249 -249
  245. package/skills/a2h-resource-convert/references/step5-reference-resolution.md +154 -154
  246. package/skills/a2h-resource-convert/references/step7-report-template.md +217 -217
  247. package/skills/a2h-resource-convert/references/xml-drawable-to-svg-rules.md +630 -630
  248. package/skills/a2h-resource-convert/scripts/a2h_resource_convert.ts +2529 -2529
  249. package/skills/a2h-resource-convert/scripts/a2h_resource_incremental.ts +1072 -1072
  250. package/skills/a2h-resource-convert/scripts/code_vector_icons.ts +607 -607
  251. package/skills/a2h-resource-convert/scripts/extract_page_resources.ts +989 -989
  252. package/skills/a2h-resource-convert/scripts/extract_project_resources.ts +1464 -1464
  253. package/skills/a2h-resource-convert/scripts/svg_fidelity_check.ts +632 -632
  254. package/skills/a2h-resource-convert/scripts/tests/adaptive_icon.test.mjs +182 -182
  255. package/skills/a2h-spec-design/scripts/inspect_spec_design_inputs.mjs +146 -146
  256. package/skills/a2h-spec-design/scripts/lib/py_compat.mjs +481 -481
  257. package/skills/a2h-spec-design/scripts/move_spec_technical_reference.mjs +159 -159
  258. package/skills/a2h-spec-design/scripts/resolve_module_design.mjs +102 -102
  259. package/skills/a2h-spec-design/scripts/validate_spec_design_output.mjs +285 -285
  260. package/skills/a2h-spec-design/test/golden/inspect_happy.json +20 -20
  261. package/skills/a2h-spec-design/test/golden/move_design.md +18 -18
  262. package/skills/a2h-spec-design/test/golden/move_spec.md +7 -7
  263. package/skills/a2h-spec-design/test/golden/resolve_cases.json +36 -36
  264. package/skills/a2h-spec-design/test/golden/validate_issue_file.md +12 -12
  265. package/skills/a2h-spec-design/test/golden/validate_issues.json +57 -57
  266. package/skills/a2h-spec-design/test/test_spec_design_scripts.mjs +381 -381
  267. package/skills/a2h-spec-design-pipeline/package.json +4 -4
  268. package/skills/a2h-spec-design-pipeline/references/execution-model.md +69 -69
  269. package/skills/a2h-spec-design-pipeline/references/final-report-template.md +24 -24
  270. package/skills/a2h-spec-design-pipeline/references/specs.example.json +19 -19
  271. package/skills/a2h-spec-design-pipeline/scripts/atomic_write.ts +42 -42
  272. package/skills/a2h-spec-design-pipeline/scripts/audit_claims.ts +252 -252
  273. package/skills/a2h-spec-design-pipeline/scripts/branch_landed.ts +77 -77
  274. package/skills/a2h-spec-design-pipeline/scripts/deps_ready.ts +195 -195
  275. package/skills/a2h-spec-design-pipeline/scripts/git_baseline.ts +124 -124
  276. package/skills/a2h-spec-design-pipeline/scripts/lib/bgcli.mjs +95 -95
  277. package/skills/a2h-spec-design-pipeline/scripts/plan_waves.ts +475 -475
  278. package/skills/a2h-spec-design-pipeline/scripts/resolve_wiring.ts +164 -164
  279. package/skills/a2h-spec-design-pipeline/scripts/test_atomic_write.ts +44 -44
  280. package/skills/a2h-spec-design-pipeline/scripts/test_audit_claims.ts +301 -301
  281. package/skills/a2h-spec-design-pipeline/scripts/test_bgcli.mjs +64 -64
  282. package/skills/a2h-spec-design-pipeline/scripts/test_branch_landed.ts +87 -87
  283. package/skills/a2h-spec-design-pipeline/scripts/test_deps_ready.ts +265 -265
  284. package/skills/a2h-spec-design-pipeline/scripts/test_git_baseline.ts +105 -105
  285. package/skills/a2h-spec-design-pipeline/scripts/test_plan_waves.ts +561 -561
  286. package/skills/a2h-spec-design-pipeline/scripts/test_resolve_wiring.ts +138 -138
  287. package/skills/a2h-spec-design-pipeline/scripts/test_watchdog.mjs +289 -289
  288. package/skills/a2h-spec-design-pipeline/scripts/watchdog.mjs +441 -441
  289. package/skills/a2h-spec-generate/scripts/parse_requirements.ts +515 -515
  290. package/skills/a2h-spec-generate/template/REQ.txt +22 -22
  291. package/skills/a2h-spec-generate/test/detect-project.test.mjs +37 -37
  292. package/skills/a2h-spec-generate/test/fixtures/android/app/src/main/AndroidManifest.xml +3 -3
  293. package/skills/a2h-spec-generate/test/fixtures/android/build.gradle +3 -3
  294. package/skills/a2h-spec-generate/test/fixtures/android/settings.gradle +3 -3
  295. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/package.json +9 -9
  296. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/App.vue +8 -8
  297. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/components/MyCard.vue +9 -9
  298. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/feature/editor/index.vue +1 -1
  299. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/main.ts +6 -6
  300. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/manifest.json +4 -4
  301. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/detail/index.vue +1 -1
  302. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/home/index.vue +33 -33
  303. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages/settings/index.vue +1 -1
  304. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/pages.json +23 -23
  305. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/src/services/items.ts +3 -3
  306. package/skills/a2h-spec-generate/test/fixtures/uniapp-src/tsconfig.json +8 -8
  307. package/skills/a2h-spec-generate/test/fixtures/unknown/README.txt +1 -1
  308. package/skills/a2h-spec-generate/test/inspect-uniapp.test.mjs +54 -54
  309. package/skills/a2h-utg-explorer/SKILL.md +1 -1
  310. package/skills/a2h-utg-explorer/assets/final_viewer.html +64 -64
  311. package/skills/a2h-utg-explorer/assets/u2.LICENSE +21 -21
  312. package/skills/a2h-utg-explorer/assets/u2.NOTICE +25 -25
  313. package/skills/a2h-utg-explorer/references/protocol.md +9 -9
  314. package/skills/a2h-utg-explorer/scripts/app_settings.mjs +143 -143
  315. package/skills/a2h-utg-explorer/scripts/close_phases.mjs +66 -66
  316. package/skills/a2h-utg-explorer/scripts/d_prereqs.mjs +597 -597
  317. package/skills/a2h-utg-explorer/scripts/device_health.mjs +227 -227
  318. package/skills/a2h-utg-explorer/scripts/evidence.mjs +108 -108
  319. package/skills/a2h-utg-explorer/scripts/final_utg.mjs +61 -9
  320. package/skills/a2h-utg-explorer/scripts/hint_check.mjs +89 -89
  321. package/skills/a2h-utg-explorer/scripts/plan.mjs +258 -258
  322. package/skills/a2h-utg-explorer/scripts/promote_dynamic.mjs +170 -170
  323. package/skills/a2h-utg-explorer/scripts/recover_d.mjs +369 -302
  324. package/skills/a2h-utg-explorer/scripts/report.mjs +143 -143
  325. package/skills/a2h-utg-explorer/scripts/run_cycle.mjs +13 -0
  326. package/skills/a2h-utg-explorer/scripts/run_device.mjs +137 -137
  327. package/skills/a2h-utg-explorer/scripts/tests/attest.test.mjs +66 -66
  328. package/skills/a2h-utg-explorer/scripts/tests/chain.test.mjs +45 -45
  329. package/skills/a2h-utg-explorer/scripts/tests/compose_identity.test.mjs +37 -1
  330. package/skills/a2h-utg-explorer/scripts/tests/coverage_rules.test.mjs +104 -104
  331. package/skills/a2h-utg-explorer/scripts/tests/d_prereqs.test.mjs +223 -223
  332. package/skills/a2h-utg-explorer/scripts/tests/device_health.test.mjs +88 -88
  333. package/skills/a2h-utg-explorer/scripts/tests/device_lock_retry.test.mjs +187 -187
  334. package/skills/a2h-utg-explorer/scripts/tests/direct_launch.test.mjs +130 -130
  335. package/skills/a2h-utg-explorer/scripts/tests/explorer_review_fixes.test.mjs +136 -136
  336. package/skills/a2h-utg-explorer/scripts/tests/final_utg.test.mjs +135 -135
  337. package/skills/a2h-utg-explorer/scripts/tests/generalization_fixes.test.mjs +251 -251
  338. package/skills/a2h-utg-explorer/scripts/tests/hint_check.test.mjs +42 -42
  339. package/skills/a2h-utg-explorer/scripts/tests/interruptions.test.mjs +162 -162
  340. package/skills/a2h-utg-explorer/scripts/tests/node_coverage.test.mjs +193 -193
  341. package/skills/a2h-utg-explorer/scripts/tests/overflow_prefix.test.mjs +204 -204
  342. package/skills/a2h-utg-explorer/scripts/tests/page_identity_tiers.test.mjs +355 -355
  343. package/skills/a2h-utg-explorer/scripts/tests/pipeline.test.mjs +240 -240
  344. package/skills/a2h-utg-explorer/scripts/tests/recover_b.test.mjs +173 -173
  345. package/skills/a2h-utg-explorer/scripts/tests/recover_d.test.mjs +267 -207
  346. package/skills/a2h-utg-explorer/scripts/tests/review_fixes.test.mjs +213 -213
  347. package/skills/a2h-utg-explorer/scripts/tests/robustness_fixes.test.mjs +345 -345
  348. package/skills/a2h-utg-explorer/scripts/tests/runner_capabilities.test.mjs +131 -131
  349. package/skills/a2h-utg-explorer/scripts/tests/scope.test.mjs +229 -229
  350. package/skills/a2h-utg-explorer/scripts/tests/scroll_sweep.test.mjs +336 -321
  351. package/skills/a2h-utg-explorer/scripts/tests/semantics.test.mjs +102 -102
  352. package/skills/a2h-utg-explorer/scripts/tests/state_ambiguity.test.mjs +92 -0
  353. package/skills/a2h-utg-explorer/scripts/tests/u2_backend.test.mjs +346 -346
  354. package/skills/a2h-utg-explorer/scripts/tests/worklist_parts.test.mjs +24 -24
  355. package/skills/a2h-utg-explorer/scripts/utg_explorer/_device_io.mjs +244 -244
  356. package/skills/a2h-utg-explorer/scripts/utg_explorer/_py.mjs +2097 -2097
  357. package/skills/a2h-utg-explorer/scripts/utg_explorer/adapters.mjs +18 -0
  358. package/skills/a2h-utg-explorer/scripts/utg_explorer/attest.mjs +63 -63
  359. package/skills/a2h-utg-explorer/scripts/utg_explorer/chain.mjs +63 -63
  360. package/skills/a2h-utg-explorer/scripts/utg_explorer/coverage.mjs +89 -89
  361. package/skills/a2h-utg-explorer/scripts/utg_explorer/device_lock.mjs +46 -46
  362. package/skills/a2h-utg-explorer/scripts/utg_explorer/semantics.mjs +66 -2
  363. package/skills/a2h-utg-explorer/scripts/utg_explorer/task_runner.mjs +49 -4
  364. package/skills/a2h-utg-explorer/scripts/variant.mjs +75 -75
  365. package/skills/a2h-utg-explorer/scripts/worklist_parts.mjs +122 -122
  366. package/skills/a2h-utg-static/config.json +19 -19
  367. package/skills/a2h-utg-static/references/ui-elements-static-utg-schema.md +248 -248
  368. package/skills/a2h-utg-static/references/view-interactions.md +215 -215
  369. package/skills/a2h-utg-static/scripts/_graph.mjs +361 -361
  370. package/skills/a2h-utg-static/scripts/_py.mjs +2177 -2177
  371. package/skills/a2h-utg-static/scripts/_spawn.mjs +45 -45
  372. package/skills/a2h-utg-static/scripts/activity_widgets.mjs +254 -254
  373. package/skills/a2h-utg-static/scripts/adapter_nav.mjs +229 -229
  374. package/skills/a2h-utg-static/scripts/androidfragment_nav.mjs +208 -208
  375. package/skills/a2h-utg-static/scripts/audit.mjs +268 -268
  376. package/skills/a2h-utg-static/scripts/carry_answers.mjs +201 -201
  377. package/skills/a2h-utg-static/scripts/compose_body_text.mjs +54 -0
  378. package/skills/a2h-utg-static/scripts/dialog_listener_nav.mjs +237 -237
  379. package/skills/a2h-utg-static/scripts/guard_subjects.mjs +162 -162
  380. package/skills/a2h-utg-static/scripts/hg_query.mjs +137 -137
  381. package/skills/a2h-utg-static/scripts/hybrid_bundle.mjs +165 -165
  382. package/skills/a2h-utg-static/scripts/hybrid_pages.mjs +713 -713
  383. package/skills/a2h-utg-static/scripts/hybrid_scope.mjs +660 -660
  384. package/skills/a2h-utg-static/scripts/interaction_sites.mjs +267 -267
  385. package/skills/a2h-utg-static/scripts/io_utils.mjs +59 -59
  386. package/skills/a2h-utg-static/scripts/measure/measure_corpus.mjs +297 -297
  387. package/skills/a2h-utg-static/scripts/measure/measure_guards.mjs +98 -98
  388. package/skills/a2h-utg-static/scripts/media_browse_nav.mjs +356 -356
  389. package/skills/a2h-utg-static/scripts/orphan_overlay_nav.mjs +89 -89
  390. package/skills/a2h-utg-static/scripts/phase_plan.mjs +108 -108
  391. package/skills/a2h-utg-static/scripts/phase_planner.mjs +119 -119
  392. package/skills/a2h-utg-static/scripts/plaindialog_nav.mjs +411 -411
  393. package/skills/a2h-utg-static/scripts/preference_widgets.mjs +142 -142
  394. package/skills/a2h-utg-static/scripts/presenter_nav.mjs +490 -490
  395. package/skills/a2h-utg-static/scripts/registry_nav.mjs +288 -288
  396. package/skills/a2h-utg-static/scripts/run_pipeline.mjs +870 -870
  397. package/skills/a2h-utg-static/scripts/screen_merge.mjs +287 -287
  398. package/skills/a2h-utg-static/scripts/screen_nav.mjs +279 -279
  399. package/skills/a2h-utg-static/scripts/starter_nav.mjs +198 -198
  400. package/skills/a2h-utg-static/scripts/static_prior.mjs +904 -904
  401. package/skills/a2h-utg-static/scripts/tests/_zipw.mjs +28 -28
  402. package/skills/a2h-utg-static/scripts/tests/probe_autoload.mjs +108 -108
  403. package/skills/a2h-utg-static/scripts/tests/probe_layout_fragments.mjs +90 -90
  404. package/skills/a2h-utg-static/scripts/tests/probe_unknown_scope.mjs +61 -61
  405. package/skills/a2h-utg-static/scripts/tests/regression_matrix.mjs +1261 -1261
  406. package/skills/a2h-utg-static/scripts/tests/test_activity_alias_launcher.mjs +90 -90
  407. package/skills/a2h-utg-static/scripts/tests/test_bottom_sheet_container.mjs +58 -58
  408. package/skills/a2h-utg-static/scripts/tests/test_branch_guard.mjs +19 -19
  409. package/skills/a2h-utg-static/scripts/tests/test_carry_answers.mjs +103 -103
  410. package/skills/a2h-utg-static/scripts/tests/test_chrome_tokens.mjs +60 -60
  411. package/skills/a2h-utg-static/scripts/tests/test_commented_out_trigger.mjs +111 -111
  412. package/skills/a2h-utg-static/scripts/tests/test_commit_scope.mjs +113 -113
  413. package/skills/a2h-utg-static/scripts/tests/test_compose_vm_nav.mjs +17 -0
  414. package/skills/a2h-utg-static/scripts/tests/test_defensive_null_guard.mjs +77 -77
  415. package/skills/a2h-utg-static/scripts/tests/test_dialog_orphan_entries.mjs +99 -99
  416. package/skills/a2h-utg-static/scripts/tests/test_dialog_page_owner.mjs +69 -69
  417. package/skills/a2h-utg-static/scripts/tests/test_dialogshow_java_factory.mjs +37 -37
  418. package/skills/a2h-utg-static/scripts/tests/test_disabled_guard.mjs +42 -42
  419. package/skills/a2h-utg-static/scripts/tests/test_drawer_panel_gesture.mjs +140 -140
  420. package/skills/a2h-utg-static/scripts/tests/test_edge_dedupe_by_gesture.mjs +111 -111
  421. package/skills/a2h-utg-static/scripts/tests/test_edge_provenance_lint.mjs +70 -70
  422. package/skills/a2h-utg-static/scripts/tests/test_enclosing_gesture.mjs +69 -69
  423. package/skills/a2h-utg-static/scripts/tests/test_external_surface_roots.mjs +43 -43
  424. package/skills/a2h-utg-static/scripts/tests/test_find_package_indirect.mjs +67 -67
  425. package/skills/a2h-utg-static/scripts/tests/test_forwarding_wrapper.mjs +38 -38
  426. package/skills/a2h-utg-static/scripts/tests/test_fragment_containment.mjs +85 -85
  427. package/skills/a2h-utg-static/scripts/tests/test_fragment_helper_trigger.mjs +92 -92
  428. package/skills/a2h-utg-static/scripts/tests/test_graph.mjs +55 -55
  429. package/skills/a2h-utg-static/scripts/tests/test_guard_clause.mjs +86 -86
  430. package/skills/a2h-utg-static/scripts/tests/test_hybrid_bundle_attribution.mjs +74 -74
  431. package/skills/a2h-utg-static/scripts/tests/test_hybrid_bundled_pages.mjs +181 -181
  432. package/skills/a2h-utg-static/scripts/tests/test_hybrid_scope.mjs +293 -293
  433. package/skills/a2h-utg-static/scripts/tests/test_hybrid_title_renders.mjs +118 -118
  434. package/skills/a2h-utg-static/scripts/tests/test_interaction_sites.mjs +272 -272
  435. package/skills/a2h-utg-static/scripts/tests/test_item_data_instance.mjs +51 -51
  436. package/skills/a2h-utg-static/scripts/tests/test_kotlin_fn_spans.mjs +69 -69
  437. package/skills/a2h-utg-static/scripts/tests/test_label_accessor_forms.mjs +187 -187
  438. package/skills/a2h-utg-static/scripts/tests/test_label_source.mjs +70 -70
  439. package/skills/a2h-utg-static/scripts/tests/test_launch_intent_guard.mjs +67 -67
  440. package/skills/a2h-utg-static/scripts/tests/test_layout_declared_fragment.mjs +103 -103
  441. package/skills/a2h-utg-static/scripts/tests/test_listener_call_forms.mjs +79 -79
  442. package/skills/a2h-utg-static/scripts/tests/test_listener_receiver_binding.mjs +47 -47
  443. package/skills/a2h-utg-static/scripts/tests/test_manifest_exported_default.mjs +40 -40
  444. package/skills/a2h-utg-static/scripts/tests/test_manifest_filters_modules.mjs +84 -84
  445. package/skills/a2h-utg-static/scripts/tests/test_mode_and_cb_param.mjs +172 -172
  446. package/skills/a2h-utg-static/scripts/tests/test_module_namespace.mjs +33 -33
  447. package/skills/a2h-utg-static/scripts/tests/test_multiple_entry_contracts.mjs +80 -80
  448. package/skills/a2h-utg-static/scripts/tests/test_nav_graph_xml.mjs +35 -35
  449. package/skills/a2h-utg-static/scripts/tests/test_nl_hints_gate.mjs +85 -85
  450. package/skills/a2h-utg-static/scripts/tests/test_node_id_collision.mjs +57 -57
  451. package/skills/a2h-utg-static/scripts/tests/test_non_gesture_step_flag.mjs +62 -62
  452. package/skills/a2h-utg-static/scripts/tests/test_out_of_scope_and_settings.mjs +72 -72
  453. package/skills/a2h-utg-static/scripts/tests/test_overload_and_climb.mjs +86 -86
  454. package/skills/a2h-utg-static/scripts/tests/test_pager_page_source.mjs +78 -78
  455. package/skills/a2h-utg-static/scripts/tests/test_pager_position_zero.mjs +65 -65
  456. package/skills/a2h-utg-static/scripts/tests/test_pager_variant_guard.mjs +172 -172
  457. package/skills/a2h-utg-static/scripts/tests/test_pipeline_llm_phases.mjs +107 -107
  458. package/skills/a2h-utg-static/scripts/tests/test_plain_dialog_nodes.mjs +167 -167
  459. package/skills/a2h-utg-static/scripts/tests/test_plaindialog_shared_anchor.mjs +117 -117
  460. package/skills/a2h-utg-static/scripts/tests/test_preference_click_nav.mjs +98 -98
  461. package/skills/a2h-utg-static/scripts/tests/test_preference_nesting.mjs +183 -183
  462. package/skills/a2h-utg-static/scripts/tests/test_preference_widgets.mjs +48 -48
  463. package/skills/a2h-utg-static/scripts/tests/test_read_text_crlf.mjs +41 -41
  464. package/skills/a2h-utg-static/scripts/tests/test_resolver_tier_parity.mjs +126 -126
  465. package/skills/a2h-utg-static/scripts/tests/test_review_fixes.mjs +135 -135
  466. package/skills/a2h-utg-static/scripts/tests/test_scope_utils.mjs +85 -85
  467. package/skills/a2h-utg-static/scripts/tests/test_sealed_dialog_state.mjs +148 -148
  468. package/skills/a2h-utg-static/scripts/tests/test_shared_overlay_split.mjs +63 -63
  469. package/skills/a2h-utg-static/scripts/tests/test_slug_parity.mjs +58 -58
  470. package/skills/a2h-utg-static/scripts/tests/test_starter_node_id.mjs +41 -41
  471. package/skills/a2h-utg-static/scripts/tests/test_state_guard_arity.mjs +109 -109
  472. package/skills/a2h-utg-static/scripts/tests/test_state_guard_commented_candidates.mjs +68 -68
  473. package/skills/a2h-utg-static/scripts/tests/test_state_guard_model_gates.mjs +127 -127
  474. package/skills/a2h-utg-static/scripts/tests/test_state_specific_hop.mjs +130 -130
  475. package/skills/a2h-utg-static/scripts/tests/test_synthetic_label_identity.mjs +51 -51
  476. package/skills/a2h-utg-static/scripts/tests/test_template_method_layout.mjs +81 -81
  477. package/skills/a2h-utg-static/scripts/tests/test_trigger_id_spelling.mjs +68 -68
  478. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_action_override.mjs +91 -91
  479. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_flow_filter.mjs +110 -110
  480. package/skills/a2h-utg-static/scripts/tests/test_ui_elements_nl_hint_key.mjs +89 -89
  481. package/skills/a2h-utg-static/scripts/tests/test_uiless_host_fold.mjs +98 -98
  482. package/skills/a2h-utg-static/scripts/tests/test_uniapp_source.mjs +231 -231
  483. package/skills/a2h-utg-static/scripts/tests/test_view_click_refs.mjs +104 -104
  484. package/skills/a2h-utg-static/scripts/tests/test_view_id_label.mjs +69 -69
  485. package/skills/a2h-utg-static/scripts/tests/test_view_interactions.mjs +346 -346
  486. package/skills/a2h-utg-static/scripts/tests/test_viewpage_nav.mjs +340 -273
  487. package/skills/a2h-utg-static/scripts/tests/test_widget_class_scope.mjs +92 -92
  488. package/skills/a2h-utg-static/scripts/tests/test_window_nav_kotlin.mjs +158 -158
  489. package/skills/a2h-utg-static/scripts/tests/test_worklist_parts.mjs +65 -65
  490. package/skills/a2h-utg-static/scripts/uniapp_nav.mjs +1119 -1119
  491. package/skills/a2h-utg-static/scripts/uniapp_widgets.mjs +244 -244
  492. package/skills/a2h-utg-static/scripts/utg_html.mjs +721 -721
  493. package/skills/a2h-utg-static/scripts/viewpage_nav.mjs +589 -485
  494. package/skills/a2h-utg-static/scripts/window_nav.mjs +240 -240
  495. package/skills/a2h-utg-static/scripts/worklist_parts.mjs +154 -154
  496. package/skills/a2h-utg-static/tools/convert_static_utg_to_ui_elements.ts +769 -769
  497. package/skills/a2h-utg-static/tools/package.json +3 -3
@@ -1,1124 +1,1179 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Phase 5 mechanical checks for one group's files, in one call per verification round.
4
- *
5
- * Measured on a 14-group run, each Phase 5 round cost an agent 2-3 model turns of
6
- * greps and checker runs (EVIDENCE coverage, resource existence, static GATE for
7
- * its own files, "did round 2 change anything"), ~10% of its slot time. Those
8
- * answers are lexical; this script gives all of them at once so the agent's turns
9
- * go to the semantic checks only. It decides nothing the agent must judge: missing
10
- * coverage may be legitimately N/A, and every finding names the file:line to look at.
11
- *
12
- * node phase5_check.mjs <harmony_dir> --files pages/A.ets,components/B.ets --round 1
13
- * node phase5_check.mjs <harmony_dir> --group G012 --round 2
14
- *
15
- * Sections: changed-since-last-round (round rule), static GATE for these files,
16
- * resource references that do not resolve, EVIDENCE names not matching a Phase 5
17
- * heading, B-tier items with no EVIDENCE tag, over-budget EVIDENCE blocks,
18
- * forbidden patterns, brace balance. Exit 1 when a blocking finding exists
19
- * (GATE, unresolved resource, unbalanced braces, misnamed EVIDENCE).
20
- *
21
- * (Node >= 22.18, ESM, zero dependencies. Behaviour-identical port of
22
- * phase5_check.py: same args, exit codes, stdout and snapshot file.)
23
- */
24
-
25
- import * as crypto from 'node:crypto';
26
- import * as fs from 'node:fs';
27
- import * as path from 'node:path';
28
- import { spawnSync } from 'node:child_process';
29
- import { fileURLToPath, pathToFileURL } from 'node:url';
30
-
31
- import { _reported, _replace, _uiModule, etsSplit, reportPath } from './group_watch.mjs';
32
-
33
- // ---------------------------------------------------------------- Python 兼容层
34
- // 输出是 agent 读取的契约,须与原 Python 版逐字节一致:JSON 按 json.dumps 的格式
35
- // (对象键按插入顺序,快照文件 ensure_ascii=True),Windows 文本按 \r\n 写出,
36
- // 字符串长度/切片按码点,正则的 \w \s \d \b 按 Python 的 Unicode 语义。
37
-
38
- const IS_WIN = process.platform === 'win32';
39
- const EOL = IS_WIN ? '\r\n' : '\n';
40
-
41
- /** json.loads 读到的浮点数:保留「它是 float」这一事实,写回时按 Python repr 输出。 */
42
- class PyFloat {
43
- constructor(value) { this.value = value; }
44
- valueOf() { return this.value; }
45
- }
46
-
47
- // 含整数形键("0"、"12")的对象,JS 会把这些键提前;记下 Python 的插入顺序。
48
- const KEY_ORDER = Symbol('pyKeyOrder');
49
- const INDEX_KEY = /^(?:0|[1-9][0-9]*)$/;
50
-
51
- function floatRepr(x) {
52
- if (!Number.isFinite(x)) {
53
- if (Number.isNaN(x)) { return 'NaN'; }
54
- return x > 0 ? 'Infinity' : '-Infinity';
55
- }
56
- if (x === 0) { return Object.is(x, -0) ? '-0.0' : '0.0'; }
57
- const [m, e] = Math.abs(x).toExponential().split('e');
58
- const digits = m.replace('.', '');
59
- const exp = Number(e);
60
- let s;
61
- if (exp >= -4 && exp < 16) {
62
- if (exp >= 0) {
63
- const ip = digits.slice(0, exp + 1).padEnd(exp + 1, '0');
64
- s = ip + '.' + (digits.slice(exp + 1) || '0');
65
- } else {
66
- s = '0.' + '0'.repeat(-exp - 1) + digits;
67
- }
68
- } else {
69
- s = digits[0] + (digits.length > 1 ? '.' + digits.slice(1) : '') + 'e' + (exp < 0 ? '-' : '+') +
70
- String(Math.abs(exp)).padStart(2, '0');
71
- }
72
- return (x < 0 ? '-' : '') + s;
73
- }
74
-
75
- /** json.loads:浮点 → PyFloat,超出安全整数范围的整数 → BigInt,保留键序。 */
76
- function pyJsonLoads(text) {
77
- let i = 0;
78
- const n = text.length;
79
- const fail = (msg) => { throw new SyntaxError(`${msg}: char ${i}`); };
80
- const ws = () => {
81
- while (i < n) {
82
- const c = text.charCodeAt(i);
83
- if (c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d) { i++; } else { break; }
84
- }
85
- };
86
- const NUM = /-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/y;
87
- const str = () => {
88
- i++;
89
- let out = '';
90
- let start = i;
91
- for (;;) {
92
- if (i >= n) { fail('Unterminated string'); }
93
- const c = text.charCodeAt(i);
94
- if (c === 0x22) { out += text.slice(start, i); i++; return out; }
95
- if (c < 0x20) { fail('Invalid control character'); }
96
- if (c === 0x5c) {
97
- out += text.slice(start, i);
98
- const esc = text[i + 1];
99
- const simple = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }[esc];
100
- if (simple !== undefined) {
101
- out += simple;
102
- i += 2;
103
- } else if (esc === 'u') {
104
- const hex = text.slice(i + 2, i + 6);
105
- if (!/^[0-9a-fA-F]{4}$/.test(hex)) { fail('Invalid \\uXXXX escape'); }
106
- out += String.fromCharCode(parseInt(hex, 16));
107
- i += 6;
108
- } else {
109
- fail('Invalid \\escape');
110
- }
111
- start = i;
112
- continue;
113
- }
114
- i++;
115
- }
116
- };
117
- const value = () => {
118
- ws();
119
- const c = text[i];
120
- if (c === '{') {
121
- i++;
122
- const o = {};
123
- ws();
124
- if (text[i] === '}') { i++; return o; }
125
- for (;;) {
126
- ws();
127
- if (text[i] !== '"') { fail('Expecting property name enclosed in double quotes'); }
128
- const k = str();
129
- ws();
130
- if (text[i] !== ':') { fail("Expecting ':' delimiter"); }
131
- i++;
132
- pySet(o, k, value());
133
- ws();
134
- if (text[i] === ',') { i++; continue; }
135
- if (text[i] === '}') { i++; break; }
136
- fail("Expecting ',' delimiter");
137
- }
138
- return o;
139
- }
140
- if (c === '[') {
141
- i++;
142
- const a = [];
143
- ws();
144
- if (text[i] === ']') { i++; return a; }
145
- for (;;) {
146
- a.push(value());
147
- ws();
148
- if (text[i] === ',') { i++; continue; }
149
- if (text[i] === ']') { i++; break; }
150
- fail("Expecting ',' delimiter");
151
- }
152
- return a;
153
- }
154
- if (c === '"') { return str(); }
155
- if (text.startsWith('null', i)) { i += 4; return null; }
156
- if (text.startsWith('true', i)) { i += 4; return true; }
157
- if (text.startsWith('false', i)) { i += 5; return false; }
158
- if (text.startsWith('NaN', i)) { i += 3; return new PyFloat(NaN); }
159
- if (text.startsWith('Infinity', i)) { i += 8; return new PyFloat(Infinity); }
160
- if (text.startsWith('-Infinity', i)) { i += 9; return new PyFloat(-Infinity); }
161
- NUM.lastIndex = i;
162
- const m = NUM.exec(text);
163
- if (!m) { fail('Expecting value'); }
164
- i += m[0].length;
165
- if (m[1] !== undefined || m[2] !== undefined) { return new PyFloat(Number(m[0])); }
166
- const num = Number(m[0]);
167
- return Number.isSafeInteger(num) ? (num === 0 ? 0 : num) : BigInt(m[0]);
168
- };
169
- const v = value();
170
- ws();
171
- if (i !== n) { fail('Extra data'); }
172
- return v;
173
- }
174
-
175
- /** d[k] = v with Python dict insertion order (new keys go last, existing keys keep their slot). */
176
- function pySet(o, k, v) {
177
- if (!Object.hasOwn(o, k)) {
178
- if (o[KEY_ORDER]) { o[KEY_ORDER].push(k); }
179
- else if (INDEX_KEY.test(k)) { o[KEY_ORDER] = [...Object.keys(o), k]; }
180
- }
181
- Object.defineProperty(o, k, { value: v, enumerable: true, writable: true, configurable: true });
182
- }
183
-
184
- function keysOf(o) {
185
- const ord = o[KEY_ORDER];
186
- return ord ? ord.filter((k) => Object.hasOwn(o, k)) : Object.keys(o);
187
- }
188
-
189
- /** A JSON string literal: ensure_ascii escapes everything outside ' '..'~' (UTF-16 units, lowercase hex). */
190
- function jsonStr(s, ascii) {
191
- if (!ascii) { return JSON.stringify(s); }
192
- const short = { '"': '\\"', '\\': '\\\\', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\b': '\\b', '\f': '\\f' };
193
- let r = '"';
194
- for (let i = 0; i < s.length; i++) {
195
- const ch = s[i];
196
- const c = s.charCodeAt(i);
197
- if (short[ch] !== undefined) { r += short[ch]; }
198
- else if (c < 0x20 || c > 0x7e) { r += '\\u' + c.toString(16).padStart(4, '0'); }
199
- else { r += ch; }
200
- }
201
- return r + '"';
202
- }
203
-
204
- /** json.dumps(v, indent=indent, ensure_ascii=ascii). undefined is treated as None. */
205
- function pyJsonDumps(v, indent, ascii, level = 0) {
206
- if (v === null || v === undefined) { return 'null'; }
207
- if (v === true) { return 'true'; }
208
- if (v === false) { return 'false'; }
209
- if (typeof v === 'bigint') { return v.toString(); }
210
- if (v instanceof PyFloat) { return floatRepr(v.value); }
211
- if (typeof v === 'number') { return Number.isInteger(v) ? (Object.is(v, -0) ? '0' : String(v)) : floatRepr(v); }
212
- if (typeof v === 'string') { return jsonStr(v, ascii); }
213
- const pad = '\n' + ' '.repeat(indent * (level + 1));
214
- const end = '\n' + ' '.repeat(indent * level);
215
- if (Array.isArray(v)) {
216
- if (v.length === 0) { return '[]'; }
217
- return '[' + pad + v.map((x) => pyJsonDumps(x, indent, ascii, level + 1)).join(',' + pad) + end + ']';
218
- }
219
- const ks = keysOf(v);
220
- if (ks.length === 0) { return '{}'; }
221
- return '{' + pad + ks.map((k) => jsonStr(k, ascii) + ': ' + pyJsonDumps(v[k], indent, ascii, level + 1))
222
- .join(',' + pad) + end + '}';
223
- }
224
-
225
- const UTF8_STRICT = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
226
- const UTF8_REPLACE = new TextDecoder('utf-8', { fatal: false, ignoreBOM: true });
227
-
228
- /** Path.read_text(encoding="utf-8"[, errors="replace"]): keeps a BOM, universal newlines. */
229
- function readText(p, replace = false) {
230
- return (replace ? UTF8_REPLACE : UTF8_STRICT).decode(fs.readFileSync(p)).replace(/\r\n?/g, '\n');
231
- }
232
-
233
- /** Path.write_text: Windows text mode writes \n as \r\n. */
234
- function writeText(p, s) {
235
- fs.writeFileSync(p, IS_WIN ? s.replace(/\n/g, '\r\n') : s, 'utf8');
236
- }
237
-
238
- /** print() on a text-mode stdout. */
239
- function out(s = '') { process.stdout.write((s + '\n').replace(/\n/g, EOL)); }
240
- function err(s = '') { process.stderr.write((s + '\n').replace(/\n/g, EOL)); }
241
-
242
- function isFile(p) {
243
- try { return fs.statSync(p, { throwIfNoEntry: false })?.isFile() ?? false; } catch { return false; }
244
- }
245
-
246
- /** Path(a) / b / c: an absolute (or drive-qualified) segment replaces what came before. */
247
- function pjoin(base, ...segs) {
248
- let acc = String(base);
249
- for (const s of segs.map(String)) {
250
- if (IS_WIN && /^[\\/](?![\\/])/.test(s)) {
251
- // rooted but driveless: keeps the drive of what came before
252
- const drv = /^([A-Za-z]:|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.exec(acc);
253
- acc = (drv ? drv[0] : '') + s;
254
- } else if (path.isAbsolute(s) || (IS_WIN && /^[A-Za-z]:/.test(s))) {
255
- acc = s;
256
- } else {
257
- acc = path.join(acc, s);
258
- }
259
- }
260
- return acc;
261
- }
262
-
263
- /** dict.get(k, d): the default only when the key is absent (a null value is returned as null). */
264
- function get(o, k, d = undefined) {
265
- if (o === null || typeof o !== 'object') { throw new TypeError(`'${o === null ? 'NoneType' : typeof o}' object has no attribute 'get'`); }
266
- if (Array.isArray(o)) { throw new TypeError("'list' object has no attribute 'get'"); }
267
- return Object.hasOwn(o, k) ? o[k] : d;
268
- }
269
-
270
- function truthy(v) {
271
- if (v === null || v === undefined || v === false) { return false; }
272
- if (v === true) { return true; }
273
- if (typeof v === 'number') { return v !== 0; }
274
- if (typeof v === 'bigint') { return v !== 0n; }
275
- if (v instanceof PyFloat) { return v.value !== 0; }
276
- if (typeof v === 'string' || Array.isArray(v)) { return v.length > 0; }
277
- if (v instanceof Map || v instanceof Set) { return v.size > 0; }
278
- return Object.keys(v).length > 0;
279
- }
280
-
281
- /** Python `a or b`. */
282
- function or(a, b) { return truthy(a) ? a : b; }
283
-
284
- /** _load(p) or {}, which must then be a dict (`.get` / `.items()` on anything else raises). */
285
- function loadDict(p) {
286
- const v = or(_load(p, {}), {});
287
- if (typeof v !== 'object' || Array.isArray(v)) { throw new TypeError(`'${Array.isArray(v) ? 'list' : typeof v}' object has no attribute 'get'`); }
288
- return v;
289
- }
290
-
291
- // str.isspace() / re's Unicode \s, and re's Unicode \w (str.isalnum() or '_').
292
- const PY_WS = '\\t\\n\\x0b\\x0c\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000';
293
- const S = `[${PY_WS}]`;
294
- const NS = `[^${PY_WS}]`;
295
- const W = '[\\p{L}\\p{N}_]';
296
- const STRIP_RE = new RegExp(`^${S}+|${S}+$`, 'gu');
297
-
298
- /** str.strip(). */
299
- function pyStrip(s) { return s.replace(STRIP_RE, ''); }
300
-
301
- /** str.splitlines(): every Python line boundary, no trailing empty item. */
302
- function pySplitlines(s) {
303
- if (s === '') { return []; }
304
- const parts = s.split(/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/);
305
- if (parts[parts.length - 1] === '') { parts.pop(); }
306
- return parts;
307
- }
308
-
309
- /** len(s): code points. */
310
- function pyLen(s) {
311
- let n = 0;
312
- for (const _ of s) { n++; }
313
- return n;
314
- }
315
-
316
- /** s[:k] by code points. */
317
- function pyHead(s, k) {
318
- let r = '';
319
- let n = 0;
320
- for (const ch of s) {
321
- if (n++ >= k) { break; }
322
- r += ch;
323
- }
324
- return r;
325
- }
326
-
327
- /** String `<` as Python compares str: by code point. */
328
- function cmpStr(a, b) {
329
- const x = [...a];
330
- const y = [...b];
331
- for (let i = 0; i < Math.min(x.length, y.length); i++) {
332
- const d = x[i].codePointAt(0) - y[i].codePointAt(0);
333
- if (d !== 0) { return d < 0 ? -1 : 1; }
334
- }
335
- return x.length < y.length ? -1 : x.length > y.length ? 1 : 0;
336
- }
337
-
338
- function pySorted(items) {
339
- for (const x of items) {
340
- if (typeof x !== 'string') { throw new TypeError("'<' not supported between instances of non-str values"); }
341
- }
342
- return [...items].sort(cmpStr);
343
- }
344
-
345
- /** str(Path(p)): separators normalised, `.` parts and trailing separators dropped. */
346
- function pathStr(p) {
347
- if (!IS_WIN) {
348
- const s = String(p);
349
- const root = s.startsWith('//') && !s.startsWith('///') ? '//' : s.startsWith('/') ? '/' : '';
350
- return (root + s.split('/').filter((x) => x !== '' && x !== '.').join('/')) || '.';
351
- }
352
- const s = String(p).replace(/\//g, '\\');
353
- let drive = '';
354
- let rest = s;
355
- const unc = /^\\\\([^\\]+)\\([^\\]+)/.exec(s);
356
- if (unc) { drive = unc[0]; rest = s.slice(drive.length); }
357
- else if (/^[A-Za-z]:/.test(s)) { drive = s.slice(0, 2); rest = s.slice(2); }
358
- const root = rest.startsWith('\\') ? '\\' : '';
359
- return (drive + root + rest.split('\\').filter((x) => x !== '' && x !== '.').join('\\')) || '.';
360
- }
361
-
362
- /** Path(p).stem (3.13: a trailing dot is not a suffix). */
363
- function pathStem(name) {
364
- const i = name.lastIndexOf('.');
365
- return i > 0 && i < name.length - 1 ? name.slice(0, i) : name;
366
- }
367
-
368
- /** Entries of dir whose name matches a glob `*` segment (`*` or `*<suffix>`), case-insensitive on Windows. */
369
- function globDir(dir, suffix = '', dirsOnly = false) {
370
- const outp = [];
371
- let ents;
372
- try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return outp; }
373
- for (const e of ents) {
374
- const nm = e.name;
375
- const ok = IS_WIN ? nm.toLowerCase().endsWith(suffix.toLowerCase()) : nm.endsWith(suffix);
376
- if (!ok || nm.length < suffix.length) { continue; }
377
- const full = path.join(dir, nm);
378
- if (dirsOnly) {
379
- let isDir = e.isDirectory();
380
- if (e.isSymbolicLink()) { try { isDir = fs.statSync(full).isDirectory(); } catch { isDir = false; } }
381
- if (!isDir) { continue; }
382
- }
383
- outp.push(full);
384
- }
385
- return outp;
386
- }
387
-
388
- // Path(root).glob("*/<sub>/*<suffix>"): a literal middle segment is joined as-is (pathlib 3.13).
389
- function globSub(root, sub, suffix = '') {
390
- return globDir(root, '', true).flatMap((d) => globDir(path.join(d, sub), suffix));
391
- }
392
-
393
- /** repr() of a list of str (for the TimeoutExpired message). */
394
- function strListRepr(xs) {
395
- return '[' + xs.map((s) => {
396
- const q = s.includes("'") && !s.includes('"') ? '"' : "'";
397
- return q + s.replace(/\\/g, '\\\\').replace(new RegExp(q, 'g'), '\\' + q) + q;
398
- }).join(', ') + ']';
399
- }
400
-
401
- // ---------------------------------------------------------------- constants
402
-
403
- const HERE = fs.realpathSync.native(path.dirname(fileURLToPath(import.meta.url)));
404
- export const PROCEDURE = path.join(path.dirname(HERE), 'references', 'conversion-procedure.md');
405
- // rules whose subject is the whole batch (Step 5.5 parent wiring), not one group
406
- export const BATCH_RULES = new Set(['orphan-component', 'converted-page-unreachable', 'entry-route-not-converted']);
407
- export const EVIDENCE_BUDGET = { A: 200, B: 400 }; // chars per EVIDENCE comment block
408
- // Python: \$r\(\s*['"]app\.(\w+)\.([\w.]+)['"]\s*\) (Unicode \s / \w)
409
- export const R_CALL = new RegExp(`\\$r\\(${S}*['"]app\\.(${W}+)\\.((?:${W}|\\.)+)['"]${S}*\\)`, 'gu');
410
- export const RAW_CALL = new RegExp(`\\$rawfile\\(${S}*['"]([^'"]+)['"]${S}*\\)`, 'gu');
411
- export const JSON_OF = new Map([['string', 'string'], ['color', 'color'], ['float', 'float'], ['integer', 'integer'],
412
- ['boolean', 'boolean'], ['plural', 'plural'], ['strarray', 'strarray'],
413
- ['intarray', 'intarray'], ['pattern', 'pattern'], ['theme', 'theme']]);
414
- // Python: @(...)\b(?!V2) — the name always ends in a word char, so \b == "next char is not \w"
415
- export const V1_DECORATORS = new RegExp('@(Component|State|Prop|Link|Provide|Consume|Observed|ObjectLink|' +
416
- `Track|StorageLink|StorageProp|Watch)(?!${W})(?!V2)`, 'u');
417
- /** The checker's first line: `arkts_static_check — 扫描 <n> 个 .ets 文件(...)`. */
418
- const STATIC_HEAD = /^arkts_static_check\b.*?扫描 (\d+) 个 \.ets 文件/mu;
419
- const STATIC_LINE = new RegExp(`^${S}{2}([a-z0-9-]+)${S}+(${NS}+?):(\\p{Nd}+)${S}*$`, 'u');
420
-
421
- function _load(p, dflt = null) {
422
- return isFile(p) ? pyJsonLoads(readText(p)) : dflt;
423
- }
424
-
425
- /** (all Phase 5 item headings, A-tier subset) parsed from conversion-procedure.md. */
426
- export function procedureItems(p = PROCEDURE) {
427
- const text = readText(p);
428
- const at = text.indexOf('## Phase 5');
429
- if (at < 0) { throw new Error('substring not found'); }
430
- let sec = text.slice(at);
431
- if (sec.slice(5).includes('\n## ')) { sec = sec.slice(0, sec.indexOf('\n## ', 5)); }
432
- const start = sec.indexOf('逐项**走完以下检查'); // the check-item list follows this line
433
- let body = start >= 0 ? sec.slice(start) : sec;
434
- if (body.includes('\n### ')) { body = body.slice(0, body.indexOf('\n### ')); }
435
- // re.M `^` matches at the start and after "\n" only
436
- const items = [...body.matchAll(/(?:^|(?<=\n))- \*\*([^*]+?)\*\*/g)].map((m) => m[1]);
437
- const aLine = /\*\*A 档[^\n]*\n([^\n]+)/.exec(sec);
438
- const aTier = new Set(aLine ? [...aLine[1].matchAll(/`([^`]+)`/g)].map((m) => m[1]) : []);
439
- const names = [];
440
- for (let it of items) {
441
- // re.sub(r"[((].*$", "", it): `.` is not "\n", `$` is the end or before a final "\n"
442
- it = pyStrip(it.replace(/[((][^\n]*(?=\n?$)/g, ''));
443
- if (it && !names.includes(it)) { names.push(it); }
444
- }
445
- return [names, aTier];
446
- }
447
-
448
- /** Blank out comments and string bodies (same length) so code-only scans stay line-true. */
449
- export function stripComments(src) {
450
- const blank = (s) => s.replace(/[^\n]/gu, ' '); // one space per code point, like Python
451
- const outp = [];
452
- let i = 0;
453
- const n = src.length;
454
- while (i < n) {
455
- const two = src.slice(i, i + 2);
456
- if (two === '//') {
457
- let j = src.indexOf('\n', i);
458
- j = j < 0 ? n : j;
459
- outp.push(blank(src.slice(i, j))); i = j;
460
- } else if (two === '/*') {
461
- let j = src.indexOf('*/', i + 2);
462
- j = j < 0 ? n : j + 2;
463
- outp.push(blank(src.slice(i, j))); i = j;
464
- } else if ("'\"`".includes(src[i])) {
465
- const q = src[i];
466
- let j = i + 1;
467
- while (j < n && src[j] !== q) { j += src[j] === '\\' ? 2 : 1; }
468
- outp.push(q + blank(src.slice(i + 1, j)) + (j < n ? q : '')); i = j + 1;
469
- } else {
470
- outp.push(src[i]); i += 1;
471
- }
472
- }
473
- return outp.join('');
474
- }
475
-
476
- /** [[line_no, name, chars]] -- a block is the EVIDENCE line plus its indented // continuation. */
477
- export function evidenceBlocks(lines) {
478
- const blocks = [];
479
- let cur = null;
480
- lines.forEach((line, k) => {
481
- const no = k + 1;
482
- const s = pyStrip(line);
483
- const m = s.startsWith('//') ? /EVIDENCE\(([^)]*)\)/.exec(s) : null;
484
- if (m) {
485
- cur = [no, pyStrip(m[1]), pyLen(s)];
486
- blocks.push(cur);
487
- } else if (cur && s.startsWith('//') && !s.startsWith('// EVIDENCE')) {
488
- cur[2] += pyLen(s);
489
- } else {
490
- cur = null;
491
- }
492
- });
493
- return blocks.map((b) => [...b]);
494
- }
495
-
496
- export class Resources {
497
- constructor(resRoot) {
498
- this.root = String(resRoot);
499
- this.names = new Map();
500
- for (const f of globSub(this.root, 'element', '.json')) {
501
- const data = or(_load(f, {}), {});
502
- if (typeof data !== 'object' || Array.isArray(data)) { throw new TypeError("object has no attribute 'items'"); }
503
- for (const kind of keysOf(data)) {
504
- const rows = data[kind];
505
- for (const r of Array.isArray(rows) ? rows : []) {
506
- if (r !== null && typeof r === 'object' && !Array.isArray(r) && Object.hasOwn(r, 'name')) {
507
- setdefault(this.names, kind, new Set()).add(r.name);
508
- }
509
- }
510
- }
511
- }
512
- this.media = new Set(globSub(this.root, 'media').map((p) => pathStem(path.basename(p))));
513
- this.profile = new Set(globSub(this.root, 'profile').map((p) => pathStem(path.basename(p))));
514
- this.raw = path.join(this.root, 'rawfile');
515
- }
516
-
517
- resolves(kind, name) {
518
- if (kind === 'media') { return this.media.has(name); }
519
- if (kind === 'profile') { return this.profile.has(name); }
520
- const k = JSON_OF.has(kind) ? JSON_OF.get(kind) : kind;
521
- return (this.names.get(k) ?? new Set()).has(name);
522
- }
523
- }
524
-
525
- function setdefault(m, k, d) {
526
- if (!m.has(k)) { m.set(k, d); }
527
- return m.get(k);
528
- }
529
-
530
- /** Runs arkts_static_check.ts and keeps the GATE / CANDIDATES rows for `files`. Returns [result, error]. */
531
- export function staticGate(ets, res, files) {
532
- const script = path.join(HERE, 'arkts_static_check.ts');
533
- const args = [script, '--ets', pathStr(ets), '--resources', pathStr(res)];
534
- const r = spawnSync(process.execPath, args, { timeout: 300 * 1000, maxBuffer: 1 << 30, windowsHide: true });
535
- if (r.error) {
536
- const e = r.error;
537
- const msg = e.code === 'ETIMEDOUT'
538
- ? `Command '${strListRepr(['node', ...args])}' timed out after 300 seconds`
539
- : (IS_WIN && e.code === 'ENOENT' ? '[WinError 2] The system cannot find the file specified'
540
- : `[Errno ${-(e.errno ?? 0)}] ${e.message}`);
541
- return [null, `static checker did not run: ${msg}`];
542
- }
543
- // text=True, encoding="utf-8": strict decode + universal newlines
544
- const outText = UTF8_STRICT.decode(r.stdout ?? Buffer.alloc(0)).replace(/\r\n?/g, '\n');
545
- // The checker's contract (arkts_static_check.ts main): exit 0 = no GATE, 1 = GATE findings,
546
- // 2 = bad args / no --ets root. Anything else (a crash, a kill) or output without its header
547
- // and [GATE] section is no verdict: read as a pass it would wave the group through.
548
- const tail = (b) => pyHead(String(b ?? '').trim().split(/\r?\n/).slice(-3).join(' | '), 300);
549
- if (r.signal) { return [null, `static checker killed by ${r.signal}`]; }
550
- if (r.status !== 0 && r.status !== 1) {
551
- return [null, `static checker exit ${r.status}: ${tail(r.stderr) || tail(outText) || 'no output'}`];
552
- }
553
- const scanned = STATIC_HEAD.exec(outText);
554
- if (!scanned || !/^\[GATE\]/m.test(outText)) {
555
- return [null, `static checker exit ${r.status} printed no report: ${tail(r.stderr) || tail(outText) || 'no output'}`];
556
- }
557
- // Its own note: 0 files scanned prints "GATE 0" and exits 0, the same shape as a full pass.
558
- if (Number(scanned[1]) === 0) { return [null, `static checker scanned 0 .ets files under ${pathStr(ets)}`]; }
559
- const mine = [];
560
- let batch = 0;
561
- let section = null;
562
- let last = null;
563
- const want = new Set(files.map((f) => f.replace(/\\/g, '/')));
564
- for (const line of pySplitlines(outText)) {
565
- if (line.startsWith('[GATE]')) {
566
- section = 'gate';
567
- } else if (line.startsWith('[CANDIDATES]')) {
568
- section = 'cand';
569
- }
570
- const m = STATIC_LINE.exec(line);
571
- if (m && (section === 'gate' || section === 'cand')) {
572
- const [, rule, f, ln] = m;
573
- last = null;
574
- if (want.has(f)) {
575
- if (BATCH_RULES.has(rule)) {
576
- batch += 1;
577
- } else {
578
- last = { kind: section, rule, at: `${f}:${ln}`, msg: '' };
579
- mine.push(last);
580
- }
581
- }
582
- } else if (last !== null && line.startsWith(' '.repeat(10)) && !last.msg) {
583
- last.msg = pyHead(pyStrip(line), 160);
584
- }
585
- }
586
- return [{ mine, batch_level: batch }, null];
587
- }
588
-
589
- // Tests replace hooks.staticGate (the Python tests monkeypatch pc.static_gate).
590
- export const hooks = { staticGate };
591
-
592
- /** File name of a round-snapshot key: the group id, or a digest of a --files list. */
593
- export function roundsName(key) {
594
- const k = String(key);
595
- return /^[\w.-]{1,80}$/.test(k) ? k : `files-${crypto.createHash('sha1').update(k, 'utf8').digest('hex').slice(0, 16)}`;
596
- }
597
-
598
- /**
599
- * The static gate per module root: one run over each module root the files live in, asked for
600
- * the module-relative names the checker prints (a UI-module file given as
601
- * `entry/src/main/ets/pages/A.ets` is `pages/A.ets` to it); findings are mapped back to the
602
- * name each file was given.
603
- */
604
- export function gateByModule(ets, res, files, rootOf) {
605
- const ui = path.resolve(ets);
606
- const by = new Map();
607
- for (const rel of files) {
608
- const [root, inner] = rootOf.get(rel) ?? [ui, rel];
609
- if (!by.has(root)) by.set(root, new Map());
610
- by.get(root).set(inner, rel);
611
- }
612
- if (!by.size) return hooks.staticGate(ets, res, files);
613
- const merged = { mine: [], batch_level: 0 };
614
- for (const [root, names] of by) {
615
- const [g, e] = root === ui ? hooks.staticGate(ets, res, [...names.keys()])
616
- : hooks.staticGate(root, path.join(path.dirname(root), 'resources'), [...names.keys()]);
617
- if (g === null) return [null, root === ui ? e : `${e} (module ${root})`];
618
- merged.batch_level += g.batch_level ?? 0;
619
- for (const f of g.mine) {
620
- const at = /^(.*):(\d+)$/.exec(f.at);
621
- merged.mine.push(at && names.has(at[1]) ? { ...f, at: `${names.get(at[1])}:${at[2]}` } : f);
622
- }
623
- }
624
- return [merged, null];
625
- }
626
-
627
- export function check(hp, files, rnd = null, group = null) {
628
- hp = String(hp);
629
- const meta = pjoin(hp, '.hometrans');
630
- const progress = loadDict(pjoin(meta, 'batch_progress.json'));
631
- const module = String(_uiModule(hp, progress)); // the queue's resolution (group_watch._paths)
632
- const ets = pjoin(hp, module, 'src', 'main', 'ets');
633
- const res = pjoin(hp, module, 'src', 'main', 'resources');
634
- const paradigm = get(progress, 'paradigm');
635
- const [names, aTier] = procedureItems();
636
- const rres = new Resources(res);
637
- // A file of another module (`features/x/src/main/ets/pages/A.ets`, group_watch.etsSplit) is
638
- // read from that module, its $r resolved against that module's resources as well as the UI one's.
639
- const resOf = new Map([[path.resolve(ets), rres]]);
640
- const rootOf = new Map();
641
- const rep = { files: [], missing_files: [], blocking: 0 };
642
- const texts = new Map();
643
- // One name per file: a UI-module file given as `<ui>/src/main/ets/pages/A.ets` is `pages/A.ets`
644
- // (the --group form), so the two spellings are not read, gated and reported twice.
645
- const uiRoot = path.resolve(ets);
646
- const canon = [];
647
- for (const f of files) {
648
- const [root, inner] = etsSplit(hp, ets, f);
649
- const c = path.resolve(root) === uiRoot ? inner : String(f).replace(/\\/g, '/');
650
- if (!canon.includes(c)) canon.push(c);
651
- }
652
- files = canon;
653
- for (const rel of files) {
654
- const [root, inner] = etsSplit(hp, ets, rel);
655
- const r = path.resolve(root);
656
- rootOf.set(rel, [r, inner]);
657
- if (!resOf.has(r)) resOf.set(r, new Resources(path.join(path.dirname(r), 'resources')));
658
- const f = pjoin(root, inner);
659
- if (isFile(f)) {
660
- texts.set(rel, readText(f, true));
661
- rep.files.push(rel);
662
- } else {
663
- rep.missing_files.push(rel);
664
- }
665
- }
666
-
667
- // round rule: what changed since the previous round's snapshot
668
- // One file per group (work/phase5_rounds/<key>.json, atomic replace): parallel groups shared
669
- // one phase5_rounds.json, overwrote each other's snapshots and could read it half-written.
670
- // The shared file of an earlier run is still read while a group has no file of its own.
671
- const key = or(group, pySorted(files).join(','));
672
- const snapF = pjoin(meta, 'work', 'phase5_rounds', `${roundsName(key)}.json`);
673
- let snaps = loadDict(snapF);
674
- if (!Object.hasOwn(snaps, key)) {
675
- let legacy = {};
676
- try { legacy = loadDict(pjoin(meta, 'work', 'phase5_rounds.json')); } catch { /* torn legacy file */ }
677
- snaps = Object.hasOwn(legacy, key) ? { [key]: legacy[key] } : {};
678
- }
679
- const now = {};
680
- for (const [rel, t] of texts) { pySet(now, rel, crypto.createHash('sha1').update(t, 'utf8').digest('hex')); }
681
- if (truthy(rnd)) {
682
- const prev = get(get(snaps, key, {}), String(rnd - 1));
683
- if (prev !== undefined && prev !== null) {
684
- const union = [...keysOf(now)];
685
- for (const k of keysOf(prev)) { if (!union.includes(k)) { union.push(k); } }
686
- const changed = pySorted(union.filter((k) => get(now, k) !== get(prev, k)));
687
- rep.changed_since_round = {
688
- round: rnd - 1, files: changed,
689
- verdict: changed.length ? `round ${rnd - 1} made changes: run round ${rnd}` : `round ${rnd - 1} made zero changes`,
690
- };
691
- }
692
- if (!Object.hasOwn(snaps, key)) { pySet(snaps, key, {}); }
693
- pySet(snaps[key], String(rnd), now);
694
- fs.mkdirSync(path.dirname(snapF), { recursive: true });
695
- const body = pyJsonDumps(snaps, 1, true);
696
- _replace(snapF, IS_WIN ? body.replace(/\n/g, '\r\n') : body);
697
- }
698
-
699
- const [gate, gateErr] = gateByModule(ets, res, rep.files, rootOf);
700
- rep.static = gate !== null ? gate : { error: gateErr };
701
- if (truthy(gate)) {
702
- rep.blocking += gate.mine.filter((g) => g.kind === 'gate').length;
703
- } else {
704
- rep.blocking += 1; // no GATE verdict is not a pass
705
- }
706
-
707
- const unresolved = [];
708
- const misnamed = [];
709
- const overlong = [];
710
- const forbidden = [];
711
- const braces = [];
712
- const covered = new Set();
713
- const resolvers = (rel) => [...new Set([rres, resOf.get(rootOf.get(rel)[0])])];
714
- for (const [rel, text] of texts) {
715
- const lines = pySplitlines(text);
716
- lines.forEach((line, k) => {
717
- const no = k + 1;
718
- for (const [, kind, name] of line.matchAll(R_CALL)) {
719
- if (!resolvers(rel).some((x) => x.resolves(kind, name))) { unresolved.push(`${rel}:${no} app.${kind}.${name}`); }
720
- }
721
- for (const [, raw] of line.matchAll(RAW_CALL)) {
722
- if (!resolvers(rel).some((x) => isFile(pjoin(x.raw, raw)))) { unresolved.push(`${rel}:${no} rawfile ${raw}`); }
723
- }
724
- });
725
- for (const [no, name, chars] of evidenceBlocks(lines)) {
726
- if (!names.includes(name)) {
727
- misnamed.push(`${rel}:${no} EVIDENCE(${name})`);
728
- continue;
729
- }
730
- covered.add(name);
731
- const tier = aTier.has(name) ? 'A' : 'B';
732
- if (chars > EVIDENCE_BUDGET[tier]) {
733
- overlong.push(`${rel}:${no} ${name} ${chars} chars (budget ${EVIDENCE_BUDGET[tier]}, tier ${tier})`);
734
- }
735
- }
736
- const code = stripComments(text);
737
- pySplitlines(code).forEach((line, k) => {
738
- const no = k + 1;
739
- if (line.includes('$r(`')) { // the backtick survives strip_comments; its body does not
740
- forbidden.push(`${rel}:${no} $r(\` template literal`);
741
- }
742
- const v1 = paradigm === 'V2' ? V1_DECORATORS.exec(line) : null;
743
- if (v1) {
744
- forbidden.push(`${rel}:${no} V1 decorator in V2 project: ${v1[0]}`);
745
- }
746
- if (/\.(position|offset)\(/.test(line)) {
747
- // Python's second search uses an unescaped `.` (any char but "\n"), kept as-is
748
- forbidden.push(`${rel}:${no} .${/[^\n](position|offset)/u.exec(line)[1]}() — needs 位置锚点证据`);
749
- }
750
- });
751
- const bal = code.split('{').length - code.split('}').length;
752
- if (bal) {
753
- braces.push(`${rel}: braces unbalanced by ${bal > 0 ? '+' : ''}${bal}`);
754
- }
755
- }
756
- rep.unresolved_resources = unresolved;
757
- rep.evidence_misnamed = misnamed;
758
- const usesLottie = [...texts.values()].some((t) => t.toLowerCase().includes('lottie'));
759
- rep.evidence_uncovered_B = names.filter((n) => !aTier.has(n) && !covered.has(n) &&
760
- (usesLottie || !n.includes('Lottie')));
761
- rep.evidence_overlong = overlong;
762
- rep.forbidden_or_candidates = forbidden;
763
- rep.braces = braces;
764
- rep.blocking += unresolved.length + misnamed.length + braces.length + rep.missing_files.length;
765
- return rep;
766
- }
767
-
768
- const pad26 = (s) => s + ' '.repeat(Math.max(0, 26 - pyLen(s))); // f"{s:26s}"
769
-
770
- export function render(rep) {
771
- const outp = [`phase5_check — ${rep.files.length} file(s); blocking=${rep.blocking}`];
772
- if (truthy(rep.changed_since_round)) {
773
- const c = rep.changed_since_round;
774
- outp.push(`\n[round rule] ${c.verdict}` + (c.files.length ? `: ${c.files.join(', ')}` : ''));
775
- }
776
- const sections = [
777
- ['missing_files', 'files not found (blocking)'],
778
- ['unresolved_resources', '$r / $rawfile that do not resolve in resources/ (blocking)'],
779
- ['evidence_misnamed', 'EVIDENCE(name) not a Phase 5 heading verbatim (blocking: rename)'],
780
- ['braces', 'brace balance (blocking)'],
781
- ['evidence_uncovered_B', 'B-tier items with no EVIDENCE tag in these files (add one, or state N/A in the report)'],
782
- ['evidence_overlong', 'EVIDENCE blocks over budget (compress: conclusion + source pointer)'],
783
- ['forbidden_or_candidates', 'patterns to justify or fix'],
784
- ];
785
- const st = or(rep.static, {});
786
- if (Object.hasOwn(st, 'error')) {
787
- outp.push(`\n[static] ${st.error} (blocking: no GATE verdict; fix the checker run and re-run)`);
788
- } else {
789
- const mine = get(st, 'mine', []);
790
- const gates = mine.filter((g) => g.kind === 'gate');
791
- const cands = mine.filter((g) => g.kind === 'cand');
792
- outp.push(`\n[static GATE, these files] ${gates.length} (blocking)`);
793
- outp.push(...gates.map((g) => ` ${pad26(g.rule)} ${g.at} ${g.msg}`));
794
- outp.push(`[static CANDIDATES, these files] ${cands.length} — annotate in the matching EVIDENCE item`);
795
- outp.push(...cands.map((g) => ` ${pad26(g.rule)} ${g.at}`));
796
- if (truthy(get(st, 'batch_level'))) {
797
- outp.push(`[static] ${st.batch_level} batch-level hit(s) (orphan/unreachable) — parent wiring, Step 5.5`);
798
- }
799
- }
800
- for (const [k, title] of sections) {
801
- const v = or(rep[k], []);
802
- outp.push(`\n[${k}] ${title}: ${v.length}`);
803
- outp.push(...v.map((x) => ` ${x}`));
804
- }
805
- return outp.join('\n');
806
- }
807
-
808
- /** Raised where Python raises SystemExit(msg): main prints msg to stderr and exits 1. */
809
- export class SystemExit extends Error {}
810
-
811
- export function _groupFiles(hp, gid) {
812
- const meta = pjoin(String(hp), '.hometrans');
813
- const progress = loadDict(pjoin(meta, 'batch_progress.json'));
814
- const uiInfo = String(or(get(progress, 'ui_info_root'), pjoin(meta, 'ui_info')));
815
- const groups = get(get(loadDict(pjoin(uiInfo, 'conversion_set.json')), 'plan', {}), 'groups', []);
816
- const g = groups.find((x) => {
817
- if (!Object.hasOwn(x, 'id')) { throw new Error("KeyError: 'id'"); }
818
- return x.id === gid;
819
- });
820
- if (g === undefined) {
821
- throw new SystemExit(`unknown group ${gid}`);
822
- }
823
- const files = get(g, 'predicted_writes', []).filter((w) => w !== 'ENTRY_PAGE');
824
- const module = String(_uiModule(hp, progress)); // the queue's resolution (group_watch._paths)
825
- const prefix = `${module}/src/main/ets/`;
826
- for (const d of get(g, 'page_dirs', [])) {
827
- // `output` 是单个路径,或(批次记账约定)路径数组 —— 实测一次运行里多文件组被记成数组,
828
- // 旧代码对数组调 .replace 直接抛 TypeError,--group 整条不可用(安装副本当场手补过)
829
- const outs = get(or(get(get(progress, 'pages', {}), d), {}), 'output', []);
830
- for (const one of (Array.isArray(outs) ? outs : [outs]).filter((x) => typeof x === 'string' && x)) {
831
- const o = one.replace(/\\/g, '/');
832
- if (o.startsWith(prefix)) {
833
- files.push(o.slice(prefix.length));
834
- } else if (!path.isAbsolute(o) && o.includes('/src/main/ets/')) {
835
- files.push(o); // a page of another module, kept with its module (group_watch.etsSplit)
836
- }
837
- }
838
- }
839
- // predicted_writes 只是调度时的**预测**:family leader 实际还写了供 follower 复用的共享组件,
840
- // 子代理也会写到预测之外的路径。实测这些文件不进 --group 的扫描面,B 档 EVIDENCE 全报
841
- // 「uncovered」,只能改用 --files 重跑。补两处「实际写了什么」的记录(与 group_watch 同源):
842
- // (a) 组报告 queue_logs/<GID>.report.md 点名、且磁盘上存在的 .ets(group_watch._reported);
843
- // (b) 该组 leader 发布的 provides/<GID>__<family>.json 标记里的 files。
844
- const ets = pjoin(String(hp), module, 'src', 'main', 'ets');
845
- const rp = reportPath(meta, gid);
846
- if (isFile(rp)) {
847
- files.push(..._reported(ets, readText(rp, true), hp));
848
- }
849
- const pdir = pjoin(meta, 'provides');
850
- let markers = [];
851
- try {
852
- markers = fs.readdirSync(pdir).filter((n) => n.startsWith(`${gid}__`) && n.endsWith('.json'));
853
- } catch { /* 尚无 provides 目录 */ }
854
- for (const n of markers) {
855
- let m;
856
- try { m = JSON.parse(readText(pjoin(pdir, n), true)); } catch { continue; }
857
- if (m === null || typeof m !== 'object' || m.group !== gid || !Array.isArray(m.files)) { continue; }
858
- for (const rel of m.files) {
859
- if (typeof rel === 'string' && rel) { files.push(rel.replace(/\\/g, '/')); }
860
- }
861
- }
862
- return pySorted([...new Set(files)]);
863
- }
864
-
865
- // ---------------------------------------------------------------- argparse equivalent
866
- // argparse's observable behaviour: unique long-option prefixes, `--opt=value`, `--`,
867
- // -h/--help (RawDescriptionHelpFormatter: the description is printed verbatim),
868
- // usage + error on stderr with exit 2.
869
-
870
- const DESCRIPTION = `Phase 5 mechanical checks for one group's files, in one call per verification round.
871
-
872
- Measured on a 14-group run, each Phase 5 round cost an agent 2-3 model turns of
873
- greps and checker runs (EVIDENCE coverage, resource existence, static GATE for
874
- its own files, "did round 2 change anything"), ~10% of its slot time. Those
875
- answers are lexical; this script gives all of them at once so the agent's turns
876
- go to the semantic checks only. It decides nothing the agent must judge: missing
877
- coverage may be legitimately N/A, and every finding names the file:line to look at.
878
-
879
- phase5_check.mjs <harmony_dir> --files pages/A.ets,components/B.ets --round 1
880
- phase5_check.mjs <harmony_dir> --group G012 --round 2
881
-
882
- Sections: changed-since-last-round (round rule), static GATE for these files,
883
- resource references that do not resolve, EVIDENCE names not matching a Phase 5
884
- heading, B-tier items with no EVIDENCE tag, over-budget EVIDENCE blocks,
885
- forbidden patterns, brace balance. Exit 1 when a blocking finding exists
886
- (GATE, unresolved resource, unbalanced braces, misnamed EVIDENCE).
887
- `;
888
-
889
- function termColumns() {
890
- const env = Number.parseInt(process.env.COLUMNS ?? '', 10);
891
- if (env > 0) { return env; }
892
- return process.stdout.isTTY && process.stdout.columns ? process.stdout.columns : 80;
893
- }
894
-
895
- /**
896
- * textwrap.wrap(width) subset: chunks are words and single spaces, a word also
897
- * breaks after an inner hyphen ("comma-" | "separated,"); overlong chunks are hard-split.
898
- */
899
- function wrapText(text, width) {
900
- const chunks = [];
901
- text.split(' ').filter((w) => w !== '').forEach((w, k) => {
902
- if (k) { chunks.push(' '); }
903
- chunks.push(...w.split(/(?<=[A-Za-z]-)(?=[A-Za-z])/));
904
- });
905
- chunks.reverse();
906
- const lines = [];
907
- while (chunks.length) {
908
- const cur = [];
909
- let len = 0;
910
- if (chunks[chunks.length - 1] === ' ' && lines.length) { chunks.pop(); }
911
- while (chunks.length) {
912
- const l = chunks[chunks.length - 1].length;
913
- if (len + l <= width) { cur.push(chunks.pop()); len += l; } else { break; }
914
- }
915
- if (chunks.length && chunks[chunks.length - 1].length > width) {
916
- const c = chunks.pop();
917
- const room = Math.max(width - len, 1);
918
- cur.push(c.slice(0, room));
919
- chunks.push(c.slice(room));
920
- }
921
- if (cur.length && cur[cur.length - 1] === ' ') { cur.pop(); }
922
- if (cur.length) { lines.push(cur.join('')); }
923
- }
924
- return lines;
925
- }
926
-
927
- /** argparse int(): Unicode decimal digits, optional sign, underscores between digits, surrounding whitespace. */
928
- function pyIntArg(val) {
929
- const t = pyStrip(val);
930
- if (!/^[+-]?\p{Nd}+(?:_\p{Nd}+)*$/u.test(t)) { return null; }
931
- let s = '';
932
- for (const ch of t.replace(/^[+-]|_/g, '')) {
933
- let cp = ch.codePointAt(0);
934
- let k = 0;
935
- while (/\p{Nd}/u.test(String.fromCodePoint(cp - 1))) { cp--; k++; }
936
- s += String(k % 10);
937
- }
938
- const v = Number(s) * (t.startsWith('-') ? -1 : 1);
939
- return v === 0 ? 0 : v;
940
- }
941
-
942
- function valRepr(s) {
943
- const q = s.includes("'") && !s.includes('"') ? '"' : "'";
944
- return q + s.replace(/\\/g, '\\\\').replace(new RegExp(q, 'g'), '\\' + q) + q;
945
- }
946
-
947
- const PROG = 'phase5_check.mjs';
948
- // action: 'store' | 'append' | 'store_true' | 'help'
949
- const ACTIONS = [
950
- { name: '-h', alias: '--help', action: 'help', help: 'show this help message and exit' },
951
- { name: 'harmony_dir', positional: true },
952
- { name: '--files', action: 'append', def: [],
953
- help: 'ets-root-relative files (comma-separated, repeatable) -- the files you wrote' },
954
- { name: '--group', action: 'store', help: 'group id: its predicted writes + recorded outputs (when --files omitted)' },
955
- { name: '--round', action: 'store', type: 'int', help: 'Phase 5 round number; snapshots files for the round rule' },
956
- { name: '--json', action: 'store_true', def: false },
957
- ];
958
-
959
- function parseArgs(argv) {
960
- const width = termColumns() - 2;
961
- const dest = (a) => a.name.replace(/^-+/, '').replace(/-/g, '_');
962
- const takesValue = (a) => a.action === 'store' || a.action === 'append';
963
- const metavar = (a) => dest(a).toUpperCase();
964
- const invocation = (a) => (a.positional ? a.name : a.alias ? `${a.name}, ${a.alias}`
965
- : takesValue(a) ? `${a.name} ${metavar(a)}` : a.name);
966
- const usagePart = (a) => (a.positional ? a.name : `[${takesValue(a) ? `${a.name} ${metavar(a)}` : a.name}]`);
967
- const opts = ACTIONS.filter((a) => !a.positional);
968
- const poss = ACTIONS.filter((a) => a.positional);
969
-
970
- const formatUsage = () => {
971
- const prefix = 'usage: ';
972
- const optParts = opts.map(usagePart);
973
- const posParts = poss.map(usagePart);
974
- let usage = [PROG, ...optParts, ...posParts].join(' ');
975
- if (prefix.length + usage.length > width) {
976
- const getLines = (parts, indent, pfx) => {
977
- const lines = [];
978
- let line = [];
979
- let len = pfx !== undefined ? pfx.length - 1 : indent.length - 1;
980
- for (const part of parts) {
981
- if (len + 1 + part.length > width && line.length) {
982
- lines.push(indent + line.join(' '));
983
- line = [];
984
- len = indent.length - 1;
985
- }
986
- line.push(part);
987
- len += part.length + 1;
988
- }
989
- if (line.length) { lines.push(indent + line.join(' ')); }
990
- if (pfx !== undefined) { lines[0] = lines[0].slice(indent.length); }
991
- return lines;
992
- };
993
- let lines;
994
- if (prefix.length + PROG.length <= 0.75 * width) {
995
- const indent = ' '.repeat(prefix.length + PROG.length + 1);
996
- lines = getLines([PROG, ...optParts], indent, prefix);
997
- lines.push(...getLines(posParts, indent));
998
- } else {
999
- const indent = ' '.repeat(prefix.length);
1000
- lines = getLines([...optParts, ...posParts], indent);
1001
- if (lines.length > 1) { lines = [...getLines(optParts, indent), ...getLines(posParts, indent)]; }
1002
- lines = [PROG, ...lines];
1003
- }
1004
- usage = lines.join('\n');
1005
- }
1006
- return prefix + usage;
1007
- };
1008
-
1009
- const formatHelp = () => {
1010
- const maxHelpPos = Math.min(24, Math.max(width - 20, 4));
1011
- const maxLen = Math.max(...ACTIONS.map((a) => invocation(a).length + 2));
1012
- const helpPos = Math.min(maxLen + 2, maxHelpPos);
1013
- const helpWidth = Math.max(width - helpPos, 11);
1014
- const actionWidth = helpPos - 2 - 2;
1015
- const item = (a) => {
1016
- const inv = invocation(a);
1017
- const rows = [];
1018
- if (!a.help) { rows.push(' ' + inv); return rows; }
1019
- let first;
1020
- if (inv.length <= actionWidth) { first = ' ' + inv.padEnd(actionWidth) + ' '; }
1021
- else { rows.push(' ' + inv); first = ' '.repeat(helpPos); }
1022
- const hl = wrapText(a.help.replace(/\s+/g, ' ').trim(), helpWidth);
1023
- rows.push(first + hl[0]);
1024
- for (const l of hl.slice(1)) { rows.push(' '.repeat(helpPos) + l); }
1025
- return rows;
1026
- };
1027
- // RawDescriptionHelpFormatter: description lines verbatim
1028
- const parts = [formatUsage(), '', DESCRIPTION.replace(/\n+$/, ''), ''];
1029
- parts.push('positional arguments:', ...poss.flatMap(item), '');
1030
- parts.push('options:', ...opts.flatMap(item));
1031
- return parts.join('\n');
1032
- };
1033
-
1034
- const fail = (msg) => {
1035
- err(formatUsage());
1036
- err(`${PROG}: error: ${msg}`);
1037
- process.exit(2);
1038
- };
1039
-
1040
- const result = {};
1041
- for (const a of ACTIONS) { if (a.action !== 'help') { result[dest(a)] = Array.isArray(a.def) ? [...a.def] : (a.def ?? null); } }
1042
- const seen = new Set();
1043
- const positionals = [];
1044
- const extras = [];
1045
- const longNames = opts.flatMap((a) => (a.alias ? [[a.name, a], [a.alias, a]] : [[a.name, a]]));
1046
- const looksNegative = (s) => /^-\d+$|^-\d*\.\d+$/.test(s);
1047
- const isOptionLike = (s) => s.startsWith('-') && s !== '-' && !looksNegative(s) && !(s.includes(' ') && !findOpt(s));
1048
- function findOpt(s) {
1049
- const [k] = s.split('=', 1);
1050
- const exact = longNames.find(([nm]) => nm === k);
1051
- if (exact) { return exact[1]; }
1052
- if (!k.startsWith('--')) { return null; }
1053
- const hits = longNames.filter(([nm]) => nm.startsWith(k));
1054
- const uniq = [...new Set(hits.map((h) => h[1]))];
1055
- if (uniq.length > 1) { fail(`ambiguous option: ${k} could match ${hits.map((h) => h[0]).join(', ')}`); }
1056
- return uniq[0] ?? null;
1057
- }
1058
- let i = 0;
1059
- let rest = false;
1060
- while (i < argv.length) {
1061
- const s = argv[i];
1062
- if (!rest && s === '--') { rest = true; i++; continue; }
1063
- if (rest || !isOptionLike(s)) { positionals.push(s); i++; continue; }
1064
- const a = findOpt(s);
1065
- if (!a) { extras.push(s); i++; continue; }
1066
- const eq = s.indexOf('=');
1067
- const shown = a.alias ? `${a.name}/${a.alias}` : a.name;
1068
- if (!takesValue(a)) {
1069
- if (eq >= 0) { fail(`argument ${shown}: ignored explicit argument '${s.slice(eq + 1)}'`); }
1070
- if (a.action === 'help') {
1071
- process.stdout.write((formatHelp() + '\n').replace(/\n/g, EOL));
1072
- process.exit(0);
1073
- }
1074
- result[dest(a)] = true;
1075
- i++;
1076
- continue;
1077
- }
1078
- let val;
1079
- if (eq >= 0 && s.startsWith('--')) { val = s.slice(eq + 1); i++; }
1080
- else if (i + 1 < argv.length && !(argv[i + 1] === '--' || isOptionLike(argv[i + 1]))) { val = argv[i + 1]; i += 2; }
1081
- else { fail(`argument ${shown}: expected one argument`); }
1082
- if (a.type === 'int') {
1083
- const v = pyIntArg(val);
1084
- if (v === null) { fail(`argument ${shown}: invalid int value: ${valRepr(val)}`); }
1085
- val = v;
1086
- }
1087
- if (a.action === 'append') { result[dest(a)].push(val); } else { result[dest(a)] = val; }
1088
- seen.add(a);
1089
- }
1090
- poss.forEach((a, k) => { if (k < positionals.length) { result[dest(a)] = positionals[k]; seen.add(a); } });
1091
- extras.push(...positionals.slice(poss.length));
1092
- const missing = poss.filter((a) => !seen.has(a)).map((a) => a.name);
1093
- if (missing.length) { fail(`the following arguments are required: ${missing.join(', ')}`); }
1094
- if (extras.length) { fail(`unrecognized arguments: ${extras.join(' ')}`); }
1095
- result.error = fail;
1096
- return result;
1097
- }
1098
-
1099
- export function main(argv = process.argv.slice(2)) {
1100
- const a = parseArgs(argv);
1101
- const files = a.files.flatMap((v) => v.split(',')).filter((f) => pyStrip(f)).map((f) => pyStrip(f).replace(/\\/g, '/'));
1102
- let fl = files;
1103
- try {
1104
- if (!fl.length) {
1105
- if (!truthy(a.group)) {
1106
- a.error('give --files or --group');
1107
- }
1108
- fl = _groupFiles(a.harmony_dir, a.group);
1109
- }
1110
- const rep = check(a.harmony_dir, fl, a.round, a.group);
1111
- out(a.json ? pyJsonDumps(rep, 1, false) : render(rep));
1112
- return rep.blocking ? 1 : 0;
1113
- } catch (e) {
1114
- if (e instanceof SystemExit) {
1115
- err(e.message);
1116
- return 1;
1117
- }
1118
- throw e;
1119
- }
1120
- }
1121
-
1122
- if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
1123
- process.exitCode = main();
1124
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Phase 5 mechanical checks for one group's files, in one call per verification round.
4
+ *
5
+ * Measured on a 14-group run, each Phase 5 round cost an agent 2-3 model turns of
6
+ * greps and checker runs (EVIDENCE coverage, resource existence, static GATE for
7
+ * its own files, "did round 2 change anything"), ~10% of its slot time. Those
8
+ * answers are lexical; this script gives all of them at once so the agent's turns
9
+ * go to the semantic checks only. It decides nothing the agent must judge: missing
10
+ * coverage may be legitimately N/A, and every finding names the file:line to look at.
11
+ *
12
+ * node phase5_check.mjs <harmony_dir> --files pages/A.ets,components/B.ets --round 1
13
+ * node phase5_check.mjs <harmony_dir> --group G012 --round 2
14
+ *
15
+ * Sections: changed-since-last-round (round rule), static GATE for these files,
16
+ * resource references that do not resolve, EVIDENCE names not matching a Phase 5
17
+ * heading, B-tier items with no EVIDENCE tag, over-budget EVIDENCE blocks,
18
+ * forbidden patterns, brace balance. Exit 1 when a blocking finding exists
19
+ * (GATE, unresolved resource, unbalanced braces, misnamed EVIDENCE).
20
+ *
21
+ * (Node >= 22.18, ESM, zero dependencies. Behaviour-identical port of
22
+ * phase5_check.py: same args, exit codes, stdout and snapshot file.)
23
+ */
24
+
25
+ import * as crypto from 'node:crypto';
26
+ import * as fs from 'node:fs';
27
+ import * as path from 'node:path';
28
+ import { spawnSync } from 'node:child_process';
29
+ import { fileURLToPath, pathToFileURL } from 'node:url';
30
+
31
+ import { _reported, _replace, _uiModule, etsSplit, reportPath } from './group_watch.mjs';
32
+ import { textColorDiff } from './text_color_diff.mjs';
33
+
34
+ // ---------------------------------------------------------------- Python 兼容层
35
+ // 输出是 agent 读取的契约,须与原 Python 版逐字节一致:JSON 按 json.dumps 的格式
36
+ // (对象键按插入顺序,快照文件 ensure_ascii=True),Windows 文本按 \r\n 写出,
37
+ // 字符串长度/切片按码点,正则的 \w \s \d \b 按 Python 的 Unicode 语义。
38
+
39
+ const IS_WIN = process.platform === 'win32';
40
+ const EOL = IS_WIN ? '\r\n' : '\n';
41
+
42
+ /** json.loads 读到的浮点数:保留「它是 float」这一事实,写回时按 Python repr 输出。 */
43
+ class PyFloat {
44
+ constructor(value) { this.value = value; }
45
+ valueOf() { return this.value; }
46
+ }
47
+
48
+ // 含整数形键("0"、"12")的对象,JS 会把这些键提前;记下 Python 的插入顺序。
49
+ const KEY_ORDER = Symbol('pyKeyOrder');
50
+ const INDEX_KEY = /^(?:0|[1-9][0-9]*)$/;
51
+
52
+ function floatRepr(x) {
53
+ if (!Number.isFinite(x)) {
54
+ if (Number.isNaN(x)) { return 'NaN'; }
55
+ return x > 0 ? 'Infinity' : '-Infinity';
56
+ }
57
+ if (x === 0) { return Object.is(x, -0) ? '-0.0' : '0.0'; }
58
+ const [m, e] = Math.abs(x).toExponential().split('e');
59
+ const digits = m.replace('.', '');
60
+ const exp = Number(e);
61
+ let s;
62
+ if (exp >= -4 && exp < 16) {
63
+ if (exp >= 0) {
64
+ const ip = digits.slice(0, exp + 1).padEnd(exp + 1, '0');
65
+ s = ip + '.' + (digits.slice(exp + 1) || '0');
66
+ } else {
67
+ s = '0.' + '0'.repeat(-exp - 1) + digits;
68
+ }
69
+ } else {
70
+ s = digits[0] + (digits.length > 1 ? '.' + digits.slice(1) : '') + 'e' + (exp < 0 ? '-' : '+') +
71
+ String(Math.abs(exp)).padStart(2, '0');
72
+ }
73
+ return (x < 0 ? '-' : '') + s;
74
+ }
75
+
76
+ /** json.loads:浮点 → PyFloat,超出安全整数范围的整数 → BigInt,保留键序。 */
77
+ function pyJsonLoads(text) {
78
+ let i = 0;
79
+ const n = text.length;
80
+ const fail = (msg) => { throw new SyntaxError(`${msg}: char ${i}`); };
81
+ const ws = () => {
82
+ while (i < n) {
83
+ const c = text.charCodeAt(i);
84
+ if (c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d) { i++; } else { break; }
85
+ }
86
+ };
87
+ const NUM = /-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/y;
88
+ const str = () => {
89
+ i++;
90
+ let out = '';
91
+ let start = i;
92
+ for (;;) {
93
+ if (i >= n) { fail('Unterminated string'); }
94
+ const c = text.charCodeAt(i);
95
+ if (c === 0x22) { out += text.slice(start, i); i++; return out; }
96
+ if (c < 0x20) { fail('Invalid control character'); }
97
+ if (c === 0x5c) {
98
+ out += text.slice(start, i);
99
+ const esc = text[i + 1];
100
+ const simple = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }[esc];
101
+ if (simple !== undefined) {
102
+ out += simple;
103
+ i += 2;
104
+ } else if (esc === 'u') {
105
+ const hex = text.slice(i + 2, i + 6);
106
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) { fail('Invalid \\uXXXX escape'); }
107
+ out += String.fromCharCode(parseInt(hex, 16));
108
+ i += 6;
109
+ } else {
110
+ fail('Invalid \\escape');
111
+ }
112
+ start = i;
113
+ continue;
114
+ }
115
+ i++;
116
+ }
117
+ };
118
+ const value = () => {
119
+ ws();
120
+ const c = text[i];
121
+ if (c === '{') {
122
+ i++;
123
+ const o = {};
124
+ ws();
125
+ if (text[i] === '}') { i++; return o; }
126
+ for (;;) {
127
+ ws();
128
+ if (text[i] !== '"') { fail('Expecting property name enclosed in double quotes'); }
129
+ const k = str();
130
+ ws();
131
+ if (text[i] !== ':') { fail("Expecting ':' delimiter"); }
132
+ i++;
133
+ pySet(o, k, value());
134
+ ws();
135
+ if (text[i] === ',') { i++; continue; }
136
+ if (text[i] === '}') { i++; break; }
137
+ fail("Expecting ',' delimiter");
138
+ }
139
+ return o;
140
+ }
141
+ if (c === '[') {
142
+ i++;
143
+ const a = [];
144
+ ws();
145
+ if (text[i] === ']') { i++; return a; }
146
+ for (;;) {
147
+ a.push(value());
148
+ ws();
149
+ if (text[i] === ',') { i++; continue; }
150
+ if (text[i] === ']') { i++; break; }
151
+ fail("Expecting ',' delimiter");
152
+ }
153
+ return a;
154
+ }
155
+ if (c === '"') { return str(); }
156
+ if (text.startsWith('null', i)) { i += 4; return null; }
157
+ if (text.startsWith('true', i)) { i += 4; return true; }
158
+ if (text.startsWith('false', i)) { i += 5; return false; }
159
+ if (text.startsWith('NaN', i)) { i += 3; return new PyFloat(NaN); }
160
+ if (text.startsWith('Infinity', i)) { i += 8; return new PyFloat(Infinity); }
161
+ if (text.startsWith('-Infinity', i)) { i += 9; return new PyFloat(-Infinity); }
162
+ NUM.lastIndex = i;
163
+ const m = NUM.exec(text);
164
+ if (!m) { fail('Expecting value'); }
165
+ i += m[0].length;
166
+ if (m[1] !== undefined || m[2] !== undefined) { return new PyFloat(Number(m[0])); }
167
+ const num = Number(m[0]);
168
+ return Number.isSafeInteger(num) ? (num === 0 ? 0 : num) : BigInt(m[0]);
169
+ };
170
+ const v = value();
171
+ ws();
172
+ if (i !== n) { fail('Extra data'); }
173
+ return v;
174
+ }
175
+
176
+ /** d[k] = v with Python dict insertion order (new keys go last, existing keys keep their slot). */
177
+ function pySet(o, k, v) {
178
+ if (!Object.hasOwn(o, k)) {
179
+ if (o[KEY_ORDER]) { o[KEY_ORDER].push(k); }
180
+ else if (INDEX_KEY.test(k)) { o[KEY_ORDER] = [...Object.keys(o), k]; }
181
+ }
182
+ Object.defineProperty(o, k, { value: v, enumerable: true, writable: true, configurable: true });
183
+ }
184
+
185
+ function keysOf(o) {
186
+ const ord = o[KEY_ORDER];
187
+ return ord ? ord.filter((k) => Object.hasOwn(o, k)) : Object.keys(o);
188
+ }
189
+
190
+ /** A JSON string literal: ensure_ascii escapes everything outside ' '..'~' (UTF-16 units, lowercase hex). */
191
+ function jsonStr(s, ascii) {
192
+ if (!ascii) { return JSON.stringify(s); }
193
+ const short = { '"': '\\"', '\\': '\\\\', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\b': '\\b', '\f': '\\f' };
194
+ let r = '"';
195
+ for (let i = 0; i < s.length; i++) {
196
+ const ch = s[i];
197
+ const c = s.charCodeAt(i);
198
+ if (short[ch] !== undefined) { r += short[ch]; }
199
+ else if (c < 0x20 || c > 0x7e) { r += '\\u' + c.toString(16).padStart(4, '0'); }
200
+ else { r += ch; }
201
+ }
202
+ return r + '"';
203
+ }
204
+
205
+ /** json.dumps(v, indent=indent, ensure_ascii=ascii). undefined is treated as None. */
206
+ function pyJsonDumps(v, indent, ascii, level = 0) {
207
+ if (v === null || v === undefined) { return 'null'; }
208
+ if (v === true) { return 'true'; }
209
+ if (v === false) { return 'false'; }
210
+ if (typeof v === 'bigint') { return v.toString(); }
211
+ if (v instanceof PyFloat) { return floatRepr(v.value); }
212
+ if (typeof v === 'number') { return Number.isInteger(v) ? (Object.is(v, -0) ? '0' : String(v)) : floatRepr(v); }
213
+ if (typeof v === 'string') { return jsonStr(v, ascii); }
214
+ const pad = '\n' + ' '.repeat(indent * (level + 1));
215
+ const end = '\n' + ' '.repeat(indent * level);
216
+ if (Array.isArray(v)) {
217
+ if (v.length === 0) { return '[]'; }
218
+ return '[' + pad + v.map((x) => pyJsonDumps(x, indent, ascii, level + 1)).join(',' + pad) + end + ']';
219
+ }
220
+ const ks = keysOf(v);
221
+ if (ks.length === 0) { return '{}'; }
222
+ return '{' + pad + ks.map((k) => jsonStr(k, ascii) + ': ' + pyJsonDumps(v[k], indent, ascii, level + 1))
223
+ .join(',' + pad) + end + '}';
224
+ }
225
+
226
+ const UTF8_STRICT = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
227
+ const UTF8_REPLACE = new TextDecoder('utf-8', { fatal: false, ignoreBOM: true });
228
+
229
+ /** Path.read_text(encoding="utf-8"[, errors="replace"]): keeps a BOM, universal newlines. */
230
+ function readText(p, replace = false) {
231
+ return (replace ? UTF8_REPLACE : UTF8_STRICT).decode(fs.readFileSync(p)).replace(/\r\n?/g, '\n');
232
+ }
233
+
234
+ /** Path.write_text: Windows text mode writes \n as \r\n. */
235
+ function writeText(p, s) {
236
+ fs.writeFileSync(p, IS_WIN ? s.replace(/\n/g, '\r\n') : s, 'utf8');
237
+ }
238
+
239
+ /** print() on a text-mode stdout. */
240
+ function out(s = '') { process.stdout.write((s + '\n').replace(/\n/g, EOL)); }
241
+ function err(s = '') { process.stderr.write((s + '\n').replace(/\n/g, EOL)); }
242
+
243
+ function isFile(p) {
244
+ try { return fs.statSync(p, { throwIfNoEntry: false })?.isFile() ?? false; } catch { return false; }
245
+ }
246
+
247
+ /** Path(a) / b / c: an absolute (or drive-qualified) segment replaces what came before. */
248
+ function pjoin(base, ...segs) {
249
+ let acc = String(base);
250
+ for (const s of segs.map(String)) {
251
+ if (IS_WIN && /^[\\/](?![\\/])/.test(s)) {
252
+ // rooted but driveless: keeps the drive of what came before
253
+ const drv = /^([A-Za-z]:|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.exec(acc);
254
+ acc = (drv ? drv[0] : '') + s;
255
+ } else if (path.isAbsolute(s) || (IS_WIN && /^[A-Za-z]:/.test(s))) {
256
+ acc = s;
257
+ } else {
258
+ acc = path.join(acc, s);
259
+ }
260
+ }
261
+ return acc;
262
+ }
263
+
264
+ /** dict.get(k, d): the default only when the key is absent (a null value is returned as null). */
265
+ function get(o, k, d = undefined) {
266
+ if (o === null || typeof o !== 'object') { throw new TypeError(`'${o === null ? 'NoneType' : typeof o}' object has no attribute 'get'`); }
267
+ if (Array.isArray(o)) { throw new TypeError("'list' object has no attribute 'get'"); }
268
+ return Object.hasOwn(o, k) ? o[k] : d;
269
+ }
270
+
271
+ function truthy(v) {
272
+ if (v === null || v === undefined || v === false) { return false; }
273
+ if (v === true) { return true; }
274
+ if (typeof v === 'number') { return v !== 0; }
275
+ if (typeof v === 'bigint') { return v !== 0n; }
276
+ if (v instanceof PyFloat) { return v.value !== 0; }
277
+ if (typeof v === 'string' || Array.isArray(v)) { return v.length > 0; }
278
+ if (v instanceof Map || v instanceof Set) { return v.size > 0; }
279
+ return Object.keys(v).length > 0;
280
+ }
281
+
282
+ /** Python `a or b`. */
283
+ function or(a, b) { return truthy(a) ? a : b; }
284
+
285
+ /** _load(p) or {}, which must then be a dict (`.get` / `.items()` on anything else raises). */
286
+ function loadDict(p) {
287
+ const v = or(_load(p, {}), {});
288
+ if (typeof v !== 'object' || Array.isArray(v)) { throw new TypeError(`'${Array.isArray(v) ? 'list' : typeof v}' object has no attribute 'get'`); }
289
+ return v;
290
+ }
291
+
292
+ // str.isspace() / re's Unicode \s, and re's Unicode \w (str.isalnum() or '_').
293
+ const PY_WS = '\\t\\n\\x0b\\x0c\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000';
294
+ const S = `[${PY_WS}]`;
295
+ const NS = `[^${PY_WS}]`;
296
+ const W = '[\\p{L}\\p{N}_]';
297
+ const STRIP_RE = new RegExp(`^${S}+|${S}+$`, 'gu');
298
+
299
+ /** str.strip(). */
300
+ function pyStrip(s) { return s.replace(STRIP_RE, ''); }
301
+
302
+ /** str.splitlines(): every Python line boundary, no trailing empty item. */
303
+ function pySplitlines(s) {
304
+ if (s === '') { return []; }
305
+ const parts = s.split(/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/);
306
+ if (parts[parts.length - 1] === '') { parts.pop(); }
307
+ return parts;
308
+ }
309
+
310
+ /** len(s): code points. */
311
+ function pyLen(s) {
312
+ let n = 0;
313
+ for (const _ of s) { n++; }
314
+ return n;
315
+ }
316
+
317
+ /** s[:k] by code points. */
318
+ function pyHead(s, k) {
319
+ let r = '';
320
+ let n = 0;
321
+ for (const ch of s) {
322
+ if (n++ >= k) { break; }
323
+ r += ch;
324
+ }
325
+ return r;
326
+ }
327
+
328
+ /** String `<` as Python compares str: by code point. */
329
+ function cmpStr(a, b) {
330
+ const x = [...a];
331
+ const y = [...b];
332
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
333
+ const d = x[i].codePointAt(0) - y[i].codePointAt(0);
334
+ if (d !== 0) { return d < 0 ? -1 : 1; }
335
+ }
336
+ return x.length < y.length ? -1 : x.length > y.length ? 1 : 0;
337
+ }
338
+
339
+ function pySorted(items) {
340
+ for (const x of items) {
341
+ if (typeof x !== 'string') { throw new TypeError("'<' not supported between instances of non-str values"); }
342
+ }
343
+ return [...items].sort(cmpStr);
344
+ }
345
+
346
+ /** str(Path(p)): separators normalised, `.` parts and trailing separators dropped. */
347
+ function pathStr(p) {
348
+ if (!IS_WIN) {
349
+ const s = String(p);
350
+ const root = s.startsWith('//') && !s.startsWith('///') ? '//' : s.startsWith('/') ? '/' : '';
351
+ return (root + s.split('/').filter((x) => x !== '' && x !== '.').join('/')) || '.';
352
+ }
353
+ const s = String(p).replace(/\//g, '\\');
354
+ let drive = '';
355
+ let rest = s;
356
+ const unc = /^\\\\([^\\]+)\\([^\\]+)/.exec(s);
357
+ if (unc) { drive = unc[0]; rest = s.slice(drive.length); }
358
+ else if (/^[A-Za-z]:/.test(s)) { drive = s.slice(0, 2); rest = s.slice(2); }
359
+ const root = rest.startsWith('\\') ? '\\' : '';
360
+ return (drive + root + rest.split('\\').filter((x) => x !== '' && x !== '.').join('\\')) || '.';
361
+ }
362
+
363
+ /** Path(p).stem (3.13: a trailing dot is not a suffix). */
364
+ function pathStem(name) {
365
+ const i = name.lastIndexOf('.');
366
+ return i > 0 && i < name.length - 1 ? name.slice(0, i) : name;
367
+ }
368
+
369
+ /** Entries of dir whose name matches a glob `*` segment (`*` or `*<suffix>`), case-insensitive on Windows. */
370
+ function globDir(dir, suffix = '', dirsOnly = false) {
371
+ const outp = [];
372
+ let ents;
373
+ try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return outp; }
374
+ for (const e of ents) {
375
+ const nm = e.name;
376
+ const ok = IS_WIN ? nm.toLowerCase().endsWith(suffix.toLowerCase()) : nm.endsWith(suffix);
377
+ if (!ok || nm.length < suffix.length) { continue; }
378
+ const full = path.join(dir, nm);
379
+ if (dirsOnly) {
380
+ let isDir = e.isDirectory();
381
+ if (e.isSymbolicLink()) { try { isDir = fs.statSync(full).isDirectory(); } catch { isDir = false; } }
382
+ if (!isDir) { continue; }
383
+ }
384
+ outp.push(full);
385
+ }
386
+ return outp;
387
+ }
388
+
389
+ // Path(root).glob("*/<sub>/*<suffix>"): a literal middle segment is joined as-is (pathlib 3.13).
390
+ function globSub(root, sub, suffix = '') {
391
+ return globDir(root, '', true).flatMap((d) => globDir(path.join(d, sub), suffix));
392
+ }
393
+
394
+ /** repr() of a list of str (for the TimeoutExpired message). */
395
+ function strListRepr(xs) {
396
+ return '[' + xs.map((s) => {
397
+ const q = s.includes("'") && !s.includes('"') ? '"' : "'";
398
+ return q + s.replace(/\\/g, '\\\\').replace(new RegExp(q, 'g'), '\\' + q) + q;
399
+ }).join(', ') + ']';
400
+ }
401
+
402
+ // ---------------------------------------------------------------- constants
403
+
404
+ const HERE = fs.realpathSync.native(path.dirname(fileURLToPath(import.meta.url)));
405
+ export const PROCEDURE = path.join(path.dirname(HERE), 'references', 'conversion-procedure.md');
406
+ // rules whose subject is the whole batch (Step 5.5 parent wiring), not one group
407
+ export const BATCH_RULES = new Set(['orphan-component', 'converted-page-unreachable', 'entry-route-not-converted']);
408
+ export const EVIDENCE_BUDGET = { A: 200, B: 400 }; // chars per EVIDENCE comment block
409
+ // Python: \$r\(\s*['"]app\.(\w+)\.([\w.]+)['"]\s*\) (Unicode \s / \w)
410
+ export const R_CALL = new RegExp(`\\$r\\(${S}*['"]app\\.(${W}+)\\.((?:${W}|\\.)+)['"]${S}*\\)`, 'gu');
411
+ export const RAW_CALL = new RegExp(`\\$rawfile\\(${S}*['"]([^'"]+)['"]${S}*\\)`, 'gu');
412
+ export const JSON_OF = new Map([['string', 'string'], ['color', 'color'], ['float', 'float'], ['integer', 'integer'],
413
+ ['boolean', 'boolean'], ['plural', 'plural'], ['strarray', 'strarray'],
414
+ ['intarray', 'intarray'], ['pattern', 'pattern'], ['theme', 'theme']]);
415
+ // Python: @(...)\b(?!V2) — the name always ends in a word char, so \b == "next char is not \w"
416
+ export const V1_DECORATORS = new RegExp('@(Component|State|Prop|Link|Provide|Consume|Observed|ObjectLink|' +
417
+ `Track|StorageLink|StorageProp|Watch)(?!${W})(?!V2)`, 'u');
418
+ /** The checker's first line: `arkts_static_check — 扫描 <n> 个 .ets 文件(...)`. */
419
+ const STATIC_HEAD = /^arkts_static_check\b.*?扫描 (\d+) 个 \.ets 文件/mu;
420
+ const STATIC_LINE = new RegExp(`^${S}{2}([a-z0-9-]+)${S}+(${NS}+?):(\\p{Nd}+)${S}*$`, 'u');
421
+
422
+ function _load(p, dflt = null) {
423
+ return isFile(p) ? pyJsonLoads(readText(p)) : dflt;
424
+ }
425
+
426
+ /** (all Phase 5 item headings, A-tier subset) parsed from conversion-procedure.md. */
427
+ export function procedureItems(p = PROCEDURE) {
428
+ const text = readText(p);
429
+ const at = text.indexOf('## Phase 5');
430
+ if (at < 0) { throw new Error('substring not found'); }
431
+ let sec = text.slice(at);
432
+ if (sec.slice(5).includes('\n## ')) { sec = sec.slice(0, sec.indexOf('\n## ', 5)); }
433
+ const start = sec.indexOf('逐项**走完以下检查'); // the check-item list follows this line
434
+ let body = start >= 0 ? sec.slice(start) : sec;
435
+ if (body.includes('\n### ')) { body = body.slice(0, body.indexOf('\n### ')); }
436
+ // re.M `^` matches at the start and after "\n" only
437
+ const items = [...body.matchAll(/(?:^|(?<=\n))- \*\*([^*]+?)\*\*/g)].map((m) => m[1]);
438
+ const aLine = /\*\*A 档[^\n]*\n([^\n]+)/.exec(sec);
439
+ const aTier = new Set(aLine ? [...aLine[1].matchAll(/`([^`]+)`/g)].map((m) => m[1]) : []);
440
+ const names = [];
441
+ for (let it of items) {
442
+ // re.sub(r"[((].*$", "", it): `.` is not "\n", `$` is the end or before a final "\n"
443
+ it = pyStrip(it.replace(/[((][^\n]*(?=\n?$)/g, ''));
444
+ if (it && !names.includes(it)) { names.push(it); }
445
+ }
446
+ return [names, aTier];
447
+ }
448
+
449
+ /** Blank out comments and string bodies (same length) so code-only scans stay line-true. */
450
+ export function stripComments(src) {
451
+ const blank = (s) => s.replace(/[^\n]/gu, ' '); // one space per code point, like Python
452
+ const outp = [];
453
+ let i = 0;
454
+ const n = src.length;
455
+ while (i < n) {
456
+ const two = src.slice(i, i + 2);
457
+ if (two === '//') {
458
+ let j = src.indexOf('\n', i);
459
+ j = j < 0 ? n : j;
460
+ outp.push(blank(src.slice(i, j))); i = j;
461
+ } else if (two === '/*') {
462
+ let j = src.indexOf('*/', i + 2);
463
+ j = j < 0 ? n : j + 2;
464
+ outp.push(blank(src.slice(i, j))); i = j;
465
+ } else if ("'\"`".includes(src[i])) {
466
+ const q = src[i];
467
+ let j = i + 1;
468
+ while (j < n && src[j] !== q) { j += src[j] === '\\' ? 2 : 1; }
469
+ outp.push(q + blank(src.slice(i + 1, j)) + (j < n ? q : '')); i = j + 1;
470
+ } else {
471
+ outp.push(src[i]); i += 1;
472
+ }
473
+ }
474
+ return outp.join('');
475
+ }
476
+
477
+ /** [[line_no, name, chars]] -- a block is the EVIDENCE line plus its indented // continuation. */
478
+ export function evidenceBlocks(lines) {
479
+ const blocks = [];
480
+ let cur = null;
481
+ lines.forEach((line, k) => {
482
+ const no = k + 1;
483
+ const s = pyStrip(line);
484
+ const m = s.startsWith('//') ? /EVIDENCE\(([^)]*)\)/.exec(s) : null;
485
+ if (m) {
486
+ cur = [no, pyStrip(m[1]), pyLen(s)];
487
+ blocks.push(cur);
488
+ } else if (cur && s.startsWith('//') && !s.startsWith('// EVIDENCE')) {
489
+ cur[2] += pyLen(s);
490
+ } else {
491
+ cur = null;
492
+ }
493
+ });
494
+ return blocks.map((b) => [...b]);
495
+ }
496
+
497
+ export class Resources {
498
+ constructor(resRoot) {
499
+ this.root = String(resRoot);
500
+ this.names = new Map();
501
+ for (const f of globSub(this.root, 'element', '.json')) {
502
+ const data = or(_load(f, {}), {});
503
+ if (typeof data !== 'object' || Array.isArray(data)) { throw new TypeError("object has no attribute 'items'"); }
504
+ for (const kind of keysOf(data)) {
505
+ const rows = data[kind];
506
+ for (const r of Array.isArray(rows) ? rows : []) {
507
+ if (r !== null && typeof r === 'object' && !Array.isArray(r) && Object.hasOwn(r, 'name')) {
508
+ setdefault(this.names, kind, new Set()).add(r.name);
509
+ }
510
+ }
511
+ }
512
+ }
513
+ this.media = new Set(globSub(this.root, 'media').map((p) => pathStem(path.basename(p))));
514
+ this.profile = new Set(globSub(this.root, 'profile').map((p) => pathStem(path.basename(p))));
515
+ this.raw = path.join(this.root, 'rawfile');
516
+ }
517
+
518
+ resolves(kind, name) {
519
+ if (kind === 'media') { return this.media.has(name); }
520
+ if (kind === 'profile') { return this.profile.has(name); }
521
+ const k = JSON_OF.has(kind) ? JSON_OF.get(kind) : kind;
522
+ return (this.names.get(k) ?? new Set()).has(name);
523
+ }
524
+ }
525
+
526
+ function setdefault(m, k, d) {
527
+ if (!m.has(k)) { m.set(k, d); }
528
+ return m.get(k);
529
+ }
530
+
531
+ /** Runs arkts_static_check.ts and keeps the GATE / CANDIDATES rows for `files`. Returns [result, error]. */
532
+ export function staticGate(ets, res, files, android = '') {
533
+ const script = path.join(HERE, 'arkts_static_check.ts');
534
+ const args = [script, '--ets', pathStr(ets), '--resources', pathStr(res)];
535
+ // --android enables the source-side rules (framework-picker-appearance, android-immersive-not-mirrored)
536
+ if (android) args.push('--android', pathStr(android));
537
+ const r = spawnSync(process.execPath, args, { timeout: 300 * 1000, maxBuffer: 1 << 30, windowsHide: true });
538
+ if (r.error) {
539
+ const e = r.error;
540
+ const msg = e.code === 'ETIMEDOUT'
541
+ ? `Command '${strListRepr(['node', ...args])}' timed out after 300 seconds`
542
+ : (IS_WIN && e.code === 'ENOENT' ? '[WinError 2] The system cannot find the file specified'
543
+ : `[Errno ${-(e.errno ?? 0)}] ${e.message}`);
544
+ return [null, `static checker did not run: ${msg}`];
545
+ }
546
+ // text=True, encoding="utf-8": strict decode + universal newlines
547
+ const outText = UTF8_STRICT.decode(r.stdout ?? Buffer.alloc(0)).replace(/\r\n?/g, '\n');
548
+ // The checker's contract (arkts_static_check.ts main): exit 0 = no GATE, 1 = GATE findings,
549
+ // 2 = bad args / no --ets root. Anything else (a crash, a kill) or output without its header
550
+ // and [GATE] section is no verdict: read as a pass it would wave the group through.
551
+ const tail = (b) => pyHead(String(b ?? '').trim().split(/\r?\n/).slice(-3).join(' | '), 300);
552
+ if (r.signal) { return [null, `static checker killed by ${r.signal}`]; }
553
+ if (r.status !== 0 && r.status !== 1) {
554
+ return [null, `static checker exit ${r.status}: ${tail(r.stderr) || tail(outText) || 'no output'}`];
555
+ }
556
+ const scanned = STATIC_HEAD.exec(outText);
557
+ if (!scanned || !/^\[GATE\]/m.test(outText)) {
558
+ return [null, `static checker exit ${r.status} printed no report: ${tail(r.stderr) || tail(outText) || 'no output'}`];
559
+ }
560
+ // Its own note: 0 files scanned prints "GATE 0" and exits 0, the same shape as a full pass.
561
+ if (Number(scanned[1]) === 0) { return [null, `static checker scanned 0 .ets files under ${pathStr(ets)}`]; }
562
+ const mine = [];
563
+ let batch = 0;
564
+ let section = null;
565
+ let last = null;
566
+ const want = new Set(files.map((f) => f.replace(/\\/g, '/')));
567
+ for (const line of pySplitlines(outText)) {
568
+ if (line.startsWith('[GATE]')) {
569
+ section = 'gate';
570
+ } else if (line.startsWith('[CANDIDATES]')) {
571
+ section = 'cand';
572
+ }
573
+ const m = STATIC_LINE.exec(line);
574
+ if (m && (section === 'gate' || section === 'cand')) {
575
+ const [, rule, f, ln] = m;
576
+ last = null;
577
+ if (want.has(f)) {
578
+ if (BATCH_RULES.has(rule)) {
579
+ batch += 1;
580
+ } else {
581
+ last = { kind: section, rule, at: `${f}:${ln}`, msg: '' };
582
+ mine.push(last);
583
+ }
584
+ }
585
+ } else if (last !== null && line.startsWith(' '.repeat(10)) && !last.msg) {
586
+ last.msg = pyHead(pyStrip(line), 160);
587
+ }
588
+ }
589
+ return [{ mine, batch_level: batch }, null];
590
+ }
591
+
592
+ // Tests replace hooks.staticGate (the Python tests monkeypatch pc.static_gate).
593
+ export const hooks = { staticGate };
594
+
595
+ /** File name of a round-snapshot key: the group id, or a digest of a --files list. */
596
+ export function roundsName(key) {
597
+ const k = String(key);
598
+ return /^[\w.-]{1,80}$/.test(k) ? k : `files-${crypto.createHash('sha1').update(k, 'utf8').digest('hex').slice(0, 16)}`;
599
+ }
600
+
601
+ /**
602
+ * The static gate per module root: one run over each module root the files live in, asked for
603
+ * the module-relative names the checker prints (a UI-module file given as
604
+ * `entry/src/main/ets/pages/A.ets` is `pages/A.ets` to it); findings are mapped back to the
605
+ * name each file was given.
606
+ */
607
+ export function gateByModule(ets, res, files, rootOf, android = '') {
608
+ const ui = path.resolve(ets);
609
+ const by = new Map();
610
+ for (const rel of files) {
611
+ const [root, inner] = rootOf.get(rel) ?? [ui, rel];
612
+ if (!by.has(root)) by.set(root, new Map());
613
+ by.get(root).set(inner, rel);
614
+ }
615
+ if (!by.size) return hooks.staticGate(ets, res, files, android);
616
+ const merged = { mine: [], batch_level: 0 };
617
+ for (const [root, names] of by) {
618
+ const [g, e] = root === ui ? hooks.staticGate(ets, res, [...names.keys()], android)
619
+ : hooks.staticGate(root, path.join(path.dirname(root), 'resources'), [...names.keys()], android);
620
+ if (g === null) return [null, root === ui ? e : `${e} (module ${root})`];
621
+ merged.batch_level += g.batch_level ?? 0;
622
+ for (const f of g.mine) {
623
+ const at = /^(.*):(\d+)$/.exec(f.at);
624
+ merged.mine.push(at && names.has(at[1]) ? { ...f, at: `${names.get(at[1])}:${at[2]}` } : f);
625
+ }
626
+ }
627
+ return [merged, null];
628
+ }
629
+
630
+ /**
631
+ * The Android project dir for the checker's source-side rules: --android, else what earlier steps
632
+ * recorded (batch_progress.json, then the resource-convert outputs under work/). '' when none exists.
633
+ */
634
+ export function androidDir(meta, progress, given = null) {
635
+ const cands = [given, get(progress, 'android_project_dir')];
636
+ const deps = loadDict(pjoin(meta, 'work', 'resource_deps.json'));
637
+ cands.push(get(deps, 'project_path'));
638
+ const icons = loadDict(pjoin(meta, 'work', 'icons.json'));
639
+ cands.push(get(icons, 'androidSrc'));
640
+ for (const c of cands) {
641
+ if (typeof c === 'string' && c && fs.existsSync(c)) return c;
642
+ }
643
+ return '';
644
+ }
645
+
646
+ export function check(hp, files, rnd = null, group = null, android = null) {
647
+ hp = String(hp);
648
+ const meta = pjoin(hp, '.hometrans');
649
+ const progress = loadDict(pjoin(meta, 'batch_progress.json'));
650
+ const module = String(_uiModule(hp, progress)); // the queue's resolution (group_watch._paths)
651
+ const ets = pjoin(hp, module, 'src', 'main', 'ets');
652
+ const res = pjoin(hp, module, 'src', 'main', 'resources');
653
+ const paradigm = get(progress, 'paradigm');
654
+ const [names, aTier] = procedureItems();
655
+ const rres = new Resources(res);
656
+ // A file of another module (`features/x/src/main/ets/pages/A.ets`, group_watch.etsSplit) is
657
+ // read from that module, its $r resolved against that module's resources as well as the UI one's.
658
+ const resOf = new Map([[path.resolve(ets), rres]]);
659
+ const rootOf = new Map();
660
+ const rep = { files: [], missing_files: [], blocking: 0 };
661
+ const texts = new Map();
662
+ // One name per file: a UI-module file given as `<ui>/src/main/ets/pages/A.ets` is `pages/A.ets`
663
+ // (the --group form), so the two spellings are not read, gated and reported twice.
664
+ const uiRoot = path.resolve(ets);
665
+ const canon = [];
666
+ for (const f of files) {
667
+ const [root, inner] = etsSplit(hp, ets, f);
668
+ const c = path.resolve(root) === uiRoot ? inner : String(f).replace(/\\/g, '/');
669
+ if (!canon.includes(c)) canon.push(c);
670
+ }
671
+ files = canon;
672
+ for (const rel of files) {
673
+ const [root, inner] = etsSplit(hp, ets, rel);
674
+ const r = path.resolve(root);
675
+ rootOf.set(rel, [r, inner]);
676
+ if (!resOf.has(r)) resOf.set(r, new Resources(path.join(path.dirname(r), 'resources')));
677
+ const f = pjoin(root, inner);
678
+ if (isFile(f)) {
679
+ texts.set(rel, readText(f, true));
680
+ rep.files.push(rel);
681
+ } else {
682
+ rep.missing_files.push(rel);
683
+ }
684
+ }
685
+
686
+ // round rule: what changed since the previous round's snapshot
687
+ // One file per group (work/phase5_rounds/<key>.json, atomic replace): parallel groups shared
688
+ // one phase5_rounds.json, overwrote each other's snapshots and could read it half-written.
689
+ // The shared file of an earlier run is still read while a group has no file of its own.
690
+ const key = or(group, pySorted(files).join(','));
691
+ const snapF = pjoin(meta, 'work', 'phase5_rounds', `${roundsName(key)}.json`);
692
+ let snaps = loadDict(snapF);
693
+ if (!Object.hasOwn(snaps, key)) {
694
+ let legacy = {};
695
+ try { legacy = loadDict(pjoin(meta, 'work', 'phase5_rounds.json')); } catch { /* torn legacy file */ }
696
+ snaps = Object.hasOwn(legacy, key) ? { [key]: legacy[key] } : {};
697
+ }
698
+ const now = {};
699
+ for (const [rel, t] of texts) { pySet(now, rel, crypto.createHash('sha1').update(t, 'utf8').digest('hex')); }
700
+ if (truthy(rnd)) {
701
+ const prev = get(get(snaps, key, {}), String(rnd - 1));
702
+ if (prev !== undefined && prev !== null) {
703
+ const union = [...keysOf(now)];
704
+ for (const k of keysOf(prev)) { if (!union.includes(k)) { union.push(k); } }
705
+ const changed = pySorted(union.filter((k) => get(now, k) !== get(prev, k)));
706
+ rep.changed_since_round = {
707
+ round: rnd - 1, files: changed,
708
+ verdict: changed.length ? `round ${rnd - 1} made changes: run round ${rnd}` : `round ${rnd - 1} made zero changes`,
709
+ };
710
+ }
711
+ if (!Object.hasOwn(snaps, key)) { pySet(snaps, key, {}); }
712
+ pySet(snaps[key], String(rnd), now);
713
+ fs.mkdirSync(path.dirname(snapF), { recursive: true });
714
+ const body = pyJsonDumps(snaps, 1, true);
715
+ _replace(snapF, IS_WIN ? body.replace(/\n/g, '\r\n') : body);
716
+ }
717
+
718
+ const [gate, gateErr] = gateByModule(ets, res, rep.files, rootOf, androidDir(meta, progress, android));
719
+ rep.static = gate !== null ? gate : { error: gateErr };
720
+ if (truthy(gate)) {
721
+ rep.blocking += gate.mine.filter((g) => g.kind === 'gate').length;
722
+ } else {
723
+ rep.blocking += 1; // no GATE verdict is not a pass
724
+ }
725
+
726
+ const unresolved = [];
727
+ const misnamed = [];
728
+ const overlong = [];
729
+ const forbidden = [];
730
+ const braces = [];
731
+ const covered = new Set();
732
+ const resolvers = (rel) => [...new Set([rres, resOf.get(rootOf.get(rel)[0])])];
733
+ for (const [rel, text] of texts) {
734
+ const lines = pySplitlines(text);
735
+ lines.forEach((line, k) => {
736
+ const no = k + 1;
737
+ for (const [, kind, name] of line.matchAll(R_CALL)) {
738
+ if (!resolvers(rel).some((x) => x.resolves(kind, name))) { unresolved.push(`${rel}:${no} app.${kind}.${name}`); }
739
+ }
740
+ for (const [, raw] of line.matchAll(RAW_CALL)) {
741
+ if (!resolvers(rel).some((x) => isFile(pjoin(x.raw, raw)))) { unresolved.push(`${rel}:${no} rawfile ${raw}`); }
742
+ }
743
+ });
744
+ for (const [no, name, chars] of evidenceBlocks(lines)) {
745
+ if (!names.includes(name)) {
746
+ misnamed.push(`${rel}:${no} EVIDENCE(${name})`);
747
+ continue;
748
+ }
749
+ covered.add(name);
750
+ const tier = aTier.has(name) ? 'A' : 'B';
751
+ if (chars > EVIDENCE_BUDGET[tier]) {
752
+ overlong.push(`${rel}:${no} ${name} ${chars} chars (budget ${EVIDENCE_BUDGET[tier]}, tier ${tier})`);
753
+ }
754
+ }
755
+ const code = stripComments(text);
756
+ pySplitlines(code).forEach((line, k) => {
757
+ const no = k + 1;
758
+ if (line.includes('$r(`')) { // the backtick survives strip_comments; its body does not
759
+ forbidden.push(`${rel}:${no} $r(\` template literal`);
760
+ }
761
+ const v1 = paradigm === 'V2' ? V1_DECORATORS.exec(line) : null;
762
+ if (v1) {
763
+ forbidden.push(`${rel}:${no} V1 decorator in V2 project: ${v1[0]}`);
764
+ }
765
+ if (/\.(position|offset)\(/.test(line)) {
766
+ // Python's second search uses an unescaped `.` (any char but "\n"), kept as-is
767
+ forbidden.push(`${rel}:${no} .${/[^\n](position|offset)/u.exec(line)[1]}() — needs 位置锚点证据`);
768
+ }
769
+ });
770
+ const bal = code.split('{').length - code.split('}').length;
771
+ if (bal) {
772
+ braces.push(`${rel}: braces unbalanced by ${bal > 0 ? '+' : ''}${bal}`);
773
+ }
774
+ }
775
+ // 实测文字色 vs 代码字色(text_color_diff.mjs):只在 --group 时有 page_dirs 可比
776
+ rep.text_color = { gate: [], cand: [], checked: 0, pages: 0 };
777
+ if (group) {
778
+ const uiInfo = String(or(get(progress, 'ui_info_root'), pjoin(meta, 'ui_info')));
779
+ const groups = get(get(loadDict(pjoin(uiInfo, 'conversion_set.json')), 'plan', {}), 'groups', []);
780
+ const g = Array.isArray(groups) ? groups.find((x) => x && x.id === group) : undefined;
781
+ const pageDirs = g && Array.isArray(g.page_dirs) ? g.page_dirs : [];
782
+ if (pageDirs.length) {
783
+ const etsAll = [];
784
+ const walk = (d) => {
785
+ let es = [];
786
+ try { es = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
787
+ for (const e of es) {
788
+ const p = path.join(d, e.name);
789
+ if (e.isDirectory()) walk(p);
790
+ else if (e.name.endsWith('.ets')) { try { etsAll.push(fs.readFileSync(p, 'utf8')); } catch { /* skip */ } }
791
+ }
792
+ };
793
+ for (const r of new Set([...resOf.keys()])) walk(r);
794
+ const resRoots = [res, ...[...resOf.keys()].map((r) => path.join(path.dirname(r), 'resources'))];
795
+ rep.text_color = { ...textColorDiff({ uiInfo, pageDirs, files: texts, etsAll, resRoots: [...new Set(resRoots)] }), pages: pageDirs.length };
796
+ rep.blocking += rep.text_color.gate.length;
797
+ }
798
+ }
799
+ rep.unresolved_resources = unresolved;
800
+ rep.evidence_misnamed = misnamed;
801
+ const usesLottie = [...texts.values()].some((t) => t.toLowerCase().includes('lottie'));
802
+ rep.evidence_uncovered_B = names.filter((n) => !aTier.has(n) && !covered.has(n) &&
803
+ (usesLottie || !n.includes('Lottie')));
804
+ rep.evidence_overlong = overlong;
805
+ rep.forbidden_or_candidates = forbidden;
806
+ rep.braces = braces;
807
+ rep.blocking += unresolved.length + misnamed.length + braces.length + rep.missing_files.length;
808
+ return rep;
809
+ }
810
+
811
+ const pad26 = (s) => s + ' '.repeat(Math.max(0, 26 - pyLen(s))); // f"{s:26s}"
812
+
813
+ export function render(rep) {
814
+ const outp = [`phase5_check — ${rep.files.length} file(s); blocking=${rep.blocking}`];
815
+ if (truthy(rep.changed_since_round)) {
816
+ const c = rep.changed_since_round;
817
+ outp.push(`\n[round rule] ${c.verdict}` + (c.files.length ? `: ${c.files.join(', ')}` : ''));
818
+ }
819
+ const sections = [
820
+ ['missing_files', 'files not found (blocking)'],
821
+ ['unresolved_resources', '$r / $rawfile that do not resolve in resources/ (blocking)'],
822
+ ['evidence_misnamed', 'EVIDENCE(name) not a Phase 5 heading verbatim (blocking: rename)'],
823
+ ['braces', 'brace balance (blocking)'],
824
+ ['evidence_uncovered_B', 'B-tier items with no EVIDENCE tag in these files (add one, or state N/A in the report)'],
825
+ ['evidence_overlong', 'EVIDENCE blocks over budget (compress: conclusion + source pointer)'],
826
+ ['forbidden_or_candidates', 'patterns to justify or fix'],
827
+ ];
828
+ const st = or(rep.static, {});
829
+ if (Object.hasOwn(st, 'error')) {
830
+ outp.push(`\n[static] ${st.error} (blocking: no GATE verdict; fix the checker run and re-run)`);
831
+ } else {
832
+ const mine = get(st, 'mine', []);
833
+ const gates = mine.filter((g) => g.kind === 'gate');
834
+ const cands = mine.filter((g) => g.kind === 'cand');
835
+ outp.push(`\n[static GATE, these files] ${gates.length} (blocking)`);
836
+ outp.push(...gates.map((g) => ` ${pad26(g.rule)} ${g.at} ${g.msg}`));
837
+ outp.push(`[static CANDIDATES, these files] ${cands.length} — annotate in the matching EVIDENCE item`);
838
+ outp.push(...cands.map((g) => ` ${pad26(g.rule)} ${g.at}`));
839
+ if (truthy(get(st, 'batch_level'))) {
840
+ outp.push(`[static] ${st.batch_level} batch-level hit(s) (orphan/unreachable) — parent wiring, Step 5.5`);
841
+ }
842
+ }
843
+ const tc = rep.text_color;
844
+ if (tc && tc.pages) {
845
+ outp.push(`\n[text_color] 实测文字色 vs 代码字色(${tc.pages} 个采集目录,比对 ${tc.checked} 段文本): ` +
846
+ `GATE ${tc.gate.length} (blocking), CAND ${tc.cand.length}`);
847
+ outp.push(...tc.gate.map((x) => ` ${x}`));
848
+ outp.push(...tc.cand.map((x) => ` [cand] ${x}`));
849
+ if (tc.gate.length) {
850
+ outp.push(' 修法:用与底色相同的状态条件写 .fontColor()(Span 继承外层 Text);确认差异合理时在上方写 // COLOR-DIFF-OK: <依据>');
851
+ }
852
+ }
853
+ for (const [k, title] of sections) {
854
+ const v = or(rep[k], []);
855
+ outp.push(`\n[${k}] ${title}: ${v.length}`);
856
+ outp.push(...v.map((x) => ` ${x}`));
857
+ }
858
+ return outp.join('\n');
859
+ }
860
+
861
+ /** Raised where Python raises SystemExit(msg): main prints msg to stderr and exits 1. */
862
+ export class SystemExit extends Error {}
863
+
864
+ export function _groupFiles(hp, gid) {
865
+ const meta = pjoin(String(hp), '.hometrans');
866
+ const progress = loadDict(pjoin(meta, 'batch_progress.json'));
867
+ const uiInfo = String(or(get(progress, 'ui_info_root'), pjoin(meta, 'ui_info')));
868
+ const groups = get(get(loadDict(pjoin(uiInfo, 'conversion_set.json')), 'plan', {}), 'groups', []);
869
+ const g = groups.find((x) => {
870
+ if (!Object.hasOwn(x, 'id')) { throw new Error("KeyError: 'id'"); }
871
+ return x.id === gid;
872
+ });
873
+ if (g === undefined) {
874
+ throw new SystemExit(`unknown group ${gid}`);
875
+ }
876
+ const files = get(g, 'predicted_writes', []).filter((w) => w !== 'ENTRY_PAGE');
877
+ const module = String(_uiModule(hp, progress)); // the queue's resolution (group_watch._paths)
878
+ const prefix = `${module}/src/main/ets/`;
879
+ for (const d of get(g, 'page_dirs', [])) {
880
+ // `output` 是单个路径,或(批次记账约定)路径数组 —— 实测一次运行里多文件组被记成数组,
881
+ // 旧代码对数组调 .replace 直接抛 TypeError,--group 整条不可用(安装副本当场手补过)
882
+ const outs = get(or(get(get(progress, 'pages', {}), d), {}), 'output', []);
883
+ for (const one of (Array.isArray(outs) ? outs : [outs]).filter((x) => typeof x === 'string' && x)) {
884
+ const o = one.replace(/\\/g, '/');
885
+ if (o.startsWith(prefix)) {
886
+ files.push(o.slice(prefix.length));
887
+ } else if (!path.isAbsolute(o) && o.includes('/src/main/ets/')) {
888
+ files.push(o); // a page of another module, kept with its module (group_watch.etsSplit)
889
+ }
890
+ }
891
+ }
892
+ // predicted_writes 只是调度时的**预测**:family leader 实际还写了供 follower 复用的共享组件,
893
+ // 子代理也会写到预测之外的路径。实测这些文件不进 --group 的扫描面,B 档 EVIDENCE 全报
894
+ // 「uncovered」,只能改用 --files 重跑。补两处「实际写了什么」的记录(与 group_watch 同源):
895
+ // (a) 组报告 queue_logs/<GID>.report.md 点名、且磁盘上存在的 .ets(group_watch._reported);
896
+ // (b) 该组 leader 发布的 provides/<GID>__<family>.json 标记里的 files。
897
+ const ets = pjoin(String(hp), module, 'src', 'main', 'ets');
898
+ const rp = reportPath(meta, gid);
899
+ if (isFile(rp)) {
900
+ files.push(..._reported(ets, readText(rp, true), hp));
901
+ }
902
+ const pdir = pjoin(meta, 'provides');
903
+ let markers = [];
904
+ try {
905
+ markers = fs.readdirSync(pdir).filter((n) => n.startsWith(`${gid}__`) && n.endsWith('.json'));
906
+ } catch { /* 尚无 provides 目录 */ }
907
+ for (const n of markers) {
908
+ let m;
909
+ try { m = JSON.parse(readText(pjoin(pdir, n), true)); } catch { continue; }
910
+ if (m === null || typeof m !== 'object' || m.group !== gid || !Array.isArray(m.files)) { continue; }
911
+ for (const rel of m.files) {
912
+ if (typeof rel === 'string' && rel) { files.push(rel.replace(/\\/g, '/')); }
913
+ }
914
+ }
915
+ return pySorted([...new Set(files)]);
916
+ }
917
+
918
+ // ---------------------------------------------------------------- argparse equivalent
919
+ // argparse's observable behaviour: unique long-option prefixes, `--opt=value`, `--`,
920
+ // -h/--help (RawDescriptionHelpFormatter: the description is printed verbatim),
921
+ // usage + error on stderr with exit 2.
922
+
923
+ const DESCRIPTION = `Phase 5 mechanical checks for one group's files, in one call per verification round.
924
+
925
+ Measured on a 14-group run, each Phase 5 round cost an agent 2-3 model turns of
926
+ greps and checker runs (EVIDENCE coverage, resource existence, static GATE for
927
+ its own files, "did round 2 change anything"), ~10% of its slot time. Those
928
+ answers are lexical; this script gives all of them at once so the agent's turns
929
+ go to the semantic checks only. It decides nothing the agent must judge: missing
930
+ coverage may be legitimately N/A, and every finding names the file:line to look at.
931
+
932
+ phase5_check.mjs <harmony_dir> --files pages/A.ets,components/B.ets --round 1
933
+ phase5_check.mjs <harmony_dir> --group G012 --round 2
934
+
935
+ Sections: changed-since-last-round (round rule), static GATE for these files,
936
+ resource references that do not resolve, EVIDENCE names not matching a Phase 5
937
+ heading, B-tier items with no EVIDENCE tag, over-budget EVIDENCE blocks,
938
+ forbidden patterns, brace balance. Exit 1 when a blocking finding exists
939
+ (GATE, unresolved resource, unbalanced braces, misnamed EVIDENCE).
940
+ `;
941
+
942
+ function termColumns() {
943
+ const env = Number.parseInt(process.env.COLUMNS ?? '', 10);
944
+ if (env > 0) { return env; }
945
+ return process.stdout.isTTY && process.stdout.columns ? process.stdout.columns : 80;
946
+ }
947
+
948
+ /**
949
+ * textwrap.wrap(width) subset: chunks are words and single spaces, a word also
950
+ * breaks after an inner hyphen ("comma-" | "separated,"); overlong chunks are hard-split.
951
+ */
952
+ function wrapText(text, width) {
953
+ const chunks = [];
954
+ text.split(' ').filter((w) => w !== '').forEach((w, k) => {
955
+ if (k) { chunks.push(' '); }
956
+ chunks.push(...w.split(/(?<=[A-Za-z]-)(?=[A-Za-z])/));
957
+ });
958
+ chunks.reverse();
959
+ const lines = [];
960
+ while (chunks.length) {
961
+ const cur = [];
962
+ let len = 0;
963
+ if (chunks[chunks.length - 1] === ' ' && lines.length) { chunks.pop(); }
964
+ while (chunks.length) {
965
+ const l = chunks[chunks.length - 1].length;
966
+ if (len + l <= width) { cur.push(chunks.pop()); len += l; } else { break; }
967
+ }
968
+ if (chunks.length && chunks[chunks.length - 1].length > width) {
969
+ const c = chunks.pop();
970
+ const room = Math.max(width - len, 1);
971
+ cur.push(c.slice(0, room));
972
+ chunks.push(c.slice(room));
973
+ }
974
+ if (cur.length && cur[cur.length - 1] === ' ') { cur.pop(); }
975
+ if (cur.length) { lines.push(cur.join('')); }
976
+ }
977
+ return lines;
978
+ }
979
+
980
+ /** argparse int(): Unicode decimal digits, optional sign, underscores between digits, surrounding whitespace. */
981
+ function pyIntArg(val) {
982
+ const t = pyStrip(val);
983
+ if (!/^[+-]?\p{Nd}+(?:_\p{Nd}+)*$/u.test(t)) { return null; }
984
+ let s = '';
985
+ for (const ch of t.replace(/^[+-]|_/g, '')) {
986
+ let cp = ch.codePointAt(0);
987
+ let k = 0;
988
+ while (/\p{Nd}/u.test(String.fromCodePoint(cp - 1))) { cp--; k++; }
989
+ s += String(k % 10);
990
+ }
991
+ const v = Number(s) * (t.startsWith('-') ? -1 : 1);
992
+ return v === 0 ? 0 : v;
993
+ }
994
+
995
+ function valRepr(s) {
996
+ const q = s.includes("'") && !s.includes('"') ? '"' : "'";
997
+ return q + s.replace(/\\/g, '\\\\').replace(new RegExp(q, 'g'), '\\' + q) + q;
998
+ }
999
+
1000
+ const PROG = 'phase5_check.mjs';
1001
+ // action: 'store' | 'append' | 'store_true' | 'help'
1002
+ const ACTIONS = [
1003
+ { name: '-h', alias: '--help', action: 'help', help: 'show this help message and exit' },
1004
+ { name: 'harmony_dir', positional: true },
1005
+ { name: '--files', action: 'append', def: [],
1006
+ help: 'ets-root-relative files (comma-separated, repeatable) -- the files you wrote' },
1007
+ { name: '--group', action: 'store', help: 'group id: its predicted writes + recorded outputs (when --files omitted)' },
1008
+ { name: '--round', action: 'store', type: 'int', help: 'Phase 5 round number; snapshots files for the round rule' },
1009
+ { name: '--android', action: 'store',
1010
+ help: 'android project dir (default: read from .hometrans/batch_progress.json or work/resource_deps.json)' },
1011
+ { name: '--json', action: 'store_true', def: false },
1012
+ ];
1013
+
1014
+ function parseArgs(argv) {
1015
+ const width = termColumns() - 2;
1016
+ const dest = (a) => a.name.replace(/^-+/, '').replace(/-/g, '_');
1017
+ const takesValue = (a) => a.action === 'store' || a.action === 'append';
1018
+ const metavar = (a) => dest(a).toUpperCase();
1019
+ const invocation = (a) => (a.positional ? a.name : a.alias ? `${a.name}, ${a.alias}`
1020
+ : takesValue(a) ? `${a.name} ${metavar(a)}` : a.name);
1021
+ const usagePart = (a) => (a.positional ? a.name : `[${takesValue(a) ? `${a.name} ${metavar(a)}` : a.name}]`);
1022
+ const opts = ACTIONS.filter((a) => !a.positional);
1023
+ const poss = ACTIONS.filter((a) => a.positional);
1024
+
1025
+ const formatUsage = () => {
1026
+ const prefix = 'usage: ';
1027
+ const optParts = opts.map(usagePart);
1028
+ const posParts = poss.map(usagePart);
1029
+ let usage = [PROG, ...optParts, ...posParts].join(' ');
1030
+ if (prefix.length + usage.length > width) {
1031
+ const getLines = (parts, indent, pfx) => {
1032
+ const lines = [];
1033
+ let line = [];
1034
+ let len = pfx !== undefined ? pfx.length - 1 : indent.length - 1;
1035
+ for (const part of parts) {
1036
+ if (len + 1 + part.length > width && line.length) {
1037
+ lines.push(indent + line.join(' '));
1038
+ line = [];
1039
+ len = indent.length - 1;
1040
+ }
1041
+ line.push(part);
1042
+ len += part.length + 1;
1043
+ }
1044
+ if (line.length) { lines.push(indent + line.join(' ')); }
1045
+ if (pfx !== undefined) { lines[0] = lines[0].slice(indent.length); }
1046
+ return lines;
1047
+ };
1048
+ let lines;
1049
+ if (prefix.length + PROG.length <= 0.75 * width) {
1050
+ const indent = ' '.repeat(prefix.length + PROG.length + 1);
1051
+ lines = getLines([PROG, ...optParts], indent, prefix);
1052
+ lines.push(...getLines(posParts, indent));
1053
+ } else {
1054
+ const indent = ' '.repeat(prefix.length);
1055
+ lines = getLines([...optParts, ...posParts], indent);
1056
+ if (lines.length > 1) { lines = [...getLines(optParts, indent), ...getLines(posParts, indent)]; }
1057
+ lines = [PROG, ...lines];
1058
+ }
1059
+ usage = lines.join('\n');
1060
+ }
1061
+ return prefix + usage;
1062
+ };
1063
+
1064
+ const formatHelp = () => {
1065
+ const maxHelpPos = Math.min(24, Math.max(width - 20, 4));
1066
+ const maxLen = Math.max(...ACTIONS.map((a) => invocation(a).length + 2));
1067
+ const helpPos = Math.min(maxLen + 2, maxHelpPos);
1068
+ const helpWidth = Math.max(width - helpPos, 11);
1069
+ const actionWidth = helpPos - 2 - 2;
1070
+ const item = (a) => {
1071
+ const inv = invocation(a);
1072
+ const rows = [];
1073
+ if (!a.help) { rows.push(' ' + inv); return rows; }
1074
+ let first;
1075
+ if (inv.length <= actionWidth) { first = ' ' + inv.padEnd(actionWidth) + ' '; }
1076
+ else { rows.push(' ' + inv); first = ' '.repeat(helpPos); }
1077
+ const hl = wrapText(a.help.replace(/\s+/g, ' ').trim(), helpWidth);
1078
+ rows.push(first + hl[0]);
1079
+ for (const l of hl.slice(1)) { rows.push(' '.repeat(helpPos) + l); }
1080
+ return rows;
1081
+ };
1082
+ // RawDescriptionHelpFormatter: description lines verbatim
1083
+ const parts = [formatUsage(), '', DESCRIPTION.replace(/\n+$/, ''), ''];
1084
+ parts.push('positional arguments:', ...poss.flatMap(item), '');
1085
+ parts.push('options:', ...opts.flatMap(item));
1086
+ return parts.join('\n');
1087
+ };
1088
+
1089
+ const fail = (msg) => {
1090
+ err(formatUsage());
1091
+ err(`${PROG}: error: ${msg}`);
1092
+ process.exit(2);
1093
+ };
1094
+
1095
+ const result = {};
1096
+ for (const a of ACTIONS) { if (a.action !== 'help') { result[dest(a)] = Array.isArray(a.def) ? [...a.def] : (a.def ?? null); } }
1097
+ const seen = new Set();
1098
+ const positionals = [];
1099
+ const extras = [];
1100
+ const longNames = opts.flatMap((a) => (a.alias ? [[a.name, a], [a.alias, a]] : [[a.name, a]]));
1101
+ const looksNegative = (s) => /^-\d+$|^-\d*\.\d+$/.test(s);
1102
+ const isOptionLike = (s) => s.startsWith('-') && s !== '-' && !looksNegative(s) && !(s.includes(' ') && !findOpt(s));
1103
+ function findOpt(s) {
1104
+ const [k] = s.split('=', 1);
1105
+ const exact = longNames.find(([nm]) => nm === k);
1106
+ if (exact) { return exact[1]; }
1107
+ if (!k.startsWith('--')) { return null; }
1108
+ const hits = longNames.filter(([nm]) => nm.startsWith(k));
1109
+ const uniq = [...new Set(hits.map((h) => h[1]))];
1110
+ if (uniq.length > 1) { fail(`ambiguous option: ${k} could match ${hits.map((h) => h[0]).join(', ')}`); }
1111
+ return uniq[0] ?? null;
1112
+ }
1113
+ let i = 0;
1114
+ let rest = false;
1115
+ while (i < argv.length) {
1116
+ const s = argv[i];
1117
+ if (!rest && s === '--') { rest = true; i++; continue; }
1118
+ if (rest || !isOptionLike(s)) { positionals.push(s); i++; continue; }
1119
+ const a = findOpt(s);
1120
+ if (!a) { extras.push(s); i++; continue; }
1121
+ const eq = s.indexOf('=');
1122
+ const shown = a.alias ? `${a.name}/${a.alias}` : a.name;
1123
+ if (!takesValue(a)) {
1124
+ if (eq >= 0) { fail(`argument ${shown}: ignored explicit argument '${s.slice(eq + 1)}'`); }
1125
+ if (a.action === 'help') {
1126
+ process.stdout.write((formatHelp() + '\n').replace(/\n/g, EOL));
1127
+ process.exit(0);
1128
+ }
1129
+ result[dest(a)] = true;
1130
+ i++;
1131
+ continue;
1132
+ }
1133
+ let val;
1134
+ if (eq >= 0 && s.startsWith('--')) { val = s.slice(eq + 1); i++; }
1135
+ else if (i + 1 < argv.length && !(argv[i + 1] === '--' || isOptionLike(argv[i + 1]))) { val = argv[i + 1]; i += 2; }
1136
+ else { fail(`argument ${shown}: expected one argument`); }
1137
+ if (a.type === 'int') {
1138
+ const v = pyIntArg(val);
1139
+ if (v === null) { fail(`argument ${shown}: invalid int value: ${valRepr(val)}`); }
1140
+ val = v;
1141
+ }
1142
+ if (a.action === 'append') { result[dest(a)].push(val); } else { result[dest(a)] = val; }
1143
+ seen.add(a);
1144
+ }
1145
+ poss.forEach((a, k) => { if (k < positionals.length) { result[dest(a)] = positionals[k]; seen.add(a); } });
1146
+ extras.push(...positionals.slice(poss.length));
1147
+ const missing = poss.filter((a) => !seen.has(a)).map((a) => a.name);
1148
+ if (missing.length) { fail(`the following arguments are required: ${missing.join(', ')}`); }
1149
+ if (extras.length) { fail(`unrecognized arguments: ${extras.join(' ')}`); }
1150
+ result.error = fail;
1151
+ return result;
1152
+ }
1153
+
1154
+ export function main(argv = process.argv.slice(2)) {
1155
+ const a = parseArgs(argv);
1156
+ const files = a.files.flatMap((v) => v.split(',')).filter((f) => pyStrip(f)).map((f) => pyStrip(f).replace(/\\/g, '/'));
1157
+ let fl = files;
1158
+ try {
1159
+ if (!fl.length) {
1160
+ if (!truthy(a.group)) {
1161
+ a.error('give --files or --group');
1162
+ }
1163
+ fl = _groupFiles(a.harmony_dir, a.group);
1164
+ }
1165
+ const rep = check(a.harmony_dir, fl, a.round, a.group, a.android);
1166
+ out(a.json ? pyJsonDumps(rep, 1, false) : render(rep));
1167
+ return rep.blocking ? 1 : 0;
1168
+ } catch (e) {
1169
+ if (e instanceof SystemExit) {
1170
+ err(e.message);
1171
+ return 1;
1172
+ }
1173
+ throw e;
1174
+ }
1175
+ }
1176
+
1177
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
1178
+ process.exitCode = main();
1179
+ }