@buaa_smat/hometrans 26.0.6 → 26.0.8

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 (159) hide show
  1. package/README.md +6 -3
  2. package/agents/a2h-executor.md +37 -0
  3. package/dist/cli/editors.json +13 -0
  4. package/dist/platform/compose.js +4 -0
  5. package/dist/platform/registry.js +3 -1
  6. package/dist/platform/transform.js +37 -3
  7. package/env-requirements.json +15 -1
  8. package/i18n/platforms/codebuddy/skills/a2h-app-migrate/SKILL.unique.md +2 -2
  9. package/i18n/platforms/deveco/skills/a2h-app-migrate/SKILL.unique.md +1 -1
  10. package/i18n/platforms/opencode/skills/a2h-app-migrate/SKILL.unique.md +13 -6
  11. package/i18n/skills/a2h-app-migrate/SKILL.md +2 -2
  12. package/i18n/skills/a2h-app-migrate/references/workflow.yaml +27 -4
  13. package/i18n/skills/a2h-app-migrate/scripts/opencode_depth.mjs +418 -0
  14. package/i18n/skills/a2h-arkts-logic-coder/references/ISSUES.md +2 -0
  15. package/i18n/skills/a2h-batch-ui-align/SKILL.md +7 -7
  16. package/i18n/skills/a2h-batch-ui-align/references/cards/alignment.md +1 -1
  17. package/i18n/skills/a2h-batch-ui-align/references/cards/state.md +20 -2
  18. package/i18n/skills/a2h-batch-ui-align/references/cards/widgets.md +2 -2
  19. package/i18n/skills/a2h-batch-ui-align/references/checker-rules.md +3 -3
  20. package/i18n/skills/a2h-batch-ui-align/references/conversion-procedure.md +3 -1
  21. package/i18n/skills/a2h-batch-ui-align/references/incremental-scope.md +2 -2
  22. package/i18n/skills/a2h-batch-ui-align/references/step3-capture.md +10 -6
  23. package/i18n/skills/a2h-batch-ui-align/references/step5-convert.md +13 -9
  24. package/i18n/skills/a2h-batch-ui-align/scripts/build_conversion_set.mjs +59 -7
  25. package/i18n/skills/a2h-batch-ui-align/scripts/group_pack.mjs +3 -0
  26. package/i18n/skills/a2h-batch-ui-align/scripts/interactions.mjs +186 -0
  27. package/i18n/skills/a2h-batch-ui-align/scripts/phase5_check.mjs +33 -7
  28. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/hit_test.ts +83 -22
  29. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/media_tint.ts +39 -5
  30. package/i18n/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_scroll_padding_raster.test.mjs +25 -1
  31. package/i18n/skills/a2h-page-specgen/SKILL.md +1 -1
  32. package/i18n/skills/a2h-page-specgen/references/gates.md +3 -1
  33. package/i18n/skills/a2h-page-specgen/references/scenario-authoring.md +11 -11
  34. package/i18n/skills/a2h-page-specgen/references/spec-template.md +3 -3
  35. package/i18n/skills/a2h-page-specgen/scripts/contract-calls.mjs +40 -3
  36. package/i18n/skills/a2h-page-specgen/scripts/entry-evidence.mjs +73 -5
  37. package/i18n/skills/a2h-page-specgen/scripts/gate.mjs +144 -0
  38. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.prompt.md +11 -11
  39. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.worker.md +11 -11
  40. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.prompt.md +11 -11
  41. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.worker.md +11 -11
  42. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.json +10 -10
  43. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.post-review.json +1 -1
  44. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.prompt.md +11 -11
  45. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.worker.md +11 -11
  46. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.prompt.md +11 -11
  47. package/i18n/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.worker.md +11 -11
  48. package/i18n/skills/a2h-page-specgen/scripts/test/contract-calls.test.mjs +45 -1
  49. package/i18n/skills/a2h-page-specgen/scripts/test/entry-evidence.test.mjs +100 -0
  50. package/i18n/skills/a2h-page-specgen/scripts/test/gate.test.mjs +132 -3
  51. package/i18n/skills/a2h-resource-convert/scripts/a2h_resource_convert.ts +36 -1
  52. package/i18n/skills/a2h-spec-design-pipeline/SKILL.md +1 -1
  53. package/i18n/skills/a2h-spec-design-pipeline/references/coding-loop.md +16 -0
  54. package/i18n/skills/a2h-utg-static/SKILL.md +2 -0
  55. package/package.json +1 -1
  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/skills/a2h-app-migrate/SKILL.md +29 -3
  74. package/skills/a2h-app-migrate/references/host-rules.md +33 -0
  75. package/skills/a2h-app-migrate/references/workflow.yaml +24 -4
  76. package/skills/a2h-app-migrate/scripts/opencode_depth.mjs +418 -0
  77. package/skills/a2h-app-migrate/test/test_executor_header_sync.mjs +78 -0
  78. package/skills/a2h-app-migrate/test/test_opencode_depth.mjs +312 -0
  79. package/skills/a2h-app-migrate/tools/dag.mjs +267 -0
  80. package/skills/a2h-arkts-logic-coder/references/ISSUES.md +2 -0
  81. package/skills/a2h-batch-ui-align/SKILL.md +7 -7
  82. package/skills/a2h-batch-ui-align/references/cards/alignment.md +1 -1
  83. package/skills/a2h-batch-ui-align/references/cards/state.md +20 -2
  84. package/skills/a2h-batch-ui-align/references/cards/widgets.md +2 -2
  85. package/skills/a2h-batch-ui-align/references/checker-rules.md +3 -3
  86. package/skills/a2h-batch-ui-align/references/conversion-procedure.md +3 -1
  87. package/skills/a2h-batch-ui-align/references/host-dispatch.md +5 -5
  88. package/skills/a2h-batch-ui-align/references/incremental-scope.md +2 -2
  89. package/skills/a2h-batch-ui-align/references/step3-capture.md +10 -6
  90. package/skills/a2h-batch-ui-align/references/step5-convert.md +13 -9
  91. package/skills/a2h-batch-ui-align/scripts/build_conversion_set.mjs +59 -7
  92. package/skills/a2h-batch-ui-align/scripts/group_pack.mjs +3 -0
  93. package/skills/a2h-batch-ui-align/scripts/group_pass.mjs +3 -2
  94. package/skills/a2h-batch-ui-align/scripts/group_queue.mjs +139 -23
  95. package/skills/a2h-batch-ui-align/scripts/host_env.mjs +32 -8
  96. package/skills/a2h-batch-ui-align/scripts/interactions.mjs +186 -0
  97. package/skills/a2h-batch-ui-align/scripts/phase5_check.mjs +33 -7
  98. package/skills/a2h-batch-ui-align/scripts/static_check/rules/hit_test.ts +83 -22
  99. package/skills/a2h-batch-ui-align/scripts/static_check/rules/media_tint.ts +39 -5
  100. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_hit_test.test.mjs +82 -0
  101. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_scroll_padding_raster.test.mjs +25 -1
  102. package/skills/a2h-batch-ui-align/scripts/tests/group_queue.test.mjs +184 -2
  103. package/skills/a2h-batch-ui-align/scripts/tests/host_env.test.mjs +33 -0
  104. package/skills/a2h-batch-ui-align/scripts/tests/interactions.test.mjs +258 -0
  105. package/skills/a2h-page-specgen/SKILL.md +1 -1
  106. package/skills/a2h-page-specgen/references/evidence.md +15 -0
  107. package/skills/a2h-page-specgen/references/gates.md +3 -1
  108. package/skills/a2h-page-specgen/references/scenario-authoring.md +10 -10
  109. package/skills/a2h-page-specgen/references/spec-template.md +2 -2
  110. package/skills/a2h-page-specgen/scripts/contract-calls.mjs +40 -3
  111. package/skills/a2h-page-specgen/scripts/entry-evidence.mjs +73 -5
  112. package/skills/a2h-page-specgen/scripts/gate.mjs +141 -0
  113. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.prompt.md +10 -10
  114. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/PlainDisplayPage.worker.md +10 -10
  115. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.prompt.md +10 -10
  116. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/SilentFailurePage.worker.md +10 -10
  117. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.json +10 -10
  118. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.post-review.json +1 -1
  119. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.prompt.md +10 -10
  120. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/UniAppSourcePage.worker.md +10 -10
  121. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.prompt.md +10 -10
  122. package/skills/a2h-page-specgen/scripts/test/acceptance/authoring/ValidatedSearchPage.worker.md +10 -10
  123. package/skills/a2h-page-specgen/scripts/test/contract-calls.test.mjs +45 -1
  124. package/skills/a2h-page-specgen/scripts/test/entry-evidence.test.mjs +100 -0
  125. package/skills/a2h-page-specgen/scripts/test/gate.test.mjs +104 -3
  126. package/skills/a2h-resource-convert/references/conversion-rules.md +2 -0
  127. package/skills/a2h-resource-convert/scripts/a2h_resource_convert.ts +36 -1
  128. package/skills/a2h-resource-convert/scripts/tests/adaptive_icon.test.mjs +42 -0
  129. package/skills/a2h-spec-design-pipeline/SKILL.md +1 -1
  130. package/skills/a2h-spec-design-pipeline/references/coding-loop.md +16 -0
  131. package/skills/a2h-spec-design-pipeline/references/execution-model.md +2 -2
  132. package/skills/a2h-spec-design-pipeline/references/static-defect-gate.md +5 -1
  133. package/skills/a2h-spec-design-pipeline/rules/migration-rules/config/ruleMeta.json +5 -0
  134. package/skills/a2h-spec-design-pipeline/rules/migration-rules/config/ruleSet.json +4 -0
  135. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-runtime-pitfall-cn.md +2 -1
  136. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-runtime-pitfall-en.md +3 -1
  137. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-v2-observation-cn.md +105 -0
  138. package/skills/a2h-spec-design-pipeline/rules/migration-rules/document/checker/hometrans/arkui-v2-observation-en.md +122 -0
  139. package/skills/a2h-spec-design-pipeline/rules/migration-rules/lib/checker/ArkUIRuntimePitfallCheck.js +4 -4
  140. package/skills/a2h-spec-design-pipeline/rules/migration-rules/lib/checker/ArkUIV2ObservationCheck.js +1862 -0
  141. package/skills/a2h-spec-design-pipeline/rules/migration-rules/lib/index.js +2 -0
  142. package/skills/a2h-spec-design-pipeline/rules/migration-rules/package.json +1 -1
  143. package/skills/a2h-spec-design-pipeline/scripts/dispatch/wait.mjs +15 -2
  144. package/skills/a2h-spec-design-pipeline/scripts/dispatch.mjs +20 -4
  145. package/skills/a2h-spec-design-pipeline/scripts/test_arkui_v2_observation.ts +284 -0
  146. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_commands.mjs +32 -0
  147. package/skills/a2h-spec-design-pipeline/scripts/test_dispatch_wait.mjs +22 -1
  148. package/skills/a2h-utg-static/SKILL.md +2 -0
  149. package/skills/a2h-utg-static/references/extractors.md +16 -0
  150. package/skills/a2h-utg-static/scripts/run_pipeline.mjs +22 -1
  151. package/skills/a2h-utg-static/scripts/tests/regression_matrix.mjs +4 -0
  152. package/skills/a2h-utg-static/scripts/tests/test_pr169_review_fixes.mjs +15 -0
  153. package/skills/a2h-utg-static/scripts/tests/test_view_attachments.mjs +330 -0
  154. package/skills/a2h-utg-static/scripts/view_attachments.mjs +465 -0
  155. package/platforms/codebuddy/agents/build-fixer.frontmatter.md +0 -5
  156. package/platforms/codebuddy/agents/code-reviewer.frontmatter.md +0 -5
  157. package/platforms/codebuddy/agents/model-render-worker.frontmatter.md +0 -5
  158. package/platforms/codebuddy/agents/model-worker.frontmatter.md +0 -5
  159. package/platforms/codebuddy/agents/specgen-worker.frontmatter.md +0 -5
