@buaa_smat/hometrans 26.0.7 → 26.0.8-devecocli.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/agents/a2h-executor.md +37 -0
  2. package/devecocli-plugin/common.ts +2370 -0
  3. package/devecocli-plugin/content-resolver.ts +363 -0
  4. package/devecocli-plugin/install.ts +72 -0
  5. package/devecocli-plugin/uninstall.ts +26 -0
  6. package/devecocli-plugin/update.ts +77 -0
  7. package/i18n/platforms/codebuddy/skills/a2h-app-migrate/SKILL.unique.md +2 -2
  8. package/i18n/platforms/deveco/skills/a2h-app-migrate/SKILL.unique.md +1 -1
  9. package/i18n/platforms/opencode/skills/a2h-app-migrate/SKILL.unique.md +13 -6
  10. package/i18n/skills/a2h-app-migrate/SKILL.md +2 -2
  11. package/i18n/skills/a2h-app-migrate/references/workflow.yaml +27 -4
  12. package/i18n/skills/a2h-app-migrate/scripts/opencode_depth.mjs +418 -0
  13. package/i18n/skills/a2h-arkts-logic-coder/references/ISSUES.md +2 -0
  14. package/i18n/skills/a2h-batch-ui-align/SKILL.md +7 -7
  15. package/i18n/skills/a2h-batch-ui-align/references/cards/alignment.md +1 -1
  16. package/i18n/skills/a2h-batch-ui-align/references/cards/state.md +20 -2
  17. package/i18n/skills/a2h-batch-ui-align/references/cards/widgets.md +2 -2
  18. package/i18n/skills/a2h-batch-ui-align/references/checker-rules.md +3 -3
  19. package/i18n/skills/a2h-batch-ui-align/references/conversion-procedure.md +3 -1
  20. package/i18n/skills/a2h-batch-ui-align/references/incremental-scope.md +2 -2
  21. package/i18n/skills/a2h-batch-ui-align/references/step3-capture.md +10 -6
  22. package/i18n/skills/a2h-batch-ui-align/references/step5-convert.md +13 -9
  23. package/i18n/skills/a2h-batch-ui-align/scripts/build_conversion_set.mjs +59 -7
  24. package/i18n/skills/a2h-batch-ui-align/scripts/group_pack.mjs +3 -0
  25. package/i18n/skills/a2h-batch-ui-align/scripts/interactions.mjs +186 -0
  26. package/i18n/skills/a2h-batch-ui-align/scripts/phase5_check.mjs +33 -7
  27. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/hit_test.ts +83 -22
  28. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/media_tint.ts +39 -5
  29. package/i18n/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_scroll_padding_raster.test.mjs +25 -1
  30. package/i18n/skills/a2h-page-specgen/SKILL.md +1 -1
  31. package/i18n/skills/a2h-page-specgen/references/gates.md +3 -1
  32. package/i18n/skills/a2h-page-specgen/references/scenario-authoring.md +11 -11
  33. package/i18n/skills/a2h-page-specgen/references/spec-template.md +3 -3
  34. package/i18n/skills/a2h-page-specgen/scripts/contract-calls.mjs +40 -3
  35. package/i18n/skills/a2h-page-specgen/scripts/entry-evidence.mjs +73 -5
  36. package/i18n/skills/a2h-page-specgen/scripts/gate.mjs +144 -0
  37. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.prompt.md +11 -11
  38. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.worker.md +11 -11
  39. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.prompt.md +11 -11
  40. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.worker.md +11 -11
  41. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.json +10 -10
  42. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.post-review.json +1 -1
  43. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.prompt.md +11 -11
  44. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.worker.md +11 -11
  45. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.prompt.md +11 -11
  46. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.worker.md +11 -11
  47. package/i18n/skills/a2h-page-specgen/scripts/test/contract-calls.test.mjs +45 -1
  48. package/i18n/skills/a2h-page-specgen/scripts/test/entry-evidence.test.mjs +100 -0
  49. package/i18n/skills/a2h-page-specgen/scripts/test/gate.test.mjs +132 -3
  50. package/i18n/skills/a2h-resource-convert/scripts/a2h_resource_convert.ts +36 -1
  51. package/i18n/skills/a2h-spec-design-pipeline/SKILL.md +1 -1
  52. package/i18n/skills/a2h-spec-design-pipeline/references/coding-loop.md +16 -0
  53. package/i18n/skills/a2h-utg-static/SKILL.md +2 -0
  54. package/index.js +1741 -0
  55. package/package.json +8 -8
  56. package/platforms/atomcode/agents/a2h-executor.frontmatter.md +6 -0
  57. package/platforms/codebuddy/agents/a2h-executor.frontmatter.md +5 -0
  58. package/platforms/codebuddy/skills/a2h-app-migrate/SKILL.unique.md +2 -2
  59. package/platforms/deveco/agents/a2h-executor.frontmatter.md +7 -0
  60. package/platforms/deveco/agents/build-fixer.frontmatter.md +0 -2
  61. package/platforms/deveco/agents/code-reviewer.frontmatter.md +0 -2
  62. package/platforms/deveco/agents/model-render-worker.frontmatter.md +0 -2
  63. package/platforms/deveco/agents/model-worker.frontmatter.md +0 -2
  64. package/platforms/deveco/agents/specgen-worker.frontmatter.md +0 -2
  65. package/platforms/deveco/skills/a2h-app-migrate/SKILL.unique.md +1 -1
  66. package/platforms/opencode/agents/a2h-executor.frontmatter.md +7 -0
  67. package/platforms/opencode/agents/build-fixer.frontmatter.md +0 -2
  68. package/platforms/opencode/agents/code-reviewer.frontmatter.md +0 -2
  69. package/platforms/opencode/agents/model-render-worker.frontmatter.md +0 -2
  70. package/platforms/opencode/agents/model-worker.frontmatter.md +0 -2
  71. package/platforms/opencode/agents/specgen-worker.frontmatter.md +0 -2
  72. package/platforms/opencode/skills/a2h-app-migrate/SKILL.unique.md +13 -6
  73. package/plugin.jsonc +12 -0
  74. package/skills/a2h-app-migrate/SKILL.md +29 -3
  75. package/skills/a2h-app-migrate/references/host-rules.md +33 -0
  76. package/skills/a2h-app-migrate/references/workflow.yaml +24 -4
  77. package/skills/a2h-app-migrate/scripts/opencode_depth.mjs +418 -0
  78. package/skills/a2h-app-migrate/test/test_executor_header_sync.mjs +78 -0
  79. package/skills/a2h-app-migrate/test/test_opencode_depth.mjs +312 -0
  80. package/skills/a2h-app-migrate/tools/dag.mjs +267 -0
  81. package/skills/a2h-arkts-logic-coder/references/ISSUES.md +2 -0
  82. package/skills/a2h-batch-ui-align/SKILL.md +7 -7
  83. package/skills/a2h-batch-ui-align/references/cards/alignment.md +1 -1
  84. package/skills/a2h-batch-ui-align/references/cards/state.md +20 -2
  85. package/skills/a2h-batch-ui-align/references/cards/widgets.md +2 -2
  86. package/skills/a2h-batch-ui-align/references/checker-rules.md +3 -3
  87. package/skills/a2h-batch-ui-align/references/conversion-procedure.md +3 -1
  88. package/skills/a2h-batch-ui-align/references/host-dispatch.md +5 -5
  89. package/skills/a2h-batch-ui-align/references/incremental-scope.md +2 -2
  90. package/skills/a2h-batch-ui-align/references/step3-capture.md +10 -6
  91. package/skills/a2h-batch-ui-align/references/step5-convert.md +13 -9
  92. package/skills/a2h-batch-ui-align/scripts/build_conversion_set.mjs +59 -7
  93. package/skills/a2h-batch-ui-align/scripts/group_pack.mjs +3 -0
  94. package/skills/a2h-batch-ui-align/scripts/group_pass.mjs +3 -2
  95. package/skills/a2h-batch-ui-align/scripts/group_queue.mjs +139 -23
  96. package/skills/a2h-batch-ui-align/scripts/host_env.mjs +32 -8
  97. package/skills/a2h-batch-ui-align/scripts/interactions.mjs +186 -0
  98. package/skills/a2h-batch-ui-align/scripts/phase5_check.mjs +33 -7
  99. package/skills/a2h-batch-ui-align/scripts/static_check/rules/hit_test.ts +83 -22
  100. package/skills/a2h-batch-ui-align/scripts/static_check/rules/media_tint.ts +39 -5
  101. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_hit_test.test.mjs +82 -0
  102. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_scroll_padding_raster.test.mjs +25 -1
  103. package/skills/a2h-batch-ui-align/scripts/tests/group_queue.test.mjs +184 -2
  104. package/skills/a2h-batch-ui-align/scripts/tests/host_env.test.mjs +33 -0
  105. package/skills/a2h-batch-ui-align/scripts/tests/interactions.test.mjs +258 -0
  106. package/skills/a2h-page-specgen/SKILL.md +1 -1
  107. package/skills/a2h-page-specgen/references/evidence.md +15 -0
  108. package/skills/a2h-page-specgen/references/gates.md +3 -1
  109. package/skills/a2h-page-specgen/references/scenario-authoring.md +10 -10
  110. package/skills/a2h-page-specgen/references/spec-template.md +2 -2
  111. package/skills/a2h-page-specgen/scripts/contract-calls.mjs +40 -3
  112. package/skills/a2h-page-specgen/scripts/entry-evidence.mjs +73 -5
  113. package/skills/a2h-page-specgen/scripts/gate.mjs +141 -0
  114. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.prompt.md +10 -10
  115. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.worker.md +10 -10
  116. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.prompt.md +10 -10
  117. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.worker.md +10 -10
  118. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.json +10 -10
  119. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.post-review.json +1 -1
  120. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.prompt.md +10 -10
  121. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.worker.md +10 -10
  122. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.prompt.md +10 -10
  123. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.worker.md +10 -10
  124. package/skills/a2h-page-specgen/scripts/test/contract-calls.test.mjs +45 -1
  125. package/skills/a2h-page-specgen/scripts/test/entry-evidence.test.mjs +100 -0
  126. package/skills/a2h-page-specgen/scripts/test/gate.test.mjs +104 -3
  127. package/skills/a2h-resource-convert/references/conversion-rules.md +2 -0
  128. package/skills/a2h-resource-convert/scripts/a2h_resource_convert.ts +36 -1
  129. package/skills/a2h-resource-convert/scripts/tests/adaptive_icon.test.mjs +42 -0
  130. package/skills/a2h-spec-design-pipeline/SKILL.md +1 -1
  131. package/skills/a2h-spec-design-pipeline/references/coding-loop.md +16 -0
  132. package/skills/a2h-spec-design-pipeline/references/execution-model.md +2 -2
  133. package/skills/a2h-spec-design-pipeline/references/static-defect-gate.md +5 -1
  134. package/skills/a2h-spec-design-pipeline/rules/migration-rules/config/ruleMeta.json +5 -0
  135. package/skills/a2h-spec-design-pipeline/rules/migration-rules/config/ruleSet.json +4 -0
  136. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-runtime-pitfall-cn.md +2 -1
  137. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-runtime-pitfall-en.md +3 -1
  138. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-v2-observation-cn.md +105 -0
  139. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-v2-observation-en.md +122 -0
  140. package/skills/a2h-spec-design-pipeline/rules/migration-rules/lib/checker/ArkUIRuntimePitfallCheck.js +4 -4
  141. package/skills/a2h-spec-design-pipeline/rules/migration-rules/lib/checker/ArkUIV2ObservationCheck.js +1862 -0
  142. package/skills/a2h-spec-design-pipeline/rules/migration-rules/lib/index.js +2 -0
  143. package/skills/a2h-spec-design-pipeline/rules/migration-rules/package.json +1 -1
  144. package/skills/a2h-spec-design-pipeline/scripts/dispatch/wait.mjs +15 -2
  145. package/skills/a2h-spec-design-pipeline/scripts/dispatch.mjs +20 -4
  146. package/skills/a2h-spec-design-pipeline/scripts/test_arkui_v2_observation.ts +284 -0
  147. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_commands.mjs +32 -0
  148. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_wait.mjs +22 -1
  149. package/skills/a2h-utg-static/SKILL.md +2 -0
  150. package/skills/a2h-utg-static/references/extractors.md +16 -0
  151. package/skills/a2h-utg-static/scripts/run_pipeline.mjs +22 -1
  152. package/skills/a2h-utg-static/scripts/tests/regression_matrix.mjs +4 -0
  153. package/skills/a2h-utg-static/scripts/tests/test_pr169_review_fixes.mjs +15 -0
  154. package/skills/a2h-utg-static/scripts/tests/test_view_attachments.mjs +330 -0
  155. package/skills/a2h-utg-static/scripts/view_attachments.mjs +465 -0
  156. package/README.md +0 -413
  157. package/dist/cli/config-store.js +0 -128
  158. package/dist/cli/config.js +0 -48
  159. package/dist/cli/editors.json +0 -147
  160. package/dist/cli/env-vars.js +0 -127
  161. package/dist/cli/index.js +0 -76
  162. package/dist/cli/init.js +0 -2618
  163. package/dist/cli/uninstall.js +0 -406
  164. package/dist/platform/compose.js +0 -232
  165. package/dist/platform/frontmatter.js +0 -151
  166. package/dist/platform/installer.js +0 -417
  167. package/dist/platform/language.js +0 -77
  168. package/dist/platform/registry.js +0 -340
  169. package/dist/platform/transform.js +0 -397
  170. package/dist/platform/types.js +0 -9
  171. package/dist/platform/validate.js +0 -153
  172. package/dist/utils/regex.js +0 -7
  173. package/env-requirements.json +0 -536
  174. package/platforms/codebuddy/agents/build-fixer.frontmatter.md +0 -5
  175. package/platforms/codebuddy/agents/code-reviewer.frontmatter.md +0 -5
  176. package/platforms/codebuddy/agents/model-render-worker.frontmatter.md +0 -5
  177. package/platforms/codebuddy/agents/model-worker.frontmatter.md +0 -5
  178. package/platforms/codebuddy/agents/specgen-worker.frontmatter.md +0 -5
  179. package/resource/choose_editor.png +0 -0
  180. package/resource/set_sdk.png +0 -0
  181. package/resource/title_dark.png +0 -0
