@deveco-test/deveco-cli-common 1.3.10-Test.2 → 1.3.11-Test.4

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 (223) hide show
  1. package/README.md +674 -52
  2. package/THIRD-PARTY-LICENSES +33 -3
  3. package/dist/cli.js +215 -167
  4. package/dist/design2arkts-engine/LICENSE +21 -0
  5. package/dist/design2arkts-engine/dist/index.d.ts +2739 -0
  6. package/dist/design2arkts-engine/dist/index.js +6207 -0
  7. package/dist/design2arkts-engine/package.json +40 -0
  8. package/dist/design2arkts-engine/pixso-arkts.mjs +98 -0
  9. package/dist/design2arkts-engine/resources/skill/LICENSE +21 -0
  10. package/dist/design2arkts-engine/resources/skill/SKILL.md +176 -0
  11. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkts-logic-completer/INSTRUCTIONS.md +310 -0
  12. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkts-logic-completer/evals/evals.json +249 -0
  13. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkts-logic-completer/references/basics-and-display.md +146 -0
  14. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkts-logic-completer/references/containers-and-navigation.md +527 -0
  15. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkts-logic-completer/references/feedback-and-overlay.md +275 -0
  16. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkts-logic-completer/references/hds-components.md +667 -0
  17. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkts-logic-completer/references/input-and-selection.md +382 -0
  18. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkts-logic-completer/references/patterns/data-and-form.md +440 -0
  19. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkts-logic-completer/references/patterns/state-management.md +213 -0
  20. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkui-scoring-workflow/INSTRUCTIONS.md +164 -0
  21. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkui2hds/INSTRUCTIONS.md +138 -0
  22. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkui2hds/references/components.md +777 -0
  23. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-arkui2hds/references/migration-patterns.md +187 -0
  24. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/INSTRUCTIONS.md +350 -0
  25. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-basic-mapping.md +455 -0
  26. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-common-issues.md +516 -0
  27. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/button.md +104 -0
  28. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/flex.md +115 -0
  29. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/grid.md +121 -0
  30. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/image.md +118 -0
  31. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/list.md +152 -0
  32. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/location.md +160 -0
  33. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/richeditor.md +132 -0
  34. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/row-column.md +118 -0
  35. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/stack.md +106 -0
  36. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/swiper.md +117 -0
  37. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/tabs.md +163 -0
  38. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/text-input.md +147 -0
  39. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/text.md +145 -0
  40. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/api-cards/waterflow.md +116 -0
  41. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/index.md +23 -0
  42. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/arkui-knowledge-base/matching.md +127 -0
  43. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-react-to-arkui/references/clarification-template.md +53 -0
  44. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-repo-understand/INSTRUCTIONS.md +163 -0
  45. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-repo-understand/references/architecture-patterns/api-architecture.md +17 -0
  46. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-repo-understand/references/architecture-patterns/data-architecture.md +17 -0
  47. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-repo-understand/references/architecture-patterns/logic-architecture.md +17 -0
  48. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-repo-understand/references/architecture-patterns/ui-architecture.md +23 -0
  49. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-repo-understand/references/methodology/behavior-audit.md +143 -0
  50. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-repo-understand/references/methodology/diff-analysis.md +115 -0
  51. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-repo-understand/references/methodology/dimension-identification.md +86 -0
  52. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-repo-understand/references/methodology/output-format.md +347 -0
  53. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-repo-understand/references/methodology/understanding-modes.md +214 -0
  54. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-responsive-layout-generator/INSTRUCTIONS.md +86 -0
  55. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-responsive-layout-generator/references/breakpoints.md +86 -0
  56. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-responsive-layout-generator/references/chunks.md +48 -0
  57. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-responsive-layout-generator/references/dsl-schema.md +151 -0
  58. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-responsive-layout-generator/references/patterns.md +147 -0
  59. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-responsive-layout-generator/references/rules.md +115 -0
  60. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-solution-design/INSTRUCTIONS.md +572 -0
  61. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-solution-design/assets/template-ui-page.md +293 -0
  62. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-solution-design/references/animation-design.md +84 -0
  63. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-ui-reconstruction-score/INSTRUCTIONS.md +195 -0
  64. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-ui-reconstruction-score/references/analysis_workflow.md +119 -0
  65. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-ui-reconstruction-score/references/scoring_schema.md +83 -0
  66. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-ui-reconstruction-score/references/vlm_prompt.md +61 -0
  67. package/dist/design2arkts-engine/resources/skill/references/capabilities/hmos-d2a-ui-reconstruction-score/scripts/ui_score.py +691 -0
  68. package/dist/design2arkts-engine/resources/skill/references/cli-integration.md +94 -0
  69. package/dist/design2arkts-engine/resources/skill/references/design-doc-auto-recovery.md +91 -0
  70. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/01-acquire-figma-react-source.md +96 -0
  71. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/02-convert-react-to-arkui.md +92 -0
  72. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/03-complete-interaction-logic.md +26 -0
  73. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/04-quality-and-build.md +43 -0
  74. package/dist/design2arkts-engine/resources/skill/references/figma/fast/stages/05-summary.md +36 -0
  75. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/01-acquire-figma-react-source.md +161 -0
  76. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/02-convert-react-to-arkui.md +219 -0
  77. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/03-complete-interaction-logic.md +31 -0
  78. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/04-quality-and-build.md +28 -0
  79. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/05-visual-calibration.md +190 -0
  80. package/dist/design2arkts-engine/resources/skill/references/figma/full/stages/06-summary.md +29 -0
  81. package/dist/design2arkts-engine/resources/skill/references/figma/stage-catalog-fast.json +40 -0
  82. package/dist/design2arkts-engine/resources/skill/references/figma/stage-catalog-full.json +47 -0
  83. package/dist/design2arkts-engine/resources/skill/references/host-vision.md +56 -0
  84. package/dist/design2arkts-engine/resources/skill/references/mcp-dependency.md +62 -0
  85. package/dist/design2arkts-engine/resources/skill/references/page-revisions.md +42 -0
  86. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/01-acquire-pixso-dsl.md +287 -0
  87. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/02-generate-skeleton-and-assets.md +245 -0
  88. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/03-understand-repository.md +133 -0
  89. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/05-design-component-tree.md +222 -0
  90. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/06-implement-static-layout.md +143 -0
  91. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/07-complete-interaction-logic.md +131 -0
  92. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/08-quality-build-and-audits.md +343 -0
  93. package/dist/design2arkts-engine/resources/skill/references/pixso/fast/stages/09-summary.md +103 -0
  94. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/01-acquire-pixso-dsl.md +287 -0
  95. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/02-generate-skeleton-and-assets.md +245 -0
  96. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/03-understand-repository.md +133 -0
  97. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/05-design-and-confirm-component-tree.md +282 -0
  98. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/06-implement-static-layout.md +143 -0
  99. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/07-complete-interaction-logic.md +131 -0
  100. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/08-quality-build-and-audits.md +343 -0
  101. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/09-visual-calibration.md +190 -0
  102. package/dist/design2arkts-engine/resources/skill/references/pixso/full/stages/10-summary.md +105 -0
  103. package/dist/design2arkts-engine/resources/skill/references/pixso/stage-catalog-fast.json +58 -0
  104. package/dist/design2arkts-engine/resources/skill/references/pixso/stage-catalog-full.json +64 -0
  105. package/dist/design2arkts-engine/resources/skill/references/requirement-clarification.md +131 -0
  106. package/dist/design2arkts-engine/resources/skill/references/resource-revisions.md +13 -0
  107. package/dist/design2arkts-engine/resources/skill/references/runtime-contract.md +435 -0
  108. package/dist/design2arkts-engine/resources/skill/references/score-engine.json +5 -0
  109. package/dist/design2arkts-engine/resources/skill/references/source-tools.md +17 -0
  110. package/dist/design2arkts-engine/resources/skill/references/standalone-capabilities.md +63 -0
  111. package/dist/design2arkts-engine/resources/skill/references/workflow-origin.json +96 -0
  112. package/dist/design2arkts-engine/resources/skill/scripts/file-lock.mjs +131 -0
  113. package/dist/design2arkts-engine/resources/skill/scripts/workflow.mjs +3672 -0
  114. package/dist/design2arkts-engine/runner.mjs +44 -0
  115. package/dist/internal/telemetry-upload-background.js +3 -3
  116. package/package.json +10 -5
  117. package/skills/deveco-cli/SKILL.md +144 -32
  118. package/skills/hmos-arkui-develop-skill/SKILL.md +77 -0
  119. package/skills/hmos-arkui-develop-skill/references/quick-apis/01-layout.md +634 -0
  120. package/skills/hmos-arkui-develop-skill/references/quick-apis/02-basic-components.md +649 -0
  121. package/skills/hmos-arkui-develop-skill/references/quick-apis/03-data-display.md +81 -0
  122. package/skills/hmos-arkui-develop-skill/references/quick-apis/04-selectors.md +109 -0
  123. package/skills/hmos-arkui-develop-skill/references/quick-apis/05-media.md +90 -0
  124. package/skills/hmos-arkui-develop-skill/references/quick-apis/06-advanced.md +32 -0
  125. package/skills/hmos-arkui-develop-skill/references/quick-apis/07-security.md +30 -0
  126. package/skills/hmos-arkui-develop-skill/references/quick-apis/08-state-decorators.md +120 -0
  127. package/skills/hmos-arkui-develop-skill/references/quick-apis/09-animation.md +118 -0
  128. package/skills/hmos-arkui-develop-skill/references/quick-apis/10-gesture.md +89 -0
  129. package/skills/hmos-arkui-develop-skill/references/quick-apis/11-dialog-menu.md +152 -0
  130. package/skills/hmos-arkui-develop-skill/references/quick-apis/12-navigation.md +127 -0
  131. package/skills/hmos-arkui-develop-skill/references/quick-apis/13-rendering.md +52 -0
  132. package/skills/hmos-arkui-develop-skill/references/quick-apis/14-extension.md +22 -0
  133. package/skills/hmos-arkui-develop-skill/references/quick-apis/15-theme-style.md +10 -0
  134. package/skills/hmos-arkui-develop-skill/references/quick-apis/16-enums.md +128 -0
  135. package/skills/hmos-arkui-develop-skill/references/quick-apis/17-resources.md +401 -0
  136. package/skills/hmos-arkui-develop-skill/references/quick-apis/18-error-code.md +24 -0
  137. package/skills/hmos-arkui-develop-skill/references/quick-apis/_index.md +76 -0
  138. package/skills/hmos-arkui-develop-skill/references/quick-rules/00-arkts-syntax.md +229 -0
  139. package/skills/hmos-arkui-develop-skill/references/quick-rules/01-import.md +116 -0
  140. package/skills/hmos-arkui-develop-skill/references/quick-rules/02-uicontext.md +56 -0
  141. package/skills/hmos-arkui-develop-skill/references/quick-rules/03-component.md +105 -0
  142. package/skills/hmos-arkui-develop-skill/references/quick-rules/04-build.md +41 -0
  143. package/skills/hmos-arkui-develop-skill/references/quick-rules/05-state.md +300 -0
  144. package/skills/hmos-arkui-develop-skill/references/quick-rules/06-rendering.md +67 -0
  145. package/skills/hmos-arkui-develop-skill/references/quick-rules/07-attribute-params.md +219 -0
  146. package/skills/hmos-arkui-develop-skill/references/quick-rules/08-navigation.md +102 -0
  147. package/skills/hmos-arkui-develop-skill/references/quick-rules/09-dialog.md +72 -0
  148. package/skills/hmos-arkui-develop-skill/references/quick-rules/10-style.md +90 -0
  149. package/skills/hmos-arkui-develop-skill/references/quick-rules/11-extension.md +54 -0
  150. package/skills/hmos-arkui-develop-skill/references/quick-rules/12-layout.md +69 -0
  151. package/skills/hmos-arkui-develop-skill/references/quick-rules/13-performance.md +27 -0
  152. package/skills/hmos-arkui-develop-skill/references/quick-rules/14-deprecated.md +28 -0
  153. package/skills/hmos-arkui-develop-skill/references/quick-rules/_index.md +79 -0
  154. package/skills/hmos-arkui-develop-skill/references/style-guide.md +491 -0
  155. package/skills/hmos-arkui-develop-skill/test-cases/code_gen_cases.json +292 -0
  156. package/skills/hmos-dfx-analyzer/SKILL.md +683 -0
  157. package/skills/hmos-dfx-analyzer/changelog/CHANGELOG.md +17 -0
  158. package/skills/hmos-dfx-analyzer/evals/evals.json +119 -0
  159. package/skills/hmos-dfx-analyzer/references/appfreeze/analyzer.md +471 -0
  160. package/skills/hmos-dfx-analyzer/references/appfreeze/references/fault-mode-library.md +94 -0
  161. package/skills/hmos-dfx-analyzer/references/appfreeze/references/ffrt-freeze-analysis.md +132 -0
  162. package/skills/hmos-dfx-analyzer/references/appfreeze/references/libuv-freeze-analysis.md +116 -0
  163. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/freeze/__init__.py +40 -0
  164. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/freeze/binder.py +343 -0
  165. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/freeze/collector.py +84 -0
  166. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/freeze/common.py +132 -0
  167. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/freeze/faultlog.py +212 -0
  168. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/freeze/main.py +81 -0
  169. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/freeze/report.py +675 -0
  170. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/freeze/sections.py +377 -0
  171. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/freeze/stack.py +165 -0
  172. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/llvm_addr2line.py +123 -0
  173. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/match_so.py +120 -0
  174. package/skills/hmos-dfx-analyzer/references/appfreeze/scripts/sample_stack_analyzer.py +209 -0
  175. package/skills/hmos-dfx-analyzer/references/cppcrash/analyzer.md +470 -0
  176. package/skills/hmos-dfx-analyzer/references/cppcrash/references/arkdata.md +325 -0
  177. package/skills/hmos-dfx-analyzer/references/cppcrash/references/arkui.md +266 -0
  178. package/skills/hmos-dfx-analyzer/references/cppcrash/references/arkweb.md +144 -0
  179. package/skills/hmos-dfx-analyzer/references/cppcrash/references/fault_mode.md +178 -0
  180. package/skills/hmos-dfx-analyzer/references/cppcrash/references/gwp_asan.md +300 -0
  181. package/skills/hmos-dfx-analyzer/references/cppcrash/references/jsruntime.md +339 -0
  182. package/skills/hmos-dfx-analyzer/references/cppcrash/references/jsvm.md +203 -0
  183. package/skills/hmos-dfx-analyzer/references/cppcrash/references/libuv.md +166 -0
  184. package/skills/hmos-dfx-analyzer/references/cppcrash/references/memory_corruption.md +348 -0
  185. package/skills/hmos-dfx-analyzer/references/cppcrash/references/memory_corruption_second_scene.md +74 -0
  186. package/skills/hmos-dfx-analyzer/references/cppcrash/references/multithreading.md +284 -0
  187. package/skills/hmos-dfx-analyzer/references/cppcrash/references/render_service.md +300 -0
  188. package/skills/hmos-dfx-analyzer/references/cppcrash/references/rosen_text.md +41 -0
  189. package/skills/hmos-dfx-analyzer/references/cppcrash/scripts/__init__.py +36 -0
  190. package/skills/hmos-dfx-analyzer/references/cppcrash/scripts/collector.py +93 -0
  191. package/skills/hmos-dfx-analyzer/references/cppcrash/scripts/common.py +68 -0
  192. package/skills/hmos-dfx-analyzer/references/cppcrash/scripts/crash_log.py +275 -0
  193. package/skills/hmos-dfx-analyzer/references/cppcrash/scripts/extract_hilog.py +69 -0
  194. package/skills/hmos-dfx-analyzer/references/cppcrash/scripts/hints.py +251 -0
  195. package/skills/hmos-dfx-analyzer/references/cppcrash/scripts/main.py +82 -0
  196. package/skills/hmos-dfx-analyzer/references/cppcrash/scripts/match_so.py +120 -0
  197. package/skills/hmos-dfx-analyzer/references/cppcrash/scripts/ohos_llvm_tools.py +279 -0
  198. package/skills/hmos-dfx-analyzer/references/cppcrash/scripts/report.py +226 -0
  199. package/skills/hmos-dfx-analyzer/references/jscrash/analyzer.md +174 -0
  200. package/skills/hmos-dfx-analyzer/references/jscrash/references/fault-mode-library.md +107 -0
  201. package/skills/hmos-dfx-analyzer/references/jscrash/references/jscrash-patterns.md +92 -0
  202. package/skills/hmos-dfx-analyzer/references/jscrash/references/sourcemap-symbolication.md +67 -0
  203. package/skills/hmos-dfx-analyzer/references/jscrash/scripts/hstack/bin/hstack +25 -0
  204. package/skills/hmos-dfx-analyzer/references/jscrash/scripts/hstack/bin/hstack.bat +26 -0
  205. package/skills/hmos-dfx-analyzer/references/jscrash/scripts/hstack/lib/index.js +2 -0
  206. package/skills/hmos-dfx-analyzer/references/jscrash/scripts/hstack/lib/index.js.LICENSE.txt +1 -0
  207. package/skills/hmos-dfx-analyzer/references/jscrash/scripts/hstack/lib/mappings.wasm +0 -0
  208. package/skills/hmos-dfx-analyzer/references/white-screen/analyzer.md +129 -0
  209. package/skills/hmos-dfx-analyzer/scripts/collect/collect-hilog.mjs +120 -0
  210. package/skills/hmos-dfx-analyzer/scripts/collect/jscrash-report.mjs +138 -0
  211. package/skills/hmos-dfx-analyzer/scripts/collect/parse-jscrash-log.mjs +126 -0
  212. package/skills/hmos-dfx-analyzer/scripts/collect/shared/deveco-cli.mjs +79 -0
  213. package/skills/hmos-dfx-analyzer/scripts/collect/shared/jscrash-parse.mjs +389 -0
  214. package/skills/hmos-dfx-analyzer/scripts/collect/shared/utils.mjs +27 -0
  215. package/skills/hmos-dfx-analyzer/scripts/export_report.py +373 -0
  216. package/skills/hmos-dfx-analyzer/scripts/identify_fault_log.py +500 -0
  217. package/skills/hmos-dfx-analyzer/scripts/report_template.html +103 -0
  218. package/skills/hmos-dfx-analyzer/test-cases/functional.md +112 -0
  219. package/skills/hmos-dfx-analyzer/test-cases/smoke.md +86 -0
  220. package/skills/hmos-dfx-analyzer/test-cases/test-prompts.md +35 -0
  221. package/skills/hmos-dfx-analyzer/test-cases/trigger.md +121 -0
  222. package/skills/index.json +17 -0
  223. package/src/resources/arkts-check.cjs +163 -1