@@ -8,7 +8,8 @@ description: "Use when the user wants to migrate an entire Android app to Harmon
8
8
  本 skill 是 [references/workflow.yaml](references/workflow.yaml) 声明式图的**薄执行器**。叶子 skill 对齐 **a2h-***。
9
9
 
10
10
  **拓扑、闸门、invoke、产物契约、失败策略的唯一权威:** `references/workflow.yaml`(尤其 `policy.*` + 节点 DAG)。
11
- 产物真源 / CLI 契约速查:[references/stage-map.md](references/stage-map.md)。
11
+ 产物真源 / CLI 契约速查:[references/stage-map.md](references/stage-map.md)。
12
+ **宿主终端规则(每次执行本 skill 必须先读):** [references/host-rules.md](references/host-rules.md)。
12
13
 
13
14
  加载 yaml → 按 `PROFILE` 裁剪 → 由生产 DAG Runner 按节点 `needs` 推进,并把语义 `invoke` 按节点 `dispatch` 交给当前宿主:skill 节点各派一个子 agent 执行并返回 JSON,主会话只调度并把结果回调给 Runner;MANIFEST 由生产 executor 初始化,LEDGER 与节点终态由 Runner 独占提交。细节勿在本文件复述。
14
15
 
@@ -35,7 +36,7 @@ node ${SKILLS_ROOT}/a2h-app-migrate/scripts/dag_runner.mjs status --state <DAG_R
35
36
 