@@ -37,7 +37,8 @@ policy:
37
37
  # SPEC_CONCURRENCY is passed to a2h-spec-generate as concurrency= (the number of concurrent fused per-Area workers),
38
38
  # and **must be clamped to this cap**: values above 8 become 8, non-positive integers become the default 8.
39
39
  max_spec_generate_concurrency: 8
40
- default_task_type: generalPurpose
40
+ # The node sub-agent type; when the host has none, fall back to its built-in general sub-agent (see policy.dispatch).
41
+ default_task_type: a2h-executor
41
42
  # Context length is compacted by the host. The model must not treat it as a stop condition.
42
43
  context_budget: |
43
44
  The model must not end the run on its own because of the context budget.
@@ -181,22 +182,31 @@ policy:
181
182
  calling results back, the progress checklist and talking to the user; before_run / after_run, success checks and the ledger belong to the Runner / production executor. It **loads no** leaf skill, does not read a leaf SKILL.md, and does not expand a leaf's internal Stages / waves.
182
183
  · Every type: skill node uses dispatch: task_subagent: one dispatched sub-agent runs the whole node:
183
184
  discover.arch, discover.utg_static, ui.batch, enrich.spec_gen, enrich.module_docs, logic.spec_pipeline.
185
+ The agent type is always this plugin's a2h-executor (agents/a2h-executor.md: loads the leaf skill, runs to the node's terminal state,
186
+ waits in the foreground, replies only with JSON), never the host's built-in general agent, so the node level can be configured on its own
187
+ and the host's own agents stay untouched.
188
+ How to tell: dispatch a2h-executor directly (if the host prefixes plugin agents with a namespace, use the full name it lists, e.g.
189
+ <plugin>:a2h-executor). A dispatch error saying the agent type is unknown / does not exist is not a node failure: immediately redispatch
190
+ once to the host's built-in general sub-agent with the same task prompt; the Runner callback's note is "fallback: general agent; <original note>".
191
+ A host that silently swaps an unknown agent type for its default agent cannot be detected here and records no fallback.
192
+ The note is stored with the outcome in <DAG_RUN_DIR>/attempts/<file_id>.result.json (the Runner does not write it to the ledger);
193
+ logic.finalize collects it from there, so the final report does not rely on the primary's memory.
184
194
  The only exception: enrich.spec_gen with SPEC_ENGINE=spec-generate is primary_skill_inline (a2h-spec-generate marks a worker done when its
185
195
  completion notification arrives and has no foreground wait mode; inside a sub-agent it would return as soon as it ends the round).
186
196
  · Scheduling stays serial; only one node sub-agent runs at a time:
187
197
  discover.arch -> discover.utg_static (discover legs 1 and 2);
188
198
  ui.batch -> review.ui_batch -> enrich.spec_gen -> enrich.module_docs; logic.spec_pipeline after adopt.
189
199
  · Depth: node sub-agents are at depth 1; the leaves' internal workers (arch module evidence, utg_static reviewers, ui.batch conversion,
