@buaa_smat/hometrans 0.1.17 → 0.1.19

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 (234) hide show
  1. package/README.md +120 -56
  2. package/agents/code-reviewer.md +321 -65
  3. package/agents/logic-coder.md +113 -88
  4. package/agents/logic-context-builder.md +47 -29
  5. package/agents/scripts/hmos-precheck/backends/arkts.mjs +567 -0
  6. package/agents/scripts/hmos-precheck/backends/arkts_diff.mjs +159 -0
  7. package/agents/scripts/hmos-precheck/backends/arkts_project_rules.mjs +398 -0
  8. package/agents/scripts/hmos-precheck/backends/codelinter.mjs +250 -0
  9. package/agents/scripts/hmos-precheck/backends/project_integrity.mjs +321 -0
  10. package/agents/scripts/hmos-precheck/backends/static_precheck.mjs +247 -0
  11. package/agents/scripts/hmos-precheck/core/config.mjs +184 -0
  12. package/agents/scripts/hmos-precheck/core/diagnostic_scope.mjs +20 -0
  13. package/agents/scripts/hmos-precheck/core/process_adapter.mjs +47 -0
  14. package/agents/scripts/hmos-precheck/core/project_catalog.mjs +50 -0
  15. package/agents/scripts/hmos-precheck/core/result_projection.mjs +147 -0
  16. package/agents/scripts/hmos-precheck/core/scope_plan.mjs +131 -0
  17. package/agents/scripts/hmos-precheck/core/sdk_context.mjs +67 -0
  18. package/agents/scripts/hmos-precheck/docs/architecture.md +37 -0
  19. package/agents/scripts/hmos-precheck/docs/performance-optimization.md +28 -0
  20. package/agents/scripts/hmos-precheck/docs/upstream-reference.json +19 -0
  21. package/agents/scripts/hmos-precheck/docs/validation.md +50 -0
  22. package/agents/scripts/hmos-precheck/index.mjs +17 -0
  23. package/agents/scripts/hmos-precheck/invocation.mjs +231 -0
  24. package/agents/scripts/hmos-precheck/rules/rule_case_matrix.csv +32 -0
  25. package/agents/scripts/hmos-precheck/rules/rule_inventory.csv +64 -0
  26. package/agents/scripts/hmos-precheck/rules/rule_inventory.mjs +59 -0
  27. package/agents/scripts/hmos-precheck/rules/rule_policy.mjs +54 -0
  28. package/agents/scripts/platform_query.mjs +626 -0
  29. package/agents/scripts/platform_query.test.mjs +422 -0
  30. package/agents/self-test-fixer.md +36 -34
  31. package/agents/self-tester.md +123 -143
  32. package/agents/test-case-generation-generator.md +317 -0
  33. package/agents/test-case-generation-validator.md +231 -0
  34. package/dist/cli/config-store.js +16 -63
  35. package/dist/cli/env-vars.js +1 -3
  36. package/dist/cli/index.js +0 -11
  37. package/dist/cli/init.js +123 -204
  38. package/dist/cli/uninstall.js +3 -127
  39. package/dist/utils/regex.js +8 -0
  40. package/env-requirements.json +55 -54
  41. package/package.json +6 -6
  42. package/resource/convert_pipeline_process.svg +103 -0
  43. package/resource/project_architecture.svg +122 -0
  44. package/resource/title_dark.png +0 -0
  45. package/skills/hmos-batch-ui-align/SKILL.md +345 -43
  46. package/skills/hmos-batch-ui-align/references/conversion-procedure.md +661 -180
  47. package/skills/hmos-batch-ui-align/references/mappings/android-to-harmonyOS-ui-atomic-component-mapping-reference.md +2533 -2533
  48. package/skills/hmos-batch-ui-align/references/mappings/android-to-harmonyOS-ui-interaction-mapping-reference.md +555 -555
  49. package/skills/hmos-batch-ui-align/references/mappings/android-to-harmonyOS-ui-layout-mapping-reference.md +117 -117
  50. package/skills/hmos-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
  51. package/skills/hmos-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
  52. package/skills/hmos-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
  53. package/skills/hmos-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
  54. package/skills/hmos-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
  55. package/skills/hmos-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
  56. package/skills/hmos-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
  57. package/skills/hmos-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
  58. package/skills/hmos-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
  59. package/skills/hmos-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
  60. package/skills/hmos-batch-ui-align/references/mvvm/MVVM/346/250/241/345/274/217/357/274/210V1/357/274/211.md +911 -911
  61. package/skills/hmos-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
  62. package/skills/hmos-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
  63. package/skills/hmos-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 -0
  64. package/skills/hmos-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 -0
  65. package/skills/hmos-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 -0
  66. package/skills/hmos-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 -0
  67. package/skills/hmos-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 -0
  68. package/skills/hmos-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 -0
  69. package/skills/hmos-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 -0
  70. package/skills/hmos-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 -0
  71. package/skills/hmos-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 -0
  72. package/skills/hmos-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 -0
  73. package/skills/hmos-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 -0
  74. package/skills/hmos-batch-ui-align/references/mvvm-v2/MVVM/346/250/241/345/274/217/357/274/210V2/357/274/211.md +1407 -0
  75. package/skills/hmos-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 -0
  76. package/skills/hmos-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 -0
  77. package/skills/hmos-batch-ui-align/references/mvvm-v2/_/350/243/205/351/245/260/345/231/250/351/200/237/346/237/245.md +133 -0
  78. package/skills/hmos-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 -0
  79. package/skills/hmos-batch-ui-align/scripts/android_parse_fast.ts +1798 -0
  80. package/skills/hmos-batch-ui-align/scripts/arkts_static_check.ts +1592 -0
  81. package/skills/hmos-batch-ui-align/scripts/measure_pack.ts +752 -0
  82. package/skills/hmos-convert-pipeline/SKILL.md +168 -121
  83. package/skills/hmos-fix-build-errors/SKILL.md +87 -67
  84. package/skills/hmos-fix-build-errors/references/arkts-strict-patterns.md +219 -219
  85. package/skills/hmos-fix-build-errors/references/known-patterns.md +157 -157
  86. package/skills/hmos-fix-build-errors/references/rdb-entity-pattern.md +131 -131
  87. package/skills/hmos-incremental-ui-align/README.md +53 -36
  88. package/skills/hmos-incremental-ui-align/SKILL.md +179 -23
  89. package/skills/hmos-incremental-ui-align/diff_analysis.md +52 -52
  90. package/skills/hmos-incremental-ui-align/page_align.md +62 -62
  91. package/skills/hmos-incremental-ui-align/references/Comparison_Template.md +38 -2
  92. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@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
  93. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@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
  94. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@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
  95. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@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
  96. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@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
  97. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@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
  98. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@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
  99. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/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
  100. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/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
  101. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/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
  102. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/MVVM/346/250/241/345/274/217V1.md +911 -911
  103. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/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
  104. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243//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
  105. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/!!/350/257/255/346/263/225/357/274/232/345/217/214/345/220/221/347/273/221/345/256/232.md +206 -0
  106. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@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 -0
  107. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@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 -0
  108. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@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 -0
  109. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@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 -0
  110. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@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 -0
  111. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@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 -0
  112. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@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 -0
  113. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@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 -0
  114. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@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 -0
  115. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/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 -0
  116. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/MVVM/346/250/241/345/274/217/357/274/210V2/357/274/211.md +1407 -0
  117. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/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 -0
  118. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/_/350/214/203/345/274/217/351/200/211/346/213/251/350/257/264/346/230/216.md +47 -0
  119. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2//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 -0
  120. package/skills/hmos-incremental-ui-align/references/State_Model_Template.md +74 -0
  121. package/skills/hmos-incremental-ui-align/references/UI_Analysis_Template.md +34 -4
  122. package/skills/hmos-incremental-ui-align/references/android-to-harmonyOS-ui-atomic-component-mapping-reference.md +2533 -2533
  123. package/skills/hmos-incremental-ui-align/references/android-to-harmonyOS-ui-interaction-mapping-reference.md +555 -555
  124. package/skills/hmos-incremental-ui-align/references/android-to-harmonyOS-ui-layout-mapping-reference.md +117 -117
  125. package/skills/hmos-incremental-ui-align/scripts/app_feature_verify.ts +937 -0
  126. package/skills/hmos-incremental-ui-align/scripts/extract_checklist.ts +343 -0
  127. package/skills/hmos-incremental-ui-align/scripts/navigation-capure.md +44 -5
  128. package/skills/hmos-incremental-ui-align/scripts/page_capture.ts +977 -0
  129. package/skills/hmos-incremental-ui-align/scripts/page_capture_burst.ts +188 -0
  130. package/skills/hmos-integration-test/README.md +61 -70
  131. package/skills/hmos-integration-test/SKILL.md +128 -111
  132. package/skills/hmos-resources-convert/SKILL.md +334 -66
  133. package/skills/hmos-resources-convert/references/code-vector-icon-rules.md +335 -0
  134. package/skills/hmos-resources-convert/references/conversion-rules.md +676 -663
  135. package/skills/hmos-resources-convert/references/dependency-analysis-rules.md +410 -388
  136. package/skills/hmos-resources-convert/references/lottie-conversion-rules.md +219 -0
  137. package/skills/hmos-resources-convert/references/resource-mapping-rules.md +482 -457
  138. package/skills/hmos-resources-convert/references/xml-drawable-to-svg-rules.md +592 -513
  139. package/skills/hmos-resources-convert/scripts/a2h_resource_convert.ts +2163 -0
  140. package/skills/hmos-resources-convert/scripts/code_vector_icons.ts +591 -0
  141. package/skills/hmos-resources-convert/scripts/svg_fidelity_check.ts +632 -0
  142. package/skills/hmos-spec-generate/SKILL.md +293 -214
  143. package/skills/hmos-spec-generate/scripts/parse_requirements.ts +515 -0
  144. package/skills/hmos-spec-generate/template/REQ.txt +22 -0
  145. package/skills/hmos-spec-generate/template/REQ.xlsx +0 -0
  146. package/skills/hmos-test-case-generation/README.md +241 -0
  147. package/skills/hmos-test-case-generation/SKILL.md +324 -0
  148. package/skills/hmos-test-case-generation/references/contract.md +315 -0
  149. package/skills/hmos-test-case-generation/references/review-notes-template.md +84 -0
  150. package/skills/hmos-test-case-generation/references/ui-elements-schema.md +142 -0
  151. package/skills/hmos-test-case-generation/tools/convert_to_ui_elements.ts +550 -0
  152. package/skills/hmos-test-case-generation/tools/validate.ts +1312 -0
  153. package/tools/bfs-crawl/README.md +73 -0
  154. package/tools/bfs-crawl/android_viewtree_bfs_crawler.ts +1662 -0
  155. package/tools/test-tools/autotest/config.ts +175 -0
  156. package/tools/test-tools/autotest/deps/autotest-agent-0.1.1.tgz +0 -0
  157. package/tools/test-tools/autotest/docs/README.md +266 -0
  158. package/tools/test-tools/autotest/{testcases_schema.md → docs/testcases_schema.md} +1 -1
  159. package/tools/test-tools/autotest/engine/batch-launcher.ts +327 -0
  160. package/tools/test-tools/autotest/engine/report-tool.ts +773 -0
  161. package/tools/test-tools/autotest/engine/self-test-runner.ts +961 -0
  162. package/tools/test-tools/autotest/engine/testcases-tool.ts +246 -0
  163. package/tools/test-tools/autotest/paths.ts +41 -0
  164. package/tools/test-tools/autotest/resolve-metadata-tool.ts +143 -0
  165. package/tools/test-tools/autotest/runner/logger.ts +45 -0
  166. package/tools/test-tools/autotest/runner/process-utils.ts +41 -0
  167. package/tools/test-tools/autotest/validate.ts +167 -0
  168. package/agents/build-fixer.md +0 -385
  169. package/agents/logic-coder/scripts/platform_context_query.py +0 -568
  170. package/agents/review-fixer.md +0 -405
  171. package/agents/spec-generator.md +0 -541
  172. package/dist/cli/mcp-setup.js +0 -258
  173. package/dist/cli/mcp.js +0 -94
  174. package/dist/context/index.js +0 -694
  175. package/resource/migration_process.svg +0 -94
  176. package/resource/migration_process_transparent.svg +0 -93
  177. package/skills/hmos-batch-ui-align/scripts/android_parse_fast.py +0 -1606
  178. package/skills/hmos-incremental-ui-align/scripts/__pycache__/app_feature_verify.cpython-314.pyc +0 -0
  179. package/skills/hmos-incremental-ui-align/scripts/app_feature_verify.py +0 -542
  180. package/skills/hmos-incremental-ui-align/scripts/page_capture.py +0 -597
  181. package/skills/hmos-resources-convert/evals/evals.json +0 -171
  182. package/skills/hmos-resources-convert/template/AppScope/app.json5 +0 -10
  183. package/skills/hmos-resources-convert/template/AppScope/resources/base/element/string.json +0 -8
  184. package/skills/hmos-resources-convert/template/AppScope/resources/base/media/background.png +0 -0
  185. package/skills/hmos-resources-convert/template/AppScope/resources/base/media/foreground.png +0 -0
  186. package/skills/hmos-resources-convert/template/AppScope/resources/base/media/layered_image.json +0 -7
  187. package/skills/hmos-resources-convert/template/build-profile.json5 +0 -42
  188. package/skills/hmos-resources-convert/template/code-linter.json5 +0 -32
  189. package/skills/hmos-resources-convert/template/entry/build-profile.json5 +0 -33
  190. package/skills/hmos-resources-convert/template/entry/hvigorfile.ts +0 -6
  191. package/skills/hmos-resources-convert/template/entry/obfuscation-rules.txt +0 -23
  192. package/skills/hmos-resources-convert/template/entry/oh-package.json5 +0 -10
  193. package/skills/hmos-resources-convert/template/entry/src/main/ets/entryability/EntryAbility.ets +0 -48
  194. package/skills/hmos-resources-convert/template/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +0 -16
  195. package/skills/hmos-resources-convert/template/entry/src/main/ets/pages/Index.ets +0 -23
  196. package/skills/hmos-resources-convert/template/entry/src/main/module.json5 +0 -55
  197. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/element/color.json +0 -8
  198. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/element/float.json +0 -8
  199. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/element/string.json +0 -16
  200. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/media/background.png +0 -0
  201. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/media/foreground.png +0 -0
  202. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/media/layered_image.json +0 -7
  203. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/media/startIcon.png +0 -0
  204. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/profile/backup_config.json +0 -3
  205. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/profile/main_pages.json +0 -5
  206. package/skills/hmos-resources-convert/template/entry/src/main/resources/dark/element/color.json +0 -8
  207. package/skills/hmos-resources-convert/template/entry/src/mock/mock-config.json5 +0 -2
  208. package/skills/hmos-resources-convert/template/entry/src/ohosTest/ets/test/Ability.test.ets +0 -35
  209. package/skills/hmos-resources-convert/template/entry/src/ohosTest/ets/test/List.test.ets +0 -5
  210. package/skills/hmos-resources-convert/template/entry/src/ohosTest/module.json5 +0 -16
  211. package/skills/hmos-resources-convert/template/entry/src/test/List.test.ets +0 -5
  212. package/skills/hmos-resources-convert/template/entry/src/test/LocalUnit.test.ets +0 -33
  213. package/skills/hmos-resources-convert/template/hvigor/hvigor-config.json5 +0 -23
  214. package/skills/hmos-resources-convert/template/hvigorfile.ts +0 -6
  215. package/skills/hmos-resources-convert/template/oh-package-lock.json5 +0 -28
  216. package/skills/hmos-resources-convert/template/oh-package.json5 +0 -10
  217. package/skills/hmos-resources-convert/tools/apktool_3.0.1.jar +0 -0
  218. package/skills/hmos-spec-generate/references/android-platform-tokens.md +0 -105
  219. package/skills/hmos-spec-generate/references/spec-sample-1.md +0 -78
  220. package/skills/hmos-spec-generate/references/spec-sample-2.md +0 -58
  221. package/skills/hmos-spec-generate/references/spec-sample-3.md +0 -116
  222. package/skills/hmos-spec-generate/references/step4-report-template.md +0 -33
  223. package/tools/test-tools/autotest/README.md +0 -238
  224. package/tools/test-tools/autotest/pyproject.toml +0 -26
  225. package/tools/test-tools/autotest/report_tool.py +0 -759
  226. package/tools/test-tools/autotest/self_test_runner.py +0 -895
  227. package/tools/test-tools/autotest/testcases_tool.py +0 -215
  228. package/tools/test-tools/autotest/uv.lock +0 -3156
  229. package/tools/test-tools/harmony_autotest-0.1.0-py3-none-any.whl +0 -0
  230. package/tools/test-tools/hypium-6.1.0.210-py3-none-any.whl +0 -0
  231. package/tools/test-tools/hypium_mcp-0.6.5-py3-none-any.whl +0 -0
  232. package/tools/test-tools/xdevice-6.1.0.210-py3-none-any.whl +0 -0
  233. package/tools/test-tools/xdevice_devicetest-6.1.0.210-py3-none-any.whl +0 -0
  234. package/tools/test-tools/xdevice_ohos-6.1.0.210-py3-none-any.whl +0 -0