36
37
  `run` / `continue` 返回 `waiting_external` 时,从当前 attempt 的 `<file_id>.request.json` 读取 `wait.kind`:
37
38
 
38
- - `skill`:按 `wait.dispatch` 执行。`task_subagent` → **派发一个子 agent**,由它加载 `wait.skill` 执行 `wait.invoke`(task prompt 见 `policy.dispatch`),主会话不加载叶子 skill;`primary_skill_inline` → 当前主会话加载 `wait.skill` 内联执行 `wait.invoke`。宿主不支持派发子 agent 或嵌套深度只有 1 时退回内联(`policy.dispatch`)。子 agent 不调用 executor / Runner,回调只由主会话发出。不得用 shell worker 冒充 Skill。
39
+ - `skill`:按 `wait.dispatch` 执行。`task_subagent` → **派发一个 `a2h-executor` 子 agent**(派发报错为未知 agent 类型时,用内置通用子 agent 同一 prompt 重派,note 以 `fallback: general agent` 开头),由它加载 `wait.skill` 执行 `wait.invoke`(task prompt 见 `policy.dispatch`),主会话不加载叶子 skill;`primary_skill_inline` → 当前主会话加载 `wait.skill` 内联执行 `wait.invoke`。宿主不支持派发子 agent 或嵌套深度只有 1 时退回内联(`policy.dispatch`)。子 agent 不调用 executor / Runner,回调只由主会话发出。不得用 shell worker 冒充 Skill。
39
40
  - `host_action`:当前宿主完成签名采用或最终报告等宿主动作。
40
41
  - `config`:向用户收集启动配置;`image_read`:严格按 `wait.instructions` 派一次性前台子代理读图。两者用 executor 的 `answer` 回调,其余用 `complete` 回调。
41
42
 
@@ -168,7 +169,7 @@ devecocli 登录:只在**工程还没有签名配置**、且不是「只连了
168
169
  1. **唯一权威** — 拓扑 / invoke / 闸门只认 yaml;改 invoke 前读叶子 skill Invocation(契约表见 stage-map.md)。
169
170
  2. **scaffold_new** — `discover.arch` 必须第一个碰 `${HMOS}`(`create_project` 判空只忽略 `.git`)→ `policy.parallel_rule`。
170
171
  3. **post_utg** — 固定串行:`ui.batch` → `enrich.spec_gen`;spec_gen 一律只读 `${UTG_SNAPSHOT}` → `policy.parallel_rule`。