190
- page-specgen group workers, spec_pipeline chunk / resolver / review) are at depth 2. The host must allow depth ≥ 2 (configuring it is not this skill's job).
200
+ page-specgen group workers, spec_pipeline chunk / resolver / review) are at depth 2. The host must allow depth ≥ 2 (hosts that need configuring are handled by the platform adaptation layer's Before Step, e.g. opencode writes a project-level config).
191
201
  If the primary cannot dispatch sub-agents -> that node falls back to primary_skill_inline and runs inline as before; the final report says so.
192
- · Host nesting depth 1 (e.g. atomcode / trae, CodeBuddy IDE, Qoder CLI): every type: skill node runs
202
+ · Host nesting depth 1 (e.g. atomcode / trae / trae-cn, CodeBuddy IDE, Qoder CN CLI, Qoder international): every type: skill node runs
193
203
  primary_skill_inline; never dispatch a node sub-agent — a node sub-agent cannot dispatch further sub-agents, so the leaf's internal workers cannot be dispatched.
194
204
  · A sub-agent must not end its round to wait for background notifications (ending it returns to the primary with the work unfinished):
195
205
  a2h-page-specgen gets wait_mode=foreground and a2h-spec-design-pipeline gets WAIT_MODE=foreground (block in the foreground on the waker / wait);
196
206
  a2h-batch-ui-align (group_queue.mjs wait), a2h-utg-static (reviewers waited on in the foreground by the same protocol), arch and module_docs already wait in the foreground.
197
207
  task prompt = the common header below + the node's whole invoke. Substitute the variables with real values in the primary first, evaluate
198
208
  [... only when ...] and drop entries that do not apply; never hand ${...} to the sub-agent verbatim. Common header:
199
- You are a node executor dispatched by a2h-app-migrate, node <id>. First load <leaf skill> with the skill tool (read its SKILL.md in full),
209
+ You are a node executor (a2h-executor) dispatched by a2h-app-migrate, node <id>. First load <leaf skill> with the skill tool (read its SKILL.md in full),
200
210
  then follow the invoke below until the node reaches a terminal state.
201
211
  · Context budget, context window, remaining tokens, a growing session or imminent compaction are not reasons to finish.
202
212
  · Never ask the user directly. For questions the invoke marks "interactive -> needs_input", this run's INTERACTION_MODE=<value>:
@@ -213,6 +223,7 @@ policy:
213
223
  a background notification is not an answer); once answered, redispatch the same node with "The user's answer to "<question>": <verbatim>" appended to the task prompt.
214
224
  At most 3 round trips per node; after that continue on the auto default branch.
215
225
  3) Calls back to the Runner — **never trust the return value**: the outcome is always ok:true, with the sub-agent's own ok / reason copied verbatim into note
226
+ (after a fallback to the general sub-agent, the note is "fallback: general agent; <original note>")
216
227
  (executor complete -> Runner complete, see SKILL.md "Host handling of waits and callbacks"). The executor runs after_run and the Runner judges
217
228
  completion by the node's success: success fails -> failed; the sub-agent reported ok:false but success passes -> success wins.
218
229
  The sub-agent itself never calls the executor / Runner.
@@ -2010,6 +2021,12 @@ nodes:
2010
2021
  Depth: the pipeline itself is at depth 1 (a sub-agent dispatched by migrate); the design / coding / review / conflict-resolution sub-agents it dispatches are at depth 2.
2011
2022
  Event loop (WAIT_MODE=foreground, references/coding-loop.md "Foreground wait mode"): after B1/B2 dispatch background chunks it
2012
2023
  does **not** end the round; it blocks in the foreground on dispatch.mjs wait and returns to step 1 of the event loop afterwards; no waker sub-agent is dispatched.
2024
+ Copy the wait command verbatim, one call at a time (shell timeout 600000 ms):
2025
+ node ${SKILLS_ROOT}/a2h-spec-design-pipeline/scripts/dispatch.mjs ${HMOS} wait --max-wait 300 --poll 5 --baseline ${HMOS}/.hometrans/dispatch/snapshots/orch.snapshot.json --event-file ${HMOS}/.hometrans/dispatch/orch.event.json
2026
+ It returns at the first new evidence, otherwise after about 300 s (--max-wait above 300 is clamped to 300, --poll above 30 to 30): while it runs the host cannot
2027
+ deliver sub-agent completion notifications, so every call must be short. Never write your own wait / poll / sleep script, never loop inside one shell call;
2028
+ every chunk / resolver goes through the ledger (claim → intent → confirm), and spec_pipeline_state.json is never hand-edited ahead of the ledger:
2029
+ wait only sees ledger units.
2013
2030
  It returns only after the pipeline has completed all waves + the smoke gate + Finalization (outputting the final report), or at a hard stop it names.
2014
2031
  Interaction (subject to ${INTERACTION_MODE}):
2015
2032
  · I4 announcement: announce only, never wait (both modes; I4 is an announcement with nothing for the user to decide). Put the announcement text into
@@ -2121,6 +2138,12 @@ nodes:
2121
2138
  node ${SKILLS_ROOT}/a2h-app-migrate/scripts/scope_report.mjs --hmos ${HMOS} --scope-json ${SCOPE_JSON}
2122
2139
  --specs-json ${SPECS_JSON} --android ${ANDROID} --utg <the same page graph> --work ${WORK} --lang en
2123
2140
  It never fails this node; a missing input only drops its part.