@@ -0,0 +1,1662 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ * Android BFS view-tree crawler (zero-LLM, pure Node stdlib).
4
+ *
5
+ * 靠 Node 原生类型擦除运行(Node ≥ 22.18 / 23.6 直接 `node android_viewtree_bfs_crawler.ts`),无需编译、无依赖。
6
+ * 功能:遍历每个页面,保存截图、View XML、Activity/Window 信息
7
+ *
8
+ * 策略:BFS + 重启导航
9
+ * 1. 轻量探测:点击后先快速 dump XML 判断是否新页面,重复页面跳过截图
10
+ * 2. 指数退避的 wait_for_idle(更短等待)
11
+ * 3. 过滤低价值元素(减少无效点击)
12
+ */
13
+
14
+ import * as fs from "node:fs";
15
+ import * as path from "node:path";
16
+ import { spawnSync } from "node:child_process";
17
+ import { createHash } from "node:crypto";
18
+ import * as readline from "node:readline";
19
+
20
+ type Dict = Record<string, unknown>;
21
+
22
+ // ---- config ----
23
+ const ADB_PATH_DEFAULT = "adb";
24
+ const DEVICE_SERIAL_DEFAULT = "emulator-5554";
25
+ const MUMU_EMULATOR_DEFAULT = false;
26
+ const MUMU_ADB_ADDR_DEFAULT = "127.0.0.1:7555";
27
+ const IDLE_POLL_INTERVAL_DEFAULT = 0.2;
28
+ const IDLE_TIMEOUT_DEFAULT = 5;
29
+ const MAX_PAGES_DEFAULT = 500;
30
+ const MAX_SCROLLS_DEFAULT = 10;
31
+ const MAX_DEPTH_DEFAULT = 6;
32
+ const SCROLL_DURATION_MS_DEFAULT = 300;
33
+ const SKIP_RESOURCE_ID_PATTERNS_DEFAULT = [
34
+ "statusBarBackground", "navigationBarBackground", "action_bar_container", "status_bar", "navigation_bar",
35
+ ];
36
+ const DESTRUCTIVE_TEXT_PATTERNS_DEFAULT = [
37
+ "删除", "移除", "清空", "清理", "清除", "清除全部", "全部清除", "全部删除", "重置", "恢复出厂", "卸载",
38
+ "delete", "remove", "clear all", "clear queue", "clean", "reset", "erase", "trash", "discard", "uninstall",
39
+ ];
40
+ const DESTRUCTIVE_RESOURCE_ID_PATTERNS_DEFAULT = [
41
+ "delete", "remove", "clear", "clean", "reset", "erase", "trash", "discard",
42
+ ];
43
+ const LIST_ITEM_RID_PATTERNS = ["clBase", "clItem", "rvItem", "list_item"];
44
+ const ROOT_RECOVERY_CLICKS_DEFAULT: Dict[] = [];
45
+ const BACK_UNWIND_MAX_DEFAULT = 4;
46
+ const HORIZONTAL_SCROLL_CLASSES = new Set(["android.widget.HorizontalScrollView"]);
47
+ const FOREIGN_FOCUS_MARKERS = ["TranslationWindow"];
48
+ const COLLAPSE_MIN = 2;
49
+ const CRAWL_DEADLINE_SECONDS = 7200;
50
+ const NEAR_DUP_MIN_JACCARD = 0.80;
51
+ const NEAR_DUP_WEAK_ONLY_MIN_JACCARD = 0.60;
52
+ const NEAR_DUP_MAX_STRONG_DIFFS = 0;
53
+ const NEAR_DUP_MAX_WEAK_DIFFS = 4;
54
+ const LEARNED_ROOT_PATH_LIMIT = 8;
55
+ const LEARNED_ROOT_ATTEMPTS_PER_RECOVERY = 2;
56
+
57
+ function sleepMs(ms: number): void {
58
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
59
+ }
60
+ function escapeHtml(s: string): string {
61
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
62
+ }
63
+ const ENTITIES: Record<string, string> = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": '"', "&apos;": "'" };
64
+ function unescapeHtml(s: string): string {
65
+ return s.replace(/&(?:amp|lt|gt|quot|apos);|&#x?[0-9A-Fa-f]+;/g, (m) => {
66
+ if (m in ENTITIES) return ENTITIES[m];
67
+ if (m[1] === "#") { const hex = m[2] === "x" || m[2] === "X"; const code = parseInt(m.slice(hex ? 3 : 2, -1), hex ? 16 : 10); return String.fromCodePoint(code); }
68
+ return m;
69
+ });
70
+ }
71
+ function nowStr(): string {
72
+ const d = new Date(); const p = (n: number) => String(n).padStart(2, "0");
73
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
74
+ }
75
+ // 本地时间 ISO(对齐 Python datetime.now().isoformat();toISOString() 是 UTC 会偏时区)
76
+ function nowIso(): string {
77
+ const d = new Date(); const p = (n: number) => String(n).padStart(2, "0");
78
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
79
+ }
80
+
81
+ interface XmlNode { tag: string; attrs: Record<string, string>; depth: number; }
82
+ function parseXmlNodes(xml: string): XmlNode[] {
83
+ const nodes: XmlNode[] = [];
84
+ const tagRe = /<(\/)?([A-Za-z_][\w:.\-]*)((?:\s+[\w:.\-]+\s*=\s*"[^"]*")*)\s*(\/)?>/g;
85
+ const attrRe = /([\w:.\-]+)\s*=\s*"([^"]*)"/g;
86
+ let depth = -1; let m: RegExpExecArray | null;
87
+ while ((m = tagRe.exec(xml)) !== null) {
88
+ const isClose = m[1] === "/"; const attrStr = m[3] || ""; const selfClose = m[4] === "/";
89
+ if (isClose) { depth -= 1; continue; }
90
+ depth += 1; const attrs: Record<string, string> = {};
91
+ let am: RegExpExecArray | null; attrRe.lastIndex = 0;
92
+ while ((am = attrRe.exec(attrStr)) !== null) attrs[am[1]] = unescapeHtml(am[2]);
93
+ nodes.push({ tag: m[2], attrs, depth });
94
+ if (selfClose) depth -= 1;
95
+ }
96
+ return nodes;
97
+ }
98
+ function setsEqual<T>(a: Set<T>, b: Set<T>): boolean {
99
+ if (a.size !== b.size) return false;
100
+ for (const x of a) if (!b.has(x)) return false;
101
+ return true;
102
+ }
103
+
104
+ class ADBHelper {
105
+ adbPath: string; deviceSerial: string | null; mumuEmulator: boolean; mumuAdbAddr: string;
106
+ idlePollInterval: number; idleTimeout: number; scrollDurationMs: number;
107
+ constructor(opts: { adbPath?: string; deviceSerial?: string | null; mumuEmulator?: boolean; mumuAdbAddr?: string; idlePollInterval?: number; idleTimeout?: number; scrollDurationMs?: number; } = {}) {
108
+ this.adbPath = opts.adbPath ?? ADB_PATH_DEFAULT; this.deviceSerial = opts.deviceSerial ?? DEVICE_SERIAL_DEFAULT;
109
+ this.mumuEmulator = opts.mumuEmulator ?? MUMU_EMULATOR_DEFAULT; this.mumuAdbAddr = opts.mumuAdbAddr ?? MUMU_ADB_ADDR_DEFAULT;
110
+ this.idlePollInterval = opts.idlePollInterval ?? IDLE_POLL_INTERVAL_DEFAULT; this.idleTimeout = opts.idleTimeout ?? IDLE_TIMEOUT_DEFAULT;
111
+ this.scrollDurationMs = opts.scrollDurationMs ?? SCROLL_DURATION_MS_DEFAULT;
112
+ }
113
+ _buildCmd(...args: string[]): string[] { const cmd = [this.adbPath]; if (this.deviceSerial) cmd.push("-s", this.deviceSerial); cmd.push(...args); return cmd; }
114
+ run(args: string[], timeout: number = 15): string {
115
+ const cmd = this._buildCmd(...args);
116
+ const result = spawnSync(cmd[0], cmd.slice(1), { encoding: "utf-8", timeout: timeout * 1000 });
117
+ if (result.error && (result.error as NodeJS.ErrnoException).code === "ENOENT") throw new Error("找不到 adb,请确认已安装并配置 PATH,或修改 ADB_PATH");
118
+ if (result.signal === "SIGTERM") { console.log(` [WARN] adb 命令超时: ${args.join(" ")}`); return ""; }
119
+ return (result.stdout || "").trim();
120
+ }
121
+ shell(...args: string[]): string { return this.run(["shell", ...args]); }
122
+ waitForIdle(): void {
123
+ const deadline = Date.now() / 1000 + this.idleTimeout; let prevFocus = ""; let interval = this.idlePollInterval;
124
+ while (Date.now() / 1000 < deadline) {
125
+ sleepMs(interval * 1000); interval = Math.min(interval * 1.5, 0.5);
126
+ const t = this.shell("dumpsys", "window", "animator");
127
+ if (t.includes("Transition ready") || t.includes("Running animations")) continue;
128
+ const f = this.shell("dumpsys", "window"); let cf = "";
129
+ for (const line of f.split("\n")) { if (line.includes("mCurrentFocus")) { cf = line.trim(); break; } }
130
+ if (cf && cf === prevFocus) return; prevFocus = cf;
131
+ }
132
+ console.log(` [WARN] 等待 UI 空闲超时 (${this.idleTimeout}s),继续执行`);
133
+ }
134
+ checkDevice(): boolean {
135
+ if (this.mumuEmulator) {
136
+ console.log(` 正在连接 MuMu 模拟器 (${this.mumuAdbAddr})...`);
137
+ console.log(` adb connect: ${this.run(["connect", this.mumuAdbAddr])}`);
138
+ sleepMs(1000); if (this.deviceSerial === "emulator-5554") this.deviceSerial = this.mumuAdbAddr;
139
+ }
140
+ const out = this.run(["devices"]);
141
+ const lines = out.split("\n").filter(l => l.trim() && !l.includes("List of devices"));
142
+ const online = lines.filter(l => l.includes("device") && !l.includes("offline"));
143
+ if (online.length === 0) { console.log(" 未检测到在线设备,请先启动模拟器并确认 adb devices 有输出"); return false; }
144
+ const onlineDevices = online.map(l => l.split(/\s+/)[0]);
145
+ console.log(` 在线设备: ${JSON.stringify(onlineDevices)}`);
146
+ if (this.deviceSerial === null) { this.deviceSerial = onlineDevices[0]; console.log(` 未指定设备,自动选择: ${this.deviceSerial}`); }
147
+ else if (!onlineDevices.includes(this.deviceSerial)) { console.log(` 指定的设备 ${this.deviceSerial} 不存在,自动选择: ${onlineDevices[0]}`); this.deviceSerial = onlineDevices[0]; }
148
+ else console.log(` 使用指定的设备: ${this.deviceSerial}`);
149
+ return true;
150
+ }
151
+ restartAdbServer(): void {
152
+ console.log(" [INFO] 重启 ADB server...");
153
+ this.run(["kill-server"]);
154
+ sleepMs(1000);
155
+ this.run(["start-server"]);
156
+ sleepMs(2000);
157
+ }
158
+ getCurrentActivity(): Dict {
159
+ const info: Dict = {};
160
+ const actOut = this.shell("dumpsys", "activity", "activities");
161
+ const winOut = this.shell("dumpsys", "window");
162
+ for (const line of actOut.split("\n")) { if (/ResumedActivity|topActivity/i.test(line)) { info["resumed_activity"] = line.trim(); break; } }
163
+ for (const line of winOut.split("\n")) { if (line.includes("mCurrentFocus")) { info["current_focus"] = line.trim(); break; } if (line.includes("mFocusedApp")) { if (!info["focused_app"]) info["focused_app"] = line.trim(); } }
164
+ return info;
165
+ }
166
+ tap(x: number, y: number): void { this.shell("input", "tap", String(x), String(y)); this.waitForIdle(); }
167
+ longPress(x: number, y: number, d: number = 1000): void { this.shell("input", "swipe", String(x), String(y), String(x), String(y), String(d)); this.waitForIdle(); }
168
+ tapOrLongPress(x: number, y: number, isLong: boolean = false): void { if (isLong) this.longPress(x, y); else this.tap(x, y); }
169
+ pressBack(): void { this.shell("input", "keyevent", "KEYCODE_BACK"); this.waitForIdle(); }
170
+ isSoftKeyboardShown(): boolean {
171
+ try {
172
+ const out = this.run(["shell", "dumpsys", "input_method"], 5);
173
+ if (/(mInputShown|mIsInputViewShown|inputShown|isInputViewShown)=true/i.test(out)) return true;
174
+ if (/mImeWindowVis=0x[1-9a-f]+/i.test(out)) return true;
175
+ } catch {
176
+ return false;
177
+ }
178
+ return false;
179
+ }
180
+ dumpXmlQuick(): string {
181
+ const rp = "/sdcard/ui_dump.xml";
182
+ this.run(["shell", "rm -f /sdcard/ui_dump.xml && uiautomator dump /sdcard/ui_dump.xml"], 20);
183
+ for (let i = 0; i < 6; i++) { if (this.shell("ls", rp).includes(rp)) break; sleepMs(200); }
184
+ return this.shell("cat", rp);
185
+ }
186
+ getViewXmlFast(pageDir: string): string {
187
+ const rp = "/sdcard/ui_dump.xml"; const lp = path.join(pageDir, "view.xml");
188
+ this.run(["shell", "rm -f /sdcard/ui_dump.xml && uiautomator dump /sdcard/ui_dump.xml"], 20);
189
+ for (let i = 0; i < 6; i++) { if (this.shell("ls", rp).includes(rp)) break; sleepMs(200); }
190
+ const xc = this.shell("cat", rp); if (xc) fs.writeFileSync(lp, xc, "utf-8"); return xc;
191
+ }
192
+ screencapBytes(): Buffer | null {
193
+ const cmd = this._buildCmd("exec-out", "screencap", "-p");
194
+ const r = spawnSync(cmd[0], cmd.slice(1), { timeout: 15000 });
195
+ if (r.signal === "SIGTERM") { console.log(" [WARN] 截图超时"); return null; }
196
+ if (r.stdout && (r.stdout as Buffer).length > 0) return r.stdout as Buffer;
197
+ return null;
198
+ }
199
+ takeScreenshot(pageDir: string): void {
200
+ const lp = path.join(pageDir, "screenshot.png"); const data = this.screencapBytes();
201
+ if (data) fs.writeFileSync(lp, data);
202
+ else { const rp = "/sdcard/screenshot.png"; this.shell("screencap", "-p", rp); sleepMs(300); this.run(["pull", rp, lp]); }
203
+ }
204
+ scrollToPosition(cb: [number, number, number, number], si: number): void {
205
+ if (si <= 0) return; const [x1, y1, x2, y2] = cb; const cx = Math.floor((x1 + x2) / 2); const h = y2 - y1;
206
+ const fy = y1 + Math.floor(h * 0.7); const ty = y1 + Math.floor(h * 0.3);
207
+ for (let i = 0; i < si; i++) { this.shell("input", "swipe", String(cx), String(fy), String(cx), String(ty), String(this.scrollDurationMs)); this.waitForIdle(); }
208
+ }
209
+ grantRuntimePermissions(pkg: string): void {
210
+ const out = this.shell("dumpsys", "package", pkg); const perms: string[] = []; let inReq = false;
211
+ for (const line of out.split("\n")) { const s = line.trim(); if (s.toLowerCase().includes("runtime permissions:")) { inReq = true; continue; } if (inReq) { if (!s || (!s.startsWith("android.permission") && !s.startsWith("com."))) { inReq = false; continue; } const p = s.split(":")[0].trim(); if (p) perms.push(p); } }
212
+ for (const p of perms) this.shell("pm", "grant", pkg, p);
213
+ this.shell("appops", "set", pkg, "MANAGE_EXTERNAL_STORAGE", "allow");
214
+ }
215
+ }
216
+
217
+ type TemplateKey = string | null;
218
+ type QueueItem = [Dict[], unknown[], string[], Dict | null, TemplateKey];
219
+ type NearDuplicateStats = { jaccard: number; strongDiff: string[]; weakDiff: string[] };
220
+ type LearnedRootPath = {
221
+ steps: Dict[];
222
+ successes: number;
223
+ failures: number;
224
+ };
225
+
226
+ class PageCrawler {
227
+ adb: ADBHelper; package: string; outputRoot: string; maxPages: number; maxScrolls: number;
228
+ maxDepth: number; skipSameActivityClicks: boolean; allowPmClear: boolean;
229
+ skipPatterns: string[]; rootRecoveryClicks: Dict[];
230
+ pagesIndex: Dict[] = []; visitedSignatures: Set<string> = new Set();
231
+ pathSignatures: Record<string, string> = {}; blockedElements: Set<string> = new Set();
232
+ clickResultCache: Map<string, string> = new Map();
233
+ templateResults: Map<string, string[]> = new Map();
234
+ templateCollapsed: Set<string> = new Set();
235
+ failedPaths: Set<string> = new Set();
236
+ learnedRootPaths: LearnedRootPath[] = [];
237
+ gaps: Dict[] = [];
238
+ gapKeys: Set<string> = new Set();
239
+ rootSignature: string | null = null;
240
+ rootStateSignature: string | null = null;
241
+ lastRestartRootExact = true;
242
+ queue: QueueItem[] = []; pageCounter: number = 0;
243
+ terminatedBy = "normal";
244
+ stats: Record<string, number> = {
245
+ skipped_elements: 0,
246
+ probe_skipped: 0,
247
+ cache_skipped: 0,
248
+ same_activity_skipped: 0,
249
+ merged_variants: 0,
250
+ nav_replay_failed: 0,
251
+ prefix_pruned: 0,
252
+ destructive_skipped: 0,
253
+ external_blocked: 0,
254
+ dequeued_total: 0,
255
+ list_collapsed_skipped: 0,
256
+ };
257
+ constructor(opts: { adb: ADBHelper; package: string; outputDir: string; maxPages?: number; maxScrolls?: number; maxDepth?: number; skipSameActivityClicks?: boolean; allowPmClear?: boolean; skipPatterns?: string[]; rootRecoveryClicks?: Dict[]; }) {
258
+ this.adb = opts.adb; this.package = opts.package; this.outputRoot = opts.outputDir;
259
+ this.maxPages = opts.maxPages ?? MAX_PAGES_DEFAULT; this.maxScrolls = opts.maxScrolls ?? MAX_SCROLLS_DEFAULT;
260
+ this.maxDepth = opts.maxDepth ?? MAX_DEPTH_DEFAULT; this.skipSameActivityClicks = opts.skipSameActivityClicks ?? false; this.allowPmClear = opts.allowPmClear ?? false;
261
+ this.skipPatterns = opts.skipPatterns ?? SKIP_RESOURCE_ID_PATTERNS_DEFAULT;
262
+ this.rootRecoveryClicks = opts.rootRecoveryClicks ?? ROOT_RECOVERY_CLICKS_DEFAULT;
263
+ }
264
+
265
+ static parseBoundsCenter(bounds: string): [number, number] | null {
266
+ const m = bounds.match(/\d+/g);
267
+ if (m && m.length === 4) { const [x1, y1, x2, y2] = m.map(Number); return [Math.floor((x1 + x2) / 2), Math.floor((y1 + y2) / 2)]; }
268
+ return null;
269
+ }
270
+ static parseBoundsArr(bounds: string): [number, number, number, number] | null {
271
+ const m = (bounds || "").match(/\d+/g);
272
+ if (m && m.length === 4) return m.map(Number) as [number, number, number, number];
273
+ return null;
274
+ }
275
+ static pointInBounds(point: [number, number], bounds: [number, number, number, number]): boolean {
276
+ const [x, y] = point; const [x1, y1, x2, y2] = bounds;
277
+ return x1 <= x && x <= x2 && y1 <= y && y <= y2;
278
+ }
279
+ static boundsOverlap(a: [number, number, number, number], b: [number, number, number, number]): boolean {
280
+ const [ax1, ay1, ax2, ay2] = a; const [bx1, by1, bx2, by2] = b;
281
+ return ax1 < bx2 && bx1 < ax2 && ay1 < by2 && by1 < ay2;
282
+ }
283
+ static boundsArea(bounds: [number, number, number, number]): number {
284
+ const [x1, y1, x2, y2] = bounds;
285
+ return Math.max(0, x2 - x1) * Math.max(0, y2 - y1);
286
+ }
287
+ static sameClickableElement(a: Dict, b: Dict): boolean {
288
+ return (a["bounds"] || "") === (b["bounds"] || "")
289
+ && (a["resource-id"] || "") === (b["resource-id"] || "")
290
+ && (a["text"] || "") === (b["text"] || "")
291
+ && (a["content-desc"] || "") === (b["content-desc"] || "")
292
+ && Boolean(a["long-clickable"]) === Boolean(b["long-clickable"]);
293
+ }
294
+ static chooseTapPoint(xmlContent: string, target: Dict): [number, number] | null {
295
+ const center = (target["center"] as [number, number] | null) || PageCrawler.parseBoundsCenter((target["bounds"] as string) || "");
296
+ const targetBounds = PageCrawler.parseBoundsArr((target["bounds"] as string) || "");
297
+ if (!center || !targetBounds) return center;
298
+ const targetArea = Math.max(1, PageCrawler.boundsArea(targetBounds));
299
+ const blockers: [number, number, number, number][] = [];
300
+ for (const elem of PageCrawler.getClickableElements(xmlContent)) {
301
+ if (PageCrawler.sameClickableElement(elem, target)) continue;
302
+ const elemBounds = PageCrawler.parseBoundsArr((elem["bounds"] as string) || "");
303
+ if (!elemBounds || !PageCrawler.boundsOverlap(targetBounds, elemBounds)) continue;
304
+ if (PageCrawler.boundsArea(elemBounds) <= targetArea * 0.9) blockers.push(elemBounds);
305
+ }
306
+ const blocked = (point: [number, number]) => blockers.some(b => PageCrawler.pointInBounds(point, b));
307
+ if (!blocked(center)) return center;
308
+ const [x1, y1, x2, y2] = targetBounds;
309
+ const w = Math.max(1, x2 - x1); const h = Math.max(1, y2 - y1);
310
+ const candidates: [number, number][] = [
311
+ [x1 + Math.floor(w / 5), y1 + Math.floor(h / 4)],
312
+ [x2 - Math.floor(w / 5), y1 + Math.floor(h / 4)],
313
+ [x1 + Math.floor(w / 5), y1 + Math.floor(h / 2)],
314
+ [x2 - Math.floor(w / 5), y1 + Math.floor(h / 2)],
315
+ [x1 + Math.floor(w / 2), y1 + Math.floor(h / 4)],
316
+ [x1 + Math.floor(w / 2), y2 - Math.floor(h / 4)],
317
+ ];
318
+ for (const p of candidates) {
319
+ if (PageCrawler.pointInBounds(p, targetBounds) && !blocked(p)) return p;
320
+ }
321
+ return center;
322
+ }
323
+
324
+ static getClickableElements(xmlContent: string): Dict[] {
325
+ const elements: Dict[] = []; if (!xmlContent) return elements;
326
+ try {
327
+ const nodes = parseXmlNodes(xmlContent).filter(n => n.tag === "node");
328
+ const lvChildren = new Set<number>();
329
+ for (let i = 0; i < nodes.length; i++) {
330
+ const cls = nodes[i].attrs["class"] || "";
331
+ if (cls.includes("ListView") || cls.includes("GridView")) {
332
+ const cd = nodes[i].depth + 1;
333
+ for (let j = i + 1; j < nodes.length; j++) { if (nodes[j].depth < cd) break; if (nodes[j].depth === cd) lvChildren.add(j); }
334
+ }
335
+ }
336
+ const extractText = (i: number): string => {
337
+ const t = nodes[i].attrs["text"] || ""; if (t) return t;
338
+ const d = nodes[i].depth;
339
+ for (let j = i + 1; j < nodes.length; j++) { if (nodes[j].depth <= d) break; const t2 = nodes[j].attrs["text"] || ""; if (t2) return t2; }
340
+ return "";
341
+ };
342
+ for (let i = 0; i < nodes.length; i++) {
343
+ const n = nodes[i]; if (n.attrs["enabled"] !== "true") continue;
344
+ const isClk = n.attrs["clickable"] === "true"; const isLong = n.attrs["long-clickable"] === "true";
345
+ const isLV = lvChildren.has(i); const isChk = n.attrs["checkable"] === "true";
346
+ if (!(isClk || isLong || isLV || isChk)) continue;
347
+ const bounds = n.attrs["bounds"] || ""; let text = n.attrs["text"] || ""; if (!text) text = extractText(i);
348
+ const base: Dict = {
349
+ "class": n.attrs["class"] || "",
350
+ "text": text,
351
+ "resource-id": n.attrs["resource-id"] || "",
352
+ "content-desc": n.attrs["content-desc"] || "",
353
+ "bounds": bounds,
354
+ "center": PageCrawler.parseBoundsCenter(bounds),
355
+ "focused": n.attrs["focused"] === "true",
356
+ "checkable": n.attrs["checkable"] === "true",
357
+ "checked": n.attrs["checked"] === "true",
358
+ "selected": n.attrs["selected"] === "true",
359
+ "enabled": n.attrs["enabled"] === "true",
360
+ "clickable": n.attrs["clickable"] === "true",
361
+ "scrollable": n.attrs["scrollable"] === "true",
362
+ "list-item": isLV,
363
+ };
364
+ if (isClk || isLV || isChk) elements.push({ ...base, "long-clickable": false });
365
+ if (isLong) elements.push({ ...base, "long-clickable": true });
366
+ }
367
+ } catch (e) { console.log(` [WARN] XML 解析失败: ${e}`); }
368
+ return elements;
369
+ }
370
+
371
+ static collectElementsDigest(xmlContent: string, scrollIndex: number = 0): Dict[] {
372
+ const elements: Dict[] = [];
373
+ if (!xmlContent) return elements;
374
+ try {
375
+ const nodes = parseXmlNodes(xmlContent).filter(n => n.tag === "node");
376
+ const extractText = (i: number): string => {
377
+ const t = nodes[i].attrs["text"] || "";
378
+ if (t) return t;
379
+ const d = nodes[i].depth;
380
+ for (let j = i + 1; j < nodes.length; j++) {
381
+ if (nodes[j].depth <= d) break;
382
+ const childText = nodes[j].attrs["text"] || "";
383
+ if (childText) return childText;
384
+ }
385
+ return "";
386
+ };
387
+ for (let i = 0; i < nodes.length; i++) {
388
+ const n = nodes[i];
389
+ const cls = n.attrs["class"] || "";
390
+ const text = n.attrs["text"] || extractText(i);
391
+ const desc = n.attrs["content-desc"] || "";
392
+ const rid = n.attrs["resource-id"] || "";
393
+ const clickable = n.attrs["clickable"] === "true";
394
+ const longClickable = n.attrs["long-clickable"] === "true";
395
+ const checkable = n.attrs["checkable"] === "true";
396
+ const scrollable = n.attrs["scrollable"] === "true";
397
+ if (!(text || desc || rid || clickable || longClickable || checkable || scrollable)) continue;
398
+ const bounds = n.attrs["bounds"] || "";
399
+ elements.push({
400
+ "class": cls,
401
+ "text": text,
402
+ "resource-id": rid,
403
+ "content-desc": desc,
404
+ "bounds": bounds,
405
+ "center": PageCrawler.parseBoundsCenter(bounds),
406
+ "clickable": clickable,
407
+ "long-clickable": longClickable,
408
+ "checkable": checkable,
409
+ "checked": n.attrs["checked"] === "true",
410
+ "selected": n.attrs["selected"] === "true",
411
+ "focused": n.attrs["focused"] === "true",
412
+ "enabled": n.attrs["enabled"] !== "false",
413
+ "scrollable": scrollable,
414
+ "scroll_index": scrollIndex,
415
+ });
416
+ }
417
+ } catch (e) { console.log(` [WARN] XML 解析失败: ${e}`); }
418
+ return elements;
419
+ }
420
+
421
+ static extractNodeKeys(xmlContent: string): Set<string> {
422
+ const keys = new Set<string>(); if (!xmlContent) return keys;
423
+ for (const n of parseXmlNodes(xmlContent).filter(n => n.tag === "node")) {
424
+ keys.add(JSON.stringify([n.attrs["class"] || "", n.attrs["resource-id"] || "", n.attrs["text"] || "", n.attrs["content-desc"] || "", n.attrs["bounds"] || ""]));
425
+ }
426
+ return keys;
427
+ }
428
+
429
+ static findScrollableContainers(xmlContent: string): Dict[] {
430
+ const cs: Dict[] = []; if (!xmlContent) return cs;
431
+ for (const n of parseXmlNodes(xmlContent).filter(n => n.tag === "node")) {
432
+ if (n.attrs["scrollable"] !== "true") continue;
433
+ const cls = n.attrs["class"] || ""; if (HORIZONTAL_SCROLL_CLASSES.has(cls)) continue;
434
+ const m = (n.attrs["bounds"] || "").match(/\d+/g); if (!m || m.length !== 4) continue;
435
+ const [x1, y1, x2, y2] = m.map(Number); if (y2 - y1 < 200) continue;
436
+ cs.push({ bounds: [x1, y1, x2, y2], class: cls, "resource-id": n.attrs["resource-id"] || "" });
437
+ }
438
+ cs.sort((a, b) => { const ba = a["bounds"] as number[]; const bb = b["bounds"] as number[]; return (bb[2] - bb[0]) * (bb[3] - bb[1]) - (ba[2] - ba[0]) * (ba[3] - ba[1]); });
439
+ return cs;
440
+ }
441
+
442
+ static normalizeComponent(c: string): string {
443
+ if (!c.includes("/")) return c; const [pkg, ...rest] = c.split("/"); let cls = rest.join("/"); if (cls.startsWith(".")) cls = pkg + cls; return `${pkg}/${cls}`;
444
+ }
445
+ static stableActivityKey(ai: Dict): string {
446
+ const focus = (ai["current_focus"] as string) || ""; const resumed = (ai["resumed_activity"] as string) || "";
447
+ const m = focus.match(/[\w.]+\/[\w.]+/); if (m) return PageCrawler.normalizeComponent(m[0]);
448
+ const am = resumed.match(/[\w.]+\/[\w.]+/); const act = am ? PageCrawler.normalizeComponent(am[0]) : "unknown";
449
+ const wm = focus.match(/(PopupWindow|Dialog|DecorView|Toast)/); return `${act}|${wm ? wm[1] : "overlay"}`;
450
+ }
451
+ static boundsSize(bounds: string): string {
452
+ const b = PageCrawler.parseBoundsArr(bounds);
453
+ return b ? `${b[2] - b[0]}x${b[3] - b[1]}` : "";
454
+ }
455
+ static inBounds(inner: [number, number, number, number] | null, outer: [number, number, number, number] | null): boolean {
456
+ if (!inner || !outer) return false;
457
+ const [x1, y1, x2, y2] = inner; const [ox1, oy1, ox2, oy2] = outer;
458
+ const cx = Math.floor((x1 + x2) / 2); const cy = Math.floor((y1 + y2) / 2);
459
+ return ox1 <= cx && cx <= ox2 && oy1 <= cy && cy <= oy2;
460
+ }
461
+ static xmlScreenBounds(xmlContent: string): [number, number, number, number] | null {
462
+ let maxX = 0; let maxY = 0; let minX = 0; let minY = 0;
463
+ for (const n of parseXmlNodes(xmlContent).filter(n => n.tag === "node")) {
464
+ const b = PageCrawler.parseBoundsArr(n.attrs["bounds"] || "");
465
+ if (!b) continue;
466
+ const [x1, y1, x2, y2] = b;
467
+ minX = Math.min(minX, x1); minY = Math.min(minY, y1); maxX = Math.max(maxX, x2); maxY = Math.max(maxY, y2);
468
+ }
469
+ return maxX > minX && maxY > minY ? [minX, minY, maxX, maxY] : null;
470
+ }
471
+ static inBottomBand(bounds: [number, number, number, number] | null, screenBounds: [number, number, number, number] | null): boolean {
472
+ if (!bounds || !screenBounds) return false;
473
+ const [, sy1, , sy2] = screenBounds; const [, y1, , y2] = bounds;
474
+ const h = Math.max(1, sy2 - sy1); const cy = (y1 + y2) / 2;
475
+ return cy >= sy1 + h * 0.70;
476
+ }
477
+ static looksClippedAgainstExpected(elem: Dict, expectedBounds: string): boolean {
478
+ const current = PageCrawler.parseBoundsArr(String(elem["bounds"] || ""));
479
+ const expected = PageCrawler.parseBoundsArr(expectedBounds);
480
+ if (!current || !expected || String(elem["bounds"] || "") === expectedBounds) return false;
481
+ const [, y1, , y2] = current;
482
+ const [, ey1, , ey2] = expected;
483
+ const currentH = Math.max(0, y2 - y1);
484
+ const expectedH = Math.max(1, ey2 - ey1);
485
+ return y1 < 60 || currentH < expectedH * 0.5;
486
+ }
487
+ static looksLikeDynamicBottomContent(e: Dict, screenBounds: [number, number, number, number] | null): boolean {
488
+ if (!screenBounds) return false;
489
+ if (e["resource-id"] || e["content-desc"] || !e["text"]) return false;
490
+ const b = PageCrawler.parseBoundsArr(String(e["bounds"] || ""));
491
+ if (!b) return false;
492
+ const [sx1, sy1, sx2, sy2] = screenBounds; const [x1, y1, x2, y2] = b;
493
+ const screenW = Math.max(1, sx2 - sx1); const screenH = Math.max(1, sy2 - sy1);
494
+ const elemW = x2 - x1; const elemH = y2 - y1; const cy = (y1 + y2) / 2;
495
+ return cy >= sy1 + screenH * 0.75 && elemW >= screenW * 0.45 && elemH >= 64;
496
+ }
497
+ static normTextForSignature(text: string): string {
498
+ return (text || "").trim().replace(/\d+/g, "#").replace(/\s+/g, " ").slice(0, 40);
499
+ }
500
+ static stateFeature(e: Dict): string {
501
+ const flags: string[] = [];
502
+ for (const k of ["checked", "selected", "focused"]) if (e[k]) flags.push(k);
503
+ if (e["enabled"] === false) flags.push("disabled");
504
+ if (e["checkable"]) flags.push("checkable");
505
+ if (e["scrollable"]) flags.push("scrollable");
506
+ if (e["long-clickable"]) flags.push("long");
507
+ return flags.join(",");
508
+ }
509
+ static templateKey(elem: Dict): string {
510
+ return JSON.stringify([
511
+ elem["class"] || "",
512
+ elem["resource-id"] || "",
513
+ PageCrawler.boundsSize(String(elem["bounds"] || "")),
514
+ Boolean(elem["long-clickable"]),
515
+ Boolean(elem["checkable"]),
516
+ ]);
517
+ }
518
+ static repeatedTemplates(clickable: Dict[]): Set<string> {
519
+ const buckets = new Map<string, { count: number; labels: Set<string> }>();
520
+ for (const e of clickable) {
521
+ const key = PageCrawler.templateKey(e);
522
+ const b = buckets.get(key) || { count: 0, labels: new Set<string>() };
523
+ b.count += 1; b.labels.add(JSON.stringify([e["text"] || "", e["content-desc"] || ""]));
524
+ buckets.set(key, b);
525
+ }
526
+ const out = new Set<string>();
527
+ for (const [k, b] of buckets) if (b.count >= 2 && b.labels.size >= 2) out.add(k);
528
+ return out;
529
+ }
530
+ static pageStateSignature(ai: Dict, xml: string): string {
531
+ const ak = PageCrawler.stableActivityKey(ai); if (!xml) return `${ak}|empty`;
532
+ const cl = PageCrawler.getClickableElements(xml); if (cl.length === 0) return `${ak}|no_clickable`;
533
+ const features = cl.map(e => [
534
+ e["class"] || "",
535
+ e["resource-id"] || "",
536
+ e["content-desc"] || "",
537
+ String(e["text"] || "").replace(/\d+/g, "#"),
538
+ PageCrawler.boundsSize(String(e["bounds"] || "")),
539
+ ].join("|")).sort().join(";");
540
+ return `${ak}|${createHash("md5").update(features, "utf-8").digest("hex").slice(0, 16)}`;
541
+ }
542
+ static pageIdentityFeatureMap(ai: Dict, xml: string): [string, Map<string, boolean>] {
543
+ const ak = PageCrawler.stableActivityKey(ai);
544
+ if (!xml) return [ak, new Map([["empty", false]])];
545
+ const clickable = PageCrawler.getClickableElements(xml);
546
+ if (clickable.length === 0) return [ak, new Map([["no_clickable", false]])];
547
+ const scrolls = PageCrawler.findScrollableContainers(xml);
548
+ const primary = scrolls.length ? scrolls[0]["bounds"] as [number, number, number, number] : null;
549
+ const screen = PageCrawler.xmlScreenBounds(xml);
550
+ const repeated = PageCrawler.repeatedTemplates(clickable);
551
+ const features = new Map<string, boolean>();
552
+ const addFeature = (feature: string, weak: boolean) => features.set(feature, (features.get(feature) ?? true) && weak);
553
+ for (const e of clickable) {
554
+ const cls = String(e["class"] || ""); const rid = String(e["resource-id"] || ""); const desc = String(e["content-desc"] || "");
555
+ const bounds = String(e["bounds"] || ""); const size = PageCrawler.boundsSize(bounds); const state = PageCrawler.stateFeature(e);
556
+ const inScroll = PageCrawler.inBounds(PageCrawler.parseBoundsArr(bounds), primary);
557
+ const isListLike = Boolean(e["list-item"]) || (Boolean(rid) && LIST_ITEM_RID_PATTERNS.some(p => rid.includes(p))) || (inScroll && repeated.has(PageCrawler.templateKey(e)));
558
+ const isDynamicBottom = PageCrawler.looksLikeDynamicBottomContent(e, screen);
559
+ const isAnonymous = !rid && !desc && !e["text"];
560
+ const isBottomNoId = !rid && PageCrawler.inBottomBand(PageCrawler.parseBoundsArr(bounds), screen) && !e["selected"] && !e["checkable"];
561
+ if (isListLike || isDynamicBottom) {
562
+ addFeature([isDynamicBottom ? "dynamic-bottom" : "item", cls, rid, size, state].join("|"), true);
563
+ } else {
564
+ addFeature(["ctrl", cls, rid, desc, PageCrawler.normTextForSignature(String(e["text"] || "")), state].join("|"), isAnonymous || isBottomNoId);
565
+ }
566
+ }
567
+ for (const c of scrolls.slice(0, 2)) addFeature(`scroll|${c["class"] || ""}|${c["resource-id"] || ""}`, false);
568
+ return [ak, features];
569
+ }
570
+ static pageSignature(ai: Dict, xml: string): string {
571
+ const [ak, features] = PageCrawler.pageIdentityFeatureMap(ai, xml);
572
+ return `${ak}|${createHash("md5").update([...features.keys()].sort().join(";"), "utf-8").digest("hex").slice(0, 16)}`;
573
+ }
574
+ static rootIdentifiedSet(ai: Dict, xml: string): [string, Set<string>] {
575
+ const r = (ai["resumed_activity"] as string) || ""; const m = r.match(/[\w.]+\/[\w.]+/); const ak = m ? PageCrawler.normalizeComponent(m[0]) : "unknown";
576
+ if (!xml) return [ak, new Set<string>()];
577
+ const cl = PageCrawler.getClickableElements(xml); const el = new Set<string>();
578
+ for (const e of cl) { const d = (e["content-desc"] as string) || ""; const rid = (e["resource-id"] as string) || ""; if (!d && !rid) continue; el.add(JSON.stringify([(e["class"] as string) || "", rid, d])); }
579
+ return [ak, el];
580
+ }
581
+ static isSameRootPage(ri: [string, Set<string>], ci: [string, Set<string>], th: number = 0.6): boolean {
582
+ const [ra, re] = ri; const [ca, ce] = ci; if (ra !== ca) return false;
583
+ if (re.size === 0 && ce.size === 0) return true; if (re.size === 0 || ce.size === 0) return false;
584
+ let inter = 0; for (const x of re) if (ce.has(x)) inter++; const uni = re.size + ce.size - inter; return inter / uni >= th;
585
+ }
586
+ static rootSimilarity(ri: [string, Set<string>], ci: [string, Set<string>]): [number, number, number] {
587
+ const [ra, re] = ri; const [ca, ce] = ci;
588
+ if (ra !== ca) return [0, 0, new Set([...re, ...ce]).size];
589
+ if (re.size === 0 && ce.size === 0) return [1, 0, 0];
590
+ let inter = 0; for (const x of re) if (ce.has(x)) inter++;
591
+ const uni = re.size + ce.size - inter;
592
+ return [uni ? inter / uni : 0, inter, uni];
593
+ }
594
+ static isRootShell(ri: [string, Set<string>] | null, ai: Dict, xml: string, requiredElemId: unknown[] | null = null): boolean {
595
+ if (!ri) return false;
596
+ const ci = PageCrawler.rootIdentifiedSet(ai, xml);
597
+ if (ri[0] !== ci[0]) return false;
598
+ if (requiredElemId) return PageCrawler.findElementOnScreen(xml, requiredElemId) !== null;
599
+ const [similarity, intersectionCount] = PageCrawler.rootSimilarity(ri, ci);
600
+ return similarity >= 0.5 || intersectionCount >= 2;
601
+ }
602
+ static findElementOnScreen(xml: string, eid: unknown[]): Dict | null {
603
+ let rid: string, text: string, desc: string, bounds: string; let isLong: boolean | null;
604
+ if (eid.length >= 5) { [rid, text, desc, bounds, isLong] = eid as [string, string, string, string, boolean]; }
605
+ else { [rid, text, desc, bounds] = eid as [string, string, string, string]; isLong = null; }
606
+ const els = PageCrawler.getClickableElements(xml);
607
+ if (bounds) { for (const e of els) { if ((e["resource-id"] as string) === rid && (e["text"] as string) === text && (e["content-desc"] as string) === desc && (e["bounds"] as string) === bounds && (isLong === null || e["long-clickable"] === isLong)) return e; } }
608
+ if (!rid && !text && !desc) return null;
609
+ for (const e of els) { if ((e["resource-id"] as string) === rid && (e["text"] as string) === text && (e["content-desc"] as string) === desc && (isLong === null || e["long-clickable"] === isLong)) return e; }
610
+ return null;
611
+ }
612
+
613
+ shouldSkipElement(elem: Dict): boolean {
614
+ const rid = (elem["resource-id"] as string) || ""; const text = (elem["text"] as string) || "";
615
+ const desc = (elem["content-desc"] as string) || ""; const cls = (elem["class"] as string) || "";
616
+ for (const p of this.skipPatterns) { if (rid.includes(p)) return true; }
617
+ if (PageCrawler.isDestructiveElement(elem, true)) return true;
618
+ if (!text && !desc && !rid && cls.includes("ImageView")) return true;
619
+ return false;
620
+ }
621
+ static isDestructiveElement(elem: Dict, log: boolean = false): boolean {
622
+ const rid = String(elem["resource-id"] || "");
623
+ const text = String(elem["text"] || "");
624
+ const desc = String(elem["content-desc"] || "");
625
+ const semantic = `${text} ${desc}`.trim().toLowerCase();
626
+ const ridLower = rid.toLowerCase();
627
+ if (semantic) {
628
+ for (const pattern of DESTRUCTIVE_TEXT_PATTERNS_DEFAULT) {
629
+ if (semantic.includes(pattern.toLowerCase())) {
630
+ if (log) console.log(` [SAFE-SKIP] skip possible destructive control: ${text || desc || rid}`);
631
+ return true;
632
+ }
633
+ }
634
+ }
635
+ if (ridLower) {
636
+ for (const pattern of DESTRUCTIVE_RESOURCE_ID_PATTERNS_DEFAULT) {
637
+ if (ridLower.includes(pattern)) {
638
+ if (log) console.log(` [SAFE-SKIP] skip possible destructive control: ${text || desc || rid}`);
639
+ return true;
640
+ }
641
+ }
642
+ }
643
+ return false;
644
+ }
645
+ static stepLooksDestructive(step: Dict): boolean {
646
+ return PageCrawler.isDestructiveElement({
647
+ "resource-id": step["resource-id"] || "",
648
+ "text": step["text"] || step["element"] || "",
649
+ "content-desc": step["content-desc"] || "",
650
+ });
651
+ }
652
+ static isInputElement(elem: Dict): boolean {
653
+ const cls = String(elem["class"] || "").toLowerCase();
654
+ const rid = String(elem["resource-id"] || "").toLowerCase();
655
+ const desc = String(elem["content-desc"] || "").toLowerCase();
656
+ const text = String(elem["text"] || "").toLowerCase();
657
+ if (cls.includes("edittext") || cls.includes("autocompletetext")) return true;
658
+ if (elem["focused"] && /search|input|edit|搜索|输入/.test(`${rid} ${desc} ${text}`)) return true;
659
+ return false;
660
+ }
661
+ static hasFocusedInput(xmlContent: string): boolean {
662
+ return PageCrawler.getClickableElements(xmlContent).some(e => Boolean(e["focused"]) && PageCrawler.isInputElement(e));
663
+ }
664
+ static elementLabel(elem: Dict): string {
665
+ return String(elem["text"] || elem["content-desc"] || elem["resource-id"] || elem["class"] || "unknown");
666
+ }
667
+ static elementSummary(elem: Dict): Dict {
668
+ return {
669
+ class: elem["class"] || "",
670
+ text: elem["text"] || "",
671
+ resource_id: elem["resource-id"] || "",
672
+ content_desc: elem["content-desc"] || "",
673
+ bounds: elem["bounds"] || "",
674
+ clickable: elem["clickable"],
675
+ long_clickable: elem["long-clickable"],
676
+ checkable: elem["checkable"],
677
+ checked: elem["checked"],
678
+ selected: elem["selected"],
679
+ enabled: elem["enabled"],
680
+ scrollable: elem["scrollable"],
681
+ };
682
+ }
683
+ recordGap(gap: Dict): void {
684
+ const elem = (gap["element"] as Dict | undefined) || {};
685
+ const key = JSON.stringify({
686
+ type: gap["type"],
687
+ page_id: gap["page_id"],
688
+ variant_id: gap["variant_id"],
689
+ label: gap["label"],
690
+ bounds: elem["bounds"],
691
+ reason: gap["reason"],
692
+ });
693
+ if (this.gapKeys.has(key)) return;
694
+ this.gapKeys.add(key);
695
+ this.gaps.push(gap);
696
+ }
697
+ loadGaps(): void {
698
+ this.gaps = []; this.gapKeys = new Set();
699
+ const gapFile = path.join(this.outputRoot, "gaps.json");
700
+ if (!fs.existsSync(gapFile)) return;
701
+ try {
702
+ const loaded = JSON.parse(fs.readFileSync(gapFile, "utf-8"));
703
+ if (Array.isArray(loaded)) for (const gap of loaded) if (gap && typeof gap === "object") this.recordGap(gap as Dict);
704
+ } catch (e) {
705
+ console.log(` [WARN] failed to load gaps.json: ${e}; gaps will be rebuilt`);
706
+ }
707
+ }
708
+ recordPageGaps(record: Dict, variantId: string | null = null): void {
709
+ const pageId = record["page_id"];
710
+ if (!pageId) return;
711
+ for (const elem of ((record["elements_digest"] as Dict[]) || [])) {
712
+ const label = PageCrawler.elementLabel(elem);
713
+ const base: Dict = {
714
+ page_id: pageId,
715
+ variant_id: variantId,
716
+ label,
717
+ element: PageCrawler.elementSummary(elem),
718
+ click_path: record["click_path"],
719
+ };
720
+ if (PageCrawler.isInputElement(elem)) {
721
+ this.recordGap({
722
+ ...base,
723
+ type: "input_required",
724
+ reason: "text input/search requires a semantic value; BFS click-only traversal will not fill it",
725
+ suggested_resolution: "manual_crawl or a small configured input flow",
726
+ });
727
+ }
728
+ if (PageCrawler.isDestructiveElement(elem)) {
729
+ this.recordGap({
730
+ ...base,
731
+ type: "destructive_action_skipped",
732
+ reason: "control may modify, delete, clear, reset, or remove user data; crawler will not click it",
733
+ suggested_resolution: "only enable through an explicit test fixture or manual confirmation",
734
+ });
735
+ }
736
+ }
737
+ for (const elem of ((record["clickable_elements"] as Dict[]) || [])) {
738
+ if (elem["resource-id"] || elem["text"] || elem["content-desc"]) continue;
739
+ this.recordGap({
740
+ type: "weak_locator",
741
+ page_id: pageId,
742
+ variant_id: variantId,
743
+ label: PageCrawler.elementLabel(elem),
744
+ element: PageCrawler.elementSummary(elem),
745
+ click_path: record["click_path"],
746
+ reason: "clickable element has no resource-id/text/content-desc; mapping can only fall back to bounds",
747
+ suggested_resolution: "prefer app-side stable id/content-desc when possible",
748
+ });
749
+ }
750
+ }
751
+ shouldSkipSameActivity(stepSigs: string[], elem: Dict): boolean {
752
+ if (!this.skipSameActivityClicks || stepSigs.length < 2) return false;
753
+ const parentSig = stepSigs[stepSigs.length - 1] || "";
754
+ const grandparentSig = stepSigs[stepSigs.length - 2] || "";
755
+ const parentAct = parentSig.includes("|") ? parentSig.split("|")[0] : parentSig;
756
+ const grandparentAct = grandparentSig.includes("|") ? grandparentSig.split("|")[0] : grandparentSig;
757
+ const parentCls = parentAct.includes("/") ? parentAct.split("/").pop() || parentAct : parentAct;
758
+ const grandparentCls = grandparentAct.includes("/") ? grandparentAct.split("/").pop() || grandparentAct : grandparentAct;
759
+ if (parentCls !== grandparentCls) return false;
760
+ const rid = String(elem["resource-id"] || "");
761
+ return Boolean(rid) && LIST_ITEM_RID_PATTERNS.some(p => rid.includes(p));
762
+ }
763
+ isInTargetApp(ai: Dict): boolean {
764
+ const f = (ai["current_focus"] as string) || ""; const r = (ai["resumed_activity"] as string) || "";
765
+ const m = f.match(/([\w.]+)\/[\w.]+/);
766
+ if (m && m[1] !== this.package) return false;
767
+ for (const marker of FOREIGN_FOCUS_MARKERS) if (f.includes(marker)) return false;
768
+ return f.includes(this.package) || r.includes(this.package);
769
+ }
770
+ scrollAndDump(pd: string, cb: [number, number, number, number], initXml: string = ""): { xmlList: string[]; xmlPaths: string[]; ssPaths: string[] } {
771
+ const [x1, y1, x2, y2] = cb; const cx = Math.floor((x1 + x2) / 2); const h = y2 - y1;
772
+ const fy = y1 + Math.floor(h * 0.7); const ty = y1 + Math.floor(h * 0.3);
773
+ const xmlList: string[] = []; const xmlPaths: string[] = []; const ssPaths: string[] = [];
774
+ let prevKeys: Set<string> | null = initXml ? PageCrawler.extractNodeKeys(initXml) : null;
775
+ for (let i = 0; i < this.maxScrolls; i++) {
776
+ this.adb.shell("input", "swipe", String(cx), String(fy), String(cx), String(ty), String(this.adb.scrollDurationMs));
777
+ this.adb.waitForIdle(); const nx = this.adb.dumpXmlQuick();
778
+ if (PageCrawler.hasFocusedInput(nx)) {
779
+ console.log(" [INFO] 滚动后仍处于输入态,停止滚动采集");
780
+ if (this.adb.isSoftKeyboardShown()) {
781
+ console.log(" [INFO] 软键盘可见,收起键盘");
782
+ this.adb.pressBack();
783
+ }
784
+ break;
785
+ }
786
+ const nk = PageCrawler.extractNodeKeys(nx);
787
+ if (prevKeys && setsEqual(prevKeys, nk)) { console.log(` 📜 滚动 ${i + 1} 次后到达底部,跳过截图`); break; }
788
+ prevKeys = nk; xmlList.push(nx);
789
+ const xp = path.join(pd, `view_scroll_${i + 1}.xml`); fs.writeFileSync(xp, nx, "utf-8"); xmlPaths.push(xp);
790
+ const sp = path.join(pd, `screenshot_scroll_${i + 1}.png`); const d = this.adb.screencapBytes();
791
+ if (d) { fs.writeFileSync(sp, d); ssPaths.push(sp); console.log(` 📸 滚动 ${i + 1}: XML + 截图已保存`); }
792
+ }
793
+ return { xmlList, xmlPaths, ssPaths: ssPaths };
794
+ }
795
+ capturePage(label: string): { record: Dict; xmlContent: string; clickable: Dict[]; scrollBounds: [number, number, number, number] | null } {
796
+ const tmpDir = path.join(this.outputRoot, "_tmp_capture");
797
+ if (fs.existsSync(tmpDir)) fs.rmSync(tmpDir, { recursive: true, force: true });
798
+ fs.mkdirSync(tmpDir, { recursive: true });
799
+ console.log(`\n📄 [采集中] ${label}`);
800
+ const ai = this.adb.getCurrentActivity();
801
+ console.log(` Focus : ${(ai["current_focus"] as string) || "N/A"}`);
802
+ console.log(` Activity: ${(ai["resumed_activity"] as string) || "N/A"}`);
803
+ let xc = this.adb.getViewXmlFast(tmpDir);
804
+ if (PageCrawler.hasFocusedInput(xc) && this.adb.isSoftKeyboardShown()) {
805
+ console.log(" [INFO] 检测到输入框聚焦,先收起键盘再采集");
806
+ this.adb.pressBack();
807
+ xc = this.adb.getViewXmlFast(tmpDir);
808
+ }
809
+ console.log(` View XML 已保存 (${xc.length} bytes)`); this.adb.takeScreenshot(tmpDir); console.log(` 截图已保存`);
810
+ const allSs = [path.join(tmpDir, "screenshot.png")]; const allVx = [path.join(tmpDir, "view.xml")]; const allXc = [xc];
811
+ const sc = PageCrawler.findScrollableContainers(xc); let sb: [number, number, number, number] | null = null;
812
+ if (sc.length > 0) {
813
+ const c = sc[0]; console.log(` 📜 检测到可滚动容器: ${c["class"]} ${(c["resource-id"] as string) || ""}`);
814
+ sb = c["bounds"] as [number, number, number, number];
815
+ const sr = this.scrollAndDump(tmpDir, sb, xc);
816
+ if (sr.xmlList.length) { allXc.push(...sr.xmlList); allVx.push(...sr.xmlPaths); allSs.push(...sr.ssPaths); console.log(` 📜 滚动采集完成:${sr.xmlList.length} 次滚动,共 ${allSs.length} 张截图`); }
817
+ }
818
+ const seen = new Set<string>(); const cl: Dict[] = [];
819
+ const seenDigest = new Set<string>(); const elementsDigest: Dict[] = [];
820
+ for (let idx = 0; idx < allXc.length; idx++) {
821
+ for (const e of PageCrawler.getClickableElements(allXc[idx])) {
822
+ const k = JSON.stringify([(e["resource-id"] as string) || "", (e["text"] as string) || "", (e["content-desc"] as string) || "", (e["class"] as string) || "", (e["bounds"] as string) || "", e["long-clickable"] ?? false]);
823
+ if (!seen.has(k)) { seen.add(k); e["scroll_index"] = idx; cl.push(e); }
824
+ }
825
+ for (const e of PageCrawler.collectElementsDigest(allXc[idx], idx)) {
826
+ const k = JSON.stringify([(e["class"] as string) || "", (e["resource-id"] as string) || "", (e["text"] as string) || "", (e["content-desc"] as string) || "", (e["bounds"] as string) || "", e["clickable"] || false, e["long-clickable"] || false, e["checkable"] || false, e["scrollable"] || false]);
827
+ if (!seenDigest.has(k)) { seenDigest.add(k); elementsDigest.push(e); }
828
+ }
829
+ }
830
+ console.log(` 可点击元素: ${cl.length} 个`);
831
+ return {
832
+ record: {
833
+ page_id: null,
834
+ label,
835
+ timestamp: nowIso(),
836
+ activity_info: ai,
837
+ page_identity_signature: PageCrawler.pageSignature(ai, xc),
838
+ page_state_signature: PageCrawler.pageStateSignature(ai, xc),
839
+ clickable_count: cl.length,
840
+ clickable_elements: cl,
841
+ elements_digest_count: elementsDigest.length,
842
+ elements_digest: elementsDigest,
843
+ scroll_container_bounds: sb ? Array.from(sb) : null,
844
+ _tmp_dir: tmpDir,
845
+ _screenshots: allSs,
846
+ _view_xmls: allVx,
847
+ },
848
+ xmlContent: xc,
849
+ clickable: cl,
850
+ scrollBounds: sb,
851
+ };
852
+ }
853
+ restartToRoot(lp: string | null, la: string | null, kw: string | null = null, ri: [string, Set<string>] | null = null): boolean {
854
+ if (!lp || !la) { console.log(" [WARN] 包名或 Activity 名为空,无法重启"); return false; }
855
+ const comp = `${lp}/${la}`;
856
+ const isAtRoot = (): boolean => {
857
+ const ai = this.adb.getCurrentActivity(); const f = (ai["current_focus"] as string) || ""; const r = (ai["resumed_activity"] as string) || "";
858
+ if (kw && !f.includes(kw) && !r.includes(kw)) return false;
859
+ if (ri) { const x = this.adb.dumpXmlQuick(); const ci = PageCrawler.rootIdentifiedSet(ai, x); if (!PageCrawler.isSameRootPage(ri, ci)) { let inter = 0; for (const x2 of ri[1]) if (ci[1].has(x2)) inter++; const uni = ri[1].size + ci[1].size - inter; console.log(` [DEBUG] 根页面相似度: ${(uni ? inter / uni : 0).toFixed(2)} (交集${inter}/并集${uni})`); return false; } }
860
+ return true;
861
+ };
862
+ const tryRec = (): boolean => {
863
+ if (!this.rootRecoveryClicks.length) return false; console.log(` [INFO] 尝试通过点击路径恢复到根页面...`);
864
+ for (const s of this.rootRecoveryClicks) {
865
+ const x = this.adb.dumpXmlQuick(); const cl = PageCrawler.getClickableElements(x); let found: Dict | null = null;
866
+ for (const e of cl) { if (s["content-desc"] && e["content-desc"] === s["content-desc"]) { found = e; break; } if (s["text"] && e["text"] === s["text"]) { found = e; break; } if (s["resource-id"] && e["resource-id"] === s["resource-id"]) { found = e; break; } }
867
+ if (found && found["center"]) { const c = PageCrawler.chooseTapPoint(x, found) || found["center"] as [number, number]; console.log(` [INFO] 点击: ${(s["content-desc"] as string) || (s["text"] as string) || (s["resource-id"] as string)}`); this.adb.tap(c[0], c[1]); }
868
+ else if (s["center"]) { const c = s["center"] as [number, number]; console.log(` [INFO] 使用固定坐标点击: ${JSON.stringify(c)}`); this.adb.tap(c[0], c[1]); }
869
+ else { console.log(` [WARN] 恢复路径中未找到元素: ${JSON.stringify(s)}`); return false; }
870
+ }
871
+ return isAtRoot();
872
+ };
873
+ this.adb.shell("am", "force-stop", lp); sleepMs(1000);
874
+ this.adb.shell("am", "start", "-n", comp, "--activity-clear-task", "--activity-clear-top"); this.adb.waitForIdle();
875
+ for (let i = 0; i < 4; i++) { if (isAtRoot()) return true; console.log(` [INFO] 等待页面加载完成... (重试 ${i + 1}/4)`); sleepMs(2000); }
876
+ console.log(` [WARN] force-stop 后未到达根页面(App 恢复了上次的 Tab 状态)`);
877
+ if (tryRec()) return true; console.log(` [INFO] 尝试 back + 点击路径恢复...`); this.adb.pressBack();
878
+ if (isAtRoot()) return true; if (tryRec()) return true;
879
+ console.log(` [WARN] 所有恢复方式均失败,跳过此次导航`); return false;
880
+ }
881
+ static learnedRootPathKey(clickPath: Dict[]): string {
882
+ return JSON.stringify(clickPath);
883
+ }
884
+ static learnedRootPathPriority(candidate: LearnedRootPath): number {
885
+ const attempts = candidate.successes + candidate.failures;
886
+ return attempts ? candidate.successes / attempts : 0.5;
887
+ }
888
+ static compareLearnedRootPaths(left: LearnedRootPath, right: LearnedRootPath): number {
889
+ const priorityDiff = PageCrawler.learnedRootPathPriority(right) - PageCrawler.learnedRootPathPriority(left);
890
+ if (priorityDiff !== 0) return priorityDiff;
891
+ if (left.successes !== right.successes) return right.successes - left.successes;
892
+ return left.failures - right.failures;
893
+ }
894
+ static isRootPageRecord(page: Dict): boolean {
895
+ const clickPath = page["click_path"];
896
+ return clickPath == null || (Array.isArray(clickPath) && clickPath.length === 0);
897
+ }
898
+ isKnownRootSignature(signature: string): boolean {
899
+ if (!signature) return false;
900
+ if (signature === this.rootSignature) return true;
901
+ const rootPage = this.pagesIndex.find(PageCrawler.isRootPageRecord);
902
+ return ((rootPage?.["_merged_identity_signatures"] as string[] | undefined) || []).includes(signature);
903
+ }
904
+ loadLearnedRootPaths(): void {
905
+ const statsPath = path.join(this.outputRoot, "crawl_stats.json");
906
+ if (!fs.existsSync(statsPath)) return;
907
+ try {
908
+ const payload = JSON.parse(fs.readFileSync(statsPath, "utf-8")) as Dict;
909
+ const saved = payload["learned_root_paths"];
910
+ if (!Array.isArray(saved)) return;
911
+ const restored: LearnedRootPath[] = [];
912
+ const seen = new Set<string>();
913
+ for (const item of saved as Dict[]) {
914
+ if (!Array.isArray(item["steps"]) || item["steps"].length === 0) continue;
915
+ const steps = item["steps"] as Dict[];
916
+ const key = PageCrawler.learnedRootPathKey(steps);
917
+ if (seen.has(key)) continue;
918
+ seen.add(key);
919
+ restored.push({
920
+ steps,
921
+ successes: Math.max(0, Math.trunc(Number(item["successes"]) || 0)),
922
+ failures: Math.max(0, Math.trunc(Number(item["failures"]) || 0)),
923
+ });
924
+ }
925
+ this.learnedRootPaths = restored.sort(PageCrawler.compareLearnedRootPaths).slice(0, LEARNED_ROOT_PATH_LIMIT);
926
+ if (this.learnedRootPaths.length) console.log(` [INFO] 恢复 ${this.learnedRootPaths.length} 条 learned root recovery paths`);
927
+ } catch (e) { console.log(` [WARN] 恢复 learned root recovery paths 失败: ${e}`); }
928
+ }
929
+ recordLearnedRootPath(clickPath: Dict[]): void {
930
+ if (!clickPath.length) return;
931
+ const key = PageCrawler.learnedRootPathKey(clickPath);
932
+ if (this.learnedRootPaths.some(candidate => PageCrawler.learnedRootPathKey(candidate.steps) === key)) return;
933
+ const candidate: LearnedRootPath = {
934
+ steps: JSON.parse(JSON.stringify(clickPath)) as Dict[],
935
+ successes: 0,
936
+ failures: 0,
937
+ };
938
+ this.learnedRootPaths.push(candidate);
939
+ this.learnedRootPaths.sort(PageCrawler.compareLearnedRootPaths);
940
+ const evicted = this.learnedRootPaths.length > LEARNED_ROOT_PATH_LIMIT ? this.learnedRootPaths.pop()! : null;
941
+ console.log(` [INFO] learned root recovery path: ${clickPath.map(s => s["element"] || "?").join(" -> ")}`);
942
+ if (evicted) {
943
+ console.log(` [INFO] 淘汰 learned root recovery path: ${evicted.steps.map(s => s["element"] || "?").join(" -> ")} (success=${evicted.successes}, failure=${evicted.failures})`);
944
+ }
945
+ this.writeCrawlStats();
946
+ }
947
+ tryReplayLearnedPath(clickPath: Dict[], acceptRoot: () => boolean): boolean {
948
+ if (!clickPath.length) return false;
949
+ console.log(` [INFO] try learned root recovery path: ${clickPath.map(s => s["element"] || "?").join(" -> ")}`);
950
+ const elemIdForStep = (step: Dict): unknown[] => [
951
+ String(step["resource-id"] || ""),
952
+ String(step["text"] || ""),
953
+ String(step["content-desc"] || ""),
954
+ String(step["bounds"] || ""),
955
+ Boolean(step["long-clickable"]),
956
+ ];
957
+ let startIndex = 0; let startFound: Dict | null = null;
958
+ let currentXml = this.adb.dumpXmlQuick();
959
+ for (let i = clickPath.length - 1; i >= 0; i--) {
960
+ const found = PageCrawler.findElementOnScreen(currentXml, elemIdForStep(clickPath[i]));
961
+ if (found && found["center"]) { startIndex = i; startFound = found; if (i > 0) console.log(` [INFO] learned path resumes from step ${i + 1}/${clickPath.length}`); break; }
962
+ }
963
+ for (let i = startIndex; i < clickPath.length; i++) {
964
+ const step = clickPath[i];
965
+ if (PageCrawler.stepLooksDestructive(step)) return false;
966
+ let xml = (i === startIndex) ? currentXml : this.adb.dumpXmlQuick();
967
+ const ssc = step["scroll_info"] as Dict | undefined;
968
+ if (ssc && ((ssc["scroll_index"] as number) || 0) > 0) {
969
+ this.adb.scrollToPosition(ssc["container_bounds"] as [number, number, number, number], ssc["scroll_index"] as number);
970
+ xml = this.adb.dumpXmlQuick();
971
+ }
972
+ const found = (i === startIndex && startFound) ? startFound : PageCrawler.findElementOnScreen(xml, elemIdForStep(step));
973
+ if (!found || !found["center"] || PageCrawler.isDestructiveElement(found)) return false;
974
+ const isLong = Boolean(step["long-clickable"]);
975
+ const c = PageCrawler.chooseTapPoint(xml, found) || found["center"] as [number, number];
976
+ this.adb.tapOrLongPress(c[0], c[1], isLong);
977
+ currentXml = "";
978
+ }
979
+ return acceptRoot();
980
+ }
981
+ restartToRootForNavigation(lp: string | null, la: string | null, kw: string | null = null, ri: [string, Set<string>] | null = null, requiredElemId: unknown[] | null = null): boolean {
982
+ if (!lp || !la) { console.log(" [WARN] missing package/activity, cannot restart"); return false; }
983
+ const comp = `${lp}/${la}`;
984
+ const rootStatus = (): "exact" | "shell" | "off" => {
985
+ const ai = this.adb.getCurrentActivity();
986
+ const f = String(ai["current_focus"] || ""); const r = String(ai["resumed_activity"] || "");
987
+ if (kw && !f.includes(kw) && !r.includes(kw)) return "off";
988
+ if (!ri) return "exact";
989
+ const x = this.adb.dumpXmlQuick(); const ci = PageCrawler.rootIdentifiedSet(ai, x);
990
+ if (PageCrawler.isSameRootPage(ri, ci)) return "exact";
991
+ if (PageCrawler.isRootShell(ri, ai, x, requiredElemId)) return "shell";
992
+ const [sim, inter, uni] = PageCrawler.rootSimilarity(ri, ci);
993
+ console.log(` [DEBUG] root status=off, similarity=${sim.toFixed(2)} (${inter}/${uni})`);
994
+ return "off";
995
+ };
996
+ const acceptRoot = (allowShell: boolean = false): boolean => {
997
+ const status = rootStatus();
998
+ if (status === "exact") { this.lastRestartRootExact = true; return true; }
999
+ if (status === "shell" && allowShell) {
1000
+ this.lastRestartRootExact = false;
1001
+ if (ri) {
1002
+ const ai = this.adb.getCurrentActivity();
1003
+ const x = this.adb.dumpXmlQuick();
1004
+ const [sim, inter, uni] = PageCrawler.rootSimilarity(ri, PageCrawler.rootIdentifiedSet(ai, x));
1005
+ console.log(` [WARN] 所有 exact root 恢复方式失败,最后兜底接受 root shell (similarity=${sim.toFixed(2)}, 交集${inter}/并集${uni})`);
1006
+ } else {
1007
+ console.log(" [WARN] 所有 exact root 恢复方式失败,最后兜底接受 root shell");
1008
+ }
1009
+ return true;
1010
+ }
1011
+ return false;
1012
+ };
1013
+ const isCurrentTargetApp = (): boolean => this.isInTargetApp(this.adb.getCurrentActivity());
1014
+ const tryRecoveryClicks = (): boolean => {
1015
+ if (!this.rootRecoveryClicks.length) return false;
1016
+ if (!isCurrentTargetApp()) { console.log(" [INFO] 当前已不在目标 App,跳过点击路径恢复"); return false; }
1017
+ console.log(" [INFO] 尝试通过点击路径恢复到根页面...");
1018
+ for (const s of this.rootRecoveryClicks) {
1019
+ if (PageCrawler.stepLooksDestructive(s)) { console.log(" [SAFE-SKIP] 恢复路径包含可能修改/清理数据的控件,放弃该恢复路径"); return false; }
1020
+ const x = this.adb.dumpXmlQuick(); const cl = PageCrawler.getClickableElements(x); let found: Dict | null = null;
1021
+ for (const e of cl) {
1022
+ if (s["content-desc"] && e["content-desc"] === s["content-desc"]) { found = e; break; }
1023
+ if (s["text"] && e["text"] === s["text"]) { found = e; break; }
1024
+ if (s["resource-id"] && e["resource-id"] === s["resource-id"]) { found = e; break; }
1025
+ }
1026
+ if (found && PageCrawler.isDestructiveElement(found)) { console.log(" [SAFE-SKIP] 恢复路径命中可能修改/清理数据的控件,放弃点击"); return false; }
1027
+ if (found && found["center"]) { const c = PageCrawler.chooseTapPoint(x, found) || found["center"] as [number, number]; console.log(` [INFO] 点击: ${String(s["content-desc"] || s["text"] || s["resource-id"] || "?")}`); this.adb.tap(c[0], c[1]); }
1028
+ else if (s["center"]) { const c = s["center"] as [number, number]; console.log(` [INFO] 使用固定坐标点击: ${JSON.stringify(c)}`); this.adb.tap(c[0], c[1]); }
1029
+ else { console.log(` [WARN] 恢复路径中未找到元素: ${JSON.stringify(s)}`); return false; }
1030
+ }
1031
+ return acceptRoot();
1032
+ };
1033
+ let learnedRecoveryAllowed = false;
1034
+ const tryLearned = (): boolean => {
1035
+ if (!learnedRecoveryAllowed) return false;
1036
+ if (!isCurrentTargetApp()) { console.log(" [INFO] 当前已不在目标 App,跳过 learned root recovery"); return false; }
1037
+ const candidates = this.learnedRootPaths.slice(0, LEARNED_ROOT_ATTEMPTS_PER_RECOVERY);
1038
+ const resetToLaunchState = (): boolean => {
1039
+ this.adb.shell("am", "force-stop", lp); sleepMs(1000);
1040
+ this.adb.shell("am", "start", "-n", comp, "--activity-clear-task", "--activity-clear-top"); this.adb.waitForIdle();
1041
+ return isCurrentTargetApp();
1042
+ };
1043
+ for (let i = 0; i < candidates.length; i++) {
1044
+ if (i > 0) {
1045
+ console.log(" [INFO] 重置 App 状态后尝试下一条 learned root recovery path...");
1046
+ if (!resetToLaunchState()) break;
1047
+ if (acceptRoot()) return true;
1048
+ }
1049
+ const candidate = candidates[i];
1050
+ const success = this.tryReplayLearnedPath(candidate.steps, () => acceptRoot());
1051
+ if (success) candidate.successes++;
1052
+ else candidate.failures++;
1053
+ this.learnedRootPaths.sort(PageCrawler.compareLearnedRootPaths);
1054
+ this.writeCrawlStats();
1055
+ console.log(` [INFO] learned root path result: ${success ? "success" : "failure"} (${candidate.successes}/${candidate.successes + candidate.failures})`);
1056
+ if (success) return true;
1057
+ }
1058
+ if (!candidates.length) return false;
1059
+ console.log(" [INFO] learned root recovery 均失败,重置 App 状态后继续其他恢复方式...");
1060
+ return resetToLaunchState() && acceptRoot();
1061
+ };
1062
+ if (acceptRoot()) { console.log(" [INFO] 当前已在 exact root"); return true; }
1063
+ console.log(" [INFO] 当前不在 exact root,先尝试 Back 回退...");
1064
+ let backExitedTargetApp = false;
1065
+ for (let i = 0; i < BACK_UNWIND_MAX_DEFAULT; i++) {
1066
+ this.adb.pressBack(); sleepMs(300);
1067
+ if (!isCurrentTargetApp()) { backExitedTargetApp = true; console.log(" [INFO] Back 后已离开目标 App,停止继续 Back,改用重启恢复"); break; }
1068
+ if (acceptRoot()) { console.log(` [INFO] Back 回退成功 (${i + 1}/${BACK_UNWIND_MAX_DEFAULT})`); return true; }
1069
+ }
1070
+ console.log(" [INFO] Back 回退未恢复,执行 force-stop + start...");
1071
+ this.adb.shell("am", "force-stop", lp); sleepMs(1000);
1072
+ this.adb.shell("am", "start", "-n", comp, "--activity-clear-task", "--activity-clear-top"); this.adb.waitForIdle();
1073
+ if (isCurrentTargetApp() && acceptRoot()) { console.log(" [INFO] force-stop + start 恢复到 exact root"); return true; }
1074
+ console.log(" [INFO] 重启后暂未到达 exact root,等待 2 秒加载宽限...");
1075
+ sleepMs(2000);
1076
+ if (isCurrentTargetApp() && acceptRoot()) { console.log(" [INFO] force-stop + start 在加载宽限后恢复到 exact root"); return true; }
1077
+ learnedRecoveryAllowed = true;
1078
+ console.log(" [WARN] force-stop 后未到达根页面(App 恢复了上次的 Tab 状态)");
1079
+ if (tryLearned()) { console.log(" [INFO] learned root recovery 成功"); return true; }
1080
+ if (tryRecoveryClicks()) { console.log(" [INFO] 点击路径恢复成功"); return true; }
1081
+ if (backExitedTargetApp) {
1082
+ console.log(" [INFO] 本轮 Back 已退出过目标 App,跳过额外 back + 点击路径恢复");
1083
+ if (requiredElemId && acceptRoot(true)) return true;
1084
+ console.log(" [WARN] 所有 exact root 恢复方式均失败,跳过此次导航");
1085
+ return false;
1086
+ }
1087
+ console.log(" [INFO] 尝试 back + 点击路径恢复...");
1088
+ this.adb.pressBack(); sleepMs(300);
1089
+ if (!isCurrentTargetApp()) { console.log(" [INFO] Back 后已离开目标 App,跳过点击路径恢复"); return false; }
1090
+ if (acceptRoot()) { console.log(" [INFO] 额外 Back 后恢复到 exact root"); return true; }
1091
+ if (tryRecoveryClicks()) { console.log(" [INFO] 点击路径恢复成功"); return true; }
1092
+ if (requiredElemId && acceptRoot(true)) return true;
1093
+ console.log(" [WARN] 所有 exact root 恢复方式均失败,跳过此次导航");
1094
+ return false;
1095
+ }
1096
+ navigateViaRestart(cp: Dict[], lp: string | null, la: string | null, kw: string | null = null, ss: string[] | null = null, ri: [string, Set<string>] | null = null): boolean {
1097
+ if (!lp || !la) { console.log(" [WARN] 包名或 Activity 名为空,无法导航"); return false; }
1098
+ if (cp.length === 0) return true;
1099
+ const first = cp[0];
1100
+ const firstElemId = [(first["resource-id"] as string) || "", (first["text"] as string) || "", (first["content-desc"] as string) || "", (first["bounds"] as string) || "", Boolean(first["long-clickable"])];
1101
+ if (!this.restartToRootForNavigation(lp, la, kw, ri, firstElemId)) { console.log(" [ERR] 无法回到根页面,导航失败"); return false; }
1102
+ for (let i = 0; i < cp.length; i++) {
1103
+ const s = cp[i]; let x = this.adb.dumpXmlQuick();
1104
+ const ssc = s["scroll_info"] as Dict | undefined;
1105
+ if (ssc && ((ssc["scroll_index"] as number) || 0) > 0) { this.adb.scrollToPosition(ssc["container_bounds"] as [number, number, number, number], ssc["scroll_index"] as number); x = this.adb.dumpXmlQuick(); }
1106
+ const eid = [(s["resource-id"] as string) || "", (s["text"] as string) || "", (s["content-desc"] as string) || "", (s["bounds"] as string) || "", Boolean(s["long-clickable"])];
1107
+ const f = PageCrawler.findElementOnScreen(x, eid); const isLong = (s["long-clickable"] as boolean) || false;
1108
+ if (f && f["center"]) { if (PageCrawler.isDestructiveElement(f)) return false; const c = PageCrawler.chooseTapPoint(x, f) || f["center"] as [number, number]; this.adb.tapOrLongPress(c[0], c[1], isLong); }
1109
+ else if (i === 0 && !this.lastRestartRootExact) { console.log(" [WARN] first step not found in root shell; skip coordinate fallback"); return false; }
1110
+ else if (s["center"]) { console.log(` [WARN] 未找到元素 ${s["element"] || "?"},使用记录坐标`); const c = s["center"] as [number, number]; this.adb.tapOrLongPress(c[0], c[1], isLong); }
1111
+ else { console.log(` [ERR] 无法导航到步骤: ${s["element"] || "?"}`); return false; }
1112
+ if (ss && i < ss.length && ss[i]) { const vx = this.adb.dumpXmlQuick(); const vi = this.adb.getCurrentActivity(); const asig = PageCrawler.pageSignature(vi, vx); if (asig !== ss[i]) { const ea = ss[i].split("|")[0]; const aa = asig.split("|")[0]; if (ea !== aa) { console.log(` [WARN] 导航步骤 ${i + 1} 后 Activity 不匹配 (期望=${ea}, 实际=${aa})`); return false; } } }
1113
+ }
1114
+ return true;
1115
+ }
1116
+
1117
+ saveQueue(q: QueueItem[]): void {
1118
+ try { fs.writeFileSync(path.join(this.outputRoot, "queue_checkpoint.json"), JSON.stringify(q.map(([cp, eid, ss, si, tmpl]) => [cp, Array.from(eid), ss, si, tmpl])), "utf-8"); }
1119
+ catch (e) { console.log(` [WARN] 保存队列检查点失败: ${e}`); }
1120
+ }
1121
+ loadQueue(): QueueItem[] | null {
1122
+ const qf = path.join(this.outputRoot, "queue_checkpoint.json"); if (!fs.existsSync(qf)) return null;
1123
+ try { const items = JSON.parse(fs.readFileSync(qf, "utf-8")) as unknown[]; const q: QueueItem[] = []; for (const it of items) { const [cp, eid, ss, si, tmpl] = it as [Dict[], unknown[], string[], Dict, TemplateKey]; q.push([cp, eid, ss, si, tmpl ?? null]); } return q; }
1124
+ catch (e) { console.log(` [WARN] 加载队列检查点失败: ${e},将重建队列`); return null; }
1125
+ }
1126
+ rebuildQueueFromPages(pi: Dict[]): QueueItem[] {
1127
+ const q: QueueItem[] = [];
1128
+ for (const p of pi) { const cp = (p["click_path"] as Dict[]) || []; const cl = (p["clickable_elements"] as Dict[]) || []; const scb = p["scroll_container_bounds"] as number[] | null; const repeated = PageCrawler.repeatedTemplates(cl);
1129
+ for (const e of cl) { if (this.shouldSkipElement(e)) continue; const eid: unknown[] = [(e["resource-id"] as string) || "", (e["text"] as string) || "", (e["content-desc"] as string) || "", (e["bounds"] as string) || "", (e["long-clickable"] as boolean) || false]; const si = (e["scroll_index"] as number) || 0; let sInfo: Dict | null = null; if (si > 0 && scb) sInfo = { scroll_index: si, container_bounds: Array.from(scb) }; const tmpl = repeated.has(PageCrawler.templateKey(e)) ? PageCrawler.templateKey(e) : null; q.push([cp, eid, [], sInfo, tmpl]); } }
1130
+ return q;
1131
+ }
1132
+ tryLoadCheckpoint(): [Dict[], Set<string>, number, QueueItem[], Set<string>] | null {
1133
+ const idx = path.join(this.outputRoot, "index.json"); if (!fs.existsSync(idx)) return null;
1134
+ if (fs.readdirSync(this.outputRoot).filter(n => n.startsWith("page_")).length === 0) return null;
1135
+ let pi: Dict[]; try { pi = JSON.parse(fs.readFileSync(idx, "utf-8")) as Dict[]; } catch (e) { console.log(` [WARN] 读取 index.json 失败: ${e},重新开始`); return null; }
1136
+ if (!pi.length) return null; console.log(`\n⏩ 发现已有检查点:${pi.length} 个页面,尝试断点续跑...`);
1137
+ const vs = new Set<string>(); let pc = 0;
1138
+ for (const p of pi) {
1139
+ const pid = (p["page_id"] as string) || ""; if (!pid) continue;
1140
+ const m = pid.match(/page_(\d+)/); if (m) pc = Math.max(pc, parseInt(m[1], 10));
1141
+ const vp = path.join(this.outputRoot, pid, "view.xml");
1142
+ if (fs.existsSync(vp)) vs.add(PageCrawler.pageSignature(p["activity_info"] as Dict, fs.readFileSync(vp, "utf-8")));
1143
+ for (const mergedSig of ((p["_merged_identity_signatures"] as string[]) || [])) if (mergedSig) vs.add(mergedSig);
1144
+ }
1145
+ const sq = this.loadQueue(); let q: QueueItem[];
1146
+ if (sq) { q = sq; console.log(` 队列已从检查点恢复:${q.length} 个待处理元素(精确续跑)`); } else { q = this.rebuildQueueFromPages(pi); console.log(` 队列已重建(fallback):${q.length} 个元素(含已探索项,BFS 会自动跳过)`); }
1147
+ console.log(` 已恢复 ${vs.size} 个已访问签名,队列 ${q.length} 个待处理元素`);
1148
+ return [pi, vs, pc, q, new Set<string>()];
1149
+ }
1150
+
1151
+ _commitCommon(record: Dict, pageId: string): string {
1152
+ const pageDir = path.join(this.outputRoot, pageId); const tmpDir = record["_tmp_dir"] as string;
1153
+ if (fs.existsSync(tmpDir)) fs.renameSync(tmpDir, pageDir); else fs.mkdirSync(pageDir, { recursive: true });
1154
+ record["page_id"] = pageId; record["screenshot"] = `${pageId}/screenshot.png`; record["view_xml"] = `${pageId}/view.xml`;
1155
+ const ssList = [`${pageId}/screenshot.png`]; for (const ss of (record["_screenshots"] as string[]) || []) { const n = path.basename(ss); if (n !== "screenshot.png") ssList.push(`${pageId}/${n}`); } record["screenshots"] = ssList;
1156
+ const vxList = [`${pageId}/view.xml`]; for (const vx of (record["_view_xmls"] as string[]) || []) { const n = path.basename(vx); if (n !== "view.xml") vxList.push(`${pageId}/${n}`); } record["view_xmls"] = vxList;
1157
+ this.recordPageGaps(record);
1158
+ delete record["_tmp_dir"]; delete record["_screenshots"]; delete record["_view_xmls"]; fs.writeFileSync(path.join(pageDir, "meta.json"), JSON.stringify(record, null, 2), "utf-8"); console.log(` ✅ 已保存为 [${pageId}]`); return pageId;
1159
+ }
1160
+ commitPage(record: Dict): string {
1161
+ this.pageCounter += 1; let an = ""; const ai = record["activity_info"] as Dict; const r = (ai["resumed_activity"] as string) || "";
1162
+ let ma = r.match(/[\w.]+\/([\w.]+)/); if (!ma) { const f = (ai["current_focus"] as string) || ""; ma = f.match(/[\w.]+\/([\w.]+)/); }
1163
+ if (ma) an = ma[1].split(".").pop()!;
1164
+ return this._commitCommon(record, `page_${String(this.pageCounter).padStart(4, "0")}${an ? `_${an}` : ""}`);
1165
+ }
1166
+ commitManualPage(record: Dict, pc: number): string {
1167
+ let an = ""; const ai = record["activity_info"] as Dict; const r = (ai["resumed_activity"] as string) || "";
1168
+ let ma = r.match(/[\w.]+\/([\w.]+)/); if (!ma) { const f = (ai["current_focus"] as string) || ""; ma = f.match(/[\w.]+\/([\w.]+)/); }
1169
+ if (ma) an = ma[1].split(".").pop()!;
1170
+ return this._commitCommon(record, `manual_${String(pc).padStart(4, "0")}${an ? `_${an}` : ""}`);
1171
+ }
1172
+
1173
+ static mergeKey(elem: Dict): string {
1174
+ return JSON.stringify([
1175
+ elem["class"] || "",
1176
+ elem["resource-id"] || "",
1177
+ elem["text"] || "",
1178
+ elem["content-desc"] || "",
1179
+ elem["bounds"] || "",
1180
+ elem["clickable"] ?? null,
1181
+ elem["long-clickable"] || false,
1182
+ elem["checkable"] ?? null,
1183
+ elem["checked"] ?? null,
1184
+ elem["selected"] ?? null,
1185
+ elem["enabled"] ?? null,
1186
+ elem["scrollable"] ?? null,
1187
+ ]);
1188
+ }
1189
+ static appendUniqueElements(dst: Dict[], src: Dict[]): number {
1190
+ const seen = new Set(dst.map(e => PageCrawler.mergeKey(e)));
1191
+ let added = 0;
1192
+ for (const e of src) {
1193
+ const k = PageCrawler.mergeKey(e);
1194
+ if (seen.has(k)) continue;
1195
+ seen.add(k); dst.push(e); added++;
1196
+ }
1197
+ return added;
1198
+ }
1199
+ static nearDuplicateStats(leftInfo: Dict, leftXml: string, rightInfo: Dict, rightXml: string): NearDuplicateStats | null {
1200
+ const [leftAct, leftFeatures] = PageCrawler.pageIdentityFeatureMap(leftInfo, leftXml);
1201
+ const [rightAct, rightFeatures] = PageCrawler.pageIdentityFeatureMap(rightInfo, rightXml);
1202
+ if (leftAct !== rightAct) return null;
1203
+ const leftSet = new Set(leftFeatures.keys()); const rightSet = new Set(rightFeatures.keys());
1204
+ const union = new Set([...leftSet, ...rightSet]);
1205
+ if (union.size === 0) return null;
1206
+ const strongDiff: string[] = []; const weakDiff: string[] = [];
1207
+ for (const f of union) {
1208
+ if (leftSet.has(f) && rightSet.has(f)) continue;
1209
+ const isWeak = leftFeatures.get(f) ?? rightFeatures.get(f) ?? false;
1210
+ if (isWeak) weakDiff.push(f); else strongDiff.push(f);
1211
+ }
1212
+ let inter = 0; for (const f of leftSet) if (rightSet.has(f)) inter++;
1213
+ return { jaccard: inter / union.size, strongDiff: strongDiff.sort(), weakDiff: weakDiff.sort() };
1214
+ }
1215
+ static isNearDuplicate(stats: NearDuplicateStats | null): boolean {
1216
+ if (!stats) return false;
1217
+ const strict = stats.jaccard >= NEAR_DUP_MIN_JACCARD
1218
+ && stats.strongDiff.length <= NEAR_DUP_MAX_STRONG_DIFFS
1219
+ && stats.weakDiff.length <= NEAR_DUP_MAX_WEAK_DIFFS;
1220
+ const weakOnly = stats.jaccard >= NEAR_DUP_WEAK_ONLY_MIN_JACCARD
1221
+ && stats.strongDiff.length === 0
1222
+ && stats.weakDiff.length > 0
1223
+ && stats.weakDiff.length <= NEAR_DUP_MAX_WEAK_DIFFS;
1224
+ return strict || weakOnly;
1225
+ }
1226
+ findNearDuplicatePage(record: Dict, xmlContent: string): [Dict, NearDuplicateStats] | null {
1227
+ let best: [Dict, NearDuplicateStats] | null = null;
1228
+ for (const page of this.pagesIndex) {
1229
+ const pageId = page["page_id"] as string;
1230
+ if (!pageId) continue;
1231
+ const viewXmlPath = path.join(this.outputRoot, pageId, "view.xml");
1232
+ if (!fs.existsSync(viewXmlPath)) continue;
1233
+ const existingXml = fs.readFileSync(viewXmlPath, "utf-8");
1234
+ const stats = PageCrawler.nearDuplicateStats(page["activity_info"] as Dict, existingXml, record["activity_info"] as Dict, xmlContent);
1235
+ if (!PageCrawler.isNearDuplicate(stats)) continue;
1236
+ if (!best || stats!.jaccard > best[1].jaccard) best = [page, stats!];
1237
+ }
1238
+ return best;
1239
+ }
1240
+ mergePageVariant(canonical: Dict, variant: Dict, stats: NearDuplicateStats): void {
1241
+ const pageId = canonical["page_id"] as string;
1242
+ if (!pageId) return;
1243
+ const pageDir = path.join(this.outputRoot, pageId);
1244
+ fs.mkdirSync(pageDir, { recursive: true });
1245
+ const variants = (canonical["_merged_variants"] as Dict[] | undefined) || [];
1246
+ canonical["_merged_variants"] = variants;
1247
+ let variantNo = variants.length + 1;
1248
+ let variantId = `variant_${String(variantNo).padStart(3, "0")}`;
1249
+ let variantDir = path.join(pageDir, variantId);
1250
+ while (fs.existsSync(variantDir)) {
1251
+ variantNo++; variantId = `variant_${String(variantNo).padStart(3, "0")}`; variantDir = path.join(pageDir, variantId);
1252
+ }
1253
+ const tmpDir = variant["_tmp_dir"] as string;
1254
+ if (tmpDir && fs.existsSync(tmpDir)) fs.renameSync(tmpDir, variantDir);
1255
+ else fs.mkdirSync(variantDir, { recursive: true });
1256
+ const canonicalClickables = (canonical["clickable_elements"] as Dict[] | undefined) || [];
1257
+ canonical["clickable_elements"] = canonicalClickables;
1258
+ const clickableAdded = PageCrawler.appendUniqueElements(canonicalClickables, (variant["clickable_elements"] as Dict[]) || []);
1259
+ canonical["clickable_count"] = ((canonical["clickable_elements"] as Dict[]) || []).length;
1260
+ const canonicalDigest = (canonical["elements_digest"] as Dict[] | undefined) || [];
1261
+ canonical["elements_digest"] = canonicalDigest;
1262
+ const digestAdded = PageCrawler.appendUniqueElements(canonicalDigest, (variant["elements_digest"] as Dict[]) || []);
1263
+ canonical["elements_digest_count"] = ((canonical["elements_digest"] as Dict[]) || []).length;
1264
+ const sigs = new Set((canonical["_merged_identity_signatures"] as string[] | undefined) || []);
1265
+ if (variant["page_identity_signature"]) sigs.add(variant["page_identity_signature"] as string);
1266
+ canonical["_merged_identity_signatures"] = [...sigs].sort();
1267
+ const tmpScreenshots = (variant["_screenshots"] as string[]) || [];
1268
+ const tmpViewXmls = (variant["_view_xmls"] as string[]) || [];
1269
+ variants.push({
1270
+ variant_id: variantId,
1271
+ label: variant["label"],
1272
+ came_from: variant["came_from"],
1273
+ trigger_element: variant["trigger_element"],
1274
+ click_path: variant["click_path"],
1275
+ page_identity_signature: variant["page_identity_signature"],
1276
+ page_state_signature: variant["page_state_signature"],
1277
+ similarity: Math.round(stats.jaccard * 10000) / 10000,
1278
+ strong_diff: stats.strongDiff,
1279
+ weak_diff: stats.weakDiff,
1280
+ clickable_added: clickableAdded,
1281
+ digest_added: digestAdded,
1282
+ screenshots: tmpScreenshots.map(p => `${pageId}/${variantId}/${path.basename(p)}`),
1283
+ view_xmls: tmpViewXmls.map(p => `${pageId}/${variantId}/${path.basename(p)}`),
1284
+ });
1285
+ this.recordPageGaps(canonical);
1286
+ this.recordPageGaps({ ...variant, page_id: pageId }, variantId);
1287
+ fs.writeFileSync(path.join(pageDir, "meta.json"), JSON.stringify(canonical, null, 2), "utf-8");
1288
+ console.log(` ♻️ 近似重复页合并到 [${pageId}] (similarity=${stats.jaccard.toFixed(2)}, +clickable=${clickableAdded})`);
1289
+ }
1290
+
1291
+ generateHtmlReport(pages: Dict[]): void {
1292
+ let cards = "";
1293
+ for (const p of pages) {
1294
+ const activity = escapeHtml((p["activity_info"] as Dict)?.["current_focus"] as string || "N/A");
1295
+ const resumed = escapeHtml((p["activity_info"] as Dict)?.["resumed_activity"] as string || "N/A");
1296
+ const cp = p["click_path"];
1297
+ let pathDisplay: string;
1298
+ if (cp === "manual") { pathDisplay = `(手动采集:${escapeHtml((p["description"] as string) || "手动采集")})`; }
1299
+ else if (Array.isArray(cp) && cp.length) {
1300
+ const lcTag = '<b class="long-click">长按</b>';
1301
+ pathDisplay = (cp as Dict[]).map(s => `<code>${escapeHtml(s["from"] as string)}</code> ${s["long-clickable"] ? lcTag : "点击"} <b>${escapeHtml(s["element"] as string)}</b>`).join(" → ");
1302
+ } else pathDisplay = "(初始页)";
1303
+ const ssPath = escapeHtml(p["screenshot"] as string);
1304
+ const sss = (p["screenshots"] as string[]) || [ssPath];
1305
+ const vxs = (p["view_xmls"] as string[]) || [p["view_xml"] as string];
1306
+ let ssHtml: string;
1307
+ if (sss.length > 1) {
1308
+ let pairs = "";
1309
+ for (let i = 0; i < sss.length; i++) { const xl = vxs[i] || vxs[vxs.length - 1]; const lb = i === 0 ? "初始" : `滚动${i}`; pairs += `<div class="scroll-pair"><img src="${escapeHtml(sss[i])}" alt="screenshot" onerror="this.style.display='none'"/><a href="${escapeHtml(xl)}" target="_blank">${lb} XML</a></div>`; }
1310
+ ssHtml = `<div class="screenshots-gallery">${pairs}</div>`;
1311
+ } else ssHtml = `<img src="${escapeHtml(sss[0])}" alt="screenshot" onerror="this.style.display='none'"/>`;
1312
+ const label = escapeHtml(p["label"] as string); const pid = escapeHtml(p["page_id"] as string);
1313
+ let xlHtml: string;
1314
+ if (vxs.length > 1) xlHtml = vxs.map((vx, i) => `<a href="${escapeHtml(vx)}" target="_blank">📄 XML${i === 0 ? "" : `_${i}`}</a>`).join(" ");
1315
+ else xlHtml = `<a href="${escapeHtml(vxs[0])}" target="_blank">📄 查看 View XML</a>`;
1316
+ cards += `<div class="card"><div class="card-header"><span class="pid">${pid}</span><span class="label">${label}</span><span class="time">${escapeHtml((p["timestamp"] as string).slice(0, 19))}</span></div><div class="card-body">${ssHtml}<div class="meta"><div><b>Focus:</b> <code>${activity}</code></div><div><b>Activity:</b> <code>${resumed}</code></div><div><b>点击路径:</b> ${pathDisplay}</div><div><b>可点击元素:</b> ${p["clickable_count"]} 个</div><div class="links">${xlHtml}<a href="${pid}/meta.json" target="_blank">🗂 元数据 JSON</a></div></div></div></div>`;
1317
+ }
1318
+ const html = `<!DOCTYPE html><html lang="zh"><head><meta charset="UTF-8"><title>Android 页面遍历报告(加速版)</title><style>body{font-family:-apple-system,sans-serif;background:#f5f5f5;margin:0;padding:20px}h1{color:#333}.summary{background:#fff;border-radius:8px;padding:16px;margin-bottom:20px;box-shadow:0 1px 4px rgba(0,0,0,.1)}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(420px,1fr));gap:16px}.card{background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.1)}.card-header{background:#1a73e8;color:#fff;padding:10px 14px;display:flex;gap:10px;align-items:center}.pid{font-weight:bold;font-size:13px;background:rgba(255,255,255,.2);padding:2px 8px;border-radius:4px}.label{flex:1;font-size:14px}.time{font-size:11px;opacity:.8}.card-body{display:flex;gap:12px;padding:12px}.card-body img{width:140px;height:auto;border-radius:4px;border:1px solid #eee;object-fit:cover;flex-shrink:0}.screenshots-gallery{display:flex;gap:6px;overflow-x:auto;flex-shrink:0;max-width:320px;padding-bottom:4px}.screenshots-gallery img{width:120px;height:auto;border-radius:4px;border:1px solid #eee;object-fit:cover;flex-shrink:0}.scroll-pair{display:flex;flex-direction:column;align-items:center;gap:2px;flex-shrink:0}.scroll-pair a{font-size:10px;color:#1a73e8;text-decoration:none}.scroll-pair a:hover{text-decoration:underline}.meta{font-size:12px;color:#444;display:flex;flex-direction:column;gap:6px;overflow:hidden}.meta code{font-size:11px;background:#f0f0f0;padding:1px 4px;border-radius:3px;word-break:break-all}.links{display:flex;gap:10px;margin-top:4px}.links a{color:#1a73e8;text-decoration:none;font-size:12px}.links a:hover{text-decoration:underline}.long-click{color:#e65100;background:#fff3e0;padding:1px 5px;border-radius:3px;font-size:11px}</style></head><body><h1>📱 Android 页面遍历报告(加速版)</h1><div class="summary"><b>生成时间:</b>${nowStr()} &nbsp;|&nbsp;<b>共采集页面:</b>${pages.length} 个</div><div class="grid">${cards}</div></body></html>`;
1319
+ fs.writeFileSync(path.join(this.outputRoot, "report.html"), html, "utf-8");
1320
+ }
1321
+
1322
+ normalizeElemKey(elemId: unknown[]): string {
1323
+ return JSON.stringify([
1324
+ elemId[0] || "",
1325
+ elemId[1] || "",
1326
+ elemId[2] || "",
1327
+ Boolean(elemId[4]),
1328
+ ]);
1329
+ }
1330
+ clickCacheKey(parentSig: string, elemId: unknown[]): string {
1331
+ return JSON.stringify([parentSig || "", this.normalizeElemKey(elemId)]);
1332
+ }
1333
+ checkClickCache(parentSig: string, elemId: unknown[]): string | null {
1334
+ return this.clickResultCache.get(this.clickCacheKey(parentSig, elemId)) || null;
1335
+ }
1336
+ recordClickCache(parentSig: string, elemId: unknown[], sig: string): void {
1337
+ this.clickResultCache.set(this.clickCacheKey(parentSig, elemId), sig);
1338
+ }
1339
+ templateRecordKey(parentSig: string, tmpl: TemplateKey): string {
1340
+ return JSON.stringify([parentSig || "", tmpl || ""]);
1341
+ }
1342
+ recordTemplateResult(parentSig: string, tmpl: TemplateKey, sig: string): void {
1343
+ if (!tmpl) return;
1344
+ const key = this.templateRecordKey(parentSig, tmpl);
1345
+ const results = this.templateResults.get(key) || [];
1346
+ results.push(sig); this.templateResults.set(key, results);
1347
+ if (results.length >= COLLAPSE_MIN && new Set(results).size === 1) this.templateCollapsed.add(key);
1348
+ }
1349
+ logDecision(clickPath: Dict[], elemId: unknown[], decision: string): void {
1350
+ try {
1351
+ const pathDesc = clickPath.length ? clickPath.map(s => s["element"] || "?").join(" → ") : "根页面";
1352
+ const elem = String(elemId[1] || elemId[2] || elemId[0] || "unknown");
1353
+ fs.appendFileSync(path.join(this.outputRoot, "crawl_decisions.jsonl"), JSON.stringify({ path: pathDesc, elem, decision }) + "\n", "utf-8");
1354
+ } catch { /* diagnostics only */ }
1355
+ }
1356
+ writeCrawlStats(): void {
1357
+ try {
1358
+ const payload = {
1359
+ package: this.package,
1360
+ max_depth: this.maxDepth,
1361
+ skip_same_activity: this.skipSameActivityClicks,
1362
+ pages_committed: this.pageCounter,
1363
+ queue_remaining_at_end: this.queue.length,
1364
+ terminated_by: this.terminatedBy,
1365
+ stats: this.stats,
1366
+ failed_paths: [...this.failedPaths].sort(),
1367
+ learned_root_paths: this.learnedRootPaths.map(candidate => ({
1368
+ steps: candidate.steps,
1369
+ successes: candidate.successes,
1370
+ failures: candidate.failures,
1371
+ })),
1372
+ timestamp: nowIso(),
1373
+ };
1374
+ fs.writeFileSync(path.join(this.outputRoot, "crawl_stats.json"), JSON.stringify(payload, null, 2), "utf-8");
1375
+ } catch (e) { console.log(` [WARN] 写入 crawl_stats.json 失败: ${e}`); }
1376
+ }
1377
+
1378
+ flushReport(): void {
1379
+ try { fs.writeFileSync(path.join(this.outputRoot, "index.json"), JSON.stringify(this.pagesIndex, null, 2), "utf-8"); fs.writeFileSync(path.join(this.outputRoot, "gaps.json"), JSON.stringify(this.gaps, null, 2), "utf-8"); this.writeCrawlStats(); this.generateHtmlReport(this.pagesIndex); this.saveQueue(this.queue); }
1380
+ catch (e) { console.log(` [WARN] 写入报告失败: ${e}`); }
1381
+ }
1382
+
1383
+ crawl(): void {
1384
+ if (!this.adb.checkDevice()) return;
1385
+ let ai = this.adb.getCurrentActivity();
1386
+ if (!this.isInTargetApp(ai)) {
1387
+ console.log(`当前不在目标 App (${this.package}) 内,停止并启动...`);
1388
+ this.adb.shell("am", "force-stop", this.package); sleepMs(500);
1389
+ if (this.allowPmClear) {
1390
+ console.log(` [INFO] clear app data: ${this.package}`);
1391
+ this.adb.shell("pm", "clear", this.package);
1392
+ sleepMs(1000);
1393
+ }
1394
+ this.adb.shell("monkey", "-p", this.package, "-c", "android.intent.category.LAUNCHER", "1"); this.adb.waitForIdle();
1395
+ ai = this.adb.getCurrentActivity();
1396
+ if (!this.isInTargetApp(ai)) {
1397
+ for (let retry = 0; retry < 3; retry++) {
1398
+ console.log(` [INFO] waiting for app launch (retry ${retry + 1}/3)...`);
1399
+ this.adb.restartAdbServer();
1400
+ sleepMs(2000);
1401
+ this.adb.shell("monkey", "-p", this.package, "-c", "android.intent.category.LAUNCHER", "1");
1402
+ this.adb.waitForIdle();
1403
+ ai = this.adb.getCurrentActivity();
1404
+ if (this.isInTargetApp(ai)) break;
1405
+ }
1406
+ }
1407
+ ai = this.adb.getCurrentActivity();
1408
+ if (!this.isInTargetApp(ai)) { console.log(`[ERR] 启动后仍未进入目标 App (${this.package}),请检查包名是否正确`); return; }
1409
+ }
1410
+ let launchPkg: string | null = null; let launchAct: string | null = null;
1411
+ const focus = (ai["current_focus"] as string) || "";
1412
+ const m = focus.match(/([\w.]+)\/([\w.]+)/);
1413
+ if (m) { launchPkg = m[1]; launchAct = m[2]; console.log(`启动 Activity: ${launchPkg}/${launchAct}`); }
1414
+ else console.log(`[WARN] 无法从 current_focus 提取启动 Activity: ${focus}`);
1415
+ let rootKw: string | null = null; if (launchAct) { rootKw = launchAct.split(".").pop()!; console.log(`根 Activity 关键字: ${rootKw}`); }
1416
+ fs.mkdirSync(this.outputRoot, { recursive: true });
1417
+ this.pagesIndex = []; this.visitedSignatures = new Set(); this.pathSignatures = {}; this.blockedElements = new Set(); this.clickResultCache = new Map(); this.templateResults = new Map(); this.templateCollapsed = new Set(); this.failedPaths = new Set(); this.learnedRootPaths = []; this.gaps = []; this.gapKeys = new Set(); this.rootSignature = null; this.rootStateSignature = null; this.queue = []; this.pageCounter = 0; this.terminatedBy = "normal";
1418
+ this.stats = { skipped_elements: 0, probe_skipped: 0, cache_skipped: 0, same_activity_skipped: 0, merged_variants: 0, nav_replay_failed: 0, prefix_pruned: 0, destructive_skipped: 0, external_blocked: 0, dequeued_total: 0, list_collapsed_skipped: 0 };
1419
+ console.log(`\n📂 输出目录: ${path.resolve(this.outputRoot)}\n${"=".repeat(60)}\n开始遍历(加速版:BFS + 轻量探测)...\n${"=".repeat(60)}`);
1420
+ let rootId: [string, Set<string>] | null = null;
1421
+ const ck = this.tryLoadCheckpoint();
1422
+ if (ck) { this.loadGaps(); this.loadLearnedRootPaths(); }
1423
+ if (ck) {
1424
+ for (const p of ck[0]) {
1425
+ if (!PageCrawler.isRootPageRecord(p)) continue;
1426
+ const rp = path.join(this.outputRoot, p["page_id"] as string, "view.xml");
1427
+ if (fs.existsSync(rp)) {
1428
+ const rootXml = fs.readFileSync(rp, "utf-8");
1429
+ rootId = PageCrawler.rootIdentifiedSet(p["activity_info"] as Dict, rootXml);
1430
+ this.rootSignature = PageCrawler.pageSignature(p["activity_info"] as Dict, rootXml);
1431
+ this.rootStateSignature = PageCrawler.pageStateSignature(p["activity_info"] as Dict, rootXml);
1432
+ }
1433
+ break;
1434
+ }
1435
+ }
1436
+ if (ck) { [this.pagesIndex, this.visitedSignatures, this.pageCounter, this.queue, this.blockedElements] = ck; console.log(`⏩ 断点续跑:从第 ${this.pageCounter + 1} 个页面继续\n`); for (const p of this.pagesIndex) { if (PageCrawler.isRootPageRecord(p)) { const rp = path.join(this.outputRoot, p["page_id"] as string, "view.xml"); if (fs.existsSync(rp)) rootId = PageCrawler.rootIdentifiedSet(p["activity_info"] as Dict, fs.readFileSync(rp, "utf-8")); break; } } }
1437
+ else {
1438
+ try { fs.rmSync(path.join(this.outputRoot, "crawl_decisions.jsonl"), { force: true }); } catch { /* */ }
1439
+ const { record, xmlContent, clickable, scrollBounds } = this.capturePage("初始页面");
1440
+ const pageId = this.commitPage(record); record["click_path"] = [];
1441
+ fs.writeFileSync(path.join(this.outputRoot, pageId, "meta.json"), JSON.stringify(record, null, 2), "utf-8");
1442
+ const sig = PageCrawler.pageSignature(record["activity_info"] as Dict, xmlContent);
1443
+ rootId = PageCrawler.rootIdentifiedSet(record["activity_info"] as Dict, xmlContent);
1444
+ this.rootSignature = sig;
1445
+ this.rootStateSignature = PageCrawler.pageStateSignature(record["activity_info"] as Dict, xmlContent);
1446
+ this.visitedSignatures.add(sig); this.pathSignatures[JSON.stringify([])] = sig; this.pagesIndex.push(record);
1447
+ const initRepeated = PageCrawler.repeatedTemplates(clickable);
1448
+ for (const elem of clickable) {
1449
+ if (this.shouldSkipElement(elem)) { if (PageCrawler.isDestructiveElement(elem)) this.stats.destructive_skipped++; else this.stats.skipped_elements++; continue; }
1450
+ const eid: unknown[] = [(elem["resource-id"] as string) || "", (elem["text"] as string) || "", (elem["content-desc"] as string) || "", (elem["bounds"] as string) || "", (elem["long-clickable"] as boolean) || false];
1451
+ const si = (elem["scroll_index"] as number) || 0; let sInfo: Dict | null = null; if (si > 0 && scrollBounds) sInfo = { scroll_index: si, container_bounds: Array.from(scrollBounds) };
1452
+ const tmpl = initRepeated.has(PageCrawler.templateKey(elem)) ? PageCrawler.templateKey(elem) : null;
1453
+ this.queue.push([[], eid, [], sInfo, tmpl]);
1454
+ }
1455
+ this.flushReport();
1456
+ }
1457
+ const crawlDeadline = Date.now() + CRAWL_DEADLINE_SECONDS * 1000;
1458
+ while (this.queue.length > 0 && this.pageCounter < this.maxPages) {
1459
+ if (Date.now() > crawlDeadline) { this.terminatedBy = "deadline"; break; }
1460
+ const [clickPath, elemId, stepSigs, scrollInfo, tmpl] = this.queue.shift()!;
1461
+ this.stats.dequeued_total++;
1462
+ console.log(`\n📊 BFS 队列剩余: ${this.queue.length} 项, 已采集: ${this.pageCounter} 页`);
1463
+ const eidKey = JSON.stringify(elemId);
1464
+ if (this.blockedElements.has(eidKey)) continue;
1465
+ if (PageCrawler.isDestructiveElement({ "resource-id": String(elemId[0] || ""), "text": String(elemId[1] || ""), "content-desc": String(elemId[2] || ""), "bounds": String(elemId[3] || "") }, true)) {
1466
+ this.recordGap({
1467
+ type: "destructive_action_skipped",
1468
+ page_id: null,
1469
+ label: String(elemId[1] || elemId[2] || elemId[0] || "unknown"),
1470
+ element: { resource_id: elemId[0] || "", text: elemId[1] || "", content_desc: elemId[2] || "", bounds: elemId[3] || "" },
1471
+ click_path: clickPath,
1472
+ reason: "queued control may modify, delete, clear, reset, or remove user data; crawler skipped it before navigation",
1473
+ suggested_resolution: "only enable through an explicit test fixture or manual confirmation",
1474
+ });
1475
+ this.stats.destructive_skipped++;
1476
+ this.logDecision(clickPath, elemId, "destructive_skipped");
1477
+ continue;
1478
+ }
1479
+ if (clickPath.length >= this.maxDepth) continue;
1480
+ if (this.shouldSkipSameActivity(stepSigs, { "resource-id": String(elemId[0] || "") })) { this.stats.same_activity_skipped++; this.logDecision(clickPath, elemId, "same_activity_skipped"); continue; }
1481
+ const pathKey = clickPath.length ? JSON.stringify(clickPath) : "";
1482
+ if (pathKey && [...this.failedPaths].some(fp => pathKey.startsWith(fp) && fp.length > 2)) { this.stats.prefix_pruned++; this.logDecision(clickPath, elemId, "prefix_pruned"); continue; }
1483
+ const parentSig = stepSigs.length ? stepSigs[stepSigs.length - 1] : "";
1484
+ if (tmpl && this.templateCollapsed.has(this.templateRecordKey(parentSig, tmpl))) { this.stats.list_collapsed_skipped++; this.logDecision(clickPath, elemId, "list_collapsed_skipped"); continue; }
1485
+ const useCache = Boolean(parentSig) || clickPath.length === 0;
1486
+ if (useCache) {
1487
+ const cached = this.checkClickCache(parentSig, elemId);
1488
+ if (cached && (cached === "__other_app__" || this.visitedSignatures.has(cached))) { this.stats.cache_skipped++; this.logDecision(clickPath, elemId, "cache_skipped"); continue; }
1489
+ }
1490
+ const pathDesc = clickPath.length ? clickPath.map(s => s["element"] || "?").join(" → ") : "根页面";
1491
+ console.log(`\n🧭 导航到: ${pathDesc}`);
1492
+ if (!launchPkg || !launchAct) { console.log(` [ERR] 无法重启 App,缺少启动信息`); continue; }
1493
+ if (clickPath.length) { if (!this.navigateViaRestart(clickPath, launchPkg, launchAct, rootKw, stepSigs, rootId)) { console.log(` [ERR] 导航失败,跳过`); this.failedPaths.add(pathKey); this.stats.nav_replay_failed++; this.logDecision(clickPath, elemId, "nav_replay_failed"); continue; } }
1494
+ else { if (!this.restartToRootForNavigation(launchPkg, launchAct, rootKw, rootId)) { console.log(` [ERR] 无法回到根页面,跳过`); continue; } }
1495
+ let freshXml = this.adb.dumpXmlQuick();
1496
+ if (scrollInfo && (scrollInfo["scroll_index"] as number) > 0) { console.log(` 📜 滚动 ${scrollInfo["scroll_index"]} 次到达元素位置`); this.adb.scrollToPosition(scrollInfo["container_bounds"] as [number, number, number, number], scrollInfo["scroll_index"] as number); freshXml = this.adb.dumpXmlQuick(); }
1497
+ let foundElem = PageCrawler.findElementOnScreen(freshXml, elemId);
1498
+ if (!foundElem || !foundElem["center"]) {
1499
+ console.log(` [SKIP] 无法找到元素: ${JSON.stringify(elemId.slice(0, 3))}`);
1500
+ this.recordGap({
1501
+ type: "target_not_found_after_replay",
1502
+ page_id: null,
1503
+ label: String(elemId[1] || elemId[2] || elemId[0] || "unknown"),
1504
+ element: { resource_id: elemId[0] || "", text: elemId[1] || "", content_desc: elemId[2] || "", bounds: elemId[3] || "" },
1505
+ click_path: clickPath,
1506
+ reason: "target element was collected earlier but was not present after replaying the navigation path; likely weak locator or UI state drift",
1507
+ suggested_resolution: "prefer stable resource-id/content-desc, or inspect the replay path and scroll state for this page",
1508
+ });
1509
+ this.logDecision(clickPath, elemId, "target_not_found_after_replay");
1510
+ continue;
1511
+ }
1512
+ const expectedBounds = String(elemId[3] || "");
1513
+ if (expectedBounds && PageCrawler.looksClippedAgainstExpected(foundElem, expectedBounds)) {
1514
+ console.log(` [WARN] matched element appears clipped/shifted: expected=${expectedBounds}, actual=${foundElem["bounds"]}; trying to restore scroll`);
1515
+ const expectedCenter = PageCrawler.parseBoundsCenter(expectedBounds);
1516
+ const containers = PageCrawler.findScrollableContainers(freshXml);
1517
+ const restoreContainer = containers.find(c => {
1518
+ const b = c["bounds"] as [number, number, number, number];
1519
+ return expectedCenter ? b[0] <= expectedCenter[0] && expectedCenter[0] <= b[2] : true;
1520
+ }) || containers[0];
1521
+ if (restoreContainer) {
1522
+ const [x1, y1, x2, y2] = restoreContainer["bounds"] as [number, number, number, number];
1523
+ const cx = Math.floor((x1 + x2) / 2);
1524
+ const h = y2 - y1;
1525
+ this.adb.shell("input", "swipe", String(cx), String(y1 + Math.floor(h * 0.30)), String(cx), String(y1 + Math.floor(h * 0.70)), String(this.adb.scrollDurationMs));
1526
+ this.adb.waitForIdle();
1527
+ freshXml = this.adb.dumpXmlQuick();
1528
+ foundElem = PageCrawler.findElementOnScreen(freshXml, elemId);
1529
+ }
1530
+ if (!foundElem || !foundElem["center"] || PageCrawler.looksClippedAgainstExpected(foundElem, expectedBounds)) {
1531
+ console.log(` [SKIP] element still clipped after restore: ${JSON.stringify(elemId.slice(0, 4))}`);
1532
+ this.logDecision(clickPath, elemId, "clipped_target_skipped");
1533
+ continue;
1534
+ }
1535
+ }
1536
+ const originalCenter = foundElem["center"] as [number, number];
1537
+ const center = PageCrawler.chooseTapPoint(freshXml, foundElem) || originalCenter;
1538
+ const labelText = (foundElem["text"] as string) || (foundElem["content-desc"] as string) || (foundElem["resource-id"] as string) || "unknown";
1539
+ if (PageCrawler.isDestructiveElement(foundElem)) {
1540
+ this.recordGap({
1541
+ type: "destructive_action_skipped",
1542
+ page_id: null,
1543
+ label: labelText,
1544
+ element: PageCrawler.elementSummary(foundElem),
1545
+ click_path: clickPath,
1546
+ reason: "control may modify, delete, clear, reset, or remove user data; crawler skipped it before tapping",
1547
+ suggested_resolution: "only enable through an explicit test fixture or manual confirmation",
1548
+ });
1549
+ this.stats.destructive_skipped++;
1550
+ this.logDecision(clickPath, elemId, "destructive_skipped");
1551
+ continue;
1552
+ }
1553
+ if (center[0] !== originalCenter[0] || center[1] !== originalCenter[1]) console.log(` [INFO] 调整点击点以避开遮挡: ${JSON.stringify(originalCenter)} -> ${JSON.stringify(center)}`);
1554
+ console.log(`\n👆 点击: [${labelText}] @ ${JSON.stringify(center)}`);
1555
+ const isLong = (foundElem["long-clickable"] as boolean) || false;
1556
+ const attemptedStep = { from: pathDesc, element: labelText, center: Array.from(center), "resource-id": (foundElem["resource-id"] as string) || "", text: (foundElem["text"] as string) || "", "content-desc": (foundElem["content-desc"] as string) || "", bounds: (foundElem["bounds"] as string) || "", "long-clickable": isLong, scroll_info: scrollInfo };
1557
+ const newCp = [...clickPath, attemptedStep];
1558
+ if (isLong) console.log(` 🔁 使用长按触发`);
1559
+ this.adb.tapOrLongPress(center[0], center[1], isLong);
1560
+ const probeXml = this.adb.dumpXmlQuick(); const probeInfo = this.adb.getCurrentActivity();
1561
+ const newSig = PageCrawler.pageSignature(probeInfo, probeXml);
1562
+ const newStateSig = PageCrawler.pageStateSignature(probeInfo, probeXml);
1563
+ if (useCache) this.recordClickCache(parentSig, elemId, newSig);
1564
+ if (!this.isInTargetApp(probeInfo)) {
1565
+ console.log(` ⚠️ 跳转到其他 App,标记并跳过`);
1566
+ this.recordGap({
1567
+ type: "external_app_blocked",
1568
+ page_id: null,
1569
+ label: labelText,
1570
+ element: PageCrawler.elementSummary(foundElem),
1571
+ click_path: newCp,
1572
+ reason: "click left the target app; crawler blocked further traversal",
1573
+ target_activity: probeInfo,
1574
+ suggested_resolution: "handle manually or add a scoped system/external-app flow if this surface is in scope",
1575
+ });
1576
+ if (useCache) this.recordClickCache(parentSig, elemId, "__other_app__");
1577
+ this.blockedElements.add(eidKey); this.stats.external_blocked++; this.logDecision(clickPath, elemId, "external_blocked"); continue;
1578
+ }
1579
+ if (this.visitedSignatures.has(newSig)) {
1580
+ console.log(` ♻️ 页面已访问过,跳过(省截图)`);
1581
+ const returnedToRoot = this.isKnownRootSignature(newSig) || Boolean(this.rootStateSignature && newStateSig === this.rootStateSignature);
1582
+ if (returnedToRoot && newCp.length) this.recordLearnedRootPath(newCp);
1583
+ this.recordTemplateResult(parentSig, tmpl, newSig); this.stats.probe_skipped++;
1584
+ this.logDecision(clickPath, elemId, returnedToRoot ? "probe_skipped_visited_root" : "probe_skipped_visited");
1585
+ continue;
1586
+ }
1587
+ const { record: newRec, xmlContent: newXml, clickable: newClk, scrollBounds: newSb } = this.capturePage(`点击'${labelText}'后`);
1588
+ const newSig2 = PageCrawler.pageSignature(newRec["activity_info"] as Dict, newXml);
1589
+ newRec["came_from"] = pathDesc; newRec["trigger_element"] = labelText; newRec["click_path"] = newCp;
1590
+ const nearDup = this.findNearDuplicatePage(newRec, newXml);
1591
+ if (nearDup) {
1592
+ const [canonicalPage, mergeStats] = nearDup;
1593
+ this.visitedSignatures.add(newSig2);
1594
+ if (useCache) this.recordClickCache(parentSig, elemId, newSig2);
1595
+ this.mergePageVariant(canonicalPage, newRec, mergeStats);
1596
+ this.recordTemplateResult(parentSig, tmpl, (canonicalPage["page_identity_signature"] as string) || newSig2);
1597
+ this.stats.merged_variants++;
1598
+ this.logDecision(clickPath, elemId, `merged_variant->${canonicalPage["page_id"] || "?"}`);
1599
+ this.flushReport();
1600
+ continue;
1601
+ }
1602
+ this.visitedSignatures.add(newSig2); if (useCache) this.recordClickCache(parentSig, elemId, newSig2); const pageId = this.commitPage(newRec);
1603
+ fs.writeFileSync(path.join(this.outputRoot, pageId, "meta.json"), JSON.stringify(newRec, null, 2), "utf-8");
1604
+ this.pagesIndex.push(newRec); this.recordTemplateResult(parentSig, tmpl, newSig2); this.logDecision(clickPath, elemId, `navigated->${pageId}`); this.flushReport();
1605
+ this.pathSignatures[JSON.stringify(newCp)] = newSig2;
1606
+ const newStepSigs = [...stepSigs, newSig2];
1607
+ const newRepeated = PageCrawler.repeatedTemplates(newClk);
1608
+ for (const ne of newClk) {
1609
+ if (this.shouldSkipElement(ne)) { if (PageCrawler.isDestructiveElement(ne)) this.stats.destructive_skipped++; else this.stats.skipped_elements++; continue; }
1610
+ const neid: unknown[] = [(ne["resource-id"] as string) || "", (ne["text"] as string) || "", (ne["content-desc"] as string) || "", (ne["bounds"] as string) || "", (ne["long-clickable"] as boolean) || false];
1611
+ const nsi = (ne["scroll_index"] as number) || 0; let nsi2: Dict | null = null; if (nsi > 0 && newSb) nsi2 = { scroll_index: nsi, container_bounds: Array.from(newSb) };
1612
+ const neTmpl = newRepeated.has(PageCrawler.templateKey(ne)) ? PageCrawler.templateKey(ne) : null;
1613
+ this.queue.push([newCp, neid, newStepSigs, nsi2, neTmpl]);
1614
+ }
1615
+ }
1616
+ if (this.terminatedBy === "normal" && this.pageCounter >= this.maxPages) this.terminatedBy = "max_pages";
1617
+ this.flushReport();
1618
+ try { fs.rmSync(path.join(this.outputRoot, "queue_checkpoint.json"), { force: true }); } catch { /* */ }
1619
+ console.log(`\n${"=".repeat(60)}\n✅ 遍历完成!共采集 ${this.pagesIndex.length} 个页面\n📂 输出目录: ${path.resolve(this.outputRoot)}\n📋 索引文件: ${path.join(this.outputRoot, "index.json")}\n🌐 HTML报告: ${path.join(this.outputRoot, "report.html")}\n\n📊 加速统计:\n 过滤低价值元素: ${this.stats.skipped_elements} 个\n 轻量探测跳过(省截图): ${this.stats.probe_skipped} 次\n 缓存预过滤跳过: ${this.stats.cache_skipped} 次\n 同 Activity 跳过: ${this.stats.same_activity_skipped} 次\n 列表塌缩跳过: ${this.stats.list_collapsed_skipped} 次\n 近似重复合并: ${this.stats.merged_variants} 次\n 重放失败: ${this.stats.nav_replay_failed} 次\n 前缀剪枝跳过: ${this.stats.prefix_pruned} 次\n 危险元素跳过: ${this.stats.destructive_skipped} 次\n 外部页拦截: ${this.stats.external_blocked} 次\n 出队总数: ${this.stats.dequeued_total} 项\n 收尾原因: ${this.terminatedBy}\n${"=".repeat(60)}`);
1620
+ }
1621
+
1622
+ async manualCrawl(): Promise<void> {
1623
+ if (!this.adb.checkDevice()) return;
1624
+ fs.mkdirSync(this.outputRoot, { recursive: true });
1625
+ this.loadGaps();
1626
+ let pi: Dict[] = [];
1627
+ const idx = path.join(this.outputRoot, "index.json");
1628
+ if (fs.existsSync(idx)) { try { pi = JSON.parse(fs.readFileSync(idx, "utf-8")) as Dict[]; console.log(`📂 已加载 ${pi.length} 个已有页面`); } catch (e) { console.log(`[WARN] 读取 index.json 失败: ${e},将创建新索引`); } }
1629
+ let mc = 0; for (const p of pi) { const m = ((p["page_id"] as string) || "").match(/manual_(\d+)/); if (m) mc = Math.max(mc, parseInt(m[1], 10)); }
1630
+ console.log(`\n📂 输出目录: ${path.resolve(this.outputRoot)}\n📝 手动采集模式已启动(manual 编号从 ${mc + 1} 开始)\n${"=".repeat(60)}\n操作说明:\n 1. 在设备上手动导航到目标页面\n 2. 输入页面描述(如"设置页 > 关于"),然后按回车开始采集\n 3. 输入 q 退出\n${"=".repeat(60)}`);
1631
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1632
+ const ask = (q: string) => new Promise<string>(r => rl.question(q, r));
1633
+ while (true) {
1634
+ const desc = ((await ask("\n📝 输入页面描述(q 退出): ")).trim());
1635
+ if (desc.toLowerCase() === "q") { console.log("👋 退出手动采集模式"); break; }
1636
+ const d = desc || "手动采集"; mc++;
1637
+ const { record } = this.capturePage(d);
1638
+ record["click_path"] = "manual"; record["description"] = d;
1639
+ this.commitManualPage(record, mc); pi.push(record);
1640
+ fs.writeFileSync(idx, JSON.stringify(pi, null, 2), "utf-8"); fs.writeFileSync(path.join(this.outputRoot, "gaps.json"), JSON.stringify(this.gaps, null, 2), "utf-8"); this.generateHtmlReport(pi);
1641
+ console.log(` 📋 index.json 和 report.html 已更新(共 ${pi.length} 个页面)`);
1642
+ }
1643
+ rl.close();
1644
+ console.log(`\n✅ 手动采集完成!共 ${pi.length} 个页面(含自动遍历)\n📂 输出目录: ${path.resolve(this.outputRoot)}`);
1645
+ }
1646
+ }
1647
+
1648
+ function parseArgs(argv: string[]): { package: string; output: string; manual: boolean; device: string; adbPath: string; maxPages: number; maxScrolls: number; maxDepth: number; skipSameActivity: boolean; allowPmClear: boolean; } {
1649
+ const o = { package: "", output: "", manual: false, device: DEVICE_SERIAL_DEFAULT, adbPath: ADB_PATH_DEFAULT, maxPages: MAX_PAGES_DEFAULT, maxScrolls: MAX_SCROLLS_DEFAULT, maxDepth: MAX_DEPTH_DEFAULT, skipSameActivity: false, allowPmClear: false };
1650
+ for (let i = 0; i < argv.length; i++) { switch (argv[i]) { case "--package": case "-p": o.package = argv[++i]; break; case "--output": case "-o": o.output = argv[++i]; break; case "--manual": o.manual = true; break; case "--device": o.device = argv[++i]; break; case "--adb-path": o.adbPath = argv[++i]; break; case "--max-pages": o.maxPages = parseInt(argv[++i], 10); break; case "--max-scrolls": o.maxScrolls = parseInt(argv[++i], 10); break; case "--max-depth": o.maxDepth = parseInt(argv[++i], 10); break; case "--skip-same-activity": o.skipSameActivity = true; break; case "--allow-pm-clear": o.allowPmClear = true; break; } }
1651
+ if (!o.package || !o.output) { console.error("android_viewtree_bfs_crawler.ts: error: --package and --output are required"); process.exit(2); }
1652
+ return o;
1653
+ }
1654
+
1655
+ async function main(): Promise<void> {
1656
+ const args = parseArgs(process.argv.slice(2));
1657
+ const adb = new ADBHelper({ adbPath: args.adbPath, deviceSerial: args.device });
1658
+ const crawler = new PageCrawler({ adb, package: args.package, outputDir: args.output, maxPages: args.maxPages, maxScrolls: args.maxScrolls, maxDepth: args.maxDepth, skipSameActivityClicks: args.skipSameActivity, allowPmClear: args.allowPmClear });
1659
+ if (args.manual) await crawler.manualCrawl(); else crawler.crawl();
1660
+ }
1661
+
1662
+ main();