171
- 4. **派发** — 主会话只加载本 skill 做调度,**不加载叶子 skill**。Runner 的 skill 等待带 `wait.dispatch`:6 个 skill 节点(arch / utg_static / ui.batch / spec_gen / module_docs / spec_pipeline)为 `task_subagent`,各自派发一个子 agent 跑完整个节点(depth 1,叶子内部 worker 在 depth 2),一次一个,顺序固定串行。task prompt = `policy.dispatch` 通用头 + `wait.invoke`。子 agent 不得结束本轮等后台通知:page-specgen 传 `wait_mode=foreground`、spec_pipeline 传 `WAIT_MODE=foreground`。返回值不可信:主会话只把它写成 outcome 回调,完成由 Runner 按节点 success 判定;返回不是 JSON → 同一会话续,最多 2 次。唯一例外:`SPEC_ENGINE=spec-generate` 时 enrich.spec_gen 为 `primary_skill_inline`,内联在主会话 → `policy.dispatch`。
172
+ 4. **派发** — 主会话只加载本 skill 做调度,**不加载叶子 skill**。Runner 的 skill 等待带 `wait.dispatch`:6 个 skill 节点(arch / utg_static / ui.batch / spec_gen / module_docs / spec_pipeline)为 `task_subagent`,各自派发一个 `a2h-executor` 子 agent 跑完整个节点(宿主没有它时退回内置通用子 agent;depth 1,叶子内部 worker 在 depth 2),一次一个,顺序固定串行。task prompt = `policy.dispatch` 通用头 + `wait.invoke`。子 agent 不得结束本轮等后台通知:page-specgen 传 `wait_mode=foreground`、spec_pipeline 传 `WAIT_MODE=foreground`。返回值不可信:主会话只把它写成 outcome 回调,完成由 Runner 按节点 success 判定;返回不是 JSON → 同一会话续,最多 2 次。唯一例外:`SPEC_ENGINE=spec-generate` 时 enrich.spec_gen 为 `primary_skill_inline`,内联在主会话 → `policy.dispatch`。
172
173
  5. **闸门** — 禁止因 `auto` 确认而 skip 节点(否则无人写 checkpoint);`auto` 或闸门不在 `INTERACTIVE_GATES` → `--write-confirmed --confirmed-by auto`;白名单内停等,用户确认后 `--write-confirmed --confirmed-by user` → `policy.human_interaction`。`review.arch` **不**因 `REUSE_DISCOVER_ARCH` 而 `skip_if`(文档复用 ≠ 确认;缺 checkpoint 时须补写/重问,见 `policy.human_gate_protocol`)。产出节点(`discover.arch` / `enrich.spec_gen` / `ui.batch`)**真正执行前**必须先跑它的 `before_run`(`--clear-checkpoint` 作废对应闸门);复用产物或 skip 时**禁止**清除。生产 executor 逐项提交 before_run cursor 后才返回 Skill 等待;节点有 `after_run` 的,宿主回调后由 executor 先执行它,再由 Runner 判 success。
173
174
  6. **spec 边界** — `specs.json` 只由 enrich.spec_gen 的叶子按 `SPEC_ENGINE` 写出(`spec-generate` → a2h-spec-generate 的 `publish-specs`;`page-specgen` → a2h-page-specgen 的 `finalize`);禁展开叶子内部;禁改 `${RUN_DIR}` 布局 → `policy.spec_order_boundary`。语义不完整时按 **deveco-cli 契约**带洞发布:三步用 `--allow-incomplete`,specs.json 记 `completeness: "incomplete-known"` + `incomplete{...}`,节点仍成功、下游照常消费,缺口只记录在 specs.json 的 incomplete 里,不写进最终报告(见 enrich.spec_gen 的 invoke);唯一例外:增量运行时范围内没生成 SPEC 的页面(`incomplete.scopeUnmatched` / `scope.unmatched`)是增量范围的结果、不是 SPEC 质量缺口,由 logic.finalize 的「增量范围」一节(`scope_report.mjs`)列进「跳过的内容」。`page-specgen` 同样带洞发布:`finalize` 只要发布出 `specs.json` 就 exit 0,partial 或 gate 失败把 `incomplete{areas,pages,failedShards,...}` 写入清单与 ledger,不写进最终报告,下游照常消费;只有“一个 SPEC 都没发布”才是节点失败。切换引擎 = 新 run。
174
175
 
@@ -215,6 +216,7 @@ node ${SKILLS_ROOT}/a2h-app-migrate/scripts/validate_workflow.mjs
215
216
  | `SKILL.md` | 执行器入口(本文件) |
216
217
  | `references/workflow.yaml` | **唯一权威:policy + DAG + invoke** |
217
218
  | `references/stage-map.md` | 产物真源 / CLI 契约表 |
219
+ | `references/host-rules.md` | **宿主终端规则(执行前必读)** |
218
220
  | `references/config.example.json` | 参数示例 |
219
221
  | `scripts/env_preflight.mjs` | 启动预检 / 客户一键自检(缺省填 work/run-dir/ui-info-root);调度固定串行 |
220
222
  | `scripts/infer_android_root.mjs` | 入口按 APK 路径前缀确定 Android 工程根(给定路径不是工程根时替换,预检前) |
@@ -238,6 +240,7 @@ node ${SKILLS_ROOT}/a2h-app-migrate/scripts/validate_workflow.mjs
238
240
  | `scripts/android_index.mjs` | discover.android_index:Android 侧 homegraph 索引只在这里建 / 同步一次(首次 init、不完整才 index、每次 sync;`--check` 只读核对),下游只读 |
239
241
  | `scripts/check_utg_static_done.mjs` | discover.utg_static 完成判定(本次 stage 全 0、未降级、跑到 Phase B、产物非残留;`next=resume` 补跑 `--resume`) |
240
242
  | `scripts/ensure_utg_snapshot.mjs` | discover.utg_snapshot:契约文件 sha256 一致则跳过拷贝,否则整树覆盖到 `${UTG_SNAPSHOT}` |
243
+ | `tools/dag.mjs` | 宿主侧包装脚本(自检 / 免引号 exec / 状态速查 / 只解析 JSON)。**不进 DAG 契约**,刻意放在 `scripts/` 之外,因此不属于 Runner 的完整性哈希(`INTEGRITY_DIRS = ["scripts"]`),增删它不会让进行中的 run 触发 `SKILL_FILES_CHANGED` |
241
244
 
242
245
  ---
243
246
 
@@ -264,6 +267,29 @@ node ${SKILLS_ROOT}/a2h-app-migrate/scripts/validate_workflow.mjs
264
267
 
265
268
  ---
266
269
 