2141
+ Node dispatch (write it after everything else in step 4 — the ledger line and the "Incremental scope" section — as the
2142
+ report's last line; never inside the scope_report output): look only at this control directory <DAG_RUN_DIR> (after a resume that switched control directories, the old
2143
+ directory's records do not count). For each skill node take the attempt in attempts/*.attempt.json with the highest index whose
2144
+ status is done or failed, and read its result.json: if evidence.host.note (details.note when ok:false) starts with
2145
+ "fallback: general agent", that node fell back. When any node fell back, end the report with one line "These stages did not use a2h-executor and fell back to the host's built-in general sub-agent:
2146
+ <each stage's user_facing.name>"; write nothing when there are none.
2124
2147
  5. After writing the report, return only ok|fail and the report path; do not append your own logic.finalize terminal record or run_end.
2125
2148
  The Runner verifies the report and commits the only logic.finalize done, then enforces full-DAG completion and writes the single run_end.
2126
2149
  If an assertion exits non-zero or evidence is incomplete, the Runner blocks certification; the host must not present the stage report as a completion certificate.
@@ -0,0 +1,418 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * opencode_depth.mjs —— opencode platform Before Step: make sure the sub-agent nesting depth is >= 2.
4
+ *
5
+ * migrate needs two nesting levels (node sub-agents at depth 1, the leaves' internal workers at depth 2). opencode defaults to 1 level,
6
+ * controlled by `subagent_depth` (verified):
7
+ * - v1 (v1.19.6): accepts both forms — top-level `"subagent_depth": 2` or `"experimental": { "subagent_depth": 2 }`;
8
+ * not hot-reloaded, the session must be restarted after a change.
9
+ * - v2 (v2.4.2): accepts only `"experimental": { "subagent_depth": 2 }`; hot-reloaded, effective immediately.
10
+ *
11
+ * Logic:
12
+ * 1. Version: --version first, otherwise `opencode --version`; undetectable → treated as v1 (conservative: restart).
13
+ * 2. The effective depth follows opencode's load order (see configLayers: global, OPENCODE_CONFIG, project files from the
14
+ * git root down to cwd, .opencode directories, the system-managed directory, OPENCODE_CONFIG_CONTENT; later ones override earlier ones); none declares it → 1.
15
+ * 3. Effective depth >= 2 → touch no file, continue.
16
+ * 4. Otherwise declare only `experimental.subagent_depth = 2` in the project-level config of cwd (the v2 form, which v1 also
17
+ * accepts; an existing file gets only this entry changed, other keys are kept). v1 → next=restart (ask the user to restart); v2 → next=continue (hot reload).
18
+ * next=manual (nothing written, the user edits it): a source loaded after the project files pins the depth below 2; the project
19
+ * file has comments or its root is not an object; OPENCODE_DISABLE_PROJECT_CONFIG is set.
20
+ * When a file was written report=true: the primary session must state it in the final report. Only a file this script created,
21
+ * inside a git worktree and untracked, is added to .git/info/exclude (with a marker line); the user's own files are left alone. A v1 rerun after the restart whose effective value comes from the file this script wrote also carries report.
22
+ *
23
+ * node opencode_depth.mjs [--dir <project dir, default cwd>] [--version <opencode version>]
24
+ *
25
+ * Prints one JSON line; exit code 0 = may continue, 2 = must stop (restart / manual).
26
+ */
27
+ import cp from "node:child_process";
28
+ import fs from "node:fs";
29
+ import os from "node:os";
30
+ import path from "node:path";
31
+ import { pathToFileURL } from "node:url";
32
+
33
+ import { stripBom, writeJsonAtomic } from "./json_io.mjs";
34
+
35
+ export const REQUIRED_DEPTH = 2;
36
+ const CONFIG_NAMES = ["opencode.json", "opencode.jsonc"];
37
+
38
+ /** 'opencode v2.4.2' / '2.4.2' → 2; undetectable → null. */
39
+ export function majorOf(raw) {
40
+ const m = String(raw ?? "").match(/(\d+)\.\d+/) ?? String(raw ?? "").match(/\b(\d+)\b/);
41
+ return m ? Number.parseInt(m[1], 10) : null;
42
+ }
43
+
44
+ /** Index of a string literal's closing quote; i points at the opening quote. */
45
+ function stringEnd(s, i) {
46
+ let j = i + 1;
47
+ while (j < s.length && s[j] !== '"') j += s[j] === "\\" ? 2 : 1;
48
+ return j;
49
+ }
50
+
51
+ /** Strip // and /* *\/ comments and trailing commas (both passes skip string contents); read-only — writes only target strict JSON. */
52
+ export function parseJsonc(text) {
53
+ const s = stripBom(text);
54
+ let noComments = "";
55
+ for (let i = 0; i < s.length; i++) {
56
+ const c = s[i];
57
+ if (c === '"') {
58
+ const j = stringEnd(s, i);
59
+ noComments += s.slice(i, j + 1);
60
+ i = j;
61
+ } else if (c === "/" && s[i + 1] === "/") {
62
+ while (i < s.length && s[i] !== "\n") i++;
63
+ noComments += "\n";
64
+ } else if (c === "/" && s[i + 1] === "*") {
65
+ i = s.indexOf("*/", i + 2);
66
+ if (i < 0) break;
67
+ i++;
68
+ } else noComments += c;
69
+ }
70
+ let out = "";
71
+ for (let i = 0; i < noComments.length; i++) {
72
+ const c = noComments[i];
73
+ if (c === '"') {
74
+ const j = stringEnd(noComments, i);
75
+ out += noComments.slice(i, j + 1);
76
+ i = j;
77
+ } else if (c === "," && /^\s*[}\]]/.test(noComments.slice(i + 1))) {
78
+ continue; // trailing comma
79
+ } else out += c;
80
+ }
81
+ return JSON.parse(out);
82
+ }
83
+
84
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
85
+
86
+ /** Depth a config object declares; v1 accepts both forms, v2 only experimental. Undeclared → null. */
87
+ export function depthOf(config, major) {
88
+ if (!config || typeof config !== "object") return null;
89
+ const values = [num(config.experimental?.subagent_depth)];
90
+ if (!(major >= 2)) values.push(num(config.subagent_depth)); // v1 or unknown version: the top-level form counts too
91
+ const found = values.filter((v) => v !== null);
92
+ return found.length ? Math.max(...found) : null;
93
+ }
94
+
95
+ /** Read one config file; missing → null. object=false means the root is not an object (e.g. `[]`) and cannot be written. */
96
+ export function readConfigFile(file, major) {
97
+ if (!file || !fs.existsSync(file)) return null;
98
+ const text = fs.readFileSync(file, "utf8");
99
+ let config = null;
100
+ let strict = true;
101
+ try {
102
+ config = JSON.parse(stripBom(text));
103
+ } catch {
104
+ strict = false;
105
+ try {
106
+ config = parseJsonc(text);
107
+ } catch {
108
+ config = null;
109
+ }
110
+ }
111
+ const object = !!config && typeof config === "object" && !Array.isArray(config);
112
+ return { file, depth: object ? depthOf(config, major) : null, parsed: config !== null, object, strict, config };
113
+ }
114
+
115
+ export function globalConfigDir(env = process.env, home = os.homedir()) {
116
+ return path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "opencode");
117
+ }
118
+
119
+ /** opencode's system-managed config directory (as in the opencode source). */
120
+ export function managedConfigDir(env = process.env, platform = process.platform) {
121
+ if (platform === "darwin") return "/Library/Application Support/opencode";
122
+ if (platform === "win32") return path.join(env.ProgramData || "C:\\ProgramData", "opencode");
123
+ return "/etc/opencode";
124
+ }
125
+
126
+ function probeVersion() {
127
+ try {
128
+ const r = cp.spawnSync("opencode", ["--version"], {
129
+ encoding: "utf8",
130
+ windowsHide: true,
131
+ timeout: 8000,
132
+ shell: process.platform === "win32", // on Windows opencode is a .cmd shim
133
+ });
134
+ return r.status === 0 ? String(r.stdout).trim() : null;
135
+ } catch {
136
+ return null;
137
+ }
138
+ }
139
+
140
+ function git(dir, args) {
141
+ try {
142
+ const r = cp.spawnSync("git", ["-C", dir, ...args], { encoding: "utf8", windowsHide: true, timeout: 8000 });
143
+ return r.status === 0 ? String(r.stdout).trim() : null;
144
+ } catch {
145
+ return null;
146
+ }
147
+ }
148
+
149
+ /** Real path (resolves symlinks and Windows 8.3 short names); falls back to resolve. */
150
+ function realDir(d) {
151
+ try {
152
+ return fs.realpathSync.native(d);
153
+ } catch {
154
+ return path.resolve(d);
155
+ }
156
+ }
157
+
158
+ const samePath = (a, b) => (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
159
+ const truthy = (v) => /^(true|1)$/i.test(String(v ?? "").trim());
160
+
161
+ /** Directories from start up to stop (inclusive), nearest first; stop null → up to the filesystem root (like opencode's FileSystem.up). */
162
+ function dirsUp(start, stop) {
163
+ const out = [];
164
+ let d = start;
165
+ for (;;) {
166
+ out.push(d);
167
+ if (stop && samePath(d, stop)) break;
168
+ const parent = path.dirname(d);
169
+ if (parent === d) break;
170
+ d = parent;
171
+ }
172
+ return out;
173
+ }
174
+
175
+ /**
176
+ * Config layers in opencode's load order (v1.19.6 source: Config.loadInstanceState / ConfigPaths); later ones override earlier ones:
177
+ * global config.json → opencode.json → opencode.jsonc; OPENCODE_CONFIG;
178
+ * project files (git root → cwd, each level opencode.json then opencode.jsonc);
179
+ * .opencode directories (cwd → git root, then ~/.opencode, OPENCODE_CONFIG_DIR, each json then jsonc);
180
+ * the system-managed directory; OPENCODE_CONFIG_CONTENT.
181
+ * OPENCODE_DISABLE_PROJECT_CONFIG skips the project files and the project .opencode directories.
182
+ * Each layer carries its slot (load position); missing files still take a slot, so "would a later layer override a write in cwd" can be answered.
183
+ */
184
+ export function configLayers({ dir, env, globalDir, home, managedDir, major }) {
185
+ const layers = [];
186
+ let slot = 0;
187
+ const add = (source, file) => {
188
+ const s = slot++;
189
+ const r = readConfigFile(file, major);
190
+ if (r) layers.push({ source, slot: s, ...r });
191
+ return s;
192
+ };
193
+ for (const n of ["config.json", "opencode.json", "opencode.jsonc"]) add("global", path.join(globalDir, n));
194
+ if (env.OPENCODE_CONFIG) add("OPENCODE_CONFIG", path.resolve(env.OPENCODE_CONFIG));
195
+ const projectOn = !truthy(env.OPENCODE_DISABLE_PROJECT_CONFIG);
196
+ const cwd = realDir(dir);
197
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]);
198
+ const ups = dirsUp(cwd, top ? realDir(top) : null);
199
+ const cwdSlots = {};
200
+ if (projectOn) {
201
+ for (const d of [...ups].reverse()) {
202
+ for (const n of CONFIG_NAMES) {
203
+ const s = add("project", path.join(d, n));
204
+ if (d === cwd) cwdSlots[n] = s;
205
+ }
206
+ }
207
+ }
208
+ const dotDirs = [...(projectOn ? ups.map((d) => path.join(d, ".opencode")) : []), path.join(home, ".opencode")];
209
+ if (env.OPENCODE_CONFIG_DIR) dotDirs.push(path.resolve(env.OPENCODE_CONFIG_DIR));
210
+ const seen = new Set();
211
+ for (const d of dotDirs) {
212
+ const key = process.platform === "win32" ? d.toLowerCase() : d;
213
+ if (seen.has(key)) continue;
214
+ seen.add(key);
215
+ for (const n of CONFIG_NAMES) add(".opencode", path.join(d, n));
216
+ }
217
+ for (const n of CONFIG_NAMES) add("managed", path.join(managedDir, n));
218
+ if (env.OPENCODE_CONFIG_CONTENT) {
219
+ let config = null;
220
+ try {
221
+ config = parseJsonc(env.OPENCODE_CONFIG_CONTENT);
222
+ } catch {
223
+ config = null;
224
+ }
225
+ const object = !!config && typeof config === "object" && !Array.isArray(config);
226
+ layers.push({ source: "OPENCODE_CONFIG_CONTENT", slot: slot++, file: null, depth: object ? depthOf(config, major) : null });
227
+ }
228
+ return { layers, cwd, cwdSlots, projectOn };
229
+ }
230
+
231
+ const EXCLUDE_MARK = "# a2h-app-migrate opencode_depth.mjs";
232
+
233
+ function excludeFileOf(dir) {
234
+ const p = git(dir, ["rev-parse", "--git-path", "info/exclude"]);
235
+ return p ? path.resolve(dir, p) : null;
236
+ }
237
+
238
+ /** Is the file's directory in a git worktree, is the file tracked. git computes every path from inside that directory — no absolute-path joins (immune to symlinks and short names). */
239
+ export function gitStatusOf(file) {
240
+ const dir = path.dirname(file);
241
+ const name = path.basename(file);
242
+ const prefix = git(dir, ["rev-parse", "--show-prefix"]);
243
+ if (prefix === null) return { worktree: false };
244
+ const tracked = git(dir, ["ls-files", "--error-unmatch", "--", name]) !== null;
245
+ return { worktree: true, tracked, rule: `/${prefix}${name}` };
246
+ }
247
+
248
+ /** Did this script put the file into .git/info/exclude (with its marker line)? */
249
+ export function excludedByUs(file) {
250
+ const st = gitStatusOf(file);
251
+ if (!st.worktree || st.tracked) return false;
252
+ const ex = excludeFileOf(path.dirname(file));
253
+ if (!ex || !fs.existsSync(ex)) return false;
254
+ const lines = fs.readFileSync(ex, "utf8").split(/\r?\n/);
255
+ const i = lines.indexOf(st.rule);
256
+ return i > 0 && lines[i - 1] === EXCLUDE_MARK;
257
+ }
258
+
259
+ /**
260
+ * Only for a file this script created, inside a git worktree and untracked: append it to .git/info/exclude (local only, the user's .gitignore is untouched),
261
+ * then confirm with git check-ignore that the rule really applies; only then report excluded.
262
+ */
263
+ export function excludeCreated(file) {
264
+ const st = gitStatusOf(file);
265
+ if (!st.worktree) return { worktree: false };
266
+ if (st.tracked) return { worktree: true, tracked: true, excluded: false };
267
+ const dir = path.dirname(file);
268
+ const ex = excludeFileOf(dir);
269
+ if (!ex) return { worktree: true, tracked: false, excluded: false };
270
+ const text = fs.existsSync(ex) ? fs.readFileSync(ex, "utf8") : "";
271
+ if (!text.split(/\r?\n/).includes(st.rule)) {
272
+ fs.mkdirSync(path.dirname(ex), { recursive: true });
273
+ fs.appendFileSync(ex, `${text && !text.endsWith("\n") ? "\n" : ""}${EXCLUDE_MARK}\n${st.rule}\n`, "utf8");
274
+ }
275
+ const excluded = git(dir, ["check-ignore", "-q", "--", path.basename(file)]) !== null;
276
+ return { worktree: true, tracked: false, excluded, exclude_file: ex };
277
+ }
278
+
279
+ const describe = (l) => (l.file ? `${l.source} ${l.file}` : `the environment variable ${l.source}`);
280
+
281
+ /** Main logic; tests inject env / globalDir / home / managedDir / version. */
282
+ export function ensure({
283
+ dir = process.cwd(),
284
+ version,
285
+ env = process.env,
286
+ home = os.homedir(),
287
+ globalDir = globalConfigDir(env, home),
288
+ managedDir = managedConfigDir(env),
289
+ } = {}) {
290
+ const versionRaw = version ?? probeVersion();
291
+ const major = majorOf(versionRaw);
292
+ const v2 = major !== null && major >= 2;
293
+ const restartTail = v2 ? "it takes effect on save" : "then restart the opencode session";
294
+ const { layers, cwd, cwdSlots, projectOn } = configLayers({ dir, env, globalDir, home, managedDir, major });
295
+ const declared = layers.filter((l) => l.depth !== null);
296
+ const winner = declared.at(-1) ?? null;
297
+ const effective = winner ? winner.depth : 1;
298
+ const base = {
299
+ opencode_version: versionRaw,
300
+ major: v2 ? 2 : 1,
301
+ required_depth: REQUIRED_DEPTH,
302
+ effective_depth: effective,
303
+ source: winner ? winner.source : "default",
304
+ source_file: winner?.file ?? null,
305
+ layers: declared.map(({ source, file, depth }) => ({ source, file, depth })),
306
+ };
307
+
308
+ if (effective >= REQUIRED_DEPTH) {
309
+ // v1 rerun after the restart: an effective value from the file this script wrote still goes into the final report.
310
+ if (winner?.file && winner.source === "project" && excludedByUs(winner.file)) {
311
+ return {
312
+ ...base,
313
+ action: "none",
314
+ next: "continue",
315
+ report: true,
316
+ file: winner.file,
317
+ message: `The project-level config ${winner.file} was written by this workflow (experimental.subagent_depth=${REQUIRED_DEPTH}) and is in this repository's .git/info/exclude, so it will not be committed.`,
318
+ };
319
+ }
320
+ return { ...base, action: "none", next: "continue" };
321
+ }
322
+
323
+ if (!projectOn) {
324
+ return {
325
+ ...base,
326
+ action: "manual",
327
+ next: "manual",
328
+ message: `OPENCODE_DISABLE_PROJECT_CONFIG is set, so project-level configs are ignored: add "experimental": { "subagent_depth": ${REQUIRED_DEPTH} } to the global config ${path.join(globalDir, "opencode.json")}; ${restartTail}.`,
329
+ };
330
+ }
331
+
332
+ // Write in cwd. In one directory opencode.jsonc loads after opencode.json: if jsonc declares a depth only jsonc can fix it; otherwise edit the existing json,
333
+ // else the existing jsonc, else create opencode.json.
334
+ const at = (n) => layers.find((l) => l.slot === cwdSlots[n]);
335
+ const jsonc = at("opencode.jsonc");
336
+ const json = at("opencode.json");
337
+ const target = jsonc?.depth != null ? jsonc : (json ?? jsonc ?? null);
338
+ const targetSlot = target ? target.slot : cwdSlots["opencode.json"];
339
+ const file = target ? target.file : path.join(cwd, "opencode.json");
340
+
341
+ // A later layer declares a depth (necessarily < 2 here) → a write in cwd would be overridden; the user must edit that layer.
342
+ const later = declared.filter((l) => l.slot > targetSlot).at(-1);
343
+ if (later) {
344
+ return {
345
+ ...base,
346
+ action: "manual",
347
+ file: later.file,
348
+ next: "manual",
349
+ message: `The effective depth comes from ${describe(later)} (subagent_depth=${later.depth}), which loads after the project-level config, so writing the project config would not help: change it there to >= ${REQUIRED_DEPTH}; ${restartTail}.`,
350
+ };
351
+ }
352
+ if (target && (!target.parsed || !target.strict || !target.object)) {
353
+ return {
354
+ ...base,
355
+ action: "manual",
356
+ file: target.file,
357
+ next: "manual",
358
+ message: `${target.file} is not a JSON object that can be rewritten safely (it may contain comments) and was left alone: add "experimental": { "subagent_depth": ${REQUIRED_DEPTH} } to it; ${restartTail}.`,
359
+ };
360
+ }
361
+
362
+ const config = target ? target.config : {};
363
+ const experimental = config.experimental && typeof config.experimental === "object" ? config.experimental : {};
364
+ config.experimental = { ...experimental, subagent_depth: REQUIRED_DEPTH };
365
+ // v1 also reads the top-level form: raise a smaller top-level value too, so no two declarations contradict each other.
366
+ if (typeof config.subagent_depth === "number" && config.subagent_depth < REQUIRED_DEPTH) config.subagent_depth = REQUIRED_DEPTH;
367
+ // A symlink (e.g. into dotfiles) is written through to its target; the link is not replaced by a plain file.
368
+ writeJsonAtomic(target ? fs.realpathSync(file) : file, config);
369
+
370
+ const gitInfo = target ? gitStatusOf(file) : excludeCreated(file);
371
+ const gitNote = gitInfo.excluded
372
+ ? " It was added to this repository's .git/info/exclude and will not be committed."
373
+ : gitInfo.tracked
374
+ ? " The file is tracked by git: the change shows up in the worktree; decide yourself whether to commit it."
375
+ : gitInfo.worktree
376
+ ? " It is the user's own untracked file: only the depth was changed, and it was not added to .git/info/exclude."
377
+ : "";
378
+ const why = winner && winner.depth < REQUIRED_DEPTH ? ` (previously ${winner.depth} from ${describe(winner)} was in effect)` : "";
379
+ return {
380
+ ...base,
381
+ action: target ? "updated" : "created",
382
+ file,
383
+ git: gitInfo,
384
+ report: true,
385
+ next: v2 ? "continue" : "restart",
386
+ message: v2
387
+ ? `Declared experimental.subagent_depth=${REQUIRED_DEPTH} in the project-level config ${file}${why} (opencode v2 hot-reloads it; no restart needed).${gitNote}`
388
+ : `Declared experimental.subagent_depth=${REQUIRED_DEPTH} in the project-level config ${file}${why}. opencode v1 does not hot-reload: quit, restart the opencode session in this directory, and re-enter the original command.${gitNote}`,
389
+ };
390
+ }
391
+
392
+ function parseArgs(argv) {
393
+ const out = {};
394
+ for (let i = 0; i < argv.length; i++) {
395
+ const a = argv[i];
396
+ if (a === "--dir") out.dir = path.resolve(argv[++i]);
397
+ else if (a === "--version") out.version = argv[++i];
398
+ else if (a === "-h" || a === "--help") out.help = true;
399
+ else throw new Error(`unknown argument: ${a}`);
400
+ }
401
+ return out;
402
+ }
403
+
404
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
405
+ try {
406
+ const args = parseArgs(process.argv.slice(2));
407
+ if (args.help) {
408
+ console.log("node opencode_depth.mjs [--dir <project dir>] [--version <opencode version>]");
409
+ process.exit(0);
410
+ }
411
+ const r = ensure(args);
412
+ console.log(JSON.stringify(r));
413
+ process.exit(r.next === "continue" ? 0 : 2);
414
+ } catch (err) {
415
+ console.error(String(err?.message ?? err));
416
+ process.exit(1);
417
+ }
418
+ }
@@ -8,3 +8,5 @@ Common implementation pitfalls:
8
8
  * Do not use `ForEach` for large lists (lists/grids of songs, messages, feeds, etc. that may have hundreds of entries): it creates all child nodes on first load, so with many entries the first frame stutters noticeably or even times out with a blank screen. Prefer `LazyForEach` + `IDataSource` to create on-screen nodes on demand; note that data-source changes must be notified through interfaces such as `notifyDataReload` / `notifyDataAdd` / `notifyDataChange` — replacing the whole array without notifying does not refresh the UI (a pitfall already seen when combined with `@Observed`/`@ObjectLink`). A small fixed set of options (menus, tabs) can still use `ForEach`.