@@ -0,0 +1,3672 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ * Copyright (c) 2026 Huawei Device Co., Ltd.
4
+ * SPDX-License-Identifier: MIT
5
+ */
6
+
7
+ import { acquireFileLock } from './file-lock.mjs';
8
+ import { createHash, randomUUID } from 'node:crypto';
9
+ import { lstatSync, realpathSync, rmSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
10
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ // Run files may be written by the host shell (PowerShell 5.1 UTF-8 emits a
14
+ // BOM); JSON.parse throws on a leading U+FEFF, so strip it before parsing.
15
+ function readJsonFile(path) {
16
+ const info = lstatSync(path);
17
+ if (!info.isFile() || info.size > 50 * 1024 * 1024 || realpathSync(path) !== resolve(path)) { fail('Expected a bounded regular JSON file without symlinks: ' + path); }
18
+ const raw = readFileSync(path, 'utf8')
19
+ return JSON.parse(raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw)
20
+ }
21
+
22
+ const DESIGN_DOC_RECOVERY_REQUEST = 'design-doc-recovery-request.json';
23
+
24
+ const VALID_MODES = new Set(['init', 'status', 'stage-start', 'confirm', 'stage-complete']);
25
+ const VALID_DECISIONS = new Set(['request', 'accepted', 'revision-requested']);
26
+ const VALID_RESULTS = new Set(['passed', 'blocked']);
27
+ const VALID_SOURCES = new Set(['pixso', 'figma']);
28
+ const VALID_REASON_CODES = new Set([
29
+ 'build_failed',
30
+ 'dependency_unavailable',
31
+ 'invalid_input',
32
+ 'missing_asset',
33
+ 'security_blocked',
34
+ 'evidence_invalid',
35
+ 'external_tool_failed',
36
+ ]);
37
+
38
+ function fail(message) {
39
+ process.stderr.write(`workflow: ${message}\n`);
40
+ process.exit(1);
41
+ }
42
+
43
+ function parseArgs(argv) {
44
+ const result = {};
45
+ for (let index = 0; index < argv.length; index += 1) {
46
+ const token = argv[index];
47
+ if (!token.startsWith('--')) {
48
+ fail(`unexpected argument: ${token}`);
49
+ }
50
+ const key = token.slice(2);
51
+ const value = argv[index + 1];
52
+ if (!value || value.startsWith('--')) {
53
+ fail(`missing value for --${key}`);
54
+ }
55
+ result[key] = value;
56
+ index += 1;
57
+ }
58
+ return result;
59
+ }
60
+
61
+ function readJson(path, label) {
62
+ try {
63
+ return readJsonFile(path);
64
+ } catch (error) {
65
+ fail(`${label} is missing or invalid JSON: ${path} (${error.message})`);
66
+ }
67
+ }
68
+
69
+ function readJsonOrNull(path, label, issues) {
70
+ if (!existsSync(path)) {
71
+ issues.push(`${label} is missing: ${path}`);
72
+ return null;
73
+ }
74
+ try {
75
+ return readJsonFile(path);
76
+ } catch (error) {
77
+ issues.push(`${label} is invalid JSON: ${path} (${error.message})`);
78
+ return null;
79
+ }
80
+ }
81
+
82
+ function writeJsonAtomic(path, value) {
83
+ assertWritablePath(path);
84
+ mkdirSync(dirname(path), { recursive: true });
85
+ const tmp = path + '.' + randomUUID() + '.tmp';
86
+ try {
87
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', flag: 'wx' });
88
+ renameSync(tmp, path);
89
+ } finally { rmSync(tmp, { force: true }); }
90
+ }
91
+
92
+ function hashFile(path) {
93
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
94
+ }
95
+
96
+ function gatePath(runDir, stage) {
97
+ return join(runDir, 'stage-gates', `stage${String(stage).padStart(2, '0')}-gate.json`);
98
+ }
99
+
100
+ function readGate(runDir, stage) {
101
+ const path = gatePath(runDir, stage);
102
+ if (!existsSync(path)) {
103
+ return null;
104
+ }
105
+ return readJson(path, `stage ${stage} gate`);
106
+ }
107
+
108
+ function isPassed(gate) {
109
+ return gate?.status === 'passed';
110
+ }
111
+
112
+ function resolveEvidencePath(runDir, value, label, issues) {
113
+ if (typeof value !== 'string' || value.length === 0) {
114
+ issues.push(`${label} path is missing`);
115
+ return null;
116
+ }
117
+ const path = resolve(runDir, value);
118
+ const pathFromRunDir = relative(runDir, path);
119
+ if (pathFromRunDir.startsWith('..') || isAbsolute(pathFromRunDir)) {
120
+ issues.push(`${label} must stay inside the run directory`);
121
+ return null;
122
+ }
123
+ return path;
124
+ }
125
+
126
+ function reportCheckPassed(report, name) {
127
+ if (report?.checks && !Array.isArray(report.checks)) {
128
+ return report.checks[name] === true;
129
+ }
130
+ if (Array.isArray(report?.checks)) {
131
+ const check = report.checks.find((item) => item?.name === name);
132
+ return check?.result === true || check?.result === 'pass' || check?.status === 'passed';
133
+ }
134
+ return false;
135
+ }
136
+
137
+ const FIGMA_COMPONENT_RECOGNITION_IMAGE = 'source/figma/component-recognition-screenshot.png';
138
+ const FIGMA_REFERENCE_SCREENSHOT = 'source/figma/reference-screenshot.png';
139
+
140
+ function collectFigmaComponentRecognitionEvidenceIssues(runDir) {
141
+ const issues = [];
142
+ const artifactPath = join(runDir, 'stage2', 'component-vision-analysis.json');
143
+ if (existsSync(artifactPath) && statSync(artifactPath).size > 2 * 1024 * 1024) {
144
+ issues.push(`stage 2 component recognition artifact exceeds the 2 MB limit: ${artifactPath}`);
145
+ return issues;
146
+ }
147
+ const artifact = readJsonOrNull(
148
+ artifactPath,
149
+ 'stage 2 component recognition artifact',
150
+ issues
151
+ );
152
+ if (!artifact) {
153
+ return issues;
154
+ }
155
+
156
+ const agentProduced = artifact.schemaVersion === 3;
157
+ if (![1, 2, 3].includes(artifact.schemaVersion)) {
158
+ issues.push('stage 2 component recognition artifact schemaVersion must equal 1, 2 or 3');
159
+ }
160
+ if (
161
+ (agentProduced
162
+ ? artifact.producer?.kind !== 'agent' ||
163
+ !isNonEmptyBoundedString(artifact.producer?.agent, 128) ||
164
+ !isNonEmptyBoundedString(artifact.producer?.tool, 256) ||
165
+ (artifact.producer?.model !== undefined &&
166
+ !isNonEmptyBoundedString(artifact.producer.model, 256))
167
+ : artifact.producer?.tool !== 'recognize_ui_components' ||
168
+ typeof artifact.producer?.model !== 'string' ||
169
+ artifact.producer.model.length === 0) ||
170
+ typeof artifact.producer?.invocationId !== 'string' ||
171
+ artifact.producer.invocationId.length === 0 ||
172
+ typeof artifact.producer?.createdAt !== 'string' ||
173
+ !Number.isFinite(Date.parse(artifact.producer.createdAt))
174
+ ) {
175
+ issues.push('stage 2 component recognition artifact producer metadata is invalid');
176
+ }
177
+ if (agentProduced && artifact.status !== 'ok') {
178
+ issues.push('stage 2 Agent component recognition requires a nonempty visual inventory');
179
+ }
180
+
181
+ if (artifact.schemaVersion === 2 && artifact.status !== 'ok' && artifact.status !== 'degraded') {
182
+ issues.push('stage 2 component recognition artifact status must be ok or degraded for schemaVersion 2');
183
+ }
184
+
185
+ if (artifact.inputs?.source !== undefined) {
186
+ issues.push('stage 2 component recognition must not include source input');
187
+ }
188
+
189
+ const image = artifact.inputs?.image;
190
+ const normalizedPath = typeof image?.path === 'string' ? image.path.replaceAll('\\', '/') : '';
191
+ if (
192
+ normalizedPath.length === 0 ||
193
+ (agentProduced && normalizedPath !== FIGMA_COMPONENT_RECOGNITION_IMAGE) ||
194
+ isAbsolute(normalizedPath) ||
195
+ normalizedPath.split('/').includes('..') ||
196
+ !normalizedPath.endsWith(FIGMA_COMPONENT_RECOGNITION_IMAGE)
197
+ ) {
198
+ if (normalizedPath.endsWith(FIGMA_REFERENCE_SCREENSHOT)) {
199
+ issues.push(
200
+ `stage 2 component recognition image must not use the 2x ${FIGMA_REFERENCE_SCREENSHOT}`
201
+ );
202
+ } else {
203
+ issues.push('stage 2 component recognition image path is invalid');
204
+ }
205
+ }
206
+ if (typeof image?.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(image.sha256)) {
207
+ issues.push('stage 2 component recognition image sha256 is invalid');
208
+ } else {
209
+ const expectedPath = join(runDir, ...FIGMA_COMPONENT_RECOGNITION_IMAGE.split('/'));
210
+ if (!existsSync(expectedPath) || !statSync(expectedPath).isFile()) {
211
+ issues.push(`stage 2 component recognition image input is missing: ${expectedPath}`);
212
+ } else if (hashFile(expectedPath) !== image.sha256) {
213
+ issues.push('stage 2 component recognition image sha256 does not match the current input');
214
+ }
215
+ }
216
+
217
+ const requirements = artifact.inputs?.requirements;
218
+ if (
219
+ typeof requirements?.text !== 'string' ||
220
+ (agentProduced && requirements.text !== 'Identify UI components') ||
221
+ requirements.text.length > 8000 ||
222
+ typeof requirements?.sha256 !== 'string' ||
223
+ sha256Text(requirements?.text ?? '') !== requirements?.sha256
224
+ ) {
225
+ issues.push('stage 2 component recognition requirements evidence is invalid');
226
+ }
227
+
228
+ const analysisError = validateComponentRecognitionAnalysis(artifact);
229
+ if (analysisError) {
230
+ issues.push(analysisError);
231
+ }
232
+ return issues;
233
+ }
234
+
235
+ function validateComponentRecognitionAnalysis(artifact) {
236
+ if (artifact.schemaVersion === 1) {
237
+ return isValidLegacyComponentRecognitionAnalysis(artifact.analysis)
238
+ ? null
239
+ : 'stage 2 component recognition analysis does not match the required schema';
240
+ }
241
+ if ([2, 3].includes(artifact.schemaVersion) && artifact.status === 'ok') {
242
+ return isValidComponentRecognitionInventory(artifact.analysis)
243
+ ? null
244
+ : 'stage 2 component recognition analysis does not match the required schema';
245
+ }
246
+ if (artifact.schemaVersion === 2 && artifact.status === 'degraded') {
247
+ return isValidComponentRecognitionDegraded(artifact)
248
+ ? null
249
+ : 'stage 2 component recognition degraded evidence does not match the required schema';
250
+ }
251
+ return 'stage 2 component recognition artifact schemaVersion or status is not supported';
252
+ }
253
+
254
+ function collectFigmaStage1EvidenceIssues(runDir, catalog, ctx = {}) {
255
+ const issues = [];
256
+ const manifest = readJsonOrNull(
257
+ join(runDir, 'inputs-manifest.json'),
258
+ 'stage 1 inputs manifest',
259
+ issues
260
+ );
261
+ if (!manifest) {
262
+ return issues;
263
+ }
264
+
265
+ const screenshots = manifest.screenshots;
266
+ if (!screenshots || typeof screenshots !== 'object') {
267
+ issues.push('stage 1 inputs manifest must record screenshots for the figma source');
268
+ return issues;
269
+ }
270
+
271
+ for (const [name, expectedPath, expectedPurpose, expectedScale] of [
272
+ ['reference', FIGMA_REFERENCE_SCREENSHOT, 'general-visual-reference', 2],
273
+ ['componentRecognition', FIGMA_COMPONENT_RECOGNITION_IMAGE, 'recognize-ui-components-only', 1]
274
+ ]) {
275
+ const entry = screenshots[name];
276
+ const normalizedPath =
277
+ typeof entry?.path === 'string' ? entry.path.replaceAll('\\', '/') : '';
278
+ if (
279
+ normalizedPath.length === 0 ||
280
+ isAbsolute(normalizedPath) ||
281
+ normalizedPath.split('/').includes('..') ||
282
+ normalizedPath !== expectedPath
283
+ ) {
284
+ issues.push(`stage 1 screenshot ${name} path must be ${expectedPath}`);
285
+ }
286
+ if (entry?.purpose !== expectedPurpose) {
287
+ issues.push(`stage 1 screenshot ${name} purpose must be ${expectedPurpose}`);
288
+ }
289
+ if (entry?.scale !== expectedScale) {
290
+ issues.push(`stage 1 screenshot ${name} scale must be ${expectedScale}`);
291
+ }
292
+ if (
293
+ !isPositiveBoundedNumber(entry?.width, 100000) ||
294
+ !isPositiveBoundedNumber(entry?.height, 100000) ||
295
+ typeof entry?.size !== 'number' ||
296
+ !Number.isFinite(entry.size) ||
297
+ entry.size <= 0
298
+ ) {
299
+ issues.push(`stage 1 screenshot ${name} dimensions and size must be positive numbers`);
300
+ }
301
+ if (typeof entry?.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(entry.sha256)) {
302
+ issues.push(`stage 1 screenshot ${name} sha256 is invalid`);
303
+ continue;
304
+ }
305
+ const filePath = join(runDir, ...expectedPath.split('/'));
306
+ if (!existsSync(filePath) || !statSync(filePath).isFile()) {
307
+ issues.push(`stage 1 screenshot ${name} file is missing: ${expectedPath}`);
308
+ } else if (hashFile(filePath) !== entry.sha256) {
309
+ issues.push(`stage 1 screenshot ${name} sha256 does not match the current file`);
310
+ }
311
+ }
312
+
313
+ const reference = screenshots.reference;
314
+ const componentRecognition = screenshots.componentRecognition;
315
+ if (
316
+ isPositiveBoundedNumber(reference?.width, 100000) &&
317
+ isPositiveBoundedNumber(reference?.height, 100000) &&
318
+ isPositiveBoundedNumber(componentRecognition?.width, 100000) &&
319
+ isPositiveBoundedNumber(componentRecognition?.height, 100000)
320
+ ) {
321
+ if (
322
+ reference.width !== componentRecognition.width * 2 ||
323
+ reference.height !== componentRecognition.height * 2
324
+ ) {
325
+ issues.push(
326
+ 'stage 1 screenshots must render the same target node: the 2x reference dimensions must be exactly twice the 1x component recognition dimensions'
327
+ );
328
+ }
329
+ }
330
+ issues.push(...collectFigmaStage1IntegrationIssues(runDir, catalog, manifest, ctx));
331
+ return issues;
332
+ }
333
+
334
+ const FIGMA_REQUIRED_SNAPSHOT_FIELDS = [
335
+ 'projectRootPath',
336
+ 'runIndexFile',
337
+ 'existingGeneratedPages',
338
+ 'existingGeneratedRoutes',
339
+ 'startupPageBefore',
340
+ 'defaultPageBefore',
341
+ 'indexPageFile',
342
+ 'entryAbilityFile',
343
+ 'mainPagesFile',
344
+ 'registrationMode',
345
+ ];
346
+
347
+ function figmaIntegrationSnapshotDigest(snapshot) {
348
+ const fields = [...FIGMA_REQUIRED_SNAPSHOT_FIELDS, 'mainPagesBefore'];
349
+ return sha256Text(JSON.stringify(fields.map((field) => snapshot[field])));
350
+ }
351
+
352
+ function collectFigmaIntegrationSnapshotLockIssues(runDir, snapshot, ctx) {
353
+ const gate = readGateOrNull(runDir, 1);
354
+ if (gate?.status !== 'passed') return [];
355
+ const digest = gate.integrationSnapshotSha256;
356
+ if (digest === undefined && ctx.requireIntegrationSnapshotLock !== true) {
357
+ return snapshot.startupPageBefore === 'pages/Index'
358
+ ? []
359
+ : ['legacy stage 1 has no locked startup snapshot; create a new run for a custom startup page'];
360
+ }
361
+ if (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest) ||
362
+ digest !== figmaIntegrationSnapshotDigest(snapshot)) {
363
+ return ['stage 1 integrationSnapshot differs from its Controller-locked startup snapshot'];
364
+ }
365
+ return [];
366
+ }
367
+
368
+ function collectFigmaStage1IntegrationIssues(runDir, catalog, manifest, ctx = {}) {
369
+ const issues = [];
370
+ const snapshot = manifest.integrationSnapshot;
371
+ if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) {
372
+ issues.push('stage 1 integrationSnapshot is missing');
373
+ return issues;
374
+ }
375
+ issues.push(...collectFigmaIntegrationSnapshotLockIssues(runDir, snapshot, ctx));
376
+ for (const field of FIGMA_REQUIRED_SNAPSHOT_FIELDS) {
377
+ if (snapshot[field] === undefined || snapshot[field] === null) {
378
+ issues.push(`stage 1 integrationSnapshot.${field} is missing`);
379
+ }
380
+ }
381
+ if (typeof snapshot.existingGeneratedPages !== 'object' || !Array.isArray(snapshot.existingGeneratedPages)) {
382
+ issues.push('stage 1 integrationSnapshot.existingGeneratedPages must be an array');
383
+ }
384
+ if (typeof snapshot.existingGeneratedRoutes !== 'object' || !Array.isArray(snapshot.existingGeneratedRoutes)) {
385
+ issues.push('stage 1 integrationSnapshot.existingGeneratedRoutes must be an array');
386
+ }
387
+ if ((ctx.requireIntegrationSnapshotLock === true && !Array.isArray(snapshot.mainPagesBefore)) ||
388
+ (Array.isArray(snapshot.mainPagesBefore) &&
389
+ !snapshot.mainPagesBefore.every((page) => typeof page === 'string' && page.trim()))) {
390
+ issues.push('stage 1 integrationSnapshot.mainPagesBefore must record the actual page configuration as a string array');
391
+ }
392
+ if (!FIGMA_VALID_REGISTRATION_MODES.has(snapshot.registrationMode)) {
393
+ issues.push('stage 1 integrationSnapshot.registrationMode must be index-navigation, route-table or existing-router');
394
+ }
395
+ // The global run-index is variant-scoped and shared between Figma and Pixso;
396
+ // a mismatched path would silently split or cross-read the wrong index.
397
+ const expectedRunIndexFile = skillIndexRelativePath(catalog.variant);
398
+ if (snapshot.runIndexFile !== expectedRunIndexFile) {
399
+ issues.push(
400
+ `stage 1 integrationSnapshot.runIndexFile must match the ${catalog.variant} workflow index path: ${expectedRunIndexFile}`
401
+ );
402
+ }
403
+
404
+ const projectRoot = resolveLockedProjectRoot(
405
+ runDir,
406
+ snapshot.projectRootPath,
407
+ 'stage 1 integrationSnapshot.projectRootPath',
408
+ issues
409
+ );
410
+ if (!projectRoot) {
411
+ return issues;
412
+ }
413
+ if (!isArkUIProject(projectRoot)) {
414
+ issues.push(`stage 1 integrationSnapshot.projectRootPath is not an ArkUI project (missing AppScope/app.json5 or entry/src/main/module.json5): ${snapshot.projectRootPath}`);
415
+ }
416
+
417
+ const appFiles = [
418
+ ['integrationSnapshot.indexPageFile', snapshot.indexPageFile, 'Index'],
419
+ ['integrationSnapshot.entryAbilityFile', snapshot.entryAbilityFile, 'EntryAbility'],
420
+ ['integrationSnapshot.mainPagesFile', snapshot.mainPagesFile, 'main_pages'],
421
+ ];
422
+ for (const [label, rel, humanLabel] of appFiles) {
423
+ const path = resolveProjectFile(projectRoot, rel, `stage 1 ${label}`, issues);
424
+ if (path && (!existsSync(path) || !statSync(path).isFile())) {
425
+ issues.push(`stage 1 ${humanLabel} file does not exist within projectRoot: ${rel}`);
426
+ }
427
+ }
428
+
429
+ const entryFile = readProjectFile(projectRoot, snapshot.entryAbilityFile, 'stage 1 integrationSnapshot.entryAbilityFile', issues);
430
+ const startupBefore = snapshot.startupPageBefore;
431
+ if (typeof startupBefore !== 'string' || !startupBefore.trim()) {
432
+ issues.push('stage 1 integrationSnapshot.startupPageBefore must identify the actual startup page');
433
+ }
434
+ if (ctx.live && entryFile.content !== null) {
435
+ const loaded = findLoadContentPage(entryFile.content);
436
+ if (loaded === null) {
437
+ issues.push('stage 1 EntryAbility must load the startup page through a loadContent string literal argument; the loaded page could not be determined');
438
+ } else if (loaded !== startupBefore) {
439
+ issues.push(`stage 1 EntryAbility actually loads "${loaded}", but integrationSnapshot.startupPageBefore is "${startupBefore}"`);
440
+ }
441
+ }
442
+
443
+ const mainPagesFile = readProjectFile(projectRoot, snapshot.mainPagesFile, 'stage 1 integrationSnapshot.mainPagesFile', issues);
444
+ if (ctx.live && mainPagesFile.content !== null) {
445
+ const src = parseMainPagesSrc(mainPagesFile.content);
446
+ if (src === null) {
447
+ issues.push('stage 1 main_pages.json is not valid JSON');
448
+ } else if (!src.includes(startupBefore)) {
449
+ issues.push(`stage 1 main_pages.json must contain ${startupBefore}`);
450
+ }
451
+ if (snapshot.mainPagesBefore !== undefined &&
452
+ (src === null || !Array.isArray(snapshot.mainPagesBefore) ||
453
+ sortedStringify(snapshot.mainPagesBefore) !== sortedStringify(src))) {
454
+ issues.push('stage 1 integrationSnapshot.mainPagesBefore must match the actual page configuration');
455
+ }
456
+ }
457
+
458
+ const declaredPages = Array.isArray(snapshot.existingGeneratedPages) ? snapshot.existingGeneratedPages : [];
459
+ const declaredRoutes = Array.isArray(snapshot.existingGeneratedRoutes) ? snapshot.existingGeneratedRoutes : [];
460
+ const { pages } = readRunIndexPages(projectRoot, snapshot.runIndexFile, issues);
461
+ // The snapshot describes the project state before this run started. Records
462
+ // legitimately added by the current run (stage 2 completion) are excluded from
463
+ // the comparison, but only after identity validation against the stage 2
464
+ // policy; anything else that differs from the snapshot is an error.
465
+ const stage2 = ctx.stage2 ?? null;
466
+ const declaredPageSet = new Set(declaredPages.map((page) => String(page)));
467
+ const isCurrentRunRecord = (page) =>
468
+ !!page && typeof page === 'object' &&
469
+ page.designSource === 'figma' && page.runId === stage2?.runId;
470
+ if (stage2 && stage2.scenario !== 'pre-commit' && stage2.identity) {
471
+ const comparablePages = pages.filter((page) => {
472
+ if (!isCurrentRunRecord(page)) return true;
473
+ // A record already covered by the snapshot is historical (runId collision),
474
+ // never a newly added current-run record.
475
+ if (declaredPageSet.has(String(page.pageFile ?? ''))) return true;
476
+ return !matchesFigmaStage2Identity(page, stage2.identity);
477
+ });
478
+ collectFigmaStage1PageComparisonIssues(projectRoot, comparablePages, declaredPages, declaredRoutes, issues);
479
+ } else {
480
+ if (stage2) {
481
+ for (const page of pages) {
482
+ if (isCurrentRunRecord(page) && !declaredPageSet.has(String(page.pageFile ?? ''))) {
483
+ issues.push(stage2.scenario === 'pre-commit'
484
+ ? 'run-index contains a record for the current run before stage 2 completion; the controller writes it during stage-complete 2'
485
+ : 'run-index contains a current-run record but the stage 2 target identity is unavailable; restore stage2/startup-page-policy.json');
486
+ }
487
+ }
488
+ }
489
+ collectFigmaStage1PageComparisonIssues(projectRoot, pages, declaredPages, declaredRoutes, issues);
490
+ }
491
+ return issues;
492
+ }
493
+
494
+ function collectFigmaStage1PageComparisonIssues(projectRoot, pages, declaredPages, declaredRoutes, issues) {
495
+ const actualPages = pages.map((page) => page?.pageFile);
496
+ const actualRoutes = pages.map((page) => page?.route);
497
+ if (sortedStringify(declaredPages) !== sortedStringify(actualPages)) {
498
+ issues.push('stage 1 integrationSnapshot.existingGeneratedPages does not match the real run-index');
499
+ }
500
+ if (sortedStringify(declaredRoutes) !== sortedStringify(actualRoutes)) {
501
+ issues.push('stage 1 integrationSnapshot.existingGeneratedRoutes does not match the real run-index');
502
+ }
503
+
504
+ for (const pageFile of actualPages) {
505
+ const path = resolveProjectFile(projectRoot, pageFile, 'stage 1 run-index historical page file', issues);
506
+ if (path && (!existsSync(path) || !statSync(path).isFile())) {
507
+ issues.push(`stage 1 historical generated page no longer exists: ${pageFile}`);
508
+ }
509
+ }
510
+ }
511
+
512
+ function sortedStringify(values) {
513
+ return JSON.stringify([...(values ?? [])].map((value) => String(value)).sort());
514
+ }
515
+
516
+ function sha256Text(value) {
517
+ return createHash('sha256').update(value, 'utf8').digest('hex');
518
+ }
519
+
520
+ const FIGMA_STAGE2_STARTUP_POLICY = 'stage2/startup-page-policy.json';
521
+ const FIGMA_STAGE2_GENERATED_MANIFEST = 'stage2/generated-ui-manifest.json';
522
+ const FIGMA_STAGE2_INITIAL_BUILD_REPORT = 'stage2/initial-build-report.json';
523
+ const FIGMA_VALID_REGISTRATION_MODES = new Set(['index-navigation', 'route-table', 'existing-router']);
524
+
525
+ function resolveLockedProjectRoot(runDir, value, label, issues) {
526
+ if (typeof value !== 'string' || value.length === 0) {
527
+ issues.push(`${label} is missing`);
528
+ return null;
529
+ }
530
+ const root = isAbsolute(value) ? resolve(value) : resolve(runDir, value);
531
+ if (!existsSync(root) || !statSync(root).isDirectory()) {
532
+ issues.push(`${label} is not an existing directory: ${value}`);
533
+ return null;
534
+ }
535
+ return root;
536
+ }
537
+
538
+ function isArkUIProject(projectRoot) {
539
+ return (
540
+ existsSync(join(projectRoot, 'AppScope', 'app.json5')) ||
541
+ existsSync(join(projectRoot, 'entry', 'src', 'main', 'module.json5'))
542
+ );
543
+ }
544
+
545
+ function stripArkTsComments(content) {
546
+ let result = '';
547
+ let index = 0;
548
+ const length = content.length;
549
+ while (index < length) {
550
+ const ch = content[index];
551
+ const next = content[index + 1];
552
+ if (ch === "'" || ch === '"' || ch === '`') {
553
+ const quote = ch;
554
+ result += ch;
555
+ index += 1;
556
+ while (index < length) {
557
+ if (content[index] === '\\') {
558
+ result += content[index] + (content[index + 1] ?? '');
559
+ index += 2;
560
+ continue;
561
+ }
562
+ result += content[index];
563
+ if (content[index] === quote) {
564
+ index += 1;
565
+ break;
566
+ }
567
+ index += 1;
568
+ }
569
+ } else if (ch === '/' && next === '/') {
570
+ while (index < length && content[index] !== '\n') index += 1;
571
+ } else if (ch === '/' && next === '*') {
572
+ index += 2;
573
+ while (index < length && !(content[index] === '*' && content[index + 1] === '/')) index += 1;
574
+ index += 2;
575
+ } else {
576
+ result += ch;
577
+ index += 1;
578
+ }
579
+ }
580
+ return result;
581
+ }
582
+
583
+ function hasArkTsDecorator(content, decorator) {
584
+ return new RegExp(`^\\s*@${decorator}\\b`, 'm').test(stripArkTsComments(content));
585
+ }
586
+
587
+ function isArkTsIdentifier(value) {
588
+ return typeof value === 'string' && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value);
589
+ }
590
+
591
+ function escapeRegExp(value) {
592
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
593
+ }
594
+
595
+ function hasDecoratedExportStruct(content, decorator, componentName) {
596
+ const stripped = stripArkTsComments(content);
597
+ const componentPattern = escapeRegExp(componentName);
598
+ const decl = new RegExp(`(^|[^\\w$])export\\s+struct\\s+${componentPattern}\\b`, 'm');
599
+ const match = decl.exec(stripped);
600
+ if (!match) return false;
601
+ const declIndex = match.index + match[1].length;
602
+ const after = stripped.slice(declIndex + `export struct ${componentName}`.length);
603
+ if (!/^\s*\{/.test(after)) return false;
604
+ // Walk backwards from the declaration over whitespace and other legal decorators.
605
+ // The target decorator must directly precede the export, possibly with other
606
+ // decorators, whitespace, or decorator argument lists in between.
607
+ let end = declIndex;
608
+ while (end > 0) {
609
+ // Skip trailing whitespace before the declaration
610
+ let start = end;
611
+ while (start > 0 && /\s/.test(stripped[start - 1])) start -= 1;
612
+ if (start === 0) return false;
613
+ // Expect a decorator (optionally with a balanced argument list) ending at `start`
614
+ const before = stripped.slice(0, start);
615
+ const decoratorMatch = /@[\w$]+(\s*\([^()]*\))?[\s]*$/.exec(before);
616
+ if (!decoratorMatch) return false;
617
+ const decoratorStart = start - decoratorMatch[0].length;
618
+ const nameOnly = /^@[\w$]+/.exec(decoratorMatch[0]);
619
+ if (nameOnly && nameOnly[0] === `@${decorator}`) return true;
620
+ end = decoratorStart;
621
+ }
622
+ return false;
623
+ }
624
+
625
+ function isComponentInstantiated(content, componentName) {
626
+ const stripped = stripArkTsComments(content);
627
+ return new RegExp(`(^|[^\\w$])${escapeRegExp(componentName)}\\s*\\(`).test(stripped);
628
+ }
629
+
630
+ function routeAndComponentRegisteredTogether(content, route, component) {
631
+ const stripped = stripArkTsComments(content);
632
+ const routePattern = escapeRegExp(route);
633
+ const componentPattern = escapeRegExp(component);
634
+ const pairPatterns = [
635
+ new RegExp(`['"]${routePattern}['"]\\s*:\\s*${componentPattern}\\b`),
636
+ new RegExp(`\\.set\\s*\\(\\s*['"]${routePattern}['"]\\s*,\\s*${componentPattern}\\b`),
637
+ new RegExp(`['"]${routePattern}['"]\\s*,\\s*${componentPattern}\\s*[,)]`),
638
+ new RegExp(`\\(\\s*\\{\\s*[^(){}]*['"]${routePattern}['"][^(){}]*${componentPattern}[^(){}]*\\}\\s*\\)`)
639
+ ];
640
+ return pairPatterns.some((pattern) => pattern.test(stripped));
641
+ }
642
+
643
+ const LOAD_CONTENT_CALL = 'loadContent';
644
+
645
+ // Extracts the page path when the first loadContent argument is a plain string
646
+ // literal followed by the argument separator or the closing parenthesis.
647
+ // Dynamic expressions, template literals, and string concatenations stay
648
+ // unresolved (null) instead of guessing a partial path.
649
+ function extractLoadContentFirstArgument(stripped, openParenIndex) {
650
+ let index = openParenIndex;
651
+ while (index < stripped.length && /\s/.test(stripped[index])) index += 1;
652
+ const quote = stripped[index];
653
+ if (quote !== "'" && quote !== '"') {
654
+ return null;
655
+ }
656
+ index += 1;
657
+ let value = '';
658
+ while (index < stripped.length) {
659
+ const ch = stripped[index];
660
+ if (ch === '\\') {
661
+ const escaped = stripped[index + 1];
662
+ if (escaped === undefined) {
663
+ return null;
664
+ }
665
+ value += escaped;
666
+ index += 2;
667
+ continue;
668
+ }
669
+ if (ch === quote) {
670
+ index += 1;
671
+ break;
672
+ }
673
+ value += ch;
674
+ index += 1;
675
+ if (value.length > 4096) {
676
+ return null;
677
+ }
678
+ }
679
+ if (index > stripped.length || stripped[index - 1] !== quote) {
680
+ return null;
681
+ }
682
+ let after = index;
683
+ while (after < stripped.length && /\s/.test(stripped[after])) after += 1;
684
+ if (after >= stripped.length || (stripped[after] !== ')' && stripped[after] !== ',')) {
685
+ return null;
686
+ }
687
+ return value;
688
+ }
689
+
690
+ // Scans comment-stripped source outside string literals so that example text
691
+ // inside comments or ordinary strings is never treated as a real call.
692
+ function findLoadContentPage(content) {
693
+ const stripped = stripArkTsComments(content);
694
+ const length = stripped.length;
695
+ let index = 0;
696
+ while (index < length) {
697
+ const ch = stripped[index];
698
+ if (ch === "'" || ch === '"' || ch === '`') {
699
+ const quote = ch;
700
+ index += 1;
701
+ while (index < length) {
702
+ if (stripped[index] === '\\') {
703
+ index += 2;
704
+ continue;
705
+ }
706
+ if (stripped[index] === quote) {
707
+ index += 1;
708
+ break;
709
+ }
710
+ index += 1;
711
+ }
712
+ continue;
713
+ }
714
+ if (
715
+ ch === 'l' &&
716
+ stripped.startsWith(LOAD_CONTENT_CALL, index) &&
717
+ (index === 0 || !/[A-Za-z0-9_$]/.test(stripped[index - 1]))
718
+ ) {
719
+ let parenIndex = index + LOAD_CONTENT_CALL.length;
720
+ while (parenIndex < length && /\s/.test(stripped[parenIndex])) parenIndex += 1;
721
+ if (parenIndex < length && stripped[parenIndex] === '(') {
722
+ return extractLoadContentFirstArgument(stripped, parenIndex + 1);
723
+ }
724
+ index += LOAD_CONTENT_CALL.length;
725
+ continue;
726
+ }
727
+ index += 1;
728
+ }
729
+ return null;
730
+ }
731
+
732
+ function parseMainPagesSrc(content) {
733
+ try {
734
+ const parsed = JSON.parse(stripArkTsComments(content));
735
+ const src = parsed?.src;
736
+ return Array.isArray(src) ? src : null;
737
+ } catch {
738
+ return null;
739
+ }
740
+ }
741
+
742
+ function readRunIndexPages(projectRoot, runIndexFileRel, issues) {
743
+ if (typeof runIndexFileRel !== 'string' || runIndexFileRel.length === 0) {
744
+ issues.push('run-index path is missing');
745
+ return { path: null, pages: [], exists: false };
746
+ }
747
+ const indexPath = resolve(projectRoot, runIndexFileRel);
748
+ const relFromRoot = relative(projectRoot, indexPath);
749
+ if (relFromRoot.startsWith('..') || isAbsolute(relFromRoot)) {
750
+ issues.push(`run-index path must stay within the project root: ${runIndexFileRel}`);
751
+ return { path: null, pages: [], exists: false };
752
+ }
753
+ if (!existsSync(indexPath)) {
754
+ return { path: indexPath, pages: [], exists: false };
755
+ }
756
+ if (!statSync(indexPath).isFile()) {
757
+ issues.push(`run-index is not a file: ${runIndexFileRel}`);
758
+ return { path: indexPath, pages: [], exists: false };
759
+ }
760
+ let parsed;
761
+ try {
762
+ parsed = readJsonFile(indexPath);
763
+ } catch (error) {
764
+ issues.push(`run-index is invalid JSON: ${runIndexFileRel} (${error.message})`);
765
+ return { path: indexPath, pages: [], exists: false };
766
+ }
767
+ if (!Array.isArray(parsed?.pages)) {
768
+ issues.push(`run-index pages must be an array: ${runIndexFileRel}`);
769
+ return { path: indexPath, pages: [], exists: false };
770
+ }
771
+ return { path: indexPath, pages: parsed.pages, exists: true };
772
+ }
773
+
774
+ function targetRegistrationFileOf(policy) {
775
+ if (typeof policy.targetRegistrationFile === 'string' && policy.targetRegistrationFile.length > 0) {
776
+ return policy.targetRegistrationFile;
777
+ }
778
+ if (policy.targetRegistrationMode === 'index-navigation') {
779
+ return policy.indexPageFile;
780
+ }
781
+ return undefined;
782
+ }
783
+
784
+ function resolveProjectFile(projectRoot, rel, label, issues) {
785
+ if (typeof rel !== 'string' || rel.length === 0) {
786
+ issues.push(`${label} is missing`);
787
+ return null;
788
+ }
789
+ const path = resolve(projectRoot, rel);
790
+ const relFromRoot = relative(projectRoot, path);
791
+ if (relFromRoot.startsWith('..') || isAbsolute(relFromRoot)) {
792
+ issues.push(`${label} must stay within the project root: ${rel}`);
793
+ return null;
794
+ }
795
+ return path;
796
+ }
797
+
798
+ function readProjectFile(projectRoot, rel, label, issues) {
799
+ const path = resolveProjectFile(projectRoot, rel, label, issues);
800
+ if (!path) {
801
+ return { path: null, content: null };
802
+ }
803
+ if (!existsSync(path) || !statSync(path).isFile()) {
804
+ issues.push(`${label} is missing: ${rel}`);
805
+ return { path, content: null };
806
+ }
807
+ return { path, content: readFileSync(path, 'utf8') };
808
+ }
809
+
810
+ // Stage 2 run-index validation scenarios, derived from persisted state and the
811
+ // stage 2 gate — never from caller-provided stage numbers or file timestamps.
812
+ // pre-commit: stage 2 not completed and no valid passed gate; the current-run
813
+ // record must not exist yet (the controller writes it).
814
+ // recovery: gate written (and for Full, confirmation accepted) but state not
815
+ // advanced; the interrupted stage-complete 2 may be replayed, so
816
+ // 0 or 1 identity-validated current records are allowed.
817
+ // completed: stage 2 in completedStages; exactly 1 current record is required
818
+ // and later stages may legitimately edit the page content, so the
819
+ // registered content hash is not re-compared.
820
+ function deriveFigmaStage2IndexContext(runDir, catalog, state) {
821
+ if ((catalog.designSource ?? 'pixso') !== 'figma') {
822
+ return null;
823
+ }
824
+ const runId = basename(runDir);
825
+ if (state.completedStages.includes(2)) {
826
+ return { scenario: 'completed', runId, identity: readFigmaStage2TargetIdentity(runDir) };
827
+ }
828
+ const gate = readGateOrNull(runDir, 2);
829
+ const stage2Confirmed = !requiresFigmaStage2Confirmation(catalog, 2) ||
830
+ (Array.isArray(state.confirmedStages) && state.confirmedStages.includes(2));
831
+ if (
832
+ Number(gate?.stage) === 2 &&
833
+ gate?.status === 'passed' &&
834
+ state.currentStage === 2 &&
835
+ state.status === 'running' &&
836
+ stage2Confirmed
837
+ ) {
838
+ return { scenario: 'recovery', runId, identity: readFigmaStage2TargetIdentity(runDir) };
839
+ }
840
+ return { scenario: 'pre-commit', runId, identity: null };
841
+ }
842
+
843
+ function readGateOrNull(runDir, stage) {
844
+ const path = gatePath(runDir, stage);
845
+ if (!existsSync(path)) {
846
+ return null;
847
+ }
848
+ try {
849
+ return readJsonFile(path);
850
+ } catch {
851
+ return null;
852
+ }
853
+ }
854
+
855
+ function readFigmaStage2TargetIdentity(runDir) {
856
+ const policyPath = join(runDir, FIGMA_STAGE2_STARTUP_POLICY);
857
+ if (!existsSync(policyPath) || !statSync(policyPath).isFile()) {
858
+ return null;
859
+ }
860
+ let policy;
861
+ try {
862
+ policy = readJsonFile(policyPath);
863
+ } catch {
864
+ return null;
865
+ }
866
+ const pageFile = typeof policy.targetPageFile === 'string' && policy.targetPageFile.length > 0
867
+ ? policy.targetPageFile.replaceAll('\\', '/')
868
+ : null;
869
+ const componentName = isArkTsIdentifier(policy.targetComponentName)
870
+ ? policy.targetComponentName
871
+ : null;
872
+ const route = typeof policy.targetRoute === 'string' && policy.targetRoute.length > 0
873
+ ? policy.targetRoute
874
+ : null;
875
+ if (!pageFile || !componentName || !route) {
876
+ return null;
877
+ }
878
+ return { pageFile, componentName, route };
879
+ }
880
+
881
+ function matchesFigmaStage2Identity(record, identity) {
882
+ return !!identity &&
883
+ String(record.pageFile ?? '').replaceAll('\\', '/') === identity.pageFile &&
884
+ record.componentName === identity.componentName &&
885
+ record.route === identity.route;
886
+ }
887
+
888
+ function collectFigmaRunIndexIssues(runDir, projectRoot, policy, targetComponentName, targetRoute, indexContext) {
889
+ const issues = [];
890
+ const runId = basename(runDir);
891
+ const { pages, exists } = readRunIndexPages(projectRoot, policy.runIndexFile, issues);
892
+ const pageFile = policy.targetPageFile;
893
+ const normalizedTargetPage = String(pageFile ?? '').replaceAll('\\', '/');
894
+ const scenario = indexContext?.scenario ?? 'pre-commit';
895
+
896
+ let contentSha256 = null;
897
+ const targetPath = resolveProjectFile(projectRoot, pageFile, 'stage 2 target page file hash', issues);
898
+ if (targetPath && existsSync(targetPath) && statSync(targetPath).isFile()) {
899
+ contentSha256 = hashFile(targetPath);
900
+ }
901
+
902
+ if (scenario === 'completed' && !exists) {
903
+ issues.push(`run-index is missing although stage 2 is completed: ${policy.runIndexFile}`);
904
+ }
905
+
906
+ const currentRecords = [];
907
+ for (const existing of pages) {
908
+ if (!existing || typeof existing !== 'object') {
909
+ continue;
910
+ }
911
+ const existingPage = String(existing.pageFile ?? '').replaceAll('\\', '/');
912
+ const existingPath = resolveProjectFile(projectRoot, existing.pageFile, 'run-index historical page file', issues);
913
+ if (existingPath && (!existsSync(existingPath) || !statSync(existingPath).isFile())) {
914
+ issues.push(`stage 2 historical generated page no longer exists: ${existing.pageFile}`);
915
+ }
916
+ if (typeof existing.registrationFile === 'string' && existing.registrationFile.length > 0) {
917
+ const regPath = resolveProjectFile(projectRoot, existing.registrationFile, 'run-index historical registration file', issues);
918
+ if (regPath && (!existsSync(regPath) || !statSync(regPath).isFile())) {
919
+ issues.push(`stage 2 historical registration file no longer exists: ${existing.registrationFile}`);
920
+ }
921
+ }
922
+
923
+ if (existing.designSource === 'figma' && existing.runId === runId) {
924
+ currentRecords.push(existing);
925
+ continue;
926
+ }
927
+
928
+ if (existingPage.length > 0 && existingPage === normalizedTargetPage) {
929
+ issues.push(`stage 2 target page file conflicts with an existing run: ${pageFile}`);
930
+ }
931
+ if (existing.componentName && existing.componentName === targetComponentName) {
932
+ issues.push(`stage 2 target component name conflicts with an existing run: ${targetComponentName}`);
933
+ }
934
+ if (existing.route && existing.route === targetRoute) {
935
+ issues.push(`stage 2 target route conflicts with an existing run: ${targetRoute}`);
936
+ }
937
+ }
938
+
939
+ const declaredPageSet = new Set(
940
+ (Array.isArray(indexContext?.declaredPages) ? indexContext.declaredPages : []).map((page) => String(page))
941
+ );
942
+ if (scenario === 'pre-commit') {
943
+ for (const record of currentRecords) {
944
+ if (declaredPageSet.has(String(record.pageFile ?? ''))) {
945
+ issues.push(`stage 2 runId ${runId} collides with a historical run-index record; use a new runId`);
946
+ } else {
947
+ issues.push('stage 2 run-index record for the current run must not exist before stage 2 completion; the controller writes it during stage-complete 2');
948
+ }
949
+ }
950
+ return issues;
951
+ }
952
+
953
+ const validCurrentRecords = [];
954
+ for (const record of currentRecords) {
955
+ if (declaredPageSet.has(String(record.pageFile ?? ''))) {
956
+ issues.push(`stage 2 runId ${runId} collides with a historical run-index record; use a new runId`);
957
+ continue;
958
+ }
959
+ if (!matchesFigmaStage2Identity(record, { pageFile: normalizedTargetPage, componentName: targetComponentName, route: targetRoute })) {
960
+ issues.push('stage 2 same run with a different target identity or content must use a new runId');
961
+ continue;
962
+ }
963
+ if (scenario === 'recovery' && record.contentSha256 !== contentSha256) {
964
+ // Replay consistency: gate and index are written but state has not
965
+ // advanced, so the submitted page content must still match the
966
+ // registered hash.
967
+ issues.push('stage 2 same run with a different target identity or content must use a new runId');
968
+ continue;
969
+ }
970
+ validCurrentRecords.push(record);
971
+ }
972
+ if (scenario === 'completed' && validCurrentRecords.length !== 1) {
973
+ issues.push('run-index must contain exactly one record for the current run after stage 2 completion');
974
+ }
975
+ if (scenario === 'recovery' && validCurrentRecords.length > 1) {
976
+ issues.push('run-index must contain at most one record for the current run during stage 2 recovery');
977
+ }
978
+ return issues;
979
+ }
980
+
981
+ function collectFigmaStartupPolicyIssues(projectRoot, policy, snapshot) {
982
+ const issues = [];
983
+ const startupPage = snapshot.startupPageBefore;
984
+ if (typeof startupPage !== 'string' || !startupPage.trim()) {
985
+ return ['stage 1 integrationSnapshot.startupPageBefore must identify the actual startup page'];
986
+ }
987
+ for (const field of ['startupPageBefore', 'startupPageAfter', 'entryAbilityLoadContentBefore', 'entryAbilityLoadContentAfter']) {
988
+ if (policy[field] !== startupPage) {
989
+ issues.push(`stage 2 ${field} must preserve stage 1 startup page ${startupPage}`);
990
+ }
991
+ }
992
+ const entryFile = readProjectFile(projectRoot, policy.entryAbilityFile, 'stage 2 entryAbilityFile', issues);
993
+ if (entryFile.content !== null && findLoadContentPage(entryFile.content) !== startupPage) {
994
+ issues.push(`stage 2 EntryAbility must still load ${startupPage} through a loadContent string literal`);
995
+ }
996
+ const mainPagesFile = readProjectFile(projectRoot, policy.mainPagesFile, 'stage 2 mainPagesFile', issues);
997
+ if (mainPagesFile.content !== null) {
998
+ const src = parseMainPagesSrc(mainPagesFile.content);
999
+ if (src === null) {
1000
+ issues.push('stage 2 main_pages.json must be valid JSON');
1001
+ } else {
1002
+ const expected = snapshot.mainPagesBefore ?? [startupPage];
1003
+ if (!Array.isArray(expected) || ![startupPage, ...expected].every((page) => src.includes(page))) {
1004
+ issues.push('stage 2 main_pages.json must preserve the stage 1 startup page and existing page registrations');
1005
+ }
1006
+ }
1007
+ }
1008
+ return issues;
1009
+ }
1010
+
1011
+ function collectFigmaStartupManifestIssues(startup, policy, snapshot) {
1012
+ const issues = [];
1013
+ if (startup?.indexFile !== policy.indexPageFile) {
1014
+ issues.push('stage 2 generated ui manifest startup.indexFile must match indexPageFile');
1015
+ }
1016
+ if (startup?.entryAbilityPage !== snapshot.startupPageBefore) {
1017
+ issues.push('stage 2 generated ui manifest startup.entryAbilityPage must match the stage 1 startup page');
1018
+ }
1019
+ const containsStartup = startup?.mainPagesContainsStartup ??
1020
+ (snapshot.startupPageBefore === 'pages/Index' ? startup?.mainPagesContainsIndex : undefined);
1021
+ if (containsStartup !== true) {
1022
+ issues.push('stage 2 generated ui manifest startup.mainPagesContainsStartup must be true');
1023
+ }
1024
+ return issues;
1025
+ }
1026
+
1027
+ function collectFigmaStage2RegistrationEvidenceIssues(runDir, ctx = {}) {
1028
+ const issues = [];
1029
+ const policy = readJsonOrNull(
1030
+ join(runDir, FIGMA_STAGE2_STARTUP_POLICY),
1031
+ 'stage 2 startup page policy',
1032
+ issues
1033
+ );
1034
+ if (!policy) {
1035
+ return issues;
1036
+ }
1037
+
1038
+ if (policy.preserveIndexEntry !== true) {
1039
+ issues.push('stage 2 startup page policy must set preserveIndexEntry=true');
1040
+ }
1041
+ if (policy.indexRole !== 'stable-navigation-shell') {
1042
+ issues.push('stage 2 startup page policy must set indexRole=stable-navigation-shell');
1043
+ }
1044
+ if (typeof policy.changeDefaultPage !== 'boolean') {
1045
+ issues.push('stage 2 startup page policy changeDefaultPage must be a boolean');
1046
+ }
1047
+ if (typeof policy.targetRegistrationMode !== 'string' ||
1048
+ !FIGMA_VALID_REGISTRATION_MODES.has(policy.targetRegistrationMode)) {
1049
+ issues.push('stage 2 startup page policy targetRegistrationMode must be one of index-navigation, route-table, existing-router');
1050
+ }
1051
+ for (const key of ['defaultPageBefore', 'defaultPageAfter']) {
1052
+ if (typeof policy[key] !== 'string') {
1053
+ issues.push(`stage 2 startup page policy ${key} must be a string`);
1054
+ }
1055
+ }
1056
+ if (typeof policy.projectType !== 'string' || !['template', 'business'].includes(policy.projectType)) {
1057
+ issues.push('stage 2 startup page policy projectType must be template or business');
1058
+ }
1059
+ if (typeof policy.userRequestedDefaultChange !== 'boolean') {
1060
+ issues.push('stage 2 startup page policy userRequestedDefaultChange must be a boolean');
1061
+ }
1062
+ const targetComponentName = policy.targetComponentName;
1063
+ if (typeof targetComponentName !== 'string' || targetComponentName.length === 0) {
1064
+ issues.push('stage 2 startup page policy targetComponentName is missing');
1065
+ }
1066
+ const validTargetComponentName = isArkTsIdentifier(targetComponentName);
1067
+ if (!validTargetComponentName) {
1068
+ issues.push('stage 2 startup page policy targetComponentName must be a valid ArkTS identifier');
1069
+ }
1070
+ const targetRoute = policy.targetRoute;
1071
+ if (typeof targetRoute !== 'string' || targetRoute.length === 0) {
1072
+ issues.push('stage 2 startup page policy targetRoute is missing');
1073
+ }
1074
+
1075
+ const projectRoot = resolveLockedProjectRoot(runDir, policy.projectRootPath, 'stage 2 startup page policy projectRootPath', issues);
1076
+ if (!projectRoot) {
1077
+ return issues;
1078
+ }
1079
+
1080
+ const inputsManifest = readJsonOrNull(
1081
+ join(runDir, 'inputs-manifest.json'),
1082
+ 'stage 1 inputs manifest',
1083
+ issues
1084
+ );
1085
+ const snapshot = inputsManifest?.integrationSnapshot;
1086
+ if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) {
1087
+ issues.push('stage 1 integrationSnapshot is missing; stage 2 cannot bind the target project');
1088
+ return issues;
1089
+ }
1090
+ const snapshotRoot = resolveLockedProjectRoot(runDir, snapshot.projectRootPath, 'stage 1 integrationSnapshot.projectRootPath', issues);
1091
+ if (!snapshotRoot) {
1092
+ return issues;
1093
+ }
1094
+ if (snapshotRoot !== projectRoot) {
1095
+ issues.push('stage 2 projectRootPath must equal stage 1 integrationSnapshot.projectRootPath');
1096
+ }
1097
+ for (const field of ['indexPageFile', 'entryAbilityFile', 'mainPagesFile', 'runIndexFile']) {
1098
+ if (String(policy[field] ?? '') !== String(snapshot[field] ?? '')) {
1099
+ issues.push(`stage 2 ${field} must equal stage 1 integrationSnapshot.${field}`);
1100
+ }
1101
+ }
1102
+ issues.push(...collectFigmaStartupPolicyIssues(projectRoot, policy, snapshot));
1103
+
1104
+ const indexFile = readProjectFile(projectRoot, policy.indexPageFile, 'stage 2 indexPageFile', issues);
1105
+ if (indexFile.content !== null && !hasArkTsDecorator(indexFile.content, 'Entry')) {
1106
+ issues.push('stage 2 index page must retain the startup @Entry decorator');
1107
+ }
1108
+
1109
+ const targetFile = readProjectFile(projectRoot, policy.targetPageFile, 'stage 2 targetPageFile', issues);
1110
+ if (targetFile.content !== null) {
1111
+ if (hasArkTsDecorator(targetFile.content, 'Entry')) {
1112
+ issues.push('stage 2 target page must not declare @Entry');
1113
+ }
1114
+ if (validTargetComponentName && !hasDecoratedExportStruct(targetFile.content, 'Component', targetComponentName)) {
1115
+ issues.push(`stage 2 target page must be a reusable @Component decorating export struct ${targetComponentName}`)
1116
+ }
1117
+ }
1118
+
1119
+ const registrationFileRel = targetRegistrationFileOf(policy);
1120
+ if (!registrationFileRel) {
1121
+ issues.push(`stage 2 ${policy.targetRegistrationMode} requires startup page policy targetRegistrationFile`);
1122
+ } else {
1123
+ const registrationFile = readProjectFile(projectRoot, registrationFileRel, 'stage 2 target registration file', issues);
1124
+ if (registrationFile.content !== null) {
1125
+ if (policy.targetRegistrationMode === 'index-navigation') {
1126
+ if (validTargetComponentName && !isComponentInstantiated(registrationFile.content, targetComponentName)) {
1127
+ issues.push('stage 2 index-navigation registration must instantiate the target component in the startup shell');
1128
+ }
1129
+ } else if (validTargetComponentName && !routeAndComponentRegisteredTogether(registrationFile.content, targetRoute, targetComponentName)) {
1130
+ issues.push(`stage 2 ${policy.targetRegistrationMode} registration must register the target route and component together`);
1131
+ }
1132
+ }
1133
+ }
1134
+
1135
+ issues.push(...collectFigmaRunIndexIssues(runDir, projectRoot, policy, targetComponentName, targetRoute, {
1136
+ scenario: ctx.stage2?.scenario ?? 'pre-commit',
1137
+ declaredPages: Array.isArray(snapshot.existingGeneratedPages) ? snapshot.existingGeneratedPages : null,
1138
+ }));
1139
+
1140
+ const uiManifest = readJsonOrNull(
1141
+ join(runDir, FIGMA_STAGE2_GENERATED_MANIFEST),
1142
+ 'stage 2 generated ui manifest',
1143
+ issues
1144
+ );
1145
+ if (uiManifest) {
1146
+ const page = uiManifest.page;
1147
+ const registration = uiManifest.registration;
1148
+ const startup = uiManifest.startup;
1149
+ if (typeof page?.file !== 'string' || page.file !== policy.targetPageFile) {
1150
+ issues.push('stage 2 generated ui manifest page.file must match startup page policy targetPageFile');
1151
+ }
1152
+ if (typeof page?.component !== 'string' || page.component !== targetComponentName) {
1153
+ issues.push('stage 2 generated ui manifest page.component must match targetComponentName');
1154
+ }
1155
+ if (page?.hasEntry !== false) {
1156
+ issues.push('stage 2 generated ui manifest page.hasEntry must be false');
1157
+ }
1158
+ if (typeof registration?.file !== 'string' || registration.file !== registrationFileRel) {
1159
+ issues.push('stage 2 generated ui manifest registration.file must match the target registration file');
1160
+ }
1161
+ if (typeof registration?.component !== 'string' || registration.component !== targetComponentName) {
1162
+ issues.push('stage 2 generated ui manifest registration.component must match targetComponentName');
1163
+ }
1164
+ if (typeof registration?.mode !== 'string' || registration.mode !== policy.targetRegistrationMode) {
1165
+ issues.push('stage 2 generated ui manifest registration.mode must match targetRegistrationMode');
1166
+ }
1167
+ if (typeof registration?.route !== 'string' || registration.route !== targetRoute) {
1168
+ issues.push('stage 2 generated ui manifest registration.route must match targetRoute');
1169
+ }
1170
+ if (registration?.default !== policy.changeDefaultPage) {
1171
+ issues.push('stage 2 generated ui manifest registration.default must match changeDefaultPage');
1172
+ }
1173
+ issues.push(...collectFigmaStartupManifestIssues(startup, policy, snapshot));
1174
+ }
1175
+
1176
+ const buildReport = readJsonOrNull(
1177
+ join(runDir, FIGMA_STAGE2_INITIAL_BUILD_REPORT),
1178
+ 'stage 2 initial build report',
1179
+ issues
1180
+ );
1181
+ if (buildReport) {
1182
+ if (buildReport.success !== true) {
1183
+ issues.push('stage 2 initial build report must record success=true');
1184
+ }
1185
+ if (typeof buildReport.command !== 'string' || buildReport.command.trim().length === 0) {
1186
+ issues.push('stage 2 initial build report must record a non-empty command');
1187
+ }
1188
+ if (buildReport.exitCode !== 0) {
1189
+ issues.push('stage 2 initial build report must record exitCode=0');
1190
+ }
1191
+ if (typeof buildReport.completedAt !== 'string' || !Number.isFinite(Date.parse(buildReport.completedAt))) {
1192
+ issues.push('stage 2 initial build report must record a valid completedAt timestamp');
1193
+ }
1194
+ }
1195
+
1196
+ if (policy.changeDefaultPage === true) {
1197
+ if (typeof policy.changeDefaultPageReason !== 'string' || policy.changeDefaultPageReason.length === 0) {
1198
+ issues.push('stage 2 must record changeDefaultPageReason when changing the default page');
1199
+ }
1200
+ const evidence = policy.defaultDecisionEvidence ?? {};
1201
+ const templateFirstRun = policy.projectType === 'template' &&
1202
+ evidence.templateHelloWorldOnly === true &&
1203
+ evidence.hasBusinessHome === false &&
1204
+ evidence.hasHistoricalGeneratedPages === false;
1205
+ if (!templateFirstRun && policy.userRequestedDefaultChange !== true) {
1206
+ issues.push('stage 2 must not change the default page unless it is the first generated page in a template project or the user explicitly requests it');
1207
+ }
1208
+ } else if (policy.changeDefaultPage === false && policy.defaultPageAfter !== policy.defaultPageBefore) {
1209
+ issues.push('stage 2 defaultPageAfter must equal defaultPageBefore when the default page is unchanged');
1210
+ }
1211
+
1212
+ return issues;
1213
+ }
1214
+
1215
+ function isCanonicalProjectRelativePath(value) {
1216
+ return typeof value === 'string' && !isAbsolute(value) && !/[\\:\0]/.test(value) &&
1217
+ value.split('/').every((part) => part.length > 0 && part !== '.' && part !== '..');
1218
+ }
1219
+ function readPixsoRoutePolicy(runDir, issues) {
1220
+ const report = readJsonOrNull(join(runDir, 'stage2/route-registration.json'), 'Pixso route registration', issues);
1221
+ if (!report) return null;
1222
+ if (report.schemaVersion !== 1 || report.projectRootPath !== metadata.projectRoot) issues.push('Pixso route registration must bind schemaVersion=1 and the CLI project root');
1223
+ for (const key of ['pageFile', 'componentName', 'route', 'registrationFile']) {
1224
+ if (typeof report[key] !== 'string' || report[key].length === 0) issues.push(`Pixso route registration ${key} is required`);
1225
+ }
1226
+ for (const key of ['pageFile', 'registrationFile']) {
1227
+ if (!isCanonicalProjectRelativePath(report[key])) issues.push(`Pixso route registration ${key} must be a canonical project-relative path without traversal or backslashes`);
1228
+ }
1229
+ if (!['index-navigation', 'route-table', 'existing-router', 'pages-profile'].includes(report.registrationMode)) issues.push('Pixso route registration mode is invalid');
1230
+ if (typeof report.default !== 'boolean') issues.push('Pixso route registration default must be boolean');
1231
+ if (!isArkTsIdentifier(report.componentName)) issues.push('Pixso component name is invalid');
1232
+ if (issues.length) return null;
1233
+ return {
1234
+ projectRootPath: metadata.projectRoot,
1235
+ runIndexFile: skillIndexRelativePath(metadata.variant),
1236
+ targetPageFile: report.pageFile,
1237
+ targetComponentName: report.componentName,
1238
+ targetRoute: report.route,
1239
+ targetRegistrationMode: report.registrationMode,
1240
+ targetRegistrationFile: report.registrationFile,
1241
+ changeDefaultPage: report.default,
1242
+ defaultChangeAuthorized: report.defaultChangeAuthorized === true,
1243
+ };
1244
+ }
1245
+ function readPixsoProjectEvidence(relativePath, label, issues) {
1246
+ const resolved = resolveProjectFile(metadata.projectRoot, relativePath, label, issues);
1247
+ if (!resolved) return null;
1248
+ if (!existsSync(resolved) || !lstatSync(resolved).isFile() || realpathSync(resolved) !== resolved) {
1249
+ issues.push(`${label} must be an existing regular project file without symlinks`);
1250
+ return null;
1251
+ }
1252
+ return readFileSync(resolved, 'utf8');
1253
+ }
1254
+ function collectPixsoRouteIssues(runDir) {
1255
+ const issues = [];
1256
+ const policy = readPixsoRoutePolicy(runDir, issues);
1257
+ if (!policy) return issues;
1258
+ const code = readPixsoProjectEvidence(policy.targetPageFile, 'Pixso page', issues);
1259
+ const registration = readPixsoProjectEvidence(policy.targetRegistrationFile, 'Pixso registration', issues);
1260
+ if (code !== null && (hasArkTsDecorator(code, 'Entry') || !hasDecoratedExportStruct(code, 'Component', policy.targetComponentName))) issues.push('Pixso target must export the requested @Component without @Entry');
1261
+ if (registration !== null) {
1262
+ if (policy.targetRegistrationMode === 'pages-profile') {
1263
+ const pages = parseMainPagesSrc(registration);
1264
+ if (!pages?.includes(policy.targetRoute)) issues.push('Pixso page route is missing from the pages profile');
1265
+ } else if (policy.targetRegistrationMode === 'index-navigation') {
1266
+ if (!isComponentInstantiated(registration, policy.targetComponentName) || !registration.includes(policy.targetRoute)) issues.push('Pixso Index must register the target route and component');
1267
+ } else if (!routeAndComponentRegisteredTogether(registration, policy.targetRoute, policy.targetComponentName)) issues.push('Pixso route and component are not registered together');
1268
+ }
1269
+ const { pages } = readRunIndexPages(metadata.projectRoot, policy.runIndexFile, issues);
1270
+ const records = pages.filter((page) => page.runId === basename(runDir) && page.designSource === 'pixso');
1271
+ for (const page of pages.filter((page) => !records.includes(page))) {
1272
+ if (page.pageFile === policy.targetPageFile || page.componentName === policy.targetComponentName || page.route === policy.targetRoute) issues.push('Pixso page, component or route conflicts with a historical run');
1273
+ }
1274
+ const state = readJson(join(runDir, 'workflow-state.json'), 'workflow-state');
1275
+ const gate = readGateOrNull(runDir, 2);
1276
+ if (records.length > 1 || (state.completedStages.includes(2) && records.length !== 1)) issues.push('Pixso route index must contain exactly one completed run record');
1277
+ for (const record of records) {
1278
+ if (!matchesFigmaStage2Identity(record, { pageFile: policy.targetPageFile, componentName: policy.targetComponentName, route: policy.targetRoute }) || record.registrationMode !== policy.targetRegistrationMode || record.registrationFile !== policy.targetRegistrationFile) issues.push('Pixso route index identity differs from its evidence');
1279
+ if (!state.completedStages.includes(2) && (!isPassed(gate) || (code !== null && record.contentSha256 !== sha256Text(code)))) issues.push('Pixso index was changed before stage completion or during recovery');
1280
+ }
1281
+ if (!state.completedStages.includes(2) && policy.changeDefaultPage && pages.some((page) => !records.includes(page)) && !policy.defaultChangeAuthorized) issues.push('Changing the historical default page requires explicit authorization');
1282
+ return issues;
1283
+ }
1284
+
1285
+ function updateRunIndex(runDir, projectRoot, policy) {
1286
+ const runIndexFileRel = policy.runIndexFile;
1287
+ const indexPath = resolve(projectRoot, runIndexFileRel);
1288
+ assertWritablePath(indexPath);
1289
+ let release;
1290
+ try {
1291
+ release = acquireFileLock(indexPath + '.lock');
1292
+ } catch (error) {
1293
+ fail(`cannot acquire run-index lock ${indexPath}.lock: ${error.message}`);
1294
+ }
1295
+ try {
1296
+ const existing = existsSync(indexPath)
1297
+ ? readJson(indexPath, 'route index')
1298
+ : { schemaVersion: 1, pages: [] };
1299
+ if (existing.schemaVersion !== 1 || !Array.isArray(existing.pages)) fail('Invalid route index; preserve and repair its history before retrying');
1300
+ const pages = existing.pages;
1301
+ const record = {
1302
+ designSource: metadata.designSource,
1303
+ runId: basename(runDir),
1304
+ pageFile: policy.targetPageFile,
1305
+ componentName: policy.targetComponentName,
1306
+ route: policy.targetRoute,
1307
+ registrationMode: policy.targetRegistrationMode,
1308
+ registrationFile: targetRegistrationFileOf(policy),
1309
+ default: policy.changeDefaultPage === true,
1310
+ contentSha256: hashFile(resolve(projectRoot, policy.targetPageFile)),
1311
+ };
1312
+ for (const previous of pages) {
1313
+ const same = previous.designSource === record.designSource && previous.runId === record.runId && previous.pageFile === record.pageFile;
1314
+ if (!same && (previous.pageFile === record.pageFile || previous.componentName === record.componentName || previous.route === record.route)) fail('Route index changed: historical page/component/route conflict');
1315
+ if (same && (previous.componentName !== record.componentName || previous.route !== record.route || previous.registrationFile !== record.registrationFile || previous.contentSha256 !== record.contentSha256)) fail('Route index changed: current run identity or content conflict');
1316
+ }
1317
+ if (record.default && pages.some((page) => page.runId !== record.runId || page.designSource !== record.designSource) && policy.defaultChangeAuthorized !== true && policy.userRequestedDefaultChange !== true) fail('Route index changed: changing the historical default needs explicit authorization');
1318
+ const index = pages.findIndex(
1319
+ (page) => page.designSource === record.designSource && page.runId === record.runId && page.pageFile === record.pageFile
1320
+ );
1321
+ if (index === -1) {
1322
+ pages.push(record);
1323
+ } else {
1324
+ pages[index] = record;
1325
+ }
1326
+ if (record.default) {
1327
+ for (const page of pages) {
1328
+ if (page !== record) {
1329
+ page.default = false;
1330
+ }
1331
+ }
1332
+ }
1333
+ writeJsonAtomic(indexPath, { schemaVersion: 1, pages });
1334
+ } finally { release(); }
1335
+ }
1336
+
1337
+ function isValidLegacyComponentRecognitionAnalysis(analysis) {
1338
+ if (
1339
+ !analysis ||
1340
+ typeof analysis !== 'object' ||
1341
+ !isPositiveBoundedNumber(analysis.canvas?.width, 100000) ||
1342
+ !isPositiveBoundedNumber(analysis.canvas?.height, 100000) ||
1343
+ !Array.isArray(analysis.regions) ||
1344
+ analysis.regions.length === 0 ||
1345
+ analysis.regions.length > 200 ||
1346
+ !isBoundedStringArray(analysis.global_observations, 100, 4000) ||
1347
+ !isBoundedStringArray(analysis.uncertainties, 100, 4000)
1348
+ ) {
1349
+ return false;
1350
+ }
1351
+ const ids = analysis.regions.map((region) => region?.id);
1352
+ if (
1353
+ ids.some((id) => !isNonEmptyBoundedString(id, 128)) ||
1354
+ new Set(ids).size !== ids.length
1355
+ ) {
1356
+ return false;
1357
+ }
1358
+ return analysis.regions.every((region) =>
1359
+ isNonEmptyBoundedString(region?.name, 4000) &&
1360
+ isNonEmptyBoundedString(region?.visual_evidence, 4000) &&
1361
+ isValidNormalizedBounds(region?.bounds) &&
1362
+ Array.isArray(region?.component_candidates) &&
1363
+ region.component_candidates.length > 0 &&
1364
+ region.component_candidates.length <= 10 &&
1365
+ region.component_candidates.every((candidate) =>
1366
+ isNonEmptyBoundedString(candidate?.name, 4000) &&
1367
+ ['arkui-native', 'custom', 'basic-layout', 'unknown'].includes(candidate?.category) &&
1368
+ isConfidence(candidate?.confidence) &&
1369
+ isNonEmptyBoundedString(candidate?.reason, 4000)
1370
+ ) &&
1371
+ isBoundedStringArray(region?.children, 100, 128) &&
1372
+ region.children.every((child) => child !== region.id && ids.includes(child)) &&
1373
+ isBoundedStringArray(region?.interaction_hints, 20, 4000) &&
1374
+ typeof region?.overlay === 'boolean' &&
1375
+ isConfidence(region?.confidence)
1376
+ );
1377
+ }
1378
+
1379
+ function isValidNormalizedBounds(bounds) {
1380
+ return bounds &&
1381
+ typeof bounds.x === 'number' && Number.isFinite(bounds.x) && bounds.x >= 0 && bounds.x <= 1000 &&
1382
+ typeof bounds.y === 'number' && Number.isFinite(bounds.y) && bounds.y >= 0 && bounds.y <= 1000 &&
1383
+ isPositiveBoundedNumber(bounds.width, 1000) &&
1384
+ isPositiveBoundedNumber(bounds.height, 1000) &&
1385
+ bounds.x + bounds.width <= 1000 &&
1386
+ bounds.y + bounds.height <= 1000;
1387
+ }
1388
+
1389
+ function isValidComponentRecognitionInventory(analysis) {
1390
+ if (
1391
+ !analysis ||
1392
+ typeof analysis !== 'object' ||
1393
+ !isPositiveBoundedNumber(analysis.canvas?.width, 100000) ||
1394
+ !isPositiveBoundedNumber(analysis.canvas?.height, 100000) ||
1395
+ !Array.isArray(analysis.visible_components) ||
1396
+ analysis.visible_components.length === 0 ||
1397
+ analysis.visible_components.length > 200 ||
1398
+ !isBoundedStringArray(analysis.global_observations, 100, 4000) ||
1399
+ !isBoundedStringArray(analysis.uncertainties, 100, 4000)
1400
+ ) {
1401
+ return false;
1402
+ }
1403
+ const ids = analysis.visible_components.map((component) => component?.id);
1404
+ if (
1405
+ ids.some((id) => !isNonEmptyBoundedString(id, 128)) ||
1406
+ new Set(ids).size !== ids.length
1407
+ ) {
1408
+ return false;
1409
+ }
1410
+ return analysis.visible_components.every((component) =>
1411
+ isNonEmptyBoundedString(component?.name, 4000) &&
1412
+ isNonEmptyBoundedString(component?.visual_evidence, 4000) &&
1413
+ Array.isArray(component?.component_candidates) &&
1414
+ component.component_candidates.length > 0 &&
1415
+ component.component_candidates.length <= 10 &&
1416
+ component.component_candidates.every((candidate) =>
1417
+ isNonEmptyBoundedString(candidate?.name, 4000) &&
1418
+ isConfidence(candidate?.confidence) &&
1419
+ isNonEmptyBoundedString(candidate?.reason, 4000)
1420
+ )
1421
+ );
1422
+ }
1423
+
1424
+ function isValidComponentRecognitionDegraded(artifact) {
1425
+ return artifact.analysis === null &&
1426
+ artifact.failure?.code === 'empty_components' &&
1427
+ artifact.failure?.attempts === 2 &&
1428
+ artifact.failure?.fallbackPolicy === 'ignore-visual-component-recognition';
1429
+ }
1430
+
1431
+ function isBoundedStringArray(value, maxItems, maxChars) {
1432
+ return Array.isArray(value) &&
1433
+ value.length <= maxItems &&
1434
+ value.every((item) => isNonEmptyBoundedString(item, maxChars));
1435
+ }
1436
+
1437
+ function isNonEmptyBoundedString(value, maxChars) {
1438
+ return typeof value === 'string' && value.length > 0 && value.length <= maxChars;
1439
+ }
1440
+
1441
+ function isPositiveBoundedNumber(value, max) {
1442
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= max;
1443
+ }
1444
+
1445
+ function isConfidence(value) {
1446
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1;
1447
+ }
1448
+
1449
+ const FIGMA_STAGE2_CONFIRMATION_FILES = [
1450
+ ['componentVisionAnalysis', 'stage2/component-vision-analysis.json'],
1451
+ ['componentAnalysis', 'stage2/component-analysis.md'],
1452
+ ['componentTree', 'component-tree.md'],
1453
+ ['designDoc', 'design-doc.md']
1454
+ ];
1455
+
1456
+ function buildFigmaStage2ConfirmationSnapshot(runDir, issues) {
1457
+ const files = {};
1458
+ for (const [name, relativePath] of FIGMA_STAGE2_CONFIRMATION_FILES) {
1459
+ const path = join(runDir, ...relativePath.split('/'));
1460
+ if (!existsSync(path) || !statSync(path).isFile()) {
1461
+ issues.push(`stage 2 confirmation file is missing: ${relativePath}`);
1462
+ continue;
1463
+ }
1464
+ const size = statSync(path).size;
1465
+ if (size === 0 || size > 2 * 1024 * 1024) {
1466
+ issues.push(`stage 2 confirmation file must be between 1 byte and 2 MB: ${relativePath}`);
1467
+ continue;
1468
+ }
1469
+ files[name] = {
1470
+ path: relativePath,
1471
+ sha256: hashFile(path)
1472
+ };
1473
+ }
1474
+ if (issues.length > 0) {
1475
+ return null;
1476
+ }
1477
+ return {
1478
+ stage: 2,
1479
+ files,
1480
+ createdAt: new Date().toISOString()
1481
+ };
1482
+ }
1483
+
1484
+ function collectFigmaStage2ConfirmationSnapshotIssues(runDir, state) {
1485
+ const issues = [];
1486
+ const snapshot = state.confirmationSnapshots?.['2'];
1487
+ if (!snapshot || snapshot.stage !== 2 || !snapshot.files) {
1488
+ return ['stage 2 confirmation snapshot is missing or invalid'];
1489
+ }
1490
+ for (const [name, relativePath] of FIGMA_STAGE2_CONFIRMATION_FILES) {
1491
+ const evidence = snapshot.files[name];
1492
+ if (
1493
+ evidence?.path !== relativePath ||
1494
+ typeof evidence?.sha256 !== 'string' ||
1495
+ !/^[a-f0-9]{64}$/.test(evidence.sha256)
1496
+ ) {
1497
+ issues.push(`stage 2 confirmation snapshot entry is invalid: ${name}`);
1498
+ continue;
1499
+ }
1500
+ const path = join(runDir, ...relativePath.split('/'));
1501
+ if (!existsSync(path) || !statSync(path).isFile() || statSync(path).size === 0) {
1502
+ issues.push(`stage 2 confirmed file is missing or empty: ${relativePath}`);
1503
+ } else if (hashFile(path) !== evidence.sha256) {
1504
+ issues.push(`stage 2 confirmed file changed after confirmation request: ${relativePath}`);
1505
+ }
1506
+ }
1507
+ return issues;
1508
+ }
1509
+
1510
+ function isFigmaStage2(catalog, stage) {
1511
+ return (catalog.designSource ?? 'pixso') === 'figma' && stage === 2;
1512
+ }
1513
+
1514
+ function requiresFigmaStage2Confirmation(catalog, stage) {
1515
+ return isFigmaStage2(catalog, stage) && catalog.stages.find((entry) => entry.id === stage)?.requiresConfirmation === true;
1516
+ }
1517
+
1518
+ // Stages whose authoritative output is design-doc.md. Figma Full keeps its
1519
+ // confirmation-snapshot validation and is intentionally excluded.
1520
+ function requiresDesignDocMissingGuard(catalog, stage) {
1521
+ const designSource = catalog.designSource ?? 'pixso';
1522
+ return (
1523
+ (designSource === 'figma' && catalog.variant === 'fast' && stage === 2) ||
1524
+ (designSource === 'pixso' && stage === 5)
1525
+ );
1526
+ }
1527
+
1528
+ function collectDesignDocEvidenceIssues(runDir) {
1529
+ const path = join(runDir, 'design-doc.md');
1530
+
1531
+ if (!existsSync(path)) {
1532
+ return ['design-doc.md is missing'];
1533
+ }
1534
+
1535
+ const stat = statSync(path);
1536
+ if (!stat.isFile()) {
1537
+ return ['design-doc.md must be a regular file'];
1538
+ }
1539
+
1540
+ if (stat.size === 0) {
1541
+ return ['design-doc.md is empty'];
1542
+ }
1543
+
1544
+ if (readFileSync(path, 'utf8').trim().length === 0) {
1545
+ return ['design-doc.md contains only whitespace'];
1546
+ }
1547
+
1548
+ return [];
1549
+ }
1550
+
1551
+ const DESIGN_DOC_RECOVERY_INSTRUCTION = 'references/design-doc-auto-recovery.md';
1552
+ const SOLUTION_DESIGN_SKILL = 'hmos-d2a-solution-design';
1553
+ const FIGMA_REACT_TO_ARKUI_RUN_STATE = 'stage2/hmos-d2a-react-to-arkui-run.json';
1554
+ const FIGMA_REACT_TO_ARKUI_PHASES = new Set([
1555
+ 'analyzing',
1556
+ 'awaiting_confirmation',
1557
+ 'implementing',
1558
+ 'validating',
1559
+ 'completed'
1560
+ ]);
1561
+ const FIGMA_REACT_TO_ARKUI_RESUME_FORBIDDEN_PHASES = new Set(['implementing', 'validating', 'completed']);
1562
+
1563
+ function designDocStage(catalog) {
1564
+ if ((catalog.designSource ?? 'pixso') === 'figma') return 2;
1565
+ return 5;
1566
+ }
1567
+
1568
+ function isNonEmptyFile(path) {
1569
+ if (!existsSync(path)) return false;
1570
+ const stat = statSync(path);
1571
+ return stat.isFile() && stat.size > 0;
1572
+ }
1573
+
1574
+ function isParseableJsonFile(path) {
1575
+ if (!isNonEmptyFile(path)) return false;
1576
+ try {
1577
+ readJsonFile(path);
1578
+ return true;
1579
+ } catch {
1580
+ return false;
1581
+ }
1582
+ }
1583
+
1584
+ function runDirRelativePath(runDir, relativePath) {
1585
+ return join(runDir, ...relativePath.split('/'));
1586
+ }
1587
+
1588
+ // The page DSL is located strictly through inputs-manifest.json pages[].dslPath.
1589
+ // Two path formats are accepted: a runDir-relative `source/...` path and a
1590
+ // repo-relative `.deveco/.../runs/{runId}/source/...` path that must start with
1591
+ // the manifest's own runDir. Scanning the source directory for any parseable
1592
+ // DSL is never a pass condition.
1593
+ function collectPixsoDslEntries(runDir) {
1594
+ const issues = [];
1595
+ const entries = [];
1596
+ const manifest = readJsonOrNull(
1597
+ join(runDir, 'inputs-manifest.json'),
1598
+ 'inputs manifest',
1599
+ issues
1600
+ );
1601
+ if (!manifest) {
1602
+ return { issues, entries };
1603
+ }
1604
+ if (!Array.isArray(manifest.pages) || manifest.pages.length === 0) {
1605
+ issues.push('inputs-manifest.json pages must be a non-empty array');
1606
+ return { issues, entries };
1607
+ }
1608
+ const manifestRunDir = typeof manifest.runDir === 'string' && manifest.runDir.length > 0
1609
+ ? manifest.runDir.replaceAll('\\', '/').replace(/\/+$/, '')
1610
+ : null;
1611
+ manifest.pages.forEach((page, index) => {
1612
+ const label = `inputs-manifest.json pages[${index}]` +
1613
+ (typeof page?.pageSlug === 'string' && page.pageSlug.length > 0 ? ` (${page.pageSlug})` : '');
1614
+ const rawPath = page?.dslPath;
1615
+ if (typeof rawPath !== 'string' || rawPath.length === 0) {
1616
+ issues.push(`${label} dslPath is missing`);
1617
+ return;
1618
+ }
1619
+ const normalized = rawPath.replaceAll('\\', '/');
1620
+ let candidate;
1621
+ if (normalized.startsWith('source/')) {
1622
+ candidate = normalized;
1623
+ } else if (manifestRunDir && normalized.startsWith(`${manifestRunDir}/`)) {
1624
+ candidate = normalized.slice(manifestRunDir.length + 1);
1625
+ if (!candidate.startsWith('source/')) {
1626
+ issues.push(`${label} dslPath must resolve into the run source directory: ${rawPath}`);
1627
+ return;
1628
+ }
1629
+ } else {
1630
+ issues.push(
1631
+ `${label} dslPath must be a source/... path or start with the manifest runDir (${manifestRunDir ?? 'missing'}): ${rawPath}`
1632
+ );
1633
+ return;
1634
+ }
1635
+ const resolved = resolve(runDir, candidate);
1636
+ const relFromRunDir = relative(runDir, resolved);
1637
+ if (relFromRunDir.startsWith('..') || isAbsolute(relFromRunDir)) {
1638
+ issues.push(`${label} dslPath escapes the run directory: ${rawPath}`);
1639
+ return;
1640
+ }
1641
+ entries.push({
1642
+ label,
1643
+ rawPath,
1644
+ relPath: relFromRunDir.replaceAll('\\', '/'),
1645
+ resolved,
1646
+ expectedSha256: typeof page?.dslSha256 === 'string' ? page.dslSha256 : undefined
1647
+ });
1648
+ });
1649
+ return { issues, entries };
1650
+ }
1651
+
1652
+ function pixsoDslIssues(runDir) {
1653
+ const { issues, entries } = collectPixsoDslEntries(runDir);
1654
+ for (const entry of entries) {
1655
+ if (!existsSync(entry.resolved)) {
1656
+ issues.push(`${entry.label} DSL file is missing: ${entry.rawPath}`);
1657
+ continue;
1658
+ }
1659
+ const stat = statSync(entry.resolved);
1660
+ if (!stat.isFile()) {
1661
+ issues.push(`${entry.label} DSL file is not a regular file: ${entry.rawPath}`);
1662
+ continue;
1663
+ }
1664
+ if (stat.size === 0) {
1665
+ issues.push(`${entry.label} DSL file is empty: ${entry.rawPath}`);
1666
+ continue;
1667
+ }
1668
+ try {
1669
+ readJsonFile(entry.resolved);
1670
+ } catch (error) {
1671
+ issues.push(`${entry.label} DSL file is not valid JSON: ${entry.rawPath} (${error.message})`);
1672
+ continue;
1673
+ }
1674
+ if (entry.expectedSha256 !== undefined) {
1675
+ if (!/^[a-f0-9]{64}$/.test(entry.expectedSha256)) {
1676
+ issues.push(`${entry.label} dslSha256 must be 64 lowercase hex characters`);
1677
+ } else if (hashFile(entry.resolved) !== entry.expectedSha256) {
1678
+ issues.push(`${entry.label} dslSha256 does not match the DSL file: ${entry.rawPath}`);
1679
+ }
1680
+ }
1681
+ }
1682
+ return issues;
1683
+ }
1684
+
1685
+ function missingNonEmptyInputs(runDir, relativePaths) {
1686
+ return relativePaths
1687
+ .filter((relativePath) => !isNonEmptyFile(runDirRelativePath(runDir, relativePath)))
1688
+ .map((relativePath) => `${relativePath} is missing or empty`);
1689
+ }
1690
+
1691
+ function missingParseableJsonInputs(runDir, relativePaths) {
1692
+ return relativePaths
1693
+ .filter((relativePath) => !isParseableJsonFile(runDirRelativePath(runDir, relativePath)))
1694
+ .map((relativePath) => `${relativePath} is missing or not parseable`);
1695
+ }
1696
+
1697
+ // Authoritative inputs that let hmos-d2a-solution-design rebuild only the
1698
+ // missing design-doc.md for a Pixso run.
1699
+ function pixsoRestoreDocumentInputIssues(runDir) {
1700
+ return [
1701
+ ...missingNonEmptyInputs(runDir, ['component-tree.md']),
1702
+ ...missingParseableJsonInputs(runDir, ['requirement-clarification.json']),
1703
+ ...pixsoDslIssues(runDir),
1704
+ ...missingParseableJsonInputs(runDir, [
1705
+ 'hds-decision.json',
1706
+ 'startup-page-policy.json',
1707
+ 'system-ui-policy.json',
1708
+ 'viewport-boundary-spec.json',
1709
+ 'system-ui-coordinate-normalization.json',
1710
+ 'safe-area-unit-contract.json'
1711
+ ])
1712
+ ];
1713
+ }
1714
+
1715
+ // Stage 1-3 upstream inputs that let the Pixso stage 5 solution-design subflow
1716
+ // run again from its documented entry point.
1717
+ function pixsoUpstreamInputIssues(runDir) {
1718
+ const issues = [
1719
+ ...missingParseableJsonInputs(runDir, ['requirement-clarification.json']),
1720
+ ...pixsoDslIssues(runDir),
1721
+ ...missingParseableJsonInputs(runDir, [
1722
+ 'stage2/image-assets-manifest.json',
1723
+ 'stage3-repo-understand-report.json'
1724
+ ])
1725
+ ];
1726
+ const generatedDir = runDirRelativePath(runDir, 'stage2/generated');
1727
+ const hasSkeleton = existsSync(generatedDir) &&
1728
+ statSync(generatedDir).isDirectory() &&
1729
+ readdirSync(generatedDir).some((name) => name.endsWith('.ets'));
1730
+ if (!hasSkeleton) {
1731
+ issues.push('stage2/generated/ contains no generated page skeleton');
1732
+ }
1733
+ return issues;
1734
+ }
1735
+
1736
+ // Authoritative products that must all survive for a Figma "document-only"
1737
+ // restore; if any is missing the assessment falls through to the resume path.
1738
+ function figmaRestoreDocumentInputIssues(runDir) {
1739
+ return [
1740
+ ...missingNonEmptyInputs(runDir, [
1741
+ 'source/figma/page.jsx',
1742
+ 'source/figma/reference-screenshot.png',
1743
+ 'stage2/project-analysis.md',
1744
+ 'stage2/component-analysis.md',
1745
+ 'component-tree.md'
1746
+ ]),
1747
+ ...missingParseableJsonInputs(runDir, [
1748
+ 'system-ui-policy.json',
1749
+ 'viewport-boundary-spec.json',
1750
+ 'requirement-clarification.json'
1751
+ ])
1752
+ ];
1753
+ }
1754
+
1755
+ // Validates the persisted hmos-d2a-react-to-arkui run state. The in-run resume
1756
+ // keeps the historical restriction (the design generation must not have
1757
+ // finished); design-only recovery may read a run state that already advanced
1758
+ // past design generation but never one parked on a confirmation wait.
1759
+ const FIGMA_REACT_TO_ARKUI_DESIGN_ONLY_FORBIDDEN_PHASES = new Set(['awaiting_confirmation']);
1760
+
1761
+ function figmaRunStateIssues(runDir, options = {}) {
1762
+ const designOnlyRecovery = options.designOnlyRecovery === true;
1763
+ const runStatePath = runDirRelativePath(runDir, FIGMA_REACT_TO_ARKUI_RUN_STATE);
1764
+ if (!isNonEmptyFile(runStatePath)) {
1765
+ return [`${FIGMA_REACT_TO_ARKUI_RUN_STATE} is missing or empty`];
1766
+ }
1767
+ let runState;
1768
+ try {
1769
+ runState = readJsonFile(runStatePath);
1770
+ } catch {
1771
+ return [`${FIGMA_REACT_TO_ARKUI_RUN_STATE} is not valid JSON`];
1772
+ }
1773
+ if (typeof runState?.invocationId !== 'string' || runState.invocationId.length === 0) {
1774
+ return [`${FIGMA_REACT_TO_ARKUI_RUN_STATE} invocationId is missing`];
1775
+ }
1776
+ if (!runState.inputs || typeof runState.inputs !== 'object' || Array.isArray(runState.inputs)) {
1777
+ return [`${FIGMA_REACT_TO_ARKUI_RUN_STATE} inputs are missing`];
1778
+ }
1779
+ const pageJsxHash = runState.inputs.pageJsx;
1780
+ if (typeof pageJsxHash !== 'string' || !/^[a-f0-9]{64}$/.test(pageJsxHash)) {
1781
+ return [
1782
+ `${FIGMA_REACT_TO_ARKUI_RUN_STATE} inputs.pageJsx must be the 64-char lowercase SHA-256 of source/figma/page.jsx`
1783
+ ];
1784
+ }
1785
+ const pageJsxPath = runDirRelativePath(runDir, 'source/figma/page.jsx');
1786
+ if (!isNonEmptyFile(pageJsxPath) || hashFile(pageJsxPath) !== pageJsxHash) {
1787
+ return [`${FIGMA_REACT_TO_ARKUI_RUN_STATE} inputs.pageJsx does not match the current source/figma/page.jsx`];
1788
+ }
1789
+ if (!FIGMA_REACT_TO_ARKUI_PHASES.has(runState.phase)) {
1790
+ return [`${FIGMA_REACT_TO_ARKUI_RUN_STATE} phase is invalid`];
1791
+ }
1792
+ if (designOnlyRecovery) {
1793
+ if (FIGMA_REACT_TO_ARKUI_DESIGN_ONLY_FORBIDDEN_PHASES.has(runState.phase)) {
1794
+ return [
1795
+ `${FIGMA_REACT_TO_ARKUI_RUN_STATE} phase awaiting_confirmation cannot be resumed by design-only recovery`
1796
+ ];
1797
+ }
1798
+ } else if (FIGMA_REACT_TO_ARKUI_RESUME_FORBIDDEN_PHASES.has(runState.phase)) {
1799
+ return [`${FIGMA_REACT_TO_ARKUI_RUN_STATE} has advanced past the design generation phase: ${runState.phase}`];
1800
+ }
1801
+ return [];
1802
+ }
1803
+
1804
+ // Upstream inputs that let hmos-d2a-react-to-arkui resume its design
1805
+ // generation, which then invokes hmos-d2a-solution-design for the document.
1806
+ // Component recognition evidence is validated through the shared collector;
1807
+ // the run state never redefines those fields.
1808
+ function figmaUpstreamInputIssues(runDir, options = {}) {
1809
+ const issues = [
1810
+ ...missingNonEmptyInputs(runDir, [
1811
+ 'source/figma/page.jsx',
1812
+ 'source/figma/reference-screenshot.png',
1813
+ 'stage2/project-analysis.md',
1814
+ 'stage2/component-analysis.md'
1815
+ ]),
1816
+ ...missingParseableJsonInputs(runDir, ['requirement-clarification.json']),
1817
+ ...figmaRunStateIssues(runDir, options)
1818
+ ];
1819
+ const assetsDir = runDirRelativePath(runDir, 'source/figma/assets');
1820
+ if (!existsSync(assetsDir) || !statSync(assetsDir).isDirectory()) {
1821
+ issues.push('source/figma/assets is missing');
1822
+ }
1823
+ issues.push(...collectFigmaComponentRecognitionEvidenceIssues(runDir));
1824
+ return issues;
1825
+ }
1826
+
1827
+ // Run dirs created before the ledger rename keep the legacy filename; prefer
1828
+ // the canonical name and fall back so design-doc recovery can still read them.
1829
+ function resolveLedgerPath(runDir) {
1830
+ const ledgerPath = join(runDir, 'capability-invocation-ledger.json');
1831
+ if (existsSync(ledgerPath)) return ledgerPath;
1832
+ const legacyPath = join(runDir, 'skill-invocation-ledger.json');
1833
+ return existsSync(legacyPath) ? legacyPath : ledgerPath;
1834
+ }
1835
+
1836
+ // The design-doc.md writer is hmos-d2a-solution-design by contract; a live
1837
+ // completion of a doc stage must show a completed ledger record for it.
1838
+ function collectSolutionDesignLedgerIssues(runDir, stage) {
1839
+ const ledgerPath = resolveLedgerPath(runDir);
1840
+ if (!isNonEmptyFile(ledgerPath)) {
1841
+ return [`stage ${stage} requires capability-invocation-ledger.json with a completed ${SOLUTION_DESIGN_SKILL} invocation`];
1842
+ }
1843
+ let ledger;
1844
+ try {
1845
+ ledger = readJsonFile(ledgerPath);
1846
+ } catch {
1847
+ return [`stage ${stage} capability-invocation-ledger.json is not valid JSON`];
1848
+ }
1849
+ const entries = Array.isArray(ledger)
1850
+ ? ledger
1851
+ : Array.isArray(ledger?.invocations)
1852
+ ? ledger.invocations
1853
+ : null;
1854
+ if (!entries) {
1855
+ return [`stage ${stage} capability-invocation-ledger.json must be an array or contain an invocations array`];
1856
+ }
1857
+ const hasCompleted = entries.some(
1858
+ (entry) =>
1859
+ entry &&
1860
+ typeof entry === 'object' &&
1861
+ (entry.capability === SOLUTION_DESIGN_SKILL || entry.skill === SOLUTION_DESIGN_SKILL || entry.skillName === SOLUTION_DESIGN_SKILL) &&
1862
+ entry.status === 'completed'
1863
+ );
1864
+ if (!hasCompleted) {
1865
+ return [`stage ${stage} capability-invocation-ledger.json must contain a completed ${SOLUTION_DESIGN_SKILL} invocation record`];
1866
+ }
1867
+ return [];
1868
+ }
1869
+
1870
+ // Unified assessment for an invalid design-doc.md. Outcomes:
1871
+ // none — the document is valid
1872
+ // restore_document — authoritative inputs are complete, so
1873
+ // hmos-d2a-solution-design can rebuild
1874
+ // only the document
1875
+ // resume_design_generation — the doc generation stage is still
1876
+ // running, or it already completed and a
1877
+ // later stage lost the document; the
1878
+ // original orchestration subflow can be
1879
+ // resumed (design-only for Figma)
1880
+ // blocked_missing_upstream_evidence — recovery is impossible; report
1881
+ // design_stage_evidence_incomplete
1882
+ function assessDesignDocRecovery(runDir, catalog, state) {
1883
+ const docIssues = collectDesignDocEvidenceIssues(runDir);
1884
+ if (docIssues.length === 0) {
1885
+ return { outcome: 'none', issues: [] };
1886
+ }
1887
+
1888
+ const designSource = catalog.designSource ?? 'pixso';
1889
+ const docStage = designDocStage(catalog);
1890
+ const docStageCompleted = state.completedStages.includes(docStage);
1891
+ const inGenerationStage = state.currentStage === docStage && !docStageCompleted;
1892
+
1893
+ // Safety boundary: after Pixso Full stage 5 completed, the component tree is
1894
+ // the user-confirmed artifact and no snapshot of that confirmation exists, so
1895
+ // nothing may be regenerated in its place.
1896
+ if (designSource === 'pixso' && catalog.variant === 'full' && docStageCompleted) {
1897
+ if (!isNonEmptyFile(runDirRelativePath(runDir, 'component-tree.md'))) {
1898
+ return {
1899
+ outcome: 'blocked_missing_upstream_evidence',
1900
+ issues: [
1901
+ ...docIssues,
1902
+ 'component-tree.md is missing or empty; the user-confirmed Pixso component tree cannot be regenerated'
1903
+ ]
1904
+ };
1905
+ }
1906
+ }
1907
+
1908
+ const restoreIssues = designSource === 'figma'
1909
+ ? figmaRestoreDocumentInputIssues(runDir)
1910
+ : pixsoRestoreDocumentInputIssues(runDir);
1911
+ if (restoreIssues.length === 0) {
1912
+ return { outcome: 'restore_document', issues: docIssues };
1913
+ }
1914
+
1915
+ if (inGenerationStage || docStageCompleted) {
1916
+ const upstreamIssues = designSource === 'figma'
1917
+ ? figmaUpstreamInputIssues(runDir, { designOnlyRecovery: docStageCompleted })
1918
+ : pixsoUpstreamInputIssues(runDir);
1919
+ if (upstreamIssues.length === 0) {
1920
+ return { outcome: 'resume_design_generation', issues: docIssues };
1921
+ }
1922
+ return {
1923
+ outcome: 'blocked_missing_upstream_evidence',
1924
+ issues: [...docIssues, ...restoreIssues, ...upstreamIssues]
1925
+ };
1926
+ }
1927
+
1928
+ return {
1929
+ outcome: 'blocked_missing_upstream_evidence',
1930
+ issues: [...docIssues, ...restoreIssues]
1931
+ };
1932
+ }
1933
+
1934
+ function stageCompleteRetry(requestedStage, result, reasonCode) {
1935
+ const retry = { mode: 'stage-complete', stage: requestedStage, result };
1936
+ if (result === 'blocked') {
1937
+ retry.reasonCode = reasonCode;
1938
+ }
1939
+ return retry;
1940
+ }
1941
+
1942
+ function buildDesignDocRecoveryPayload(runDir, catalog, assessment, retry) {
1943
+ if (assessment.outcome === 'restore_document') {
1944
+ return {
1945
+ strategy: 'restore_document',
1946
+ skill: SOLUTION_DESIGN_SKILL,
1947
+ operation: 'restore_missing_design_doc',
1948
+ instructionPath: DESIGN_DOC_RECOVERY_INSTRUCTION,
1949
+ retry
1950
+ };
1951
+ }
1952
+ if ((catalog.designSource ?? 'pixso') === 'figma') {
1953
+ return {
1954
+ strategy: 'resume_design_generation',
1955
+ runnerSkill: 'hmos-d2a-react-to-arkui',
1956
+ operation: 'restore_design_artifacts',
1957
+ stopAfterDesign: true,
1958
+ runStatePath: runDirRelativePath(runDir, FIGMA_REACT_TO_ARKUI_RUN_STATE),
1959
+ mustInvokeSkill: SOLUTION_DESIGN_SKILL,
1960
+ instructionPath: DESIGN_DOC_RECOVERY_INSTRUCTION,
1961
+ retry
1962
+ };
1963
+ }
1964
+ return {
1965
+ strategy: 'resume_design_generation',
1966
+ runner: 'pixso_stage5_solution_design_subflow',
1967
+ instructionPath: DESIGN_DOC_RECOVERY_INSTRUCTION,
1968
+ stageInstructionPath: catalog.stages.find((entry) => entry.id === designDocStage(catalog)).instructionPath,
1969
+ mustInvokeSkill: SOLUTION_DESIGN_SKILL,
1970
+ retry
1971
+ };
1972
+ }
1973
+
1974
+ // Read-only inputs whose content must stay frozen for the duration of one
1975
+ // recovery event. Only files that currently exist are recorded; outputs the
1976
+ // recovery may (re)create are never hashed.
1977
+ function designDocRecoveryInputPaths(runDir, catalog, strategy) {
1978
+ const designSource = catalog.designSource ?? 'pixso';
1979
+ if (strategy === 'restore_document') {
1980
+ if (designSource === 'figma') {
1981
+ return [
1982
+ 'source/figma/page.jsx',
1983
+ 'source/figma/reference-screenshot.png',
1984
+ 'stage2/project-analysis.md',
1985
+ 'stage2/component-analysis.md',
1986
+ 'component-tree.md',
1987
+ 'system-ui-policy.json',
1988
+ 'viewport-boundary-spec.json',
1989
+ 'requirement-clarification.json',
1990
+ 'inputs-manifest.json'
1991
+ ];
1992
+ }
1993
+ return [
1994
+ 'component-tree.md',
1995
+ 'requirement-clarification.json',
1996
+ 'hds-decision.json',
1997
+ 'startup-page-policy.json',
1998
+ 'system-ui-policy.json',
1999
+ 'viewport-boundary-spec.json',
2000
+ 'system-ui-coordinate-normalization.json',
2001
+ 'safe-area-unit-contract.json',
2002
+ 'inputs-manifest.json'
2003
+ ];
2004
+ }
2005
+ if (designSource === 'figma') {
2006
+ return [
2007
+ 'source/figma/page.jsx',
2008
+ 'source/figma/reference-screenshot.png',
2009
+ 'requirement-clarification.json',
2010
+ 'stage2/project-analysis.md',
2011
+ 'stage2/component-analysis.md',
2012
+ 'source/figma/component-recognition-screenshot.png',
2013
+ 'stage2/component-vision-analysis.json',
2014
+ 'inputs-manifest.json',
2015
+ FIGMA_REACT_TO_ARKUI_RUN_STATE
2016
+ ];
2017
+ }
2018
+ return [
2019
+ 'requirement-clarification.json',
2020
+ 'inputs-manifest.json',
2021
+ 'stage2/image-assets-manifest.json',
2022
+ 'stage3-repo-understand-report.json'
2023
+ ];
2024
+ }
2025
+
2026
+ function computeDesignDocRecoveryInputHashes(runDir, catalog, strategy) {
2027
+ const inputHashes = {};
2028
+ const paths = designDocRecoveryInputPaths(runDir, catalog, strategy);
2029
+ if ((catalog.designSource ?? 'pixso') === 'pixso') {
2030
+ paths.push(...collectPixsoDslEntries(runDir).entries.map((entry) => entry.relPath));
2031
+ if (strategy === 'resume_design_generation') {
2032
+ // Freeze the stage 2 page skeletons the stage 5 subflow consumes: only
2033
+ // direct regular .ets children of stage2/generated, sorted by name so
2034
+ // the recorded set is stable.
2035
+ const generatedDir = join(runDir, 'stage2', 'generated');
2036
+ if (existsSync(generatedDir) && statSync(generatedDir).isDirectory()) {
2037
+ paths.push(
2038
+ ...readdirSync(generatedDir)
2039
+ .filter((name) => name.endsWith('.ets') && statSync(join(generatedDir, name)).isFile())
2040
+ .sort()
2041
+ .map((name) => relative(runDir, join(generatedDir, name)).replaceAll('\\', '/'))
2042
+ );
2043
+ }
2044
+ }
2045
+ }
2046
+ for (const relPath of new Set(paths)) {
2047
+ const fullPath = runDirRelativePath(runDir, relPath);
2048
+ if (isNonEmptyFile(fullPath)) {
2049
+ inputHashes[relPath] = hashFile(fullPath);
2050
+ }
2051
+ }
2052
+ return inputHashes;
2053
+ }
2054
+
2055
+ function readPendingDesignDocRecoveryRequest(runDir) {
2056
+ const requestPath = join(runDir, DESIGN_DOC_RECOVERY_REQUEST);
2057
+ if (!existsSync(requestPath)) {
2058
+ return null;
2059
+ }
2060
+ try {
2061
+ const request = readJsonFile(requestPath);
2062
+ if (
2063
+ request?.status !== 'pending' ||
2064
+ typeof request?.recoveryInvocationId !== 'string' ||
2065
+ request.recoveryInvocationId.length === 0 ||
2066
+ !request?.recovery ||
2067
+ typeof request.recovery !== 'object' ||
2068
+ Array.isArray(request.recovery)
2069
+ ) {
2070
+ return null;
2071
+ }
2072
+ return request;
2073
+ } catch {
2074
+ return null;
2075
+ }
2076
+ }
2077
+
2078
+ // Ensures a pending design-doc-recovery-request.json exists before a recovery
2079
+ // payload is returned to the agent. Within one missing-document event the
2080
+ // original ID and the original payload are reused; a completed request from an
2081
+ // earlier event is replaced by a fresh UUID.
2082
+ function prepareDesignDocRecovery(runDir, catalog, state, assessment, retry) {
2083
+ const existing = readPendingDesignDocRecoveryRequest(runDir);
2084
+ if (existing) {
2085
+ return existing.recovery;
2086
+ }
2087
+ const recoveryInvocationId = randomUUID();
2088
+ const recovery = {
2089
+ ...buildDesignDocRecoveryPayload(runDir, catalog, assessment, retry),
2090
+ recoveryInvocationId
2091
+ };
2092
+ writeJsonAtomic(join(runDir, DESIGN_DOC_RECOVERY_REQUEST), {
2093
+ schemaVersion: 1,
2094
+ recoveryInvocationId,
2095
+ strategy: assessment.outcome,
2096
+ designSource: catalog.designSource ?? 'pixso',
2097
+ documentStage: designDocStage(catalog),
2098
+ inputHashes: computeDesignDocRecoveryInputHashes(runDir, catalog, assessment.outcome),
2099
+ recovery,
2100
+ status: 'pending'
2101
+ });
2102
+ return recovery;
2103
+ }
2104
+
2105
+ function findSolutionDesignLedgerEntry(runDir, invocationId) {
2106
+ const ledgerPath = resolveLedgerPath(runDir);
2107
+ if (!isNonEmptyFile(ledgerPath)) {
2108
+ return null;
2109
+ }
2110
+ let ledger;
2111
+ try {
2112
+ ledger = readJsonFile(ledgerPath);
2113
+ } catch {
2114
+ return null;
2115
+ }
2116
+ const entries = Array.isArray(ledger)
2117
+ ? ledger
2118
+ : Array.isArray(ledger?.invocations)
2119
+ ? ledger.invocations
2120
+ : null;
2121
+ if (!entries) {
2122
+ return null;
2123
+ }
2124
+ return entries.find(
2125
+ (entry) =>
2126
+ entry &&
2127
+ typeof entry === 'object' &&
2128
+ entry.invocationId === invocationId &&
2129
+ (entry.capability === SOLUTION_DESIGN_SKILL || entry.skill === SOLUTION_DESIGN_SKILL || entry.skillName === SOLUTION_DESIGN_SKILL) &&
2130
+ entry.status === 'completed'
2131
+ ) ?? null;
2132
+ }
2133
+
2134
+ function designDocRecoveryInputHashIssues(runDir, request) {
2135
+ const issues = [];
2136
+ const inputHashes = request.inputHashes;
2137
+ if (!inputHashes || typeof inputHashes !== 'object' || Array.isArray(inputHashes)) {
2138
+ return [`${DESIGN_DOC_RECOVERY_REQUEST} inputHashes is invalid`];
2139
+ }
2140
+ for (const [relPath, expectedHash] of Object.entries(inputHashes)) {
2141
+ const fullPath = resolve(runDir, relPath);
2142
+ const relFromRunDir = relative(runDir, fullPath);
2143
+ if (relFromRunDir.startsWith('..') || isAbsolute(relFromRunDir)) {
2144
+ issues.push(`design-doc recovery input path escapes the run directory: ${relPath}`);
2145
+ continue;
2146
+ }
2147
+ if (typeof expectedHash !== 'string' || !/^[a-f0-9]{64}$/.test(expectedHash)) {
2148
+ issues.push(`design-doc recovery input hash for ${relPath} is invalid`);
2149
+ continue;
2150
+ }
2151
+ if (!isNonEmptyFile(fullPath)) {
2152
+ issues.push(`design-doc recovery input changed: ${relPath} is missing or empty`);
2153
+ continue;
2154
+ }
2155
+ if (hashFile(fullPath) !== expectedHash) {
2156
+ issues.push(`design-doc recovery input changed: ${relPath}`);
2157
+ }
2158
+ }
2159
+ return issues;
2160
+ }
2161
+
2162
+ function outputDesignDocRecoveryUnverified(runDir, catalog, state, issues) {
2163
+ process.stdout.write(`${JSON.stringify({
2164
+ workflow: catalog.workflow,
2165
+ variant: catalog.variant,
2166
+ designSource: state.designSource ?? 'pixso',
2167
+ status: state.status,
2168
+ currentStage: state.currentStage,
2169
+ error: 'design_doc_recovery_unverified',
2170
+ issues
2171
+ }, null, 2)}\n`);
2172
+ process.stderr.write('workflow: design-doc recovery could not be verified; stop and report the real failure\n');
2173
+ process.exit(1);
2174
+ }
2175
+
2176
+ function outputSavedDesignDocRecovery(runDir, catalog, state, request) {
2177
+ process.stdout.write(`${JSON.stringify({
2178
+ workflow: catalog.workflow,
2179
+ variant: catalog.variant,
2180
+ designSource: state.designSource ?? 'pixso',
2181
+ status: state.status,
2182
+ currentStage: state.currentStage,
2183
+ error: 'design_doc_invalid',
2184
+ issues: collectDesignDocEvidenceIssues(runDir),
2185
+ nextRequiredAction: request.strategy === 'restore_document'
2186
+ ? 'regenerate_design_doc'
2187
+ : 'resume_design_generation',
2188
+ recovery: request.recovery
2189
+ }, null, 2)}\n`);
2190
+ process.stderr.write('workflow: design-doc.md is still invalid; complete the pending recovery before retrying\n');
2191
+ process.exit(1);
2192
+ }
2193
+
2194
+ // Runs before ordinary gates and design-doc assessments in every mode except
2195
+ // init. A pending recovery request is either completed (document restored and
2196
+ // the same-ID solution-design ledger record verified) or it short-circuits the
2197
+ // call; it can never be silently bypassed.
2198
+ function checkPendingDesignDocRecovery(runDir, catalog, state) {
2199
+ const requestPath = join(runDir, DESIGN_DOC_RECOVERY_REQUEST);
2200
+ if (!existsSync(requestPath)) {
2201
+ return;
2202
+ }
2203
+ let request;
2204
+ try {
2205
+ request = readJsonFile(requestPath);
2206
+ } catch (error) {
2207
+ outputDesignDocRecoveryUnverified(runDir, catalog, state, [
2208
+ `${DESIGN_DOC_RECOVERY_REQUEST} is not valid JSON: ${error.message}`
2209
+ ]);
2210
+ }
2211
+ if (!request || typeof request !== 'object' || Array.isArray(request)) {
2212
+ outputDesignDocRecoveryUnverified(runDir, catalog, state, [
2213
+ `${DESIGN_DOC_RECOVERY_REQUEST} must contain a JSON object`
2214
+ ]);
2215
+ }
2216
+ if (request.status === 'completed') {
2217
+ return;
2218
+ }
2219
+ if (
2220
+ request.status !== 'pending' ||
2221
+ request.schemaVersion !== 1 ||
2222
+ typeof request.recoveryInvocationId !== 'string' ||
2223
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(request.recoveryInvocationId) ||
2224
+ !['restore_document', 'resume_design_generation'].includes(request.strategy) ||
2225
+ !request.recovery ||
2226
+ typeof request.recovery !== 'object' ||
2227
+ Array.isArray(request.recovery)
2228
+ ) {
2229
+ outputDesignDocRecoveryUnverified(runDir, catalog, state, [
2230
+ `${DESIGN_DOC_RECOVERY_REQUEST} does not match the recovery request schema`
2231
+ ]);
2232
+ }
2233
+ const hashIssues = designDocRecoveryInputHashIssues(runDir, request);
2234
+ if (hashIssues.length > 0) {
2235
+ outputDesignDocRecoveryUnverified(runDir, catalog, state, hashIssues);
2236
+ }
2237
+ if (collectDesignDocEvidenceIssues(runDir).length > 0) {
2238
+ outputSavedDesignDocRecovery(runDir, catalog, state, request);
2239
+ }
2240
+ if (!findSolutionDesignLedgerEntry(runDir, request.recoveryInvocationId)) {
2241
+ outputDesignDocRecoveryUnverified(runDir, catalog, state, [
2242
+ `design-doc.md is valid but capability-invocation-ledger.json has no completed ${SOLUTION_DESIGN_SKILL} record for recovery invocation ${request.recoveryInvocationId}`
2243
+ ]);
2244
+ }
2245
+ writeJsonAtomic(requestPath, { ...request, status: 'completed' });
2246
+ }
2247
+
2248
+ function buildDesignDocAssessmentResponse(runDir, catalog, state, assessment, retry) {
2249
+ if (assessment.outcome === 'blocked_missing_upstream_evidence') {
2250
+ return {
2251
+ workflow: catalog.workflow,
2252
+ variant: catalog.variant,
2253
+ designSource: state.designSource ?? 'pixso',
2254
+ status: state.status,
2255
+ currentStage: state.currentStage,
2256
+ error: 'design_stage_evidence_incomplete',
2257
+ issues: assessment.issues
2258
+ };
2259
+ }
2260
+ return {
2261
+ workflow: catalog.workflow,
2262
+ variant: catalog.variant,
2263
+ designSource: state.designSource ?? 'pixso',
2264
+ status: state.status,
2265
+ currentStage: state.currentStage,
2266
+ error: 'design_doc_invalid',
2267
+ issues: assessment.issues,
2268
+ nextRequiredAction: assessment.outcome === 'restore_document'
2269
+ ? 'regenerate_design_doc'
2270
+ : 'resume_design_generation',
2271
+ recovery: prepareDesignDocRecovery(runDir, catalog, state, assessment, retry)
2272
+ };
2273
+ }
2274
+
2275
+ function outputDesignDocAssessment(runDir, catalog, state, assessment, retry) {
2276
+ process.stdout.write(`${JSON.stringify(
2277
+ buildDesignDocAssessmentResponse(runDir, catalog, state, assessment, retry),
2278
+ null,
2279
+ 2
2280
+ )}\n`);
2281
+ }
2282
+
2283
+ // Recoverable design-doc failures keep the original stderr message and exit
2284
+ // code; the structured recovery protocol rides on stdout so the parent agent
2285
+ // can regenerate the document and retry the original operation.
2286
+ function failWithDesignDocAssessment(runDir, catalog, state, assessment, retry, message) {
2287
+ outputDesignDocAssessment(runDir, catalog, state, assessment, retry);
2288
+ fail(message);
2289
+ }
2290
+
2291
+ function collectVisualCalibrationEvidenceIssues(runDir, stage) {
2292
+ const issues = [];
2293
+ const clarification = readJsonOrNull(
2294
+ join(runDir, 'requirement-clarification.json'),
2295
+ `stage ${stage} requirement clarification`,
2296
+ issues
2297
+ );
2298
+ const report = readJsonOrNull(
2299
+ join(runDir, `stage${stage}-visual-calibration-report.json`),
2300
+ `stage ${stage} visual calibration report`,
2301
+ issues
2302
+ );
2303
+ if (!clarification || !report) {
2304
+ return issues;
2305
+ }
2306
+
2307
+ if (clarification.visualCalibration?.enabled === false) {
2308
+ if (
2309
+ report.status !== 'skipped' ||
2310
+ report.reason !== 'visualCalibration.disabled' ||
2311
+ report.roundsCompleted !== 0
2312
+ ) {
2313
+ issues.push(
2314
+ `stage ${stage} skipped report must use status=skipped, reason=visualCalibration.disabled, and roundsCompleted=0`
2315
+ );
2316
+ }
2317
+ return issues;
2318
+ }
2319
+
2320
+ const threshold =
2321
+ typeof clarification.visualCalibration?.scoreThreshold === 'number'
2322
+ ? clarification.visualCalibration.scoreThreshold
2323
+ : 80;
2324
+ // maxRounds is the user-configurable round cap (1-5, default 5). Stage 1
2325
+ // validation rejects out-of-range values, so the fallback here is defensive.
2326
+ const maxRounds =
2327
+ Number.isInteger(clarification.visualCalibration?.maxRounds) &&
2328
+ clarification.visualCalibration.maxRounds >= 1 &&
2329
+ clarification.visualCalibration.maxRounds <= 5
2330
+ ? clarification.visualCalibration.maxRounds
2331
+ : 5;
2332
+ const roundsCompleted = Number(report.roundsCompleted);
2333
+ const validRounds =
2334
+ Number.isInteger(roundsCompleted) && roundsCompleted >= 1 && roundsCompleted <= maxRounds;
2335
+
2336
+ if (report.status !== 'completed' || !validRounds) {
2337
+ issues.push(
2338
+ `stage ${stage} enabled calibration requires status=completed and roundsCompleted between 1 and ${maxRounds}`
2339
+ );
2340
+ }
2341
+ const invocations = Array.isArray(report.capabilityInvocations)
2342
+ ? report.capabilityInvocations
2343
+ : report.skillInvocations;
2344
+ const parentInvocation = Array.isArray(invocations)
2345
+ ? invocations.find(
2346
+ (item) =>
2347
+ (item?.capability === 'hmos-d2a-arkui-scoring-workflow' || item?.skill === 'hmos-d2a-arkui-scoring-workflow') &&
2348
+ item?.status === 'completed'
2349
+ )
2350
+ : null;
2351
+ if (!parentInvocation) {
2352
+ issues.push(`stage ${stage} report is missing completed hmos-d2a-arkui-scoring-workflow invocation`);
2353
+ }
2354
+
2355
+ const upperBound = validRounds ? roundsCompleted : 0;
2356
+ for (let round = 1; round <= upperBound; round += 1) {
2357
+ const invocation = Array.isArray(invocations)
2358
+ ? invocations.find(
2359
+ (item) =>
2360
+ (item?.capability === 'hmos-d2a-ui-reconstruction-score' || item?.skill === 'hmos-d2a-ui-reconstruction-score') &&
2361
+ Number(item?.round) === round &&
2362
+ item?.status === 'completed'
2363
+ )
2364
+ : null;
2365
+ if (!invocation) {
2366
+ issues.push(`stage ${stage} report is missing completed hmos-d2a-ui-reconstruction-score invocation for round ${round}`);
2367
+ }
2368
+
2369
+ const roundEvidence = Array.isArray(report.rounds)
2370
+ ? report.rounds.find((item) => Number(item?.round) === round)
2371
+ : null;
2372
+ if (!roundEvidence) {
2373
+ issues.push(`stage ${stage} report is missing evidence for round ${round}`);
2374
+ continue;
2375
+ }
2376
+ for (const [field, label] of [
2377
+ ['scoreJson', `stage ${stage} round ${round} score.json`],
2378
+ ['metricsJson', `stage ${stage} round ${round} metrics.json`]
2379
+ ]) {
2380
+ const path = resolveEvidencePath(runDir, roundEvidence[field], label, issues);
2381
+ if (path) {
2382
+ readJsonOrNull(path, label, issues);
2383
+ }
2384
+ }
2385
+ }
2386
+
2387
+ const validReasons = ['score-threshold-reached', 'max-rounds-reached'];
2388
+ if (!validReasons.includes(report.completionReason)) {
2389
+ issues.push(
2390
+ `stage ${stage} report must include completionReason of score-threshold-reached or max-rounds-reached`
2391
+ );
2392
+ }
2393
+ if (validRounds) {
2394
+ const lastRound = Array.isArray(report.rounds)
2395
+ ? report.rounds.find((item) => Number(item?.round) === roundsCompleted)
2396
+ : null;
2397
+ const lastScore = typeof lastRound?.score === 'number' ? lastRound.score : Number.NaN;
2398
+ if (
2399
+ report.completionReason === 'score-threshold-reached' &&
2400
+ (!Number.isFinite(lastScore) || lastScore < threshold)
2401
+ ) {
2402
+ issues.push(
2403
+ `stage ${stage} completionReason=score-threshold-reached requires last round score >= ${threshold}`
2404
+ );
2405
+ }
2406
+ if (
2407
+ report.completionReason === 'max-rounds-reached' &&
2408
+ (roundsCompleted !== maxRounds || !Number.isFinite(lastScore) || lastScore >= threshold)
2409
+ ) {
2410
+ issues.push(
2411
+ `stage ${stage} completionReason=max-rounds-reached requires roundsCompleted=${maxRounds} and last round score < ${threshold}`
2412
+ );
2413
+ }
2414
+ }
2415
+
2416
+ for (const name of [
2417
+ 'hmos-d2a-ui-reconstruction-score-invoked',
2418
+ 'score-artifacts-present',
2419
+ 'no-direct-compare-images-bypass',
2420
+ 'calibration-completed'
2421
+ ]) {
2422
+ if (!reportCheckPassed(report, name)) {
2423
+ issues.push(`stage ${stage} report check ${name} must pass`);
2424
+ }
2425
+ }
2426
+ return issues;
2427
+ }
2428
+
2429
+ // Source-agnostic stage 1 evidence: the requirement clarification document is
2430
+ // created by stage 1 itself, so it must exist and be structurally valid by the
2431
+ // time stage 1 completes. The controller only validates evidence; it never
2432
+ // creates, repairs, or rewrites this file.
2433
+ function collectRequirementClarificationEvidenceIssues(runDir, catalog) {
2434
+ const issues = [];
2435
+ const clarification = readJsonOrNull(
2436
+ join(runDir, 'requirement-clarification.json'),
2437
+ 'stage 1 requirement clarification',
2438
+ issues
2439
+ );
2440
+ // readJsonOrNull returns null both for missing/unparseable files (issue
2441
+ // already recorded) and for a legal JSON null document (no issue yet); the
2442
+ // latter must not slip through as a valid document.
2443
+ if (clarification === null) {
2444
+ if (issues.length === 0) {
2445
+ issues.push('stage 1 requirement clarification must be an object');
2446
+ }
2447
+ return issues;
2448
+ }
2449
+ if (typeof clarification !== 'object' || Array.isArray(clarification)) {
2450
+ issues.push('stage 1 requirement clarification must be an object');
2451
+ return issues;
2452
+ }
2453
+ if (clarification.preCheckCompleted !== true) {
2454
+ issues.push('stage 1 requirement clarification preCheckCompleted must be true');
2455
+ }
2456
+ const expectedSource = catalog.designSource ?? 'pixso';
2457
+ if (clarification.designSource !== expectedSource) {
2458
+ issues.push(`stage 1 requirement clarification designSource must be ${expectedSource}, got ${clarification.designSource}`);
2459
+ }
2460
+ // Only a truly absent field (undefined) skips the optional checks; a present
2461
+ // null is a type error per the runtime contract.
2462
+ if (clarification.visualCalibration !== undefined) {
2463
+ if (clarification.visualCalibration === null || typeof clarification.visualCalibration !== 'object' || Array.isArray(clarification.visualCalibration)) {
2464
+ issues.push('stage 1 requirement clarification visualCalibration must be an object');
2465
+ } else {
2466
+ if (clarification.visualCalibration.enabled !== undefined && typeof clarification.visualCalibration.enabled !== 'boolean') {
2467
+ issues.push('stage 1 requirement clarification visualCalibration.enabled must be a boolean');
2468
+ }
2469
+ if (clarification.visualCalibration.scoreThreshold !== undefined && !Number.isFinite(clarification.visualCalibration.scoreThreshold)) {
2470
+ issues.push('stage 1 requirement clarification visualCalibration.scoreThreshold must be a finite number');
2471
+ }
2472
+ if (
2473
+ clarification.visualCalibration.maxRounds !== undefined &&
2474
+ (!Number.isInteger(clarification.visualCalibration.maxRounds) ||
2475
+ clarification.visualCalibration.maxRounds < 1 ||
2476
+ clarification.visualCalibration.maxRounds > 5)
2477
+ ) {
2478
+ issues.push('stage 1 requirement clarification visualCalibration.maxRounds must be an integer between 1 and 5 when present');
2479
+ }
2480
+ }
2481
+ }
2482
+ return issues;
2483
+ }
2484
+
2485
+ function collectStageEvidenceIssues(runDir, catalog, stage, ctx = {}) {
2486
+ const issues = [];
2487
+ const designSource = catalog.designSource ?? 'pixso';
2488
+ const visualStage = designSource === 'figma' ? 5 : 9;
2489
+ if (stage === 1) {
2490
+ issues.push(...collectRequirementClarificationEvidenceIssues(runDir, catalog));
2491
+ }
2492
+ if (designSource === 'pixso' && stage === 2) { issues.push(...collectPixsoRouteIssues(runDir)); }
2493
+ if (designSource === 'figma' && stage === 1) {
2494
+ issues.push(...collectFigmaStage1EvidenceIssues(runDir, catalog, ctx));
2495
+ }
2496
+ if (designSource === 'figma' && stage === 2) {
2497
+ issues.push(...collectFigmaComponentRecognitionEvidenceIssues(runDir));
2498
+ issues.push(...collectFigmaStage2RegistrationEvidenceIssues(runDir, ctx));
2499
+ }
2500
+ if (requiresDesignDocMissingGuard(catalog, stage) && ctx.waiveDesignDocEvidence !== true) {
2501
+ issues.push(...collectDesignDocEvidenceIssues(runDir));
2502
+ // Live completion of a doc stage must prove the solution-design skill ran;
2503
+ // completed-stage replays keep working for runs predating this rule.
2504
+ if (ctx.live === true) {
2505
+ issues.push(...collectSolutionDesignLedgerIssues(runDir, stage));
2506
+ }
2507
+ }
2508
+ if (catalog.variant === 'full' && stage === visualStage) {
2509
+ issues.push(...collectVisualCalibrationEvidenceIssues(runDir, stage));
2510
+ }
2511
+ return issues;
2512
+ }
2513
+
2514
+ function validatePathWithinSkillRoot(relPath, label, skillRoot) {
2515
+ if (typeof relPath !== 'string' || relPath.length === 0) {
2516
+ fail(`${label} is missing`);
2517
+ }
2518
+ if (isAbsolute(relPath)) {
2519
+ fail(`${label} must be relative, got absolute path: ${relPath}`);
2520
+ }
2521
+ const resolved = resolve(skillRoot, relPath);
2522
+ const rel = relative(skillRoot, resolved);
2523
+ if (rel.startsWith('..') || isAbsolute(rel)) {
2524
+ fail(`${label} must stay within the skill root directory: ${relPath}`);
2525
+ }
2526
+ return resolved;
2527
+ }
2528
+
2529
+ function validateStageCatalog(catalog, expectedVariant, expectedSource, skillRoot) {
2530
+ if (catalog.schemaVersion !== 1) {
2531
+ fail(`catalog schemaVersion must be 1, got ${catalog.schemaVersion}`);
2532
+ }
2533
+ if (catalog.workflowVersion !== 4) {
2534
+ fail(`catalog workflowVersion must be 4, got ${catalog.workflowVersion}`);
2535
+ }
2536
+ if (catalog.variant !== expectedVariant) {
2537
+ fail(`catalog variant mismatch: expected ${expectedVariant}, got ${catalog.variant}`);
2538
+ }
2539
+ const catalogSource = catalog.designSource ?? 'pixso';
2540
+ if (catalogSource !== expectedSource) {
2541
+ fail(`catalog designSource mismatch: expected ${expectedSource}, got ${catalogSource}`);
2542
+ }
2543
+ if (typeof catalog.workflow !== 'string' || catalog.workflow.length === 0) {
2544
+ fail('catalog workflow must be a non-empty string');
2545
+ }
2546
+ const runtimeContractFullPath = validatePathWithinSkillRoot(catalog.runtimeContractPath, 'catalog runtimeContractPath', skillRoot);
2547
+ if (!existsSync(runtimeContractFullPath)) {
2548
+ fail(`catalog runtimeContractPath file does not exist: ${catalog.runtimeContractPath}`);
2549
+ }
2550
+ const stat = statSync(runtimeContractFullPath);
2551
+ if (!stat.isFile()) {
2552
+ fail(`catalog runtimeContractPath must be a file, not a directory: ${catalog.runtimeContractPath}`);
2553
+ }
2554
+ if (!catalog.runtimeContractPath.startsWith('references/')) {
2555
+ fail(`catalog runtimeContractPath must be under references/: ${catalog.runtimeContractPath}`);
2556
+ }
2557
+ if (!Array.isArray(catalog.stages) || catalog.stages.length === 0) {
2558
+ fail('catalog stages must be a non-empty array');
2559
+ }
2560
+ const expectedDir = `references/${expectedSource}/${expectedVariant}/stages/`;
2561
+ const instructionPaths = new Set();
2562
+ for (const [index, stage] of catalog.stages.entries()) {
2563
+ const expectedId = stage.id;
2564
+ if (!Number.isInteger(stage.id) || stage.id < 1 || (index > 0 && stage.id <= catalog.stages[index - 1].id)) {
2565
+ fail(`catalog stage IDs must be positive and strictly increasing; got ${stage.id} at index ${index}`);
2566
+ }
2567
+ if (typeof stage.title !== 'string' || stage.title.length === 0) {
2568
+ fail(`catalog stage ${expectedId} title is missing`);
2569
+ }
2570
+ const instructionFullPath = validatePathWithinSkillRoot(stage.instructionPath, `catalog stage ${expectedId} instructionPath`, skillRoot);
2571
+ if (!stage.instructionPath.startsWith(expectedDir)) {
2572
+ fail(`catalog stage ${expectedId} instructionPath must be under ${expectedDir}: ${stage.instructionPath}`);
2573
+ }
2574
+ if (instructionPaths.has(stage.instructionPath)) {
2575
+ fail(`duplicate catalog instructionPath: ${stage.instructionPath}`);
2576
+ }
2577
+ instructionPaths.add(stage.instructionPath);
2578
+ if (!existsSync(instructionFullPath)) {
2579
+ fail(`catalog stage ${expectedId} instruction file does not exist: ${stage.instructionPath}`);
2580
+ }
2581
+ const instructionStat = statSync(instructionFullPath);
2582
+ if (!instructionStat.isFile()) {
2583
+ fail(`catalog stage ${expectedId} instructionPath must be a file: ${stage.instructionPath}`);
2584
+ }
2585
+ if (typeof stage.requiresConfirmation !== 'boolean') {
2586
+ fail(`catalog stage ${expectedId} requiresConfirmation must be boolean`);
2587
+ }
2588
+ if (
2589
+ stage.confirmationContinuesStage !== undefined &&
2590
+ typeof stage.confirmationContinuesStage !== 'boolean'
2591
+ ) {
2592
+ fail(`catalog stage ${expectedId} confirmationContinuesStage must be boolean when present`);
2593
+ }
2594
+ if (stage.confirmationContinuesStage === true && stage.requiresConfirmation !== true) {
2595
+ fail(`catalog stage ${expectedId} confirmationContinuesStage requires requiresConfirmation=true`);
2596
+ }
2597
+ }
2598
+ }
2599
+
2600
+ function computeWorkflowDigest(skillRoot, catalog, catalogRelPath) {
2601
+ const paths = [
2602
+ catalogRelPath,
2603
+ catalog.runtimeContractPath,
2604
+ "references/cli-integration.md",
2605
+ "references/host-vision.md",
2606
+ "references/resource-revisions.md",
2607
+ "references/page-revisions.md",
2608
+ "scripts/workflow.mjs",
2609
+ "scripts/file-lock.mjs",
2610
+ ...catalog.stages.map((s) => s.instructionPath)
2611
+ ];
2612
+ const normalized = paths.map((p) => p.replace(/\\/g, '/')).sort();
2613
+ const hash = createHash('sha256');
2614
+ for (const p of normalized) {
2615
+ const fullPath = join(skillRoot, p);
2616
+ if (!existsSync(fullPath)) {
2617
+ fail(`workflow digest: file does not exist: ${p}`);
2618
+ }
2619
+ hash.update(Buffer.from(p, 'utf8'));
2620
+ hash.update(Buffer.from([0]));
2621
+ hash.update(readFileSync(fullPath));
2622
+ hash.update(Buffer.from([0]));
2623
+ }
2624
+ return 'sha256:' + hash.digest('hex');
2625
+ }
2626
+
2627
+ function validateState(state, catalog) {
2628
+ if (state.schemaVersion !== 2) {
2629
+ fail(`workflow-state schemaVersion must be 2, got ${state.schemaVersion}`);
2630
+ }
2631
+ if (state.workflowVersion !== 4) {
2632
+ fail(`workflow-state workflowVersion must be 4, got ${state.workflowVersion}; reinitialize this run`);
2633
+ }
2634
+ if (state.workflow !== catalog.workflow) {
2635
+ fail(`workflow-state.workflow mismatch: expected ${catalog.workflow}, got ${state.workflow}`);
2636
+ }
2637
+ if (state.variant !== catalog.variant) {
2638
+ fail(`workflow-state.variant mismatch: expected ${catalog.variant}, got ${state.variant}`);
2639
+ }
2640
+ const stateSource = state.designSource ?? 'pixso';
2641
+ const catalogSource = catalog.designSource ?? 'pixso';
2642
+ if (stateSource !== catalogSource) {
2643
+ fail(`workflow-state.designSource mismatch: expected ${catalogSource}, got ${stateSource}`);
2644
+ }
2645
+ if (typeof state.workflowDigest !== 'string' || state.workflowDigest.length === 0) {
2646
+ fail('workflow-state.workflowDigest is missing');
2647
+ }
2648
+ const currentIndex = catalog.stages.findIndex((entry) => entry.id === state.currentStage);
2649
+ if (currentIndex < 0) {
2650
+ fail('workflow-state.currentStage must be a stage ID in the catalog');
2651
+ }
2652
+ if (!Array.isArray(state.completedStages)) {
2653
+ fail('workflow-state.completedStages must be an array');
2654
+ }
2655
+ for (const [index, value] of state.completedStages.entries()) {
2656
+ const expected = catalog.stages[index]?.id;
2657
+ if (value !== expected) {
2658
+ fail(`workflow-state.completedStages must follow catalog order; got ${value} at index ${index}, expected ${expected}`);
2659
+ }
2660
+ }
2661
+ if (state.completedStages.length !== currentIndex && state.status !== 'completed') {
2662
+ fail(`workflow-state.completedStages length (${state.completedStages.length}) must equal the current catalog position (${currentIndex})`);
2663
+ }
2664
+ if (state.status === 'completed' && state.completedStages.length !== catalog.stages.length) {
2665
+ fail('workflow-state is completed but completedStages does not cover all stages');
2666
+ }
2667
+ const validStatuses = ['running', 'awaiting_confirmation', 'blocked', 'completed'];
2668
+ if (!validStatuses.includes(state.status)) {
2669
+ fail(`workflow-state.status must be one of ${validStatuses.join(', ')}, got ${state.status}`);
2670
+ }
2671
+ if (state.status === 'awaiting_confirmation') {
2672
+ if (state.awaitingConfirmationFor !== state.currentStage) {
2673
+ fail(`workflow-state.awaitingConfirmationFor must equal currentStage when awaiting_confirmation`);
2674
+ }
2675
+ }
2676
+ if (state.status === 'blocked' && (!state.blockedReasonCode || typeof state.blockedReasonCode !== 'string')) {
2677
+ fail('workflow-state.blockedReasonCode must be a non-empty string when status is blocked');
2678
+ }
2679
+ if (!Array.isArray(state.confirmedStages)) {
2680
+ fail('workflow-state.confirmedStages must be an array');
2681
+ }
2682
+ const confirmedSet = new Set(state.confirmedStages);
2683
+ if (confirmedSet.size !== state.confirmedStages.length) {
2684
+ fail('workflow-state.confirmedStages must not contain duplicates');
2685
+ }
2686
+ for (const stageId of state.confirmedStages) {
2687
+ if (!catalog.stages.some((entry) => entry.id === stageId)) {
2688
+ fail(`workflow-state.confirmedStages contains invalid stage id: ${stageId}`);
2689
+ }
2690
+ if (!catalog.stages.find((entry) => entry.id === stageId).requiresConfirmation) {
2691
+ fail(`workflow-state.confirmedStages contains stage ${stageId} which does not require confirmation`);
2692
+ }
2693
+ }
2694
+ if (state.confirmationSnapshots !== undefined) {
2695
+ if (!state.confirmationSnapshots || typeof state.confirmationSnapshots !== 'object' || Array.isArray(state.confirmationSnapshots)) {
2696
+ fail('workflow-state.confirmationSnapshots must be an object');
2697
+ }
2698
+ for (const [stageKey, snapshot] of Object.entries(state.confirmationSnapshots)) {
2699
+ const stageId = Number(stageKey);
2700
+ if (
2701
+ !catalog.stages.some((entry) => entry.id === stageId) ||
2702
+ !catalog.stages.find((entry) => entry.id === stageId).requiresConfirmation ||
2703
+ snapshot?.stage !== stageId ||
2704
+ !snapshot.files ||
2705
+ typeof snapshot.files !== 'object'
2706
+ ) {
2707
+ fail(`workflow-state.confirmationSnapshots contains invalid stage snapshot: ${stageKey}`);
2708
+ }
2709
+ }
2710
+ }
2711
+ }
2712
+
2713
+ function checkDigest(state, catalog, skillRoot, catalogRelPath) {
2714
+ const currentDigest = computeWorkflowDigest(skillRoot, catalog, catalogRelPath);
2715
+ if (currentDigest !== state.workflowDigest) {
2716
+ return {
2717
+ mismatch: true,
2718
+ expected: state.workflowDigest,
2719
+ actual: currentDigest
2720
+ };
2721
+ }
2722
+ return { mismatch: false };
2723
+ }
2724
+
2725
+ function deriveTodo(catalog, state) {
2726
+ return catalog.stages.map((stage) => {
2727
+ let status;
2728
+ if (state.status === 'completed') {
2729
+ status = 'completed';
2730
+ } else if (state.completedStages.includes(stage.id)) {
2731
+ status = 'completed';
2732
+ } else if (stage.id === state.currentStage) {
2733
+ status = 'in_progress';
2734
+ } else {
2735
+ status = 'pending';
2736
+ }
2737
+ return {
2738
+ content: stage.title,
2739
+ status,
2740
+ priority: 'high'
2741
+ };
2742
+ });
2743
+ }
2744
+
2745
+ function writeTodoPayload(runDir, catalog, state) {
2746
+ const payload = {
2747
+ workflow: catalog.workflow,
2748
+ variant: catalog.variant,
2749
+ designSource: state.designSource ?? 'pixso',
2750
+ todos: deriveTodo(catalog, state)
2751
+ };
2752
+ writeJsonAtomic(join(runDir, 'todo-payload.json'), payload);
2753
+ return payload;
2754
+ }
2755
+
2756
+ function checkCompletedGateIssues(runDir, catalog, stage, state, evidenceContext = {}) {
2757
+ const gate = readGate(runDir, stage);
2758
+ if (!gate) {
2759
+ return [`stage ${stage} gate is missing`];
2760
+ }
2761
+ if (!isPassed(gate)) {
2762
+ return [`stage ${stage} gate status must be passed, got ${gate.status}`];
2763
+ }
2764
+ if (Number(gate.stage) !== stage) {
2765
+ return [`stage ${stage} gate.stage must equal ${stage}`];
2766
+ }
2767
+ return [
2768
+ ...collectStageEvidenceIssues(runDir, catalog, stage, evidenceContext),
2769
+ ...(requiresFigmaStage2Confirmation(catalog, stage)
2770
+ ? collectFigmaStage2ConfirmationSnapshotIssues(runDir, state)
2771
+ : [])
2772
+ ];
2773
+ }
2774
+
2775
+ function collectCompletedGateIssues(runDir, catalog, state, evidenceContext = {}) {
2776
+ return state.completedStages.flatMap((stage) => checkCompletedGateIssues(runDir, catalog, stage, state, evidenceContext));
2777
+ }
2778
+
2779
+ function loadCatalogForVariant(skillRoot, variant, designSource = 'pixso') {
2780
+ if (!VALID_SOURCES.has(designSource)) {
2781
+ fail(`design source must be one of ${[...VALID_SOURCES].join(', ')}`);
2782
+ }
2783
+ const catalogRelPath = `references/${designSource}/stage-catalog-${variant}.json`;
2784
+ const catalogPath = join(skillRoot, catalogRelPath);
2785
+ const catalog = readJson(catalogPath, 'stage catalog');
2786
+ validateStageCatalog(catalog, variant, designSource, skillRoot);
2787
+ return { catalog, catalogRelPath };
2788
+ }
2789
+
2790
+ function loadCatalogFromState(skillRoot, runDir) {
2791
+ const statePath = join(runDir, 'workflow-state.json');
2792
+ const state = readJson(statePath, 'workflow-state');
2793
+ if (!state.variant || !['full', 'fast'].includes(state.variant)) {
2794
+ fail('workflow-state.variant is missing or invalid');
2795
+ }
2796
+ const designSource = state.designSource ?? 'pixso';
2797
+ if (!VALID_SOURCES.has(designSource)) {
2798
+ fail('workflow-state.designSource is invalid');
2799
+ }
2800
+ if (state.variant !== metadata.variant || designSource !== metadata.designSource) { fail('Workflow source/variant does not match CLI run.json'); }
2801
+ const { catalog, catalogRelPath } = loadCatalogForVariant(skillRoot, state.variant, designSource);
2802
+ return { state, catalog, catalogRelPath, statePath };
2803
+ }
2804
+
2805
+ function outputDigestError(state, catalog, digestResult) {
2806
+ process.stdout.write(`${JSON.stringify({
2807
+ workflow: catalog.workflow,
2808
+ variant: catalog.variant,
2809
+ designSource: state.designSource ?? 'pixso',
2810
+ status: state.status,
2811
+ currentStage: state.currentStage,
2812
+ error: 'workflow_digest_mismatch',
2813
+ message: 'Workflow instruction files have changed since initialization. Create a new run to use the updated files; preserve the existing run and its artifacts.',
2814
+ expectedDigest: digestResult.expected,
2815
+ actualDigest: digestResult.actual
2816
+ }, null, 2)}\n`);
2817
+ process.exit(1);
2818
+ }
2819
+
2820
+ function isCurrentStageConfirmed(state, catalog) {
2821
+ const stageInfo = catalog.stages.find((entry) => entry.id === state.currentStage);
2822
+ return stageInfo?.requiresConfirmation === true &&
2823
+ Array.isArray(state.confirmedStages) &&
2824
+ state.confirmedStages.includes(state.currentStage);
2825
+ }
2826
+
2827
+ function confirmedStageNextAction(state, catalog) {
2828
+ if (!isCurrentStageConfirmed(state, catalog)) {
2829
+ return null;
2830
+ }
2831
+ return catalog.stages.find((entry) => entry.id === state.currentStage).confirmationContinuesStage === true
2832
+ ? 'resume_confirmed_stage'
2833
+ : 'stage_complete';
2834
+ }
2835
+
2836
+ function checkPendingCurrentGate(runDir, state) {
2837
+ if (state.completedStages.includes(state.currentStage)) {
2838
+ return null;
2839
+ }
2840
+ const gate = readGate(runDir, state.currentStage);
2841
+ if (!gate) {
2842
+ return null;
2843
+ }
2844
+ if (Number(gate.stage) !== state.currentStage) {
2845
+ return { error: 'current_stage_gate_invalid', issues: [`gate.stage ${gate.stage} does not match currentStage ${state.currentStage}`] };
2846
+ }
2847
+ if (gate.status === 'passed') {
2848
+ return { completionResult: 'passed' };
2849
+ }
2850
+ if (gate.status === 'blocked') {
2851
+ if (!gate.reasonCode || !VALID_REASON_CODES.has(gate.reasonCode)) {
2852
+ return { error: 'current_stage_gate_invalid', issues: [`blocked gate has invalid reasonCode: ${gate.reasonCode}`] };
2853
+ }
2854
+ return { completionResult: 'blocked', reasonCode: gate.reasonCode };
2855
+ }
2856
+ return { error: 'current_stage_gate_invalid', issues: [`gate status ${gate.status} is not passed or blocked`] };
2857
+ }
2858
+
2859
+ function deriveNextRequiredAction(state, catalog, runDir) {
2860
+ if (state.status === 'completed') {
2861
+ return 'sync_final_todo_then_finish';
2862
+ }
2863
+ if (state.status === 'blocked') {
2864
+ return 'resolve_blocking_issue';
2865
+ }
2866
+ if (state.status === 'awaiting_confirmation') {
2867
+ // A valid blocked gate for the current stage means a blocked write was
2868
+ // interrupted before the state advanced; replaying the blocked completion
2869
+ // takes precedence over resuming the confirmation question. Invalid gates
2870
+ // never reach here as an action: status fails earlier with
2871
+ // current_stage_gate_invalid.
2872
+ const pendingGate = checkPendingCurrentGate(runDir, state);
2873
+ if (pendingGate?.completionResult === 'blocked') {
2874
+ return 'stage_complete';
2875
+ }
2876
+ return 'resume_confirmation';
2877
+ }
2878
+ const pendingGate = checkPendingCurrentGate(runDir, state);
2879
+ if (pendingGate) {
2880
+ return 'stage_complete';
2881
+ }
2882
+ const confirmationAction = confirmedStageNextAction(state, catalog);
2883
+ if (confirmationAction) {
2884
+ return confirmationAction;
2885
+ }
2886
+ return 'stage_start';
2887
+ }
2888
+
2889
+ function gateSemanticEquals(gate, stage, expectedStatus, expectedReasonCode) {
2890
+ if (Number(gate.stage) !== stage) {
2891
+ return false;
2892
+ }
2893
+ if (gate.status !== expectedStatus) {
2894
+ return false;
2895
+ }
2896
+ if (expectedStatus === 'blocked') {
2897
+ return gate.reasonCode === expectedReasonCode;
2898
+ }
2899
+ return true;
2900
+ }
2901
+
2902
+ function buildCanonicalGate(stage, result, reasonCode, now) {
2903
+ const gate = {
2904
+ stage,
2905
+ status: result,
2906
+ completedAt: now,
2907
+ };
2908
+ if (result === 'blocked') {
2909
+ gate.reasonCode = reasonCode;
2910
+ }
2911
+ if (stage === 1 && result === 'passed' && metadata.designSource === 'figma') {
2912
+ const manifest = readJson(join(runDir, 'inputs-manifest.json'), 'stage 1 inputs manifest');
2913
+ gate.integrationSnapshotSha256 = figmaIntegrationSnapshotDigest(manifest.integrationSnapshot);
2914
+ }
2915
+ return gate;
2916
+ }
2917
+
2918
+ const args = parseArgs(process.argv.slice(2));
2919
+ const mode = args.mode;
2920
+ if (!VALID_MODES.has(mode)) {
2921
+ fail(`--mode must be one of ${[...VALID_MODES].join(', ')}`);
2922
+ }
2923
+ if (!args['run-dir']) {
2924
+ fail('--run-dir is required');
2925
+ }
2926
+
2927
+ const scriptPath = fileURLToPath(import.meta.url);
2928
+ const skillRoot = realpathSync(dirname(dirname(scriptPath)));
2929
+ const runDir = isAbsolute(args['run-dir']) ? resolve(args['run-dir']) : resolve(process.cwd(), args['run-dir']);
2930
+
2931
+ // CLI run metadata owns storage identity; this script alone owns flow state.
2932
+ if (!existsSync(runDir) || realpathSync(runDir) !== runDir) { fail('Use the canonical runDirectory returned by d2a run create'); }
2933
+ const metadata = readJson(join(runDir, 'run.json'), 'CLI run metadata');
2934
+ if (metadata.schemaVersion !== 1 || metadata.runId !== basename(runDir) || !isAbsolute(metadata.projectRoot) || realpathSync(metadata.projectRoot) !== metadata.projectRoot || !['pixso', 'figma'].includes(metadata.designSource) || !['fast', 'full'].includes(metadata.variant)) { fail('Invalid CLI run identity'); }
2935
+ const relativeRun = relative(metadata.projectRoot, runDir).split('\\').join('/');
2936
+ if (!/^\.deveco\/(design2arkts|d2a|design2arkui)\/runs\/[a-f0-9-]{36}$/.test(relativeRun)) { fail('Run must stay inside the project D2A data directory'); }
2937
+ try {
2938
+ acquireFileLock(join(runDir, 'skill-controller.lock'));
2939
+ } catch (error) {
2940
+ fail(error.message);
2941
+ }
2942
+ function skillIndexRelativePath(variant) {
2943
+ return relative(metadata.projectRoot, join(dirname(dirname(runDir)), `skill-run-index-${variant}.json`)).split('\\').join('/');
2944
+ }
2945
+ function assertWritablePath(target) {
2946
+ const allowedIndex = ['fast', 'full'].map((variant) => resolve(metadata.projectRoot, skillIndexRelativePath(variant)));
2947
+ const rel = relative(runDir, resolve(target));
2948
+ if ((rel === '..' || rel.replaceAll('\\', '/').startsWith('../') || isAbsolute(rel)) && !allowedIndex.includes(resolve(target))) { fail('Controller write escapes its run and owned index'); }
2949
+ let parent = dirname(target);
2950
+ while (!existsSync(parent)) { parent = dirname(parent); }
2951
+ if (realpathSync(parent) !== parent) { fail('Controller output parent must not contain symlinks'); }
2952
+ const info = lstatSync(target, { throwIfNoEntry: false });
2953
+ if (info && !info.isFile()) { fail('Controller output must be a regular file without symlinks'); }
2954
+ }
2955
+
2956
+
2957
+ if (mode === 'init') {
2958
+ const variant = args.variant;
2959
+ if (!['full', 'fast'].includes(variant)) {
2960
+ fail('--variant must be full or fast');
2961
+ }
2962
+ const designSource = args.source ?? 'pixso';
2963
+ if (!VALID_SOURCES.has(designSource)) {
2964
+ fail(`--source must be one of ${[...VALID_SOURCES].join(', ')}`);
2965
+ }
2966
+ if (metadata.designSource !== designSource || metadata.variant !== variant) { fail('Controller source/variant must match CLI run.json'); }
2967
+ const statePath = join(runDir, 'workflow-state.json');
2968
+ if (existsSync(statePath)) {
2969
+ fail('workflow-state.json already exists; refusing to overwrite. Use status to inspect or allocate a new run; never delete the existing run to reinitialize.');
2970
+ }
2971
+ const { catalog, catalogRelPath } = loadCatalogForVariant(skillRoot, variant, designSource);
2972
+ const digest = computeWorkflowDigest(skillRoot, catalog, catalogRelPath);
2973
+ mkdirSync(join(runDir, 'stage-gates'), { recursive: true });
2974
+ const now = new Date().toISOString();
2975
+ const responseLanguage = args.language || 'zh-CN';
2976
+ const state = {
2977
+ schemaVersion: 2,
2978
+ workflowVersion: 4,
2979
+ workflow: catalog.workflow,
2980
+ variant,
2981
+ designSource,
2982
+ workflowDigest: digest,
2983
+ responseLanguage,
2984
+ currentStage: 1,
2985
+ completedStages: [],
2986
+ confirmedStages: [],
2987
+ confirmationSnapshots: {},
2988
+ ...(designSource === 'figma' ? { integrationSnapshotVersion: 1 } : {}),
2989
+ status: 'running',
2990
+ awaitingConfirmationFor: null,
2991
+ blockedReasonCode: null,
2992
+ createdAt: now,
2993
+ updatedAt: now
2994
+ };
2995
+ writeJsonAtomic(statePath, state);
2996
+ writeTodoPayload(runDir, catalog, state);
2997
+ process.stdout.write(`${JSON.stringify({
2998
+ workflow: catalog.workflow,
2999
+ variant,
3000
+ designSource,
3001
+ status: 'running',
3002
+ currentStage: 1,
3003
+ nextRequiredAction: 'stage_start'
3004
+ }, null, 2)}\n`);
3005
+ process.exit(0);
3006
+ }
3007
+
3008
+ if (!existsSync(runDir)) {
3009
+ fail(`run directory does not exist: ${runDir}`);
3010
+ }
3011
+
3012
+ const { state, catalog, catalogRelPath, statePath } = loadCatalogFromState(skillRoot, runDir);
3013
+
3014
+ const digestResult = checkDigest(state, catalog, skillRoot, catalogRelPath);
3015
+ if (digestResult.mismatch) {
3016
+ outputDigestError(state, catalog, digestResult);
3017
+ }
3018
+ validateState(state, catalog);
3019
+
3020
+ // Validation context derived once per invocation from the persisted state.
3021
+ // stage2 describes how the current run relates to the run-index (see
3022
+ // deriveFigmaStage2IndexContext) so that completed-stage replays, interrupted
3023
+ // recovery windows, and pre-commit checks each get the right strictness.
3024
+ const evidenceContext = {
3025
+ stage2: deriveFigmaStage2IndexContext(runDir, catalog, state),
3026
+ requireIntegrationSnapshotLock: state.integrationSnapshotVersion === 1,
3027
+ };
3028
+
3029
+ // Every non-init mode settles a pending design-doc recovery request before any
3030
+ // gate validation or design-doc assessment runs.
3031
+ checkPendingDesignDocRecovery(runDir, catalog, state);
3032
+
3033
+ if (mode === 'status') {
3034
+ // A blocked run must keep reporting its original blocker; a missing
3035
+ // design-doc.md in a completed stage is waived so it neither errors nor
3036
+ // triggers recovery. Other gate structure and non-doc evidence stay checked.
3037
+ const statusEvidenceContext = state.status === 'blocked'
3038
+ ? { ...evidenceContext, waiveDesignDocEvidence: true }
3039
+ : evidenceContext;
3040
+ const gateIssues = collectCompletedGateIssues(runDir, catalog, state, statusEvidenceContext);
3041
+ // For non-terminal states an invalid current-stage gate is an error, not a
3042
+ // nextRequiredAction. Checked once here for both Figma and Pixso so the
3043
+ // error always precedes confirmation-snapshot issues and todo writes.
3044
+ let statusPendingGate = null;
3045
+ if (state.status === 'running' || state.status === 'awaiting_confirmation') {
3046
+ statusPendingGate = checkPendingCurrentGate(runDir, state);
3047
+ if (statusPendingGate?.error) {
3048
+ process.stdout.write(`${JSON.stringify({
3049
+ workflow: catalog.workflow,
3050
+ variant: catalog.variant,
3051
+ designSource: state.designSource ?? 'pixso',
3052
+ status: state.status,
3053
+ currentStage: state.currentStage,
3054
+ error: statusPendingGate.error,
3055
+ issues: statusPendingGate.issues
3056
+ }, null, 2)}\n`);
3057
+ process.exit(1);
3058
+ }
3059
+ }
3060
+ // A pending blocked gate means the blocked write was interrupted before the
3061
+ // state advanced; replaying the blocked completion takes precedence over
3062
+ // every completed-stage evidence error below (including design-doc
3063
+ // recovery) so the state write can be completed first.
3064
+ const recoveringBlockedWrite = statusPendingGate?.completionResult === 'blocked';
3065
+ if (!recoveringBlockedWrite && state.status !== 'blocked') {
3066
+ // A completed doc stage with an invalid design-doc.md is assessed first so
3067
+ // recovery (or the explicit evidence-incomplete block) takes priority over
3068
+ // the generic completed-stage gate error below.
3069
+ const docStage = designDocStage(catalog);
3070
+ if (requiresDesignDocMissingGuard(catalog, docStage) && state.completedStages.includes(docStage)) {
3071
+ const assessment = assessDesignDocRecovery(runDir, catalog, state);
3072
+ if (assessment.outcome !== 'none') {
3073
+ outputDesignDocAssessment(runDir, catalog, state, assessment, { mode: 'status' });
3074
+ process.exit(1);
3075
+ }
3076
+ }
3077
+ }
3078
+ if (!recoveringBlockedWrite && gateIssues.length > 0) {
3079
+ process.stdout.write(`${JSON.stringify({
3080
+ workflow: catalog.workflow,
3081
+ variant: catalog.variant,
3082
+ designSource: state.designSource ?? 'pixso',
3083
+ status: state.status,
3084
+ currentStage: state.currentStage,
3085
+ error: 'completed_stage_gate_invalid',
3086
+ issues: gateIssues
3087
+ }, null, 2)}\n`);
3088
+ process.exit(1);
3089
+ }
3090
+ if (
3091
+ state.status === 'awaiting_confirmation' &&
3092
+ requiresDesignDocMissingGuard(catalog, state.currentStage) &&
3093
+ !recoveringBlockedWrite
3094
+ ) {
3095
+ const assessment = assessDesignDocRecovery(runDir, catalog, state);
3096
+ if (assessment.outcome !== 'none') {
3097
+ outputDesignDocAssessment(runDir, catalog, state, assessment, { mode: 'status' });
3098
+ process.exit(1);
3099
+ }
3100
+ }
3101
+ if (
3102
+ state.status === 'awaiting_confirmation' &&
3103
+ requiresFigmaStage2Confirmation(catalog, state.currentStage)
3104
+ ) {
3105
+ // Recovering an already-written blocked result must not depend on the
3106
+ // current stage's confirmation materials still being intact. Normal
3107
+ // confirmation waiting (and every passed path) keeps the snapshot check.
3108
+ // Invalid gates already failed above, so the gate error keeps priority
3109
+ // over missing or corrupted confirmation snapshots.
3110
+ if (!recoveringBlockedWrite) {
3111
+ const snapshotIssues = collectFigmaStage2ConfirmationSnapshotIssues(runDir, state);
3112
+ if (snapshotIssues.length > 0) {
3113
+ process.stdout.write(`${JSON.stringify({
3114
+ workflow: catalog.workflow,
3115
+ variant: catalog.variant,
3116
+ designSource: state.designSource ?? 'pixso',
3117
+ status: state.status,
3118
+ currentStage: state.currentStage,
3119
+ error: 'confirmation_snapshot_invalid',
3120
+ issues: snapshotIssues
3121
+ }, null, 2)}\n`);
3122
+ process.exit(1);
3123
+ }
3124
+ }
3125
+ }
3126
+ const payload = writeTodoPayload(runDir, catalog, state);
3127
+ const nextRequiredAction = deriveNextRequiredAction(state, catalog, runDir);
3128
+ const result = {
3129
+ workflow: catalog.workflow,
3130
+ variant: catalog.variant,
3131
+ designSource: state.designSource ?? 'pixso',
3132
+ status: state.status,
3133
+ currentStage: state.currentStage,
3134
+ completedStages: state.completedStages,
3135
+ awaitingConfirmationFor: state.awaitingConfirmationFor,
3136
+ blockedReasonCode: state.blockedReasonCode,
3137
+ nextRequiredAction
3138
+ };
3139
+ if (state.status === 'completed') {
3140
+ result.todoPayloadPath = join(runDir, 'todo-payload.json');
3141
+ }
3142
+ if (state.status === 'awaiting_confirmation') {
3143
+ result.instructionPath = catalog.stages.find((entry) => entry.id === state.currentStage).instructionPath;
3144
+ }
3145
+ if (nextRequiredAction === 'resume_confirmed_stage') {
3146
+ result.instructionPath = catalog.stages.find((entry) => entry.id === state.currentStage).instructionPath;
3147
+ }
3148
+ if (nextRequiredAction === 'stage_complete') {
3149
+ // Invalid gates already exited above with current_stage_gate_invalid; the
3150
+ // pending gate here is a valid one (or absent for a confirmed stage).
3151
+ if (statusPendingGate) {
3152
+ result.completionResult = statusPendingGate.completionResult;
3153
+ if (statusPendingGate.reasonCode) {
3154
+ result.reasonCode = statusPendingGate.reasonCode;
3155
+ }
3156
+ } else {
3157
+ result.completionResult = 'passed';
3158
+ }
3159
+ }
3160
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
3161
+ process.exit(0);
3162
+ }
3163
+
3164
+ if (mode === 'stage-start') {
3165
+ const requestedStage = Number(args.stage);
3166
+ if (!catalog.stages.some((entry) => entry.id === requestedStage)) {
3167
+ fail('--stage must be a stage ID in the catalog');
3168
+ }
3169
+ const issues = collectCompletedGateIssues(runDir, catalog, state, evidenceContext);
3170
+ if (state.status === 'blocked') {
3171
+ issues.push(`workflow is blocked: ${state.blockedReasonCode}`);
3172
+ } else if (state.status === 'completed') {
3173
+ issues.push('workflow is already completed');
3174
+ } else if (state.status === 'awaiting_confirmation') {
3175
+ issues.push(`workflow is awaiting confirmation for stage ${state.awaitingConfirmationFor}`);
3176
+ if (requiresFigmaStage2Confirmation(catalog, requestedStage)) {
3177
+ issues.push(...collectFigmaStage2ConfirmationSnapshotIssues(runDir, state));
3178
+ }
3179
+ }
3180
+ if (state.status === 'running' && isCurrentStageConfirmed(state, catalog)) {
3181
+ const action = confirmedStageNextAction(state, catalog);
3182
+ issues.push(
3183
+ action === 'resume_confirmed_stage'
3184
+ ? `stage ${requestedStage} has been confirmed; resume the loaded stage without another stage-start`
3185
+ : `stage ${requestedStage} has been confirmed; call stage-complete --result passed`
3186
+ );
3187
+ }
3188
+ // Check pending current gate
3189
+ let pendingGateResult = null;
3190
+ if (state.status === 'running' && !state.completedStages.includes(requestedStage) && requestedStage === state.currentStage) {
3191
+ pendingGateResult = checkPendingCurrentGate(runDir, state);
3192
+ if (pendingGateResult?.error) {
3193
+ process.stdout.write(`${JSON.stringify({
3194
+ ready: false,
3195
+ error: pendingGateResult.error,
3196
+ stage: requestedStage,
3197
+ issues: pendingGateResult.issues
3198
+ }, null, 2)}\n`);
3199
+ process.exit(1);
3200
+ }
3201
+ if (pendingGateResult) {
3202
+ issues.push(`stage ${requestedStage} has a pending gate; call stage-complete --result ${pendingGateResult.completionResult}`);
3203
+ }
3204
+ }
3205
+ if (requestedStage !== state.currentStage) {
3206
+ issues.push(`requested stage ${requestedStage} differs from currentStage ${state.currentStage}`);
3207
+ }
3208
+ const uniqueIssues = [...new Set(issues)];
3209
+ const ready = uniqueIssues.length === 0;
3210
+ const docStage = designDocStage(catalog);
3211
+ const completedDocAssessment =
3212
+ requiresDesignDocMissingGuard(catalog, docStage) && state.completedStages.includes(docStage)
3213
+ ? assessDesignDocRecovery(runDir, catalog, state)
3214
+ : { outcome: 'none', issues: [] };
3215
+ const designDocRecoveryNeeded = completedDocAssessment.outcome === 'restore_document' ||
3216
+ completedDocAssessment.outcome === 'resume_design_generation';
3217
+ const designDocEvidenceIncomplete = completedDocAssessment.outcome === 'blocked_missing_upstream_evidence';
3218
+ // Priority: blocked-gate recovery > design-doc recovery > design-doc evidence
3219
+ // block > pending passed gate > confirmed-stage continuation > generic
3220
+ // issue resolution.
3221
+ let nextRequiredAction;
3222
+ if (ready) {
3223
+ nextRequiredAction = 'load_instruction_then_sync_todo_then_run_stage';
3224
+ } else if (pendingGateResult?.completionResult === 'blocked') {
3225
+ nextRequiredAction = 'stage_complete';
3226
+ } else if (designDocRecoveryNeeded) {
3227
+ nextRequiredAction = completedDocAssessment.outcome === 'restore_document'
3228
+ ? 'regenerate_design_doc'
3229
+ : 'resume_design_generation';
3230
+ } else if (designDocEvidenceIncomplete) {
3231
+ nextRequiredAction = 'resolve_issues';
3232
+ } else if (pendingGateResult) {
3233
+ nextRequiredAction = 'stage_complete';
3234
+ } else if (state.status === 'running' && isCurrentStageConfirmed(state, catalog)) {
3235
+ nextRequiredAction = confirmedStageNextAction(state, catalog);
3236
+ } else {
3237
+ nextRequiredAction = 'resolve_issues';
3238
+ }
3239
+ const result = {
3240
+ ready,
3241
+ nextRequiredAction,
3242
+ stage: requestedStage,
3243
+ designSource: state.designSource ?? 'pixso',
3244
+ title: catalog.stages.find((entry) => entry.id === requestedStage)?.title,
3245
+ requiresConfirmation: catalog.stages.find((entry) => entry.id === requestedStage)?.requiresConfirmation ?? false,
3246
+ issues: uniqueIssues
3247
+ };
3248
+ if (nextRequiredAction === 'regenerate_design_doc' || nextRequiredAction === 'resume_design_generation') {
3249
+ result.error = 'design_doc_invalid';
3250
+ result.recovery = prepareDesignDocRecovery(runDir, catalog, state, completedDocAssessment, {
3251
+ mode: 'stage-start',
3252
+ stage: requestedStage
3253
+ });
3254
+ }
3255
+ if (designDocEvidenceIncomplete && nextRequiredAction === 'resolve_issues') {
3256
+ result.error = 'design_stage_evidence_incomplete';
3257
+ }
3258
+ if (ready) {
3259
+ result.instructionPath = catalog.stages.find((entry) => entry.id === requestedStage).instructionPath;
3260
+ writeTodoPayload(runDir, catalog, state);
3261
+ result.todoPayloadPath = join(runDir, 'todo-payload.json');
3262
+ }
3263
+ if (pendingGateResult && !ready) {
3264
+ result.completionResult = pendingGateResult.completionResult;
3265
+ if (pendingGateResult.reasonCode) {
3266
+ result.reasonCode = pendingGateResult.reasonCode;
3267
+ }
3268
+ }
3269
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
3270
+ process.exit(0);
3271
+ }
3272
+
3273
+ if (mode === 'confirm') {
3274
+ const requestedStage = Number(args.stage);
3275
+ if (!catalog.stages.some((entry) => entry.id === requestedStage)) {
3276
+ fail('--stage must be a stage ID in the catalog');
3277
+ }
3278
+ const decision = args.decision;
3279
+ if (!decision || !VALID_DECISIONS.has(decision)) {
3280
+ fail(`--decision must be one of ${[...VALID_DECISIONS].join(', ')}`);
3281
+ }
3282
+ if (requestedStage !== state.currentStage) {
3283
+ fail(`can only confirm the current stage ${state.currentStage}, got ${requestedStage}`);
3284
+ }
3285
+ const stageInfo = catalog.stages.find((entry) => entry.id === requestedStage);
3286
+ if (!stageInfo.requiresConfirmation) {
3287
+ fail(`stage ${requestedStage} does not require confirmation`);
3288
+ }
3289
+ // Checked before any evidence validation so a blocked (or otherwise
3290
+ // non-running) run can never be handed a design-doc recovery action.
3291
+ if (decision === 'request' && state.status !== 'running') {
3292
+ fail(`request decision requires status running, got ${state.status}`);
3293
+ }
3294
+ const gateIssues = collectCompletedGateIssues(runDir, catalog, state, evidenceContext);
3295
+ if (gateIssues.length > 0) {
3296
+ const docStage = designDocStage(catalog);
3297
+ if (requiresDesignDocMissingGuard(catalog, docStage) && state.completedStages.includes(docStage)) {
3298
+ const assessment = assessDesignDocRecovery(runDir, catalog, state);
3299
+ if (assessment.outcome !== 'none') {
3300
+ failWithDesignDocAssessment(
3301
+ runDir,
3302
+ catalog,
3303
+ state,
3304
+ assessment,
3305
+ { mode: 'confirm', stage: requestedStage, decision },
3306
+ `cannot confirm: completed stage gate issues: ${gateIssues.join('; ')}`
3307
+ );
3308
+ }
3309
+ }
3310
+ fail(`cannot confirm: completed stage gate issues: ${gateIssues.join('; ')}`);
3311
+ }
3312
+ let requestedConfirmationSnapshot = null;
3313
+ if (decision === 'request' && isFigmaStage2(catalog, requestedStage)) {
3314
+ const evidenceIssues = collectFigmaComponentRecognitionEvidenceIssues(runDir);
3315
+ requestedConfirmationSnapshot = buildFigmaStage2ConfirmationSnapshot(runDir, evidenceIssues);
3316
+ if (evidenceIssues.length > 0) {
3317
+ fail(`cannot request confirmation: ${evidenceIssues.join('; ')}`);
3318
+ }
3319
+ }
3320
+ if (decision === 'request' && requiresDesignDocMissingGuard(catalog, requestedStage)) {
3321
+ const assessment = assessDesignDocRecovery(runDir, catalog, state);
3322
+ if (assessment.outcome !== 'none') {
3323
+ failWithDesignDocAssessment(
3324
+ runDir,
3325
+ catalog,
3326
+ state,
3327
+ assessment,
3328
+ { mode: 'confirm', stage: requestedStage, decision: 'request' },
3329
+ `cannot request confirmation: ${assessment.issues.join('; ')}`
3330
+ );
3331
+ }
3332
+ }
3333
+ const now = new Date().toISOString();
3334
+ let newState;
3335
+ if (decision === 'request') {
3336
+ newState = {
3337
+ ...state,
3338
+ status: 'awaiting_confirmation',
3339
+ awaitingConfirmationFor: requestedStage,
3340
+ ...(requestedConfirmationSnapshot && {
3341
+ confirmationSnapshots: {
3342
+ ...(state.confirmationSnapshots ?? {}),
3343
+ [String(requestedStage)]: requestedConfirmationSnapshot
3344
+ }
3345
+ }),
3346
+ updatedAt: now
3347
+ };
3348
+ } else if (decision === 'accepted') {
3349
+ if (state.status !== 'awaiting_confirmation') {
3350
+ fail(`accepted decision requires status awaiting_confirmation, got ${state.status}`);
3351
+ }
3352
+ if (state.awaitingConfirmationFor !== requestedStage) {
3353
+ fail(`awaitingConfirmationFor (${state.awaitingConfirmationFor}) does not match requested stage (${requestedStage})`);
3354
+ }
3355
+ if (isFigmaStage2(catalog, requestedStage)) {
3356
+ const snapshotIssues = collectFigmaStage2ConfirmationSnapshotIssues(runDir, state);
3357
+ if (snapshotIssues.length > 0) {
3358
+ fail(`cannot accept confirmation: ${snapshotIssues.join('; ')}`);
3359
+ }
3360
+ }
3361
+ if (requiresDesignDocMissingGuard(catalog, requestedStage)) {
3362
+ const assessment = assessDesignDocRecovery(runDir, catalog, state);
3363
+ if (assessment.outcome !== 'none') {
3364
+ failWithDesignDocAssessment(
3365
+ runDir,
3366
+ catalog,
3367
+ state,
3368
+ assessment,
3369
+ { mode: 'confirm', stage: requestedStage, decision: 'accepted' },
3370
+ `cannot accept confirmation: ${assessment.issues.join('; ')}`
3371
+ );
3372
+ }
3373
+ }
3374
+ const confirmedStages = Array.isArray(state.confirmedStages) ? [...state.confirmedStages] : [];
3375
+ if (!confirmedStages.includes(requestedStage)) {
3376
+ confirmedStages.push(requestedStage);
3377
+ }
3378
+ newState = {
3379
+ ...state,
3380
+ status: 'running',
3381
+ awaitingConfirmationFor: null,
3382
+ confirmedStages,
3383
+ updatedAt: now
3384
+ };
3385
+ } else if (decision === 'revision-requested') {
3386
+ if (state.status !== 'awaiting_confirmation') {
3387
+ fail(`revision-requested decision requires status awaiting_confirmation, got ${state.status}`);
3388
+ }
3389
+ if (state.awaitingConfirmationFor !== requestedStage) {
3390
+ fail(`awaitingConfirmationFor (${state.awaitingConfirmationFor}) does not match requested stage (${requestedStage})`);
3391
+ }
3392
+ const confirmedStages = Array.isArray(state.confirmedStages) ? state.confirmedStages.filter((s) => s !== requestedStage) : [];
3393
+ const confirmationSnapshots = { ...(state.confirmationSnapshots ?? {}) };
3394
+ if (isFigmaStage2(catalog, requestedStage)) {
3395
+ delete confirmationSnapshots[2];
3396
+ }
3397
+ newState = {
3398
+ ...state,
3399
+ status: 'running',
3400
+ awaitingConfirmationFor: null,
3401
+ confirmedStages,
3402
+ confirmationSnapshots,
3403
+ updatedAt: now
3404
+ };
3405
+ }
3406
+ writeJsonAtomic(statePath, newState);
3407
+ writeTodoPayload(runDir, catalog, newState);
3408
+ const confirmNextAction = decision === 'request'
3409
+ ? 'await_user_confirmation'
3410
+ : decision === 'accepted'
3411
+ ? stageInfo.confirmationContinuesStage === true
3412
+ ? 'resume_confirmed_stage'
3413
+ : 'stage_complete'
3414
+ : 'stage_start';
3415
+ process.stdout.write(`${JSON.stringify({
3416
+ status: newState.status,
3417
+ currentStage: newState.currentStage,
3418
+ decision,
3419
+ nextRequiredAction: confirmNextAction,
3420
+ ...(confirmNextAction === 'resume_confirmed_stage'
3421
+ ? { instructionPath: stageInfo.instructionPath }
3422
+ : {})
3423
+ }, null, 2)}\n`);
3424
+ process.exit(0);
3425
+ }
3426
+
3427
+ if (mode === 'stage-complete') {
3428
+ const requestedStage = Number(args.stage);
3429
+ if (!catalog.stages.some((entry) => entry.id === requestedStage)) {
3430
+ fail('--stage must be a stage ID in the catalog');
3431
+ }
3432
+ const result = args.result;
3433
+ if (!result || !VALID_RESULTS.has(result)) {
3434
+ fail(`--result must be one of ${[...VALID_RESULTS].join(', ')}`);
3435
+ }
3436
+ const reasonCode = args['reason-code'];
3437
+ if (result === 'passed' && reasonCode) {
3438
+ fail('--result=passed must not include --reason-code');
3439
+ }
3440
+ if (result === 'blocked') {
3441
+ if (!reasonCode || !VALID_REASON_CODES.has(reasonCode)) {
3442
+ fail(`--reason-code must be one of ${[...VALID_REASON_CODES].join(', ')} when --result=blocked`);
3443
+ }
3444
+ }
3445
+
3446
+ // Idempotent replay: already completed stage
3447
+ if (state.completedStages.includes(requestedStage)) {
3448
+ if (result !== 'passed') {
3449
+ fail(`stage ${requestedStage} is already completed; only result=passed replay is allowed`);
3450
+ }
3451
+ // Full validation including gate structure and special evidence
3452
+ const replayIssues = checkCompletedGateIssues(runDir, catalog, requestedStage, state, evidenceContext);
3453
+ if (replayIssues.length > 0) {
3454
+ if (requiresDesignDocMissingGuard(catalog, requestedStage)) {
3455
+ const assessment = assessDesignDocRecovery(runDir, catalog, state);
3456
+ if (assessment.outcome !== 'none') {
3457
+ failWithDesignDocAssessment(
3458
+ runDir,
3459
+ catalog,
3460
+ state,
3461
+ assessment,
3462
+ stageCompleteRetry(requestedStage, 'passed'),
3463
+ `stage ${requestedStage} replay validation failed: ${replayIssues.join('; ')}`
3464
+ );
3465
+ }
3466
+ }
3467
+ fail(`stage ${requestedStage} replay validation failed: ${replayIssues.join('; ')}`);
3468
+ }
3469
+ writeTodoPayload(runDir, catalog, state);
3470
+ const nextRequiredAction = deriveNextRequiredAction(state, catalog, runDir);
3471
+ const replayResult = {
3472
+ alreadyCompleted: true,
3473
+ status: state.status,
3474
+ currentStage: state.currentStage,
3475
+ completedStages: state.completedStages,
3476
+ nextRequiredAction
3477
+ };
3478
+ if (state.status === 'completed') {
3479
+ replayResult.todoPayloadPath = join(runDir, 'todo-payload.json');
3480
+ }
3481
+ process.stdout.write(`${JSON.stringify(replayResult, null, 2)}\n`);
3482
+ process.exit(0);
3483
+ }
3484
+
3485
+ // Reject impossible stage requests
3486
+ if (requestedStage !== state.currentStage) {
3487
+ if (requestedStage > state.currentStage) {
3488
+ fail(`cannot complete future stage ${requestedStage}; current stage is ${state.currentStage}`);
3489
+ }
3490
+ fail(`cannot complete stage ${requestedStage}; current stage is ${state.currentStage}`);
3491
+ }
3492
+ if (state.status === 'blocked') {
3493
+ fail(`workflow is blocked: ${state.blockedReasonCode}; reinitialize the run before continuing`);
3494
+ }
3495
+ if (state.status === 'completed') {
3496
+ fail('workflow is already completed');
3497
+ }
3498
+ if (result === 'passed' && state.status === 'awaiting_confirmation') {
3499
+ fail(`stage ${requestedStage} is still awaiting confirmation; call confirm first`);
3500
+ }
3501
+
3502
+ // A consistent blocked gate on disk means the blocked write was interrupted
3503
+ // before the state advanced. Replaying it must not be blocked by completed
3504
+ // stage design-doc recovery; only the stage, status and reasonCode still
3505
+ // have to match, and the gate consistency check below enforces that.
3506
+ const existingCurrentGate = readGate(runDir, requestedStage);
3507
+ const replayingBlockedWrite =
3508
+ result === 'blocked' &&
3509
+ existingCurrentGate?.status === 'blocked' &&
3510
+ Number(existingCurrentGate.stage) === requestedStage &&
3511
+ existingCurrentGate.reasonCode === reasonCode;
3512
+
3513
+ // Validate completed stage gates
3514
+ const gateIssues = collectCompletedGateIssues(runDir, catalog, state, {
3515
+ ...evidenceContext,
3516
+ waiveDesignDocEvidence: replayingBlockedWrite
3517
+ });
3518
+ if (gateIssues.length > 0) {
3519
+ const docStage = designDocStage(catalog);
3520
+ if (
3521
+ !replayingBlockedWrite &&
3522
+ requiresDesignDocMissingGuard(catalog, docStage) &&
3523
+ state.completedStages.includes(docStage)
3524
+ ) {
3525
+ const assessment = assessDesignDocRecovery(runDir, catalog, state);
3526
+ if (assessment.outcome !== 'none') {
3527
+ failWithDesignDocAssessment(
3528
+ runDir,
3529
+ catalog,
3530
+ state,
3531
+ assessment,
3532
+ stageCompleteRetry(requestedStage, result, reasonCode),
3533
+ `cannot complete: completed stage gate issues: ${gateIssues.join('; ')}`
3534
+ );
3535
+ }
3536
+ }
3537
+ fail(`cannot complete: completed stage gate issues: ${gateIssues.join('; ')}`);
3538
+ }
3539
+
3540
+ // Validate confirmation if required — the confirmation requirement only
3541
+ // constrains passing the stage; blocked may be recorded from any non-terminal
3542
+ // state, including before or during confirmation.
3543
+ const stageInfo = catalog.stages.find((entry) => entry.id === requestedStage);
3544
+ if (result === 'passed' && stageInfo.requiresConfirmation) {
3545
+ const confirmedStages = Array.isArray(state.confirmedStages) ? state.confirmedStages : [];
3546
+ if (!confirmedStages.includes(requestedStage)) {
3547
+ fail(`stage ${requestedStage} requires confirmation but has not been confirmed`);
3548
+ }
3549
+ }
3550
+
3551
+ // Source-specific Full workflow evidence validation.
3552
+ if (result === 'passed') {
3553
+ const evidenceIssues = [
3554
+ ...collectStageEvidenceIssues(runDir, catalog, requestedStage, { ...evidenceContext, live: true }),
3555
+ ...(requiresFigmaStage2Confirmation(catalog, requestedStage)
3556
+ ? collectFigmaStage2ConfirmationSnapshotIssues(runDir, state)
3557
+ : [])
3558
+ ];
3559
+ if (requiresDesignDocMissingGuard(catalog, requestedStage)) {
3560
+ const assessment = assessDesignDocRecovery(runDir, catalog, state);
3561
+ if (assessment.outcome !== 'none') {
3562
+ failWithDesignDocAssessment(
3563
+ runDir,
3564
+ catalog,
3565
+ state,
3566
+ assessment,
3567
+ stageCompleteRetry(requestedStage, result),
3568
+ evidenceIssues.join('; ')
3569
+ );
3570
+ }
3571
+ }
3572
+ if (evidenceIssues.length > 0) {
3573
+ fail(evidenceIssues.join('; '));
3574
+ }
3575
+ }
3576
+
3577
+ const now = new Date().toISOString();
3578
+ const canonicalGate = buildCanonicalGate(requestedStage, result, reasonCode, now);
3579
+
3580
+ // Check for existing gate conflicts
3581
+ const existingGate = existingCurrentGate;
3582
+ if (existingGate) {
3583
+ if (gateSemanticEquals(existingGate, requestedStage, result, reasonCode)) {
3584
+ // Consistent gate from interrupted write — keep original completedAt, proceed to state
3585
+ canonicalGate.completedAt = existingGate.completedAt;
3586
+ } else {
3587
+ process.stdout.write(`${JSON.stringify({
3588
+ error: 'gate_result_conflict',
3589
+ stage: requestedStage,
3590
+ existingStatus: existingGate.status,
3591
+ existingReasonCode: existingGate.reasonCode,
3592
+ requestedResult: result,
3593
+ requestedReasonCode: reasonCode
3594
+ }, null, 2)}\n`);
3595
+ process.exit(1);
3596
+ }
3597
+ }
3598
+
3599
+ writeJsonAtomic(gatePath(runDir, requestedStage), canonicalGate);
3600
+
3601
+ if (result === 'passed' && isFigmaStage2(catalog, requestedStage)) {
3602
+ const policy = readJsonOrNull(join(runDir, FIGMA_STAGE2_STARTUP_POLICY), 'stage 2 startup page policy', []);
3603
+ if (policy) {
3604
+ const projectRoot = resolveLockedProjectRoot(
3605
+ runDir,
3606
+ policy.projectRootPath,
3607
+ 'stage 2 startup page policy projectRootPath',
3608
+ []
3609
+ );
3610
+ if (projectRoot) {
3611
+ updateRunIndex(runDir, projectRoot, policy);
3612
+ }
3613
+ }
3614
+ }
3615
+
3616
+ if (result === 'passed' && metadata.designSource === 'pixso' && requestedStage === 2) {
3617
+ const issues = [];
3618
+ const policy = readPixsoRoutePolicy(runDir, issues);
3619
+ if (!policy || issues.length) fail(issues.join('; '));
3620
+ updateRunIndex(runDir, metadata.projectRoot, policy);
3621
+ }
3622
+
3623
+ if (result === 'blocked') {
3624
+ const newState = {
3625
+ ...state,
3626
+ status: 'blocked',
3627
+ blockedReasonCode: reasonCode,
3628
+ awaitingConfirmationFor: null,
3629
+ updatedAt: now
3630
+ };
3631
+ writeJsonAtomic(statePath, newState);
3632
+ writeTodoPayload(runDir, catalog, newState);
3633
+ process.stdout.write(`${JSON.stringify({
3634
+ status: 'blocked',
3635
+ currentStage: newState.currentStage,
3636
+ blockedReasonCode: reasonCode,
3637
+ nextRequiredAction: 'resolve_blocking_issue'
3638
+ }, null, 2)}\n`);
3639
+ process.exit(0);
3640
+ }
3641
+
3642
+ // result === 'passed'
3643
+ const completedStages = [...state.completedStages, requestedStage];
3644
+ const nextStage = catalog.stages[catalog.stages.findIndex((entry) => entry.id === requestedStage) + 1];
3645
+ const isLastStage = nextStage === undefined;
3646
+ const newState = {
3647
+ ...state,
3648
+ completedStages,
3649
+ currentStage: isLastStage ? requestedStage : nextStage.id,
3650
+ status: isLastStage ? 'completed' : 'running',
3651
+ updatedAt: now
3652
+ };
3653
+ writeJsonAtomic(statePath, newState);
3654
+ writeTodoPayload(runDir, catalog, newState);
3655
+ if (isLastStage) {
3656
+ process.stdout.write(`${JSON.stringify({
3657
+ status: 'completed',
3658
+ currentStage: newState.currentStage,
3659
+ completedStages: newState.completedStages,
3660
+ nextRequiredAction: 'sync_final_todo_then_finish',
3661
+ todoPayloadPath: join(runDir, 'todo-payload.json')
3662
+ }, null, 2)}\n`);
3663
+ } else {
3664
+ process.stdout.write(`${JSON.stringify({
3665
+ status: 'running',
3666
+ currentStage: newState.currentStage,
3667
+ completedStages: newState.completedStages,
3668
+ nextRequiredAction: 'stage_start'
3669
+ }, null, 2)}\n`);
3670
+ }
3671
+ process.exit(0);
3672
+ }