270
+ ## 宿主侧辅助脚本(可选,`tools/dag.mjs`)
271
+
272
+ Windows / PowerShell 宿主上,手拼 `dag_runner.mjs` 命令行容易踩四类坑:shell 吃掉 `--vars` 的引号、
273
+ `Set-Content -Encoding UTF8` 写入的 BOM 让 `JSON.parse` 失败、把 `.md` 当 JSON 解析、把原生命令的 stderr
274
+ 当成崩溃。该脚本把这些坑固化掉,**只做宿主侧搬运,不改 DAG 语义**(拓扑、闸门、ledger、节点终态仍归 Runner)。
275
+
276
+ ```bash
277
+ node ${SKILLS_ROOT}/a2h-app-migrate/tools/dag.mjs selfcheck --hmos <HMOS>
278
+ node ${SKILLS_ROOT}/a2h-app-migrate/tools/dag.mjs exec <spec.json>
279
+ node ${SKILLS_ROOT}/a2h-app-migrate/tools/dag.mjs state --hmos <HMOS> [run-name]
280
+ node ${SKILLS_ROOT}/a2h-app-migrate/tools/dag.mjs json <dir>
281
+ ```
282
+
283
+ - `selfcheck`:Node ≥ 18、三个脚本齐全、`${HMOS}` 是 git 仓库根、工程形态(空目录 scaffold_new / 合法工程 existing_project / 否则 `invalid_nonempty`)、`.hometrans` 可写。**预检那两次 hard_stop 的根因就在这里**(未建仓;以及为建仓加的 `.gitignore` 让目录变成“非空且非法工程”)。自检通过后再跑 `run`,能省掉一轮预检失败。
284
+ - `exec`:读 `{"runner":"dag|executor","args":[...],"cwd?":"..."}`,用参数数组直接 spawn,不经过 shell;`run` / `continue` 自动补 `--workflow`。
285
+ - `state`:一句话看清 `status` / `current_node` / 各节点状态(只读)。
286
+ - `json`:只解析目录下的 `.json`,BOM 容错,适合核对 `attempts/` `production/`。
287
+
288
+ 约定:`--vars` 仍要按 DAG Runner 契约传**单个 JSON token**;用 shell 拼不出来时,把变量写进 JSON 文件再经 `exec` 的 spec 传入,不要用引号硬拼。
289
+ 不要把它放进 `scripts/`,也不要用它模拟 `before_run` / `after_run` / 闸门 `--write-confirmed`(这些归 Runner / 生产 executor)。
290
+
291
+ ---
292
+
267
293
  ## 何时不要用本 skill
268
294
 
269
295
  - 只跑单步 → 直接调用对应 a2h-* 叶子 skill(见 `env_preflight.mjs` 的 `CORE_SKILLS`)
@@ -0,0 +1,33 @@
1
+ # 宿主终端规则(执行 a2h-app-migrate 时必须加载)
2
+
3
+ ## 规则 1 —— shell 命令要注意编码
4
+
5
+ - Windows PowerShell 5.1 的 `Get-Content` / `Select-String` 默认按系统 ANSI(中文系统为 GBK)解码;本仓库文件都是 **UTF-8 无 BOM**,不指定编码就会显示成 `鈥�` `鍙跺瓙` 这类乱码,**但文件本身是完好的**。
6
+ - 用 shell 读/搜文本时显式指定 UTF-8:
7
+
8
+ ```powershell
9
+ Get-Content -LiteralPath <path> -Encoding UTF8
10
+ Select-String -LiteralPath <path> -Pattern <regex> -Encoding UTF8
11
+ [System.IO.File]::ReadAllText(<path>, [System.Text.Encoding]::UTF8)
12
+ ```
13
+
14
+ - 用 shell 写 `.json` 时同样要 UTF-8 无 BOM(executor / Runner 用 `JSON.parse` 读):
15
+
16
+ ```powershell
17
+ [System.IO.File]::WriteAllText($path, $json, (New-Object System.Text.UTF8Encoding($false)))
18
+ ```
19
+
20
+ - 看到乱码先按 UTF-8 复读一次确认是显示层问题,不要因此改文件;也不要把终端里复制出来的乱码文本写进 prompt、outcome 或产物。
21
+
22
+ ## 规则 2 —— PowerShell 5.1 的引号与转义
23
+
24
+ - PowerShell 的转义字符是反引号 `` ` ``,不是反斜杠。`\"` 不会转义引号,而是**提前闭合字符串**,后半截被当成额外位置参数,报
25
+ `找不到接受实际参数“...”的位置形式参数`(英文:`A positional parameter cannot be found that accepts argument ...`)。
26
+ - `Select-String` / `rg` 的 `-Pattern` 正则里需要引号时,整串用**单引号**包裹,内部直接用双引号:
27
+
28
+ ```powershell
29
+ Select-String -LiteralPath <path> -Pattern 'vars-file|"--vars"|options\.vars' -Encoding UTF8
30
+ ```
31
+
32
+ - 上述报错**不是**被查文件 / 被跑脚本的问题,只是当前这条命令没被 PowerShell 正确解析;换成单引号或改用 `-SimpleMatch` 重跑即可,不要去改工程文件或 skill 脚本。
33
+ - 需要传含引号的 JSON(如 `--vars`)时,不要用 shell 硬拼引号:写进 UTF-8 无 BOM 的 JSON 文件,再用参数数组直接 spawn(例如 `tools/dag.mjs exec`)。
@@ -37,7 +37,8 @@ policy:
37
37
  # SPEC_CONCURRENCY 传给 a2h-spec-generate 的 concurrency=(fused per-Area worker 的并发数),
38
38
  # **必须钳制到该上限**:超过 8 时取 8,非正整数时取默认 8。
39
39
  max_spec_generate_concurrency: 8