9
9
  * Every value that crosses an "untyped boundary" into strongly typed code must be normalized as nullable; never assume it has a value: deserialization results, database rows, local caches and cross-page parameters all count. An ArkTS type is a compile-time annotation only — nothing is validated at runtime, `as T` fills in no default, and `null` enters the entity as-is; a mapping that tests only `=== undefined` misses it. On the read side that throws `TypeError` (a crash) at `.length`, iteration or a method call, and in numeric comparisons `null` is silently taken as 0; on the write side it is rejected by the non-null constraint and never reaches the database, or it is written to JSON and read back with missing values (a `null` inside an object stays `null`, while the key of an `undefined` property disappears entirely). Rule: always normalize inside the function that maps external data to the entity — add one first if it does not exist; declare the field `?: T | null` and use `??` to supply the type's default when it is missing (string `''`, number `0`, array `[]`, object `{}`); catch the whole object first, then normalize item by item, field by field; when reading a database, read per the column's nullable declaration instead of substituting an empty string or 0 for missing; use only `??` for fallbacks, never `||` or `if (!v)`, which treat a legitimate `0` or `''` as empty. Writing `=== null` on a non-null field is not a fallback: it misses `undefined` and is also reported as a comparison with no type overlap; the fix is to first change the declaration to `?: T | null`.