40
- default_task_type: generalPurpose
40
+ # 节点子 agent 的类型;宿主没有它时退回宿主内置通用子 agent(见 policy.dispatch)。
41
+ default_task_type: a2h-executor
41
42
  # 上下文长度由宿主压缩。模型不得把它当成停机条件。
42
43
  context_budget: |
43
44
  禁止模型因上下文预算主动结束。
@@ -182,22 +183,29 @@ policy:
182
183
  回调结果、进度清单、和用户对话;before_run / after_run、success 判定、ledger 归 Runner / 生产 executor。**不加载**任何叶子 skill,不读叶子 SKILL.md,不展开叶子内部 Stage / wave。
183
184
  · type: skill 的节点一律 dispatch: task_subagent:**派发一个**子 agent 跑完整个节点:
184
185
  discover.arch、discover.utg_static、ui.batch、enrich.spec_gen、enrich.module_docs、logic.spec_pipeline。
186
+ agent 类型固定用本插件的 a2h-executor(agents/a2h-executor.md:加载叶子 skill、跑到节点终态、前台等待、只回 JSON),
187
+ 不用宿主内置的通用 agent,这样节点层可以单独配置,宿主自带的 agent 不受影响。
188
+ 判定方式:直接按 a2h-executor 派发(宿主给插件 agent 加了命名空间前缀时,用它列出的全名,如 <插件名>:a2h-executor)。
189
+ 派发报错为未知 agent 类型 / agent 不存在 → 这不是节点失败:立即用宿主内置的通用子 agent、同一 task prompt 重派一次;
190
+ 回调 Runner 时 note 写成「fallback: general agent; <原 note>」。宿主遇到未知 agent 类型不报错、悄悄换成默认 agent 时,
191
+ 这里识别不到,也不会记退回。note 随 outcome 存进 <DAG_RUN_DIR>/attempts/<file_id>.result.json
192
+ (Runner 不写进 ledger),logic.finalize 从那里汇总,不靠主会话记忆。
185
193
  唯一例外:enrich.spec_gen 在 SPEC_ENGINE=spec-generate 时 primary_skill_inline(a2h-spec-generate 以"收到完成通知"
186
194
  判 worker 完成,没有前台等待模式;放进子 agent 会一结束本轮就返回)。
187
195
  · 调度仍串行,同一时刻只有一个节点子 agent 在跑:
188
196
  discover.arch → discover.utg_static(discover 段第 1、2 棒);
189
197
  ui.batch → review.ui_batch → enrich.spec_gen → enrich.module_docs;logic.spec_pipeline 在 adopt 之后。
190
198
  · 深度:节点子 agent 在 depth 1,叶子内部 worker(arch 的模块证据、utg_static 的 reviewer、ui.batch 的 conversion、
191
- page-specgen 的分组 worker、spec_pipeline 的 chunk / resolver / 评审)在 depth 2。宿主须允许 depth≥2(配置不由本 skill 管)。
199
+ page-specgen 的分组 worker、spec_pipeline 的 chunk / resolver / 评审)在 depth 2。宿主须允许 depth≥2(需要配置的宿主由平台适配层 Before Step 处理,如 opencode 写项目级配置)。
192
200
  primary 无法派发子 agent → 该节点退回 primary_skill_inline 照旧内联执行,最终报告注明。
193
- · 宿主嵌套深度只有 1(如 atomcode / trae、codebuddy IDE、qoder CLI):所有 type: skill 的节点一律 primary_skill_inline
201
+ · 宿主嵌套深度只有 1(如 atomcode / trae / trae-cn、codebuddy IDE、qoder-cn CLI、qoder 国际版):所有 type: skill 的节点一律 primary_skill_inline
194
202
  内联执行,不派节点子 agent——节点子 agent 无法再派发子 agent,叶子内部 worker 派不出去。
195
203
  · 子 agent 不得为等后台通知而结束本轮(结束即返回 primary,活没干完):
196
204
  a2h-page-specgen 传 wait_mode=foreground、a2h-spec-design-pipeline 传 WAIT_MODE=foreground(前台阻塞等 waker / wait);
197
205
  a2h-batch-ui-align(group_queue.mjs wait)、a2h-utg-static(reviewer 按同一协议前台 wait)、arch、module_docs 本来就前台等待。
198
206
  task prompt = 下面的通用头 + 该节点 invoke 全文。变量先在 primary 里替换成实际值,[… 仅当 …] 先求值,
199
207
  不适用的项删掉;不要把 ${…} 原样交给子 agent。通用头:
200
- 你是 a2h-app-migrate 派出的节点执行者,节点 <id>。先用 skill 工具加载 <叶子 skill>(完整阅读它的 SKILL.md),
208
+ 你是 a2h-app-migrate 派出的节点执行者(a2h-executor),节点 <id>。先用 skill 工具加载 <叶子 skill>(完整阅读它的 SKILL.md),
201
209
  再按下面的 invoke 执行到节点终态。
202
210
  · 上下文预算、上下文窗口、token 余量、会话变长或即将压缩,都不是结束理由。
203
211
  · 不直接问用户。invoke 里写"interactive → needs_input"的提问,本轮 INTERACTION_MODE=<值>:
@@ -214,6 +222,7 @@ policy:
214
222
  后台通知不是答复);用户答完,重派同一节点,task prompt 末尾追加「用户对「<question>」的答复:<原话>」。
215
223
  同一节点最多往返 3 次,之后按 auto 默认分支继续。
216
224
  3) 回调 Runner——**不信返回值**:outcome 一律写 ok:true,子 agent 自报的 ok / reason 原样放进 note