10
10
  * Never write a platform API from memory, and never pick a page from a single search-result list: parameter order, sync/async, the lifecycle (`create` → use → `destroy`/`off`) and the returned unit come from the local `.d.ts` (a returned field's presence is part of that contract: a non-optional declaration does not guarantee a value, and when the field's JSDoc names a flag/option, confirm the call passes it); the call order and usage come from one section of the page via `scripts/state_doc.mjs search "<module or method>"` + `read-id "<documentId>" --section "<heading>" --max-lines 80` (an API page runs to a few thousand lines; reading all of it crowds out the code context; an overload list repeats the same heading, so `--section` returns every occurrence marked `<!-- section "request" 2/3 -->` — add `--occurrence <n>` to pick one). When this worktree already has a working call site for the same API: **shape** questions (parameter order, sync/async, lifecycle, returned unit) may copy it, and the `.d.ts` outranks the page; **meaning** questions (targets, ordering, grant level, boundaries, which key is addressed) still require the official page even when a call site exists, the page outranks the `.d.ts` there, and the record needs one sentence quoted from it; when the `phone 12+`-style tag beside the heading is above the project's `compatibleSdkVersion`, use the older overload or `canIUse` instead. Target the project's `compatibleSdkVersion` when reading docs; prefer a non-deprecated API - an API marked `@deprecated` in the `.d.ts` or the docs should be avoided in favour of the replacement the deprecation note names, and when it has to be used, record the reason and the planned replacement in the `conclusion` column of `## Platform API lookups`. When nothing resolves, record `api-docs: unavailable`, fall back to the `.d.ts` and this file, and never guess silently.