225
+ (退回了通用子 agent 时,note 写成「fallback: general agent; <原 note>」)
217
226
  (executor complete → Runner complete,见 SKILL.md「宿主处理等待与回调」)。after_run 由 executor 跑,完成由 Runner
218
227
  按节点 success 判定:success 不过 → 失败;子 agent 报 ok:false 但 success 通过 → 以 success 为准。
219
228
  子 agent 自己不调用 executor / Runner。
@@ -1999,6 +2008,12 @@ nodes:
1999
2008
  深度:pipeline 本身在 depth 1(migrate 派出的子 agent);它派发的设计 / 编码 / 评审 / 冲突解决 sub-agent 在 depth 2。
2000
2009
  事件循环(WAIT_MODE=foreground,references/coding-loop.md「Foreground wait mode」):B1/B2 派出后台 chunk 后
2001
2010
  **不结束本轮**,前台阻塞在 dispatch.mjs wait 上,返回后回到事件循环第 1 步;不派 waker 子 agent。
2011
+ 等待命令照抄,一次一条(shell 超时 600000 ms):
2012
+ 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
2013
+ 它一有新证据就返回,否则约 300 秒后返回(--max-wait 超过 300 压到 300,--poll 超过 30 压到 30):等待期间宿主收不到子 agent 的完成通知,
2014
+ 所以每次都要短。禁止自写等待 / 轮询 / sleep 脚本,禁止在一条 shell 里循环等待;
2015
+ 每个 chunk / resolver 都走台账(claim → intent → confirm),不在台账之前手改 spec_pipeline_state.json——
2016
+ wait 只看得见台账里的单元。
2002
2017
  只有 pipeline 走完全部 wave + 冒烟闸门 + Finalization(输出最终报告),或遇到它写明的硬停,才返回。
2003
2018
  交互(服从 ${INTERACTION_MODE}):
2004
2019
  · I4 公告:只公告、不停等(两种模式一致;I4 只是公告,没有要用户拍板的项)。公告正文放进返回 JSON 的
@@ -2109,6 +2124,11 @@ nodes:
2109
2124
  node ${SKILLS_ROOT}/a2h-app-migrate/scripts/scope_report.mjs --hmos ${HMOS} --scope-json ${SCOPE_JSON}
2110
2125
  --specs-json ${SPECS_JSON} --android ${ANDROID} --utg <同上的页面图> --work ${WORK} --lang zh
2111
2126
  它永不失败本节点;缺哪份输入就少哪部分。
2127
+ 节点派发方式(第 4 步其余内容——台账句和「增量范围」一节——都写完之后再写,作为报告的最后一行;
2128
+ 不插进 scope_report 的输出):只看本控制目录 <DAG_RUN_DIR>(续跑换了控制目录时,旧目录的记录不算)。每个 skill 节点取
2129
+ attempts/*.attempt.json 里 index 最大、status 为 done 或 failed 的那一次,读它的 result.json:
2130
+ evidence.host.note(ok:false 时为 details.note)以「fallback: general agent」开头 → 该节点算退回。
2131
+ 有退回的节点时,在报告末尾加一句"以下阶段没有用 a2h-executor,退回了宿主内置的通用子 agent:<各阶段 user_facing.name>";没有就不写。
2112
2132
  5. 报告落盘后只返回 ok|fail 与报告路径。不要自行追加 logic.finalize 终态或 run_end:
2113
2133
  Runner 先核对报告并提交唯一的 logic.finalize done,再执行全 DAG 完成度硬闸门并写唯一 run_end。
2114
2134
  assert 非零或证据不完整时由 Runner 阻止发证;宿主不得把阶段报告冒充完成证书。
@@ -0,0 +1,418 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * opencode_depth.mjs —— opencode 平台 Before Step:保证子 agent 嵌套深度 >= 2。
4
+ *
5
+ * migrate 需要两层嵌套(节点子 agent 在 depth 1,叶子内部 worker 在 depth 2)。opencode 默认只有 1 层,
6
+ * 由 `subagent_depth` 控制(实测):
7
+ * - v1(v1.19.6):两种写法都认——顶层 `"subagent_depth": 2` 或 `"experimental": { "subagent_depth": 2 }`;
8
+ * 不支持热更新,改完须重启会话。
9
+ * - v2(v2.4.2):只认 `"experimental": { "subagent_depth": 2 }`;支持热更新,改完即生效。
10
+ *
11
+ * 逻辑:
12
+ * 1. 版本:--version 优先,否则 `opencode --version`;取不到按 v1 处理(保守:要求重启)。
13
+ * 2. 生效深度按 opencode 的加载顺序算(见 configLayers:全局、OPENCODE_CONFIG、git 根到 cwd 的项目文件、
14
+ * .opencode 目录、系统托管目录、OPENCODE_CONFIG_CONTENT,后面覆盖前面),都没声明为 1。
15
+ * 3. 生效深度 >= 2 → 不动任何文件,继续。
16
+ * 4. 否则在 cwd 的项目级配置里只声明 `experimental.subagent_depth = 2`(v2 写法,v1 也认;文件已存在时只改这一项,
17
+ * 其它键原样保留)。v1 → next=restart(提示用户重启会话);v2 → next=continue(热更新)。
18
+ * next=manual(不写文件,让用户自己改):比项目文件更后加载的来源把深度定成了 < 2;项目级文件带注释或根不是对象;
19
+ * 设置了 OPENCODE_DISABLE_PROJECT_CONFIG。
20
+ * 写了文件时 report=true:主会话须在最终报告注明。只有本脚本新建、在 git 工作区且未被跟踪的文件才加入
21
+ * .git/info/exclude(带标记行),用户原有的文件不动 git。v1 重启后再跑时,生效值来自本脚本写的文件也带 report。
22
+ *
23
+ * node opencode_depth.mjs [--dir <项目目录,默认 cwd>] [--version <opencode 版本>]
24
+ *
25
+ * 输出一行 JSON;退出码 0 = 可以继续,2 = 须停下(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;取不到 → 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
+ /** 字符串字面量的结束下标(指向收尾引号);i 指向开头引号。 */
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
+ /** 去掉 // 与 /* *\/ 注释和尾随逗号(两步都跳过字符串内部),只用于读;写回只针对严格 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; // 尾随逗号
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
+ /** 一个配置对象声明的深度;v1 两种写法都认,v2 只认 experimental。未声明 → 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 或版本未知:顶层写法也认
91
+ const found = values.filter((v) => v !== null);
92
+ return found.length ? Math.max(...found) : null;
93
+ }
94
+
95
+ /** 读一个配置文件;不存在 → null。object=false 表示根不是对象(如 `[]`),无法写入。 */
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 的系统托管配置目录(与 opencode 源码一致)。 */
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", // Windows 上 opencode 是 .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
+ /** 真实路径(解析符号链接、Windows 8.3 短路径);失败时退回 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
+ /** 从 start 往上到 stop(含)的目录,近的在前;stop 为 null 时一直到文件系统根(同 opencode 的 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
+ * 按 opencode(v1.19.6 源码 Config.loadInstanceState / ConfigPaths)的加载顺序列出配置层,后面的覆盖前面的:
177
+ * 全局 config.json → opencode.json → opencode.jsonc;OPENCODE_CONFIG;
178
+ * 项目文件(git 根 → cwd,每层先 opencode.json 再 opencode.jsonc);
179
+ * .opencode 目录(cwd → git 根,然后 ~/.opencode、OPENCODE_CONFIG_DIR,每个先 json 再 jsonc);
180
+ * 系统托管目录;OPENCODE_CONFIG_CONTENT。
181
+ * OPENCODE_DISABLE_PROJECT_CONFIG 时跳过项目文件和项目内的 .opencode。
182
+ * 每层带 slot(加载次序),没有的文件也占位,便于判断“在 cwd 写入后会不会被更后面的层覆盖”。
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
+ /** 文件所在目录是否在 git 工作区、是否被跟踪。路径都让 git 在该目录里自己算,不拼绝对路径(避开符号链接和短路径)。 */
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
+ /** 本脚本是否曾把该文件写进 .git/info/exclude(带标记行)。 */
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
+ * 只对本脚本新建、在 git 工作区且未被跟踪的文件调用:追加到 .git/info/exclude(只在本地生效,不改用户的 .gitignore),
261
+ * 再用 git check-ignore 确认规则确实生效,生效才报 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}` : `环境变量 ${l.source}`);
280
+
281
+ /** 主逻辑;测试里注入 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 ? "保存即生效" : "然后重启 opencode 会话";
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 上一轮写完、用户重启后再跑:生效值来自本脚本写的文件时也要进最终报告。
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: `项目级配置 ${winner.file} 由本流程写入(experimental.subagent_depth=${REQUIRED_DEPTH}),已加入本仓库的 .git/info/exclude,不会被提交。`,
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,项目级配置不生效:请在全局配置 ${path.join(globalDir, "opencode.json")} 中加入 "experimental": { "subagent_depth": ${REQUIRED_DEPTH} },${restartTail}。`,
329
+ };
330
+ }
331
+
332
+ // 写在 cwd。同目录 opencode.jsonc 比 opencode.json 后加载:jsonc 声明了深度就只能改 jsonc;否则改已有的 json,
333
+ // 没有 json 时改已有的 jsonc,都没有就新建 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
+ // 更后加载的层声明了深度(此时必然 < 2)→ 写 cwd 也会被它覆盖,只能请用户改那里。
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: `生效深度来自 ${describe(later)}(subagent_depth=${later.depth}),它在项目级配置之后加载,写项目级配置无效:请把那里改为 >= ${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} 不是可直接改写的 JSON 对象(可能带注释),未自动改写:请在其中加入 "experimental": { "subagent_depth": ${REQUIRED_DEPTH} },${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 也认顶层写法:顶层写了更小的值时一并改掉,不留两个互相矛盾的声明。
366
+ if (typeof config.subagent_depth === "number" && config.subagent_depth < REQUIRED_DEPTH) config.subagent_depth = REQUIRED_DEPTH;
367
+ // 符号链接(如指向 dotfiles)写到真实文件上,不把链接换成普通文件。
368
+ writeJsonAtomic(target ? fs.realpathSync(file) : file, config);
369
+
370
+ const gitInfo = target ? gitStatusOf(file) : excludeCreated(file);
371
+ const gitNote = gitInfo.excluded
372
+ ? "已加入本仓库的 .git/info/exclude,不会被提交。"
373
+ : gitInfo.tracked
374
+ ? "该文件已被 git 跟踪,本次改动会出现在工作区里,请自行决定是否提交。"
375
+ : gitInfo.worktree
376
+ ? "这是用户原有、未被 git 跟踪的文件,本次只改了其中的深度,未加入 .git/info/exclude。"
377
+ : "";
378
+ const why = winner && winner.depth < REQUIRED_DEPTH ? `(原先生效的是 ${describe(winner)} 里的 ${winner.depth})` : "";
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
+ ? `已在项目级配置 ${file} 声明 experimental.subagent_depth=${REQUIRED_DEPTH}${why}(opencode v2 热更新,无需重启)。${gitNote}`
388
+ : `已在项目级配置 ${file} 声明 experimental.subagent_depth=${REQUIRED_DEPTH}${why}。opencode v1 不支持热更新:请退出并在该目录重新启动 opencode 会话,再重新输入原命令。${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
+ }