11
+ * When global state (theme/style, login state, current user, language) changes at runtime, every already-rendered page must follow: a colour that should follow the theme or light/dark mode written as a literal (`'#FFFFFF'`, `Color.Red`), or a state value computed once at initialization and then cached, both leave that page on the old value. Use `$r('app.color.*')` with a `resources/dark/` qualifier for colours (system colours: `$r('sys.color.*')`); an in-app light/dark switch takes effect only through `getApplicationContext().setColorMode(...)`, which is not persisted — re-apply the stored mode when the entry Ability starts; use `$r('app.string.*')` for texts so they follow the language, and `WithTheme`/`CustomTheme` for an in-app switchable custom theme; put any other global state on the paradigm the project already uses: V1 `AppStorage`/`PersistentStorage` (with `@StorageLink`/`@StorageProp`), V2 `AppStorageV2`/`PersistenceV2` (with `@ObservedV2`/`@Trace`) — never introduce the other paradigm into a file that already uses one; see the state-doc section of code-generation.md. For a value computed once locally, see the `@ComponentV2` entry above.
12
+ * When global state uses local storage, consider not only when to write but when to read: write-only or a late read-back leaves changes effective immediately but back to the default after a restart. Manual persistence (preferences/RDB) must **complete** its read-back before `loadContent` (starting an async read is not enough) and write it into runtime state before loading the first page; `PersistentStorage.persistProp` depends on the UI instance and must be called after it is initialized (`loadContent` callback, or the entry `@Entry` page's module top level — use the latter when the first page itself reads the key, the callback is too late), never in `onCreate` or before `loadContent`; `PersistenceV2` reads back via `connect` at the use site, and per the official examples belongs in a component (UI thread), not in `onCreate`.
@@ -48,8 +48,8 @@ Both modes also need **background sub-agents** and **pre-approved writes**. Run
48
48
  Every sub-agent of this skill (Step 2 resources, Step 3 reviewers, Step 5 groups, Step 5.5 wiring, Step 6 verify) is a **background sub-agent of the parent's own host**; which tool that is per host is in [references/host-dispatch.md](references/host-dispatch.md) — **read it before the first dispatch**. The rules, on every host:
49
49
 
50
50
  1. **One call per unit, several in one message.** Record each resume handle with `group_queue.mjs bind --task <handle>`.
51
- 2. **Completion comes from disk, not from the host:** a report file, `answers_check.mjs` complete, or `detach.mjs` exited. `group_queue.mjs wait` blocks on these (≤ 9 min); a host notice is an early hint.
52
- 3. **The parent never holds the foreground for long.** Anything over ~3 min runs through `detach.mjs start … --name <job>`; pass `--job <job>` to `wait`.
51
+ 2. **Completion comes from disk, not from the host:** a report file, `answers_check.mjs` complete, or `detach.mjs` exited. `group_queue.mjs wait` blocks on these (≤ 5 min; a larger `--timeout-s` is capped at 300); a host notice is an early hint.
52
+ 3. **The parent never holds the foreground for long.** Anything over ~3 min runs through `detach.mjs start … --name <job>`; pass `--job <job>` to `wait`. **One `group_queue.mjs wait` per shell call:** never wrap `wait` / `group_pass.mjs` in a loop or chain several waits in one call. Each return goes back to the parent, which acts on it (dispatch, bind, verify) before the next wait: while a call runs, the host queues every completion notice and no slot is refilled (measured: a 12-wait loop held the foreground for an hour while `group_pass` kept printing dispatches).
53
53
  4. **Never cancel by re-dispatching.** A stalled agent is resumed in its own session with the same handle, never replaced by a fresh one (two writers on one file). `Q requeue` enforces this; `--fresh` only after the old session's completion notice. Pass `--task <handle>` to every `Q release` that comes from a notice.
54
54
  5. **Sub-agents cannot dispatch sub-agents**; every prompt says so.
55
55
  5a. **`image_read=false` (Step 1)**: every prompt opens with the `NO_IMAGE` block of `scripts/group_queue.mjs` (`lease` adds it to group messages; the parent adds it to the others), and the parent never opens an image either.
@@ -147,10 +147,10 @@ The skeleton always ends up in `${harmony_project_dir}/.hometrans/utg_static`; S
147
147
 
148
148
  The parent drives `a2h-utg-explorer`'s `run_cycle.mjs` from its `scripts/` directory. `S` is the Step 3.1 workspace; `C=${harmony_project_dir}/.hometrans/utg_explore`.
149
149
 
150
- 1. **Install and identify.** `<adb> -s <serial> install -r <apk_path>`, where `<adb>` is `ADB_PATH` when the caller passed it and `adb` otherwise. Take package and launcher from `aapt dump badging <apk_path>` (look under `<sdk>/build-tools/<newest version>/`), or, after the install, from `<adb> -s <serial> shell cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.LAUNCHER <package>`.
150
+ 1. **Install and identify.** `<adb>` is `ADB_PATH` when the caller passed it and `adb` otherwise. Take the package from `aapt dump badging <apk_path>` (look under `<sdk>/build-tools/<newest version>/`; `package:`) or the app module's `applicationId`. **Install only when the device lacks this exact APK.** Never uninstall on your own: an uninstall wipes the app data, including a login set up by hand. Run `<adb> -s <serial> shell pm path --user 0 <package>`. Skip the install only when it prints exactly one `package:<path>` line (no splits) and the first column of `<adb> -s <serial> shell sha256sum <path>` (it prints `<hash> <path>`) equals the local APK's SHA-256 (`node -e "console.log(require('crypto').createHash('sha256').update(require('fs').readFileSync(process.argv[1])).digest('hex'))" <apk_path>`). In every other case (not installed, split APKs, a different hash, no `sha256sum` on the device) run `<adb> -s <serial> install -r -t <apk_path>`: `-r` replaces the app in place and keeps its data, `-t` lets a testOnly (IDE-built) APK install. Never compare `versionCode` / `versionName` alone: a debug rebuild keeps them while the UI changes, so the capture would show the old pages. When the install fails: on `INSTALL_FAILED_VERSION_DOWNGRADE`, retry once with `-d` added (an older build may crash on the newer one's data: note the downgrade for Step 7); on `INSTALL_FAILED_UPDATE_INCOMPATIBLE` (the installed app has another signature), or when the `-d` retry fails too (a user build refuses downgrading a non-debuggable app), stop and ask the user to choose between uninstalling (the app data and any login go with it; log in again afterwards) and supplying an APK the device accepts as an update (same signature, `versionCode` not below the installed one), and record the choice for Step 7. Take the launcher from the same `aapt dump badging` output (`launchable-activity:`) or, after the install, from `<adb> -s <serial> shell cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.LAUNCHER <package>`.
151
151
  2. **Plan and compile.** `node plan.mjs $S/utg.json $C`, review `C/plan.md`, then `node compile_tasks.mjs $S/utg.json $C --project <android_project_dir> --locale <device locale>`.
152
152
  3. **Write `$C/config.json`** — `serial`, `package`, `launch_component`, `"adb": "<ADB_PATH>"` when the caller passed `ADB_PATH`, empty fixtures for phases whose `requires` is empty, `snapshot_dir` / `fixture_server_dir` — then **start the fixture server** with `detach.mjs start … --name fixture_server --service`. `d_prereqs.mjs check` must exit 0 before the first cycle.
153
- 4. **Run the cycle.** Always in the background: `node <this skill>/scripts/detach.mjs start ${harmony_project_dir} --name run_cycle -- node run_cycle.mjs $C --config $C/config.json --static $S/utg.json --project <android_project_dir> --package <app package>`. While `finished` is false, dispatch a reviewer for every `waiting` part not yet dispatched (at most `--max-agents`, `blocked_on` first) and start the cycle again once every `blocked_on` worklist is complete. Never ask the user between calls. Recovery A–D and direct launch run inside the cycle without confirmation; pass `--skip D` only when the user forbids app-data changes.
153
+ 4. **Run the cycle.** Always in the background: `node <this skill>/scripts/detach.mjs start ${harmony_project_dir} --name run_cycle -- node run_cycle.mjs $C --config $C/config.json --static $S/utg.json --project <android_project_dir> --package <app package>`. While `finished` is false, dispatch a reviewer for every `waiting` part not yet dispatched (at most `--max-agents`, `blocked_on` first) and start the cycle again once every `blocked_on` worklist is complete. Never ask the user between calls. Recovery A–D and direct launch run inside the cycle without confirmation; pass `--skip D` only when the user forbids app-data changes, and then leave `reset_between_tasks` out as well (`--skip D` does not stop its clears). A login set up by hand on a debuggable build is archived as `initial` and restored before the login phases run and at the end of the cycle, so keep `reset_between_tasks`; on a non-debuggable build, see `references/step3-capture.md` item 3 (on an emulator it is wiped unless `config.json` holds `allow_unarchived_wipe: false` before the first cycle; check debuggability with `run-as <package> true` beforehand, since `states.json` only says so once the cycle has started).
154
154
  5. **Export and build the conversion set once `run_cycle.mjs` prints `finished: true`:**
155
155
 
156
156
  ```bash
@@ -165,9 +165,9 @@ Record for Step 7: coverage from `report.md`, phase states and `skipped` stages,
165
165
 
166
166
  ### Step 3.2-I — Scoped capture (incremental mode's I5)
167
167
 
168
- The Step 3.2 explorer cycle with three deltas, all in `./references/incremental-scope.md` I5: the campaign is planned with `plan.mjs --scope <scope.json>` (tasks, review worklists and `capture_pending.json` then cover only the scope), `run_cycle.mjs` gets `--skip D` unless the user allows app-data changes, and the builder runs with `--scope` / `--existing`. No crawler, no model key.
168
+ The Step 3.2 explorer cycle with three deltas, all in `./references/incremental-scope.md` I5: the campaign is planned with `plan.mjs --scope <scope.json>` (tasks, review worklists and `capture_pending.json` then cover only the scope), `run_cycle.mjs` gets `--skip D` unless the user allows app-data changes (and then `config.json` leaves `reset_between_tasks` out too), and the builder runs with `--scope` / `--existing`. No crawler, no model key.
169
169
 
170
- Install the APK first (`adb [-s <ADB_SERIAL>] install -r -t <apk_path>`); the explorer never installs it, and an install failure stops I5. Without a device, or when the user declines capture, skip the cycle and run only `build_conversion_set.mjs`: every member converts source-only.
170
+ Install the APK first (`adb [-s <ADB_SERIAL>] install -r -t <apk_path>`) with the same check and failure handling as Step 3.2 item 1: skipped when the device already holds this exact APK, never an uninstall on your own. The explorer never installs it, and an install that still fails after that handling stops I5. Without a device, or when the user declines capture, skip the cycle and run only `build_conversion_set.mjs`: every member converts source-only.
171
171
 
172
172
  ### Step 3.3 — Confirm pages.json and coverage
173
173
 
@@ -259,7 +259,7 @@ If a task-tracking tool is available, create one task per page, with already-`do
259
259
  - **5.3** host-chain groups run serially, self-contained groups concurrently; `group_queue.mjs` applies the rules from `plan`. When in doubt, serialize. Rule 7 binds every concurrent prompt:
260
260
 
261
261
  7. **The shared registry surface is parent-owned while any other group is in flight.** Every concurrently dispatched group's prompt states: do not edit `main_pages.json`, `resources/**/element/*.json`, `oh-package*.json5`, `module.json5` or the ability's `loadContent()`. Instead, list the additions in the report under `registry_requests`. The parent applies each group's requests when that group is released, one group at a time. Merge, never overwrite: an existing name with a different value is a conflict, so keep the existing value and record it in the report.
262
- - **5.4** Never dispatch blocking waves. `Q init` once, then one pass per parent turn: release (`Q reap` → `Q release`), lease and dispatch (`Q lease`, pass `message` verbatim, `Q bind`), verify every `returned_unverified` group (`phase5_check.mjs --group`, `Q verified --summary`, which marks its pages `done` in `batch_progress.json`, then `group_commit.mjs`), then `Q wait` with a shell timeout above 9 min. Go on only when `summary.idle` is true, nothing is unverified and `summary.stuck` is empty.
262
+ - **5.4** Never dispatch blocking waves. `Q init` once, then one pass per parent turn: release (`Q reap` → `Q release`), lease and dispatch (`Q lease`, pass `message` verbatim, `Q bind`), verify every `returned_unverified` group (`phase5_check.mjs --group`, `Q verified --summary`, which marks its pages `done` in `batch_progress.json`, then `group_commit.mjs`), then one `Q wait` with a shell timeout above 5 min (e.g. 600000 ms). Go on only when `summary.idle` is true, nothing is unverified and `summary.stuck` is empty.
263
263
  - **5.5** One background sub-agent (Step 0.1) does the wiring: confirm every `registry_requests` was applied, wire self-contained components and shell hosts, and wire navigation from `navigates_to`. No group is in flight any more, so this agent may edit the registry surface of Rule 7. The parent writes `${harmony_project_dir}/.hometrans/work/prompts/wiring.md` (the Step 5.5 procedure of step5-convert.md plus its inputs), dispatches it the way Step 2 is dispatched, and joins on `.hometrans/work/wiring.report.md`. **Entry gate:** `node scripts/group_queue.mjs status ${harmony_project_dir} --assert-settled` exits 0 (no group left open; see step5-convert.md item 5). After a `Q stop`, it cannot pass: skip Steps 5.5 and 6 and write the Step 7 report. **Gate (parent re-checks after the join):** `orphan-component` is zero, and `phase5_check.mjs --files <every file changed since the last group commit>` has `blocking` 0, and `node scripts/shell_requests.mjs verify --hp ${harmony_project_dir}` exits 0 (every ledger id answered, every deleted `.ets` has its merge line), before Step 6. Run `shell_requests.mjs collect` before writing `wiring.md` and put its table in the prompt; carry every `deferred` row into Step 7's Manual Follow-up TODOs. Take that file list from `git status --porcelain` (modified and untracked), not from the report: a file the agent edited but left out of the report would otherwise skip the gate and still be committed. The parent then commits the wiring.
264
264
 
265
265
  ## Step 6 — Static Check, Build, Smoke Gate
@@ -10,7 +10,7 @@
10
10
  **Alignment depends on the parent container, not just the container holding the Text**: as soon as a `Column` has a **shrink-wrapped** child container (a `Row`/`Column`/`Stack` with no `.width()` / `.layoutWeight()`, typically an "icon + title" row), what determines its horizontal position is the **parent** `Column`'s `alignItems`; the child `Row`'s own `justifyContent(FlexAlign.Start)` governs only the **inside** of the Row, not the Row's position in its parent. Real miss: the card title row `Row() { Image; Text }` was reported as `container-align-unset`, the answer "a Row's main axis defaults to Start" was correct in itself, so it was let through, while what actually centered it was the card `Column` with no `alignItems`. Fix: give the parent `Column` an explicit `.alignItems(HorizontalAlign.Start)`, or give the child row `.width('100%')`. Checker CAND `column-shrink-child-centered`.
11
11
  **`Scroll`'s `.align()` determines where the content sits when it is shorter than the viewport**; the default is `Alignment.Center`. **`Alignment.Start` = left + vertically centered, not top-left**. Content in Android `ScrollView`/`NestedScrollView`/`RecyclerView` starts at the top by default, so this should usually be `Alignment.TopStart` (or `Top`/`TopEnd`). Exceptions need an Android basis: `fillViewport="true"` + child layout `gravity="center"` (login pages, centered empty-state pages) corresponds to `Alignment.Center`; `stackFromEnd`/`reverseLayout` (chat pages anchored to the bottom) correspond to `Bottom*`. **`align` is a universal attribute (API reference "Location"); the docs list `Scroll` among the components it takes effect on, default `Alignment.Center`** — `align` is missing from `scroll.d.ts` because it lives in `CommonMethod`, not because Scroll lacks it, so that is no reason to skip it. "The content always exceeds the viewport" is no reason either: when the content comes from `ForEach`/`LazyForEach`/`Repeat`, a short list (after filtering, a single first page, back from the empty state) is the normal case. Checker: `Alignment.Start` reports GATE `scroll-align-not-top` (almost certainly mistaken for top-left); other non-Top values report CAND `scroll-align-not-top`; no `.align()` over data-driven content reports GATE `scroll-align-default-center`, downgraded only by `// SCROLL-CENTER: <basis>` above the Scroll (EVIDENCE text does not close it); static content without `.align()` is CAND.
12
12
  **A horizontal `Scroll` (`LazyRow` / `HorizontalScrollView`) is about the horizontal position**: without a width it shrinks to its content, and a parent `Column` (default `HorizontalAlign.Center`) pushes the whole row to the middle ("My footprints" centered with one or two items while Android starts at the left). Write `.width('100%').align(Alignment.Start)` (horizontally `Start` = left + vertically centered, which is what is wanted), or `.alignItems(HorizontalAlign.Start)` on the parent `Column`. GATE/CAND `hscroll-centered-in-column`.
13
- **Per-child alignment of Compose `Box` children (`Modifier.align(X)`)**: when a child inside `Box(contentAlignment = C)` writes `Modifier.align(X)` (X ≠ C), that child is placed by X and the rest by C. ArkUI `Stack` has no per-child alignment, and a child's `.align()` only arranges its own content, so X must be expressed separately: wrap that child in a container the same size as the Stack and arrange it by X inside that container (`BottomCenter` + `padding(bottom = 5.dp)` → `Column() { … }.width('100%').height('100%').justifyContent(FlexAlign.End).padding({ bottom: 5 })`; `CenterStart` → `Row()…justifyContent(FlexAlign.Start)`), or position it with `.position` / `.markAnchor`. **Leaving only the `padding` turned into a one-sided `margin` does not count as translating the alignment**: the Stack still centers it, and it sits on top of the centered siblings. The "Box children with their own alignment" section of the group pack lists every occurrence in this group (`file:line`); for each one, this item gives the HarmonyOS-side `file:line` and the form used. Checker: an explicit `alignContent: Alignment.Center` goes through GATE `stack-overlay-default-center` / `stack-child-align-noop` just like an unwritten one.
13
+ **Per-child alignment of Compose `Box` children (`Modifier.align(X)`)**: when a child inside `Box(contentAlignment = C)` writes `Modifier.align(X)` (X ≠ C), that child is placed by X and the rest by C. ArkUI `Stack` has no per-child alignment, and a child's `.align()` only arranges its own content, so X must be expressed separately: wrap that child in a container the same size as the Stack and arrange it by X inside that container (`BottomCenter` + `padding(bottom = 5.dp)` → `Column() { … }.width('100%').height('100%').justifyContent(FlexAlign.End).padding({ bottom: 5 }).hitTestBehavior(HitTestMode.Transparent)`; `CenterStart` → `Row()…justifyContent(FlexAlign.Start)`), or position it with `.position` / `.markAnchor`. This same-size container covers the whole Stack: without `hitTestBehavior(HitTestMode.Transparent)` its empty area blocks its siblings under `HitTestMode.Default`, and the list below can be neither tapped nor scrolled (GATE `fullsize-container`). **Leaving only the `padding` turned into a one-sided `margin` does not count as translating the alignment**: the Stack still centers it, and it sits on top of the centered siblings. The "Box children with their own alignment" section of the group pack lists every occurrence in this group (`file:line`); for each one, this item gives the HarmonyOS-side `file:line` and the form used. Checker: an explicit `alignContent: Alignment.Center` goes through GATE `stack-overlay-default-center` / `stack-child-align-noop` just like an unwritten one.
14
14
 
15
15
  ### Phase 5 "Horizontal Inset Evidence" — criteria
16
16
 
@@ -1,7 +1,7 @@
1
1
  # Knowledge card — State management: observation decorators
2
2
 
3
- > Required. The criteria for Phase 5 "Missing Observation Decorators" (the part shared by both paradigms).
4
- > This card was split out of `conversion-procedure.md` with the rule text unchanged; Phase numbers mentioned in the card refer to the corresponding phases of `conversion-procedure.md`.
3
+ > Required. The criteria for Phase 5 "Missing Observation Decorators" (the part shared by both paradigms), plus the key rules for ForEach / LazyForEach / Repeat.
4
+ > The "Missing Observation Decorators" section was split out of `conversion-procedure.md` with the rule text unchanged; the "Key generator" section is new to this card. Phase numbers mentioned in the card refer to the corresponding phases of `conversion-procedure.md`.
5
5
 
6
6
  ### Phase 5 "Missing Observation Decorators" — criteria
7
7
 
@@ -12,3 +12,21 @@
12
12
 
13
13
  - V2: do all properties of an `@ObservedV2` class used in the UI have `@Trace`? Add it if not (`@ObservedV2` and `@Trace` must be used together; either alone has no effect). Derived values use `@Computed`.
14
14
  - Paradigm consistency: are the components and VMs/Models added/modified on this page consistent with the project's paradigm? Mixing V1/V2 decorators is strictly forbidden (e.g. `@Local` in a `@Component`, `@State` in a `@ComponentV2`)
15
+
16
+ ### Key generator for ForEach / LazyForEach / Repeat
17
+
18
+ In HarmonyOS one key value decides both "is this the same item" and "does this row need rebuilding": while the key stays the same, ForEach reuses the old node and does not rerun the item generator. Android splits these into two layers: `areItemsTheSame` (identity) and `areContentsTheSame` (content). So the key must do both:
19
+
20
+ - **Unique and stable**: build it on Android's identity field, i.e. the field used by `DiffUtil.ItemCallback.areItemsTheSame`, `Adapter.getItemId` + `setHasStableIds(true)`, or Compose `items(key = { … })`. When items may be added, removed or reordered, do not use the index, `Math.random()` / `Date.now()`, or display text that may repeat (such as a title).
21
+ - **Cover display content that changes**: append the fields compared by `areContentsTheSame` that affect how the row looks, e.g. `${item.id}:${item.status}`. With an identity-only key, replacing an item with a new object of the same id leaves the row content stale (correct only after leaving and re-entering the page); `@ObservedV2` / `@Trace` cannot carry values across a reused row either. `JSON.stringify(item)` covers every field and is allowed, but costs more with many items or large objects. Use an identity-only key only when every mutable field in the row is known not to change (read-only data), and write `// FOREACH-KEY: <reason>` above the ForEach.
22
+ - **When the Android side has no stable ID** (`ArrayAdapter` / `BaseAdapter` + `notifyDataSetChanged`, Compose `items(list)` without a key): for fixed lists that are never added to, removed from or reordered (menus, tabs), the index or the omitted key generator (default rule) is fine, with a comment citing the Android basis (`file:line`); when data is added, removed or reordered, find the primary key in the data model, and fall back to `JSON.stringify(item)` if there is none; do not invent a field.
23
+ - Where it goes: the third argument of `ForEach` / `LazyForEach`, `.key()` on `Repeat`. Default rules: index + `JSON.stringify(item)` for ForEach, viewId + index for LazyForEach; neither stays stable when data is added, removed or reordered.
24
+
25
+ Checker: `foreach-key-stale-render` (warn) in a2h-spec-design-pipeline reports "the key contains only an identity field while the generator reads fields that change"; `// FOREACH-KEY: <reason>` closes a single site. The same requirement is in `a2h-arkts-logic-coder/references/ISSUES.md`.
26
+
27
+ ## Common Mistranslations (undetectable at compile time)
28
+
29
+ | Mistranslation | Why it happens | Consequence | How to self-check |
30
+ |---|---|---|---|
31
+ | **Omitting the key generator of ForEach / LazyForEach / Repeat, or keying by index / display text that may repeat, when data is added, removed or reordered** | When omitted the default rule applies (ForEach: index + `JSON.stringify(item)`; LazyForEach: viewId + index), and nothing fails at compile time | After add, remove or reorder, components are reused against the wrong items (state leaks into another row, images misplaced), or duplicate keys leave items unrendered | → "Key generator" in this card: list which fields each key comes from and its Android basis (`areItemsTheSame` / `getItemId` / `items(key=)`) |
32
+ | **Keying by id only while fields shown in the row change** | Only `areItemsTheSame` was carried over; the `areContentsTheSame` layer was missed | After replacing an item with a new object of the same id (e.g. unread → read), the row content does not refresh until the page is re-entered | → "Cover display content that changes" in this card; `foreach-key-stale-render`, and write `// FOREACH-KEY: <reason>` when the data really is read-only |