@1aboveio/skills 0.0.0-stage → 1.0.0

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 (633) hide show
  1. package/README.md +30 -2
  2. package/bin/cli.mjs +14 -0
  3. package/bin/select-core.mjs +172 -0
  4. package/package.json +146 -4
  5. package/skills/app-dev/airflow/LICENSE +3 -0
  6. package/skills/app-dev/airflow/SKILL.md +199 -0
  7. package/skills/app-dev/airflow/release-check.mjs +93 -0
  8. package/skills/app-dev/android-foundation/LICENSE +3 -0
  9. package/skills/app-dev/android-foundation/SKILL.md +192 -0
  10. package/skills/app-dev/android-foundation/assets/android-ci-job.yml +217 -0
  11. package/skills/app-dev/android-foundation/references/ci.md +87 -0
  12. package/skills/app-dev/android-foundation/references/gotchas.md +221 -0
  13. package/skills/app-dev/android-foundation/references/setup.md +164 -0
  14. package/skills/app-dev/android-foundation/release-check.mjs +93 -0
  15. package/skills/app-dev/android-foundation/scripts/device-run.sh +176 -0
  16. package/skills/app-dev/android-foundation/scripts/device-run.test.mjs +172 -0
  17. package/skills/app-dev/app-debug/LICENSE +3 -0
  18. package/skills/app-dev/app-debug/SKILL.md +110 -0
  19. package/skills/app-dev/app-debug/references/common-errors.md +128 -0
  20. package/skills/app-dev/app-debug/release-check.mjs +93 -0
  21. package/skills/app-dev/better-auth/LICENSE +3 -0
  22. package/skills/app-dev/better-auth/SKILL.md +598 -0
  23. package/skills/app-dev/better-auth/references/feishu-api.md +270 -0
  24. package/skills/app-dev/better-auth/release-check.mjs +93 -0
  25. package/skills/app-dev/data-catalog/LICENSE +3 -0
  26. package/skills/app-dev/data-catalog/SKILL.md +204 -0
  27. package/skills/app-dev/data-catalog/agents/openai.yaml +3 -0
  28. package/skills/app-dev/data-catalog/references/data-catalog-conventions.md +75 -0
  29. package/skills/app-dev/data-catalog/references/field-definitions.md +116 -0
  30. package/skills/app-dev/data-catalog/references/format.md +121 -0
  31. package/skills/app-dev/data-catalog/release-check.mjs +93 -0
  32. package/skills/app-dev/data-catalog/scripts/data-catalog.test.mjs +36 -0
  33. package/skills/app-dev/data-catalog/scripts/data_catalog.py +1392 -0
  34. package/skills/app-dev/data-catalog/scripts/persist-conventions-core.mjs +117 -0
  35. package/skills/app-dev/data-catalog/scripts/persist-conventions.mjs +17 -0
  36. package/skills/app-dev/data-catalog/scripts/test_data_catalog.py +571 -0
  37. package/skills/app-dev/ios-foundation/LICENSE +3 -0
  38. package/skills/app-dev/ios-foundation/SKILL.md +184 -0
  39. package/skills/app-dev/ios-foundation/references/setup.md +243 -0
  40. package/skills/app-dev/ios-foundation/release-check.mjs +93 -0
  41. package/skills/app-dev/monorepo/LICENSE +3 -0
  42. package/skills/app-dev/monorepo/SKILL.md +462 -0
  43. package/skills/app-dev/monorepo/release-check.mjs +93 -0
  44. package/skills/app-dev/nextjs-fullstack/LICENSE +3 -0
  45. package/skills/app-dev/nextjs-fullstack/SKILL.md +211 -0
  46. package/skills/app-dev/nextjs-fullstack/conventions.md +318 -0
  47. package/skills/app-dev/nextjs-fullstack/frontend-conventions.md +61 -0
  48. package/skills/app-dev/nextjs-fullstack/nextjs16.md +287 -0
  49. package/skills/app-dev/nextjs-fullstack/release-check.mjs +93 -0
  50. package/skills/app-dev/nextjs-fullstack/server-actions.md +409 -0
  51. package/skills/app-dev/prisma-setup/LICENSE +3 -0
  52. package/skills/app-dev/prisma-setup/SKILL.md +181 -0
  53. package/skills/app-dev/prisma-setup/nextjs.md +258 -0
  54. package/skills/app-dev/prisma-setup/release-check.mjs +93 -0
  55. package/skills/app-dev/prisma-setup/turborepo.md +301 -0
  56. package/skills/app-dev/pyspark/LICENSE +3 -0
  57. package/skills/app-dev/pyspark/SKILL.md +127 -0
  58. package/skills/app-dev/pyspark/assets/templates/etl.py +748 -0
  59. package/skills/app-dev/pyspark/assets/templates/utils/__init__.py +1 -0
  60. package/skills/app-dev/pyspark/assets/templates/utils/hudi_metadata.py +14 -0
  61. package/skills/app-dev/pyspark/references/diagnosis-and-profiling.md +169 -0
  62. package/skills/app-dev/pyspark/references/etl-contract.md +129 -0
  63. package/skills/app-dev/pyspark/references/production-validation.md +131 -0
  64. package/skills/app-dev/pyspark/references/reconciliation.md +38 -0
  65. package/skills/app-dev/pyspark/references/transformation-design.md +190 -0
  66. package/skills/app-dev/pyspark/references/velocity-feature-calculation.md +193 -0
  67. package/skills/app-dev/pyspark/release-check.mjs +93 -0
  68. package/skills/app-dev/pyspark/scripts/spark_eventlog_summary.py +223 -0
  69. package/skills/app-dev/python-backend/LICENSE +3 -0
  70. package/skills/app-dev/python-backend/SKILL.md +325 -0
  71. package/skills/app-dev/python-backend/assets/uv-install.sh +48 -0
  72. package/skills/app-dev/python-backend/references/uv-installs.md +83 -0
  73. package/skills/app-dev/python-backend/release-check.mjs +93 -0
  74. package/skills/app-dev/shadcn/LICENSE +3 -0
  75. package/skills/app-dev/shadcn/SKILL.md +120 -0
  76. package/skills/app-dev/shadcn/assets/shadcn-small.png +0 -0
  77. package/skills/app-dev/shadcn/assets/shadcn.png +0 -0
  78. package/skills/app-dev/shadcn/cli.md +411 -0
  79. package/skills/app-dev/shadcn/customization.md +224 -0
  80. package/skills/app-dev/shadcn/mcp.md +101 -0
  81. package/skills/app-dev/shadcn/release-check.mjs +93 -0
  82. package/skills/app-dev/shadcn/rules/base-vs-radix.md +323 -0
  83. package/skills/app-dev/shadcn/rules/component-selection.md +67 -0
  84. package/skills/app-dev/shadcn/rules/composition.md +195 -0
  85. package/skills/app-dev/shadcn/rules/data-table.md +201 -0
  86. package/skills/app-dev/shadcn/rules/forms.md +255 -0
  87. package/skills/app-dev/shadcn/rules/icons.md +103 -0
  88. package/skills/app-dev/shadcn/rules/styling.md +167 -0
  89. package/skills/app-dev/zod-v4/LICENSE +3 -0
  90. package/skills/app-dev/zod-v4/SKILL.md +286 -0
  91. package/skills/app-dev/zod-v4/release-check.mjs +93 -0
  92. package/skills/cicd/cloud-build/LICENSE +3 -0
  93. package/skills/cicd/cloud-build/SKILL.md +707 -0
  94. package/skills/cicd/cloud-build/release-check.mjs +93 -0
  95. package/skills/cicd/cloud-debug/LICENSE +3 -0
  96. package/skills/cicd/cloud-debug/SKILL.md +315 -0
  97. package/skills/cicd/cloud-debug/references/build-failures.md +238 -0
  98. package/skills/cicd/cloud-debug/references/deploy-failures.md +376 -0
  99. package/skills/cicd/cloud-debug/references/pipeline-failures.md +378 -0
  100. package/skills/cicd/cloud-debug/release-check.mjs +93 -0
  101. package/skills/cicd/cloud-deploy/LICENSE +3 -0
  102. package/skills/cicd/cloud-deploy/SKILL.md +230 -0
  103. package/skills/cicd/cloud-deploy/references/config-templates.md +257 -0
  104. package/skills/cicd/cloud-deploy/release-check.mjs +93 -0
  105. package/skills/cicd/docker/LICENSE +3 -0
  106. package/skills/cicd/docker/SKILL.md +151 -0
  107. package/skills/cicd/docker/release-check.mjs +93 -0
  108. package/skills/cicd/github-actions/LICENSE +3 -0
  109. package/skills/cicd/github-actions/SKILL.md +111 -0
  110. package/skills/cicd/github-actions/references/audit-profile-optimize.md +150 -0
  111. package/skills/cicd/github-actions/references/ci-case-studies.md +141 -0
  112. package/skills/cicd/github-actions/references/conditional-ci.md +214 -0
  113. package/skills/cicd/github-actions/references/debugging.md +13 -0
  114. package/skills/cicd/github-actions/references/pipeline.md +87 -0
  115. package/skills/cicd/github-actions/references/post-deploy-and-publishing.md +33 -0
  116. package/skills/cicd/github-actions/references/runners.md +253 -0
  117. package/skills/cicd/github-actions/references/security.md +29 -0
  118. package/skills/cicd/github-actions/references/speed-and-audit.md +115 -0
  119. package/skills/cicd/github-actions/references/two-pass-reading.md +92 -0
  120. package/skills/cicd/github-actions/release-check.mjs +93 -0
  121. package/skills/cicd/github-actions/scripts/ci-run-audit-core.mjs +612 -0
  122. package/skills/cicd/github-actions/scripts/ci-run-audit.mjs +4 -0
  123. package/skills/cicd/github-actions/scripts/ci-run-audit.test.mjs +637 -0
  124. package/skills/cicd/github-flow/LICENSE +3 -0
  125. package/skills/cicd/github-flow/SKILL.md +123 -0
  126. package/skills/cicd/github-flow/references/ci-conventions.md +14 -0
  127. package/skills/cicd/github-flow/release-check.mjs +93 -0
  128. package/skills/cicd/github-flow/scripts/flow-core.mjs +105 -0
  129. package/skills/cicd/github-flow/scripts/flow.mjs +81 -0
  130. package/skills/cicd/github-flow/scripts/flow.test.mjs +114 -0
  131. package/skills/cicd/github-flow/scripts/persist-conventions-core.mjs +117 -0
  132. package/skills/cicd/github-flow/scripts/persist-conventions.mjs +49 -0
  133. package/skills/cicd/github-flow/scripts/persist-conventions.test.mjs +108 -0
  134. package/skills/cicd/google-cloud/LICENSE +3 -0
  135. package/skills/cicd/google-cloud/SKILL.md +119 -0
  136. package/skills/cicd/google-cloud/references/gcs.md +469 -0
  137. package/skills/cicd/google-cloud/references/iam.md +451 -0
  138. package/skills/cicd/google-cloud/references/project.md +349 -0
  139. package/skills/cicd/google-cloud/references/secrets.md +336 -0
  140. package/skills/cicd/google-cloud/references/vpc.md +312 -0
  141. package/skills/cicd/google-cloud/release-check.mjs +93 -0
  142. package/skills/cicd/google-cloud/scripts/create-sa.sh +36 -0
  143. package/skills/cicd/google-cloud/scripts/gcp-config.sh +31 -0
  144. package/skills/cicd/google-cloud/scripts/grant-iap.sh +41 -0
  145. package/skills/cicd/google-cloud/scripts/setup-secrets.sh +48 -0
  146. package/skills/cicd/mergify/LICENSE +3 -0
  147. package/skills/cicd/mergify/SKILL.md +102 -0
  148. package/skills/cicd/mergify/assets/templates/mergify.yml +215 -0
  149. package/skills/cicd/mergify/assets/templates/ruleset.json +46 -0
  150. package/skills/cicd/mergify/references/branch-protection.md +282 -0
  151. package/skills/cicd/mergify/references/configuration.md +274 -0
  152. package/skills/cicd/mergify/references/diagnosis.md +109 -0
  153. package/skills/cicd/mergify/references/stacks.md +84 -0
  154. package/skills/cicd/mergify/references/traps.md +119 -0
  155. package/skills/cicd/mergify/references/watch-contract.md +274 -0
  156. package/skills/cicd/mergify/release-check.mjs +93 -0
  157. package/skills/cicd/mergify/scripts/audit-core.mjs +208 -0
  158. package/skills/cicd/mergify/scripts/audit.mjs +4 -0
  159. package/skills/cicd/mergify/scripts/audit.test.mjs +201 -0
  160. package/skills/cicd/mergify/scripts/entrypoints.test.mjs +106 -0
  161. package/skills/cicd/mergify/scripts/pr-620-mergify-comments.fixture.json +30 -0
  162. package/skills/cicd/mergify/scripts/stack-push-core.mjs +258 -0
  163. package/skills/cicd/mergify/scripts/stack-push.mjs +4 -0
  164. package/skills/cicd/mergify/scripts/stack-push.test.mjs +233 -0
  165. package/skills/cicd/mergify/scripts/watch-pr-delivery-core.mjs +1065 -0
  166. package/skills/cicd/mergify/scripts/watch-pr-delivery.mjs +4 -0
  167. package/skills/cicd/mergify/scripts/watch-pr-delivery.test.mjs +1826 -0
  168. package/skills/cicd/podman/LICENSE +3 -0
  169. package/skills/cicd/podman/SKILL.md +71 -0
  170. package/skills/cicd/podman/agents/openai.yaml +4 -0
  171. package/skills/cicd/podman/assets/templates/podman-compose-socket-directory.yml +6 -0
  172. package/skills/cicd/podman/assets/templates/podman-service-override.conf +3 -0
  173. package/skills/cicd/podman/references/compose-compatibility.md +70 -0
  174. package/skills/cicd/podman/references/networking-and-ports.md +74 -0
  175. package/skills/cicd/podman/references/rootless-services-and-sockets.md +156 -0
  176. package/skills/cicd/podman/references/troubleshooting.md +98 -0
  177. package/skills/cicd/podman/release-check.mjs +93 -0
  178. package/skills/content/article-review/LICENSE +3 -0
  179. package/skills/content/article-review/SKILL.md +66 -0
  180. package/skills/content/article-review/references/report-format.md +68 -0
  181. package/skills/content/article-review/references/template-guide.md +79 -0
  182. package/skills/content/article-review/references/template-wechat-payments.md +125 -0
  183. package/skills/content/article-review/release-check.mjs +93 -0
  184. package/skills/content/article-to-image/LICENSE +3 -0
  185. package/skills/content/article-to-image/SKILL.md +91 -0
  186. package/skills/content/article-to-image/references/formats.md +53 -0
  187. package/skills/content/article-to-image/release-check.mjs +93 -0
  188. package/skills/content/flowchart-svg/LICENSE +3 -0
  189. package/skills/content/flowchart-svg/SKILL.md +43 -0
  190. package/skills/content/flowchart-svg/release-check.mjs +93 -0
  191. package/skills/content/flowchart-svg/scripts/export_png.sh +8 -0
  192. package/skills/content/image-gen/LICENSE +3 -0
  193. package/skills/content/image-gen/SKILL.md +192 -0
  194. package/skills/content/image-gen/release-check.mjs +93 -0
  195. package/skills/content/image-gen/scripts/credentials.mjs +217 -0
  196. package/skills/content/image-gen/scripts/credentials.test.mjs +212 -0
  197. package/skills/content/image-gen/scripts/generate.mjs +240 -0
  198. package/skills/content/image-gen/scripts/options.mjs +293 -0
  199. package/skills/content/image-gen/scripts/options.test.mjs +245 -0
  200. package/skills/content/mermaid/LICENSE +3 -0
  201. package/skills/content/mermaid/SKILL.md +635 -0
  202. package/skills/content/mermaid/release-check.mjs +93 -0
  203. package/skills/content/wechat-article-writer/LICENSE +3 -0
  204. package/skills/content/wechat-article-writer/SKILL.md +92 -0
  205. package/skills/content/wechat-article-writer/references/style-selector.md +133 -0
  206. package/skills/content/wechat-article-writer/references/writing-rules.md +152 -0
  207. package/skills/content/wechat-article-writer/release-check.mjs +93 -0
  208. package/skills/content/wechat-article-writer/templates/wechat-comparison.md +52 -0
  209. package/skills/content/wechat-article-writer/templates/wechat-howto.md +51 -0
  210. package/skills/content/wechat-article-writer/templates/wechat-insight.md +50 -0
  211. package/skills/content/wechat-article-writer/templates/wechat-pitfall.md +52 -0
  212. package/skills/content/wechat-publisher/LICENSE +3 -0
  213. package/skills/content/wechat-publisher/SKILL.md +171 -0
  214. package/skills/content/wechat-publisher/references/api.md +105 -0
  215. package/skills/content/wechat-publisher/references/layout-rules.md +57 -0
  216. package/skills/content/wechat-publisher/references/wechat-safe-template.html +86 -0
  217. package/skills/content/wechat-publisher/release-check.mjs +93 -0
  218. package/skills/content/wechat-publisher/scripts/md_to_wechat_html.py +194 -0
  219. package/skills/content/wechat-publisher/scripts/publish.py +239 -0
  220. package/skills/content/wechat-search/LICENSE +3 -0
  221. package/skills/content/wechat-search/SKILL.md +211 -0
  222. package/skills/content/wechat-search/release-check.mjs +93 -0
  223. package/skills/content/wechat-search/scripts/start-chrome.sh +83 -0
  224. package/skills/content/xai-search/LICENSE +3 -0
  225. package/skills/content/xai-search/SKILL.md +79 -0
  226. package/skills/content/xai-search/release-check.mjs +93 -0
  227. package/skills/content/xai-search/scripts/xai_search.sh +187 -0
  228. package/skills/content/xai-search/tests/smoke_test.sh +36 -0
  229. package/skills/core/distill-writing/LICENSE +3 -0
  230. package/skills/core/distill-writing/SKILL.md +74 -0
  231. package/skills/core/distill-writing/references/extraction.md +95 -0
  232. package/skills/core/distill-writing/references/updating.md +46 -0
  233. package/skills/core/distill-writing/release-check.mjs +93 -0
  234. package/skills/core/doc-to-md/LICENSE +3 -0
  235. package/skills/core/doc-to-md/SKILL.md +78 -0
  236. package/skills/core/doc-to-md/release-check.mjs +93 -0
  237. package/skills/core/doc-to-md/scripts/convert.py +157 -0
  238. package/skills/core/editorial-review/LICENSE +3 -0
  239. package/skills/core/editorial-review/SKILL.md +79 -0
  240. package/skills/core/editorial-review/references/checklist.md +94 -0
  241. package/skills/core/editorial-review/release-check.mjs +93 -0
  242. package/skills/core/house-style/LICENSE +3 -0
  243. package/skills/core/house-style/SKILL.md +33 -0
  244. package/skills/core/house-style/references/defaults.md +66 -0
  245. package/skills/core/house-style/references/rules.md +267 -0
  246. package/skills/core/house-style/references/sources.md +27 -0
  247. package/skills/core/house-style/references/style-en.md +131 -0
  248. package/skills/core/house-style/references/style-zh.md +141 -0
  249. package/skills/core/house-style/references/terminology-zh.md +223 -0
  250. package/skills/core/house-style/release-check.mjs +93 -0
  251. package/skills/core/house-style/templates/brd.md +103 -0
  252. package/skills/core/house-style/templates/commercial-proposal.md +93 -0
  253. package/skills/core/house-style/templates/compliance-policy.md +109 -0
  254. package/skills/core/house-style/templates/gap-analysis.md +105 -0
  255. package/skills/core/house-style/templates/general.md +63 -0
  256. package/skills/core/house-style/templates/integration-guide.md +98 -0
  257. package/skills/core/house-style/templates/prd.md +81 -0
  258. package/skills/core/house-style/templates/risk-operations-procedure.md +94 -0
  259. package/skills/core/house-style/templates/technical-spec.md +96 -0
  260. package/skills/core/polish-cn/LICENSE +3 -0
  261. package/skills/core/polish-cn/SKILL.md +102 -0
  262. package/skills/core/polish-cn/references/brief.md +93 -0
  263. package/skills/core/polish-cn/references/models.md +76 -0
  264. package/skills/core/polish-cn/release-check.mjs +93 -0
  265. package/skills/core/polish-cn/scripts/polish-cn.test.mjs +244 -0
  266. package/skills/core/polish-cn/scripts/polish_blocks.py +489 -0
  267. package/skills/core/reg-parser/LICENSE +3 -0
  268. package/skills/core/reg-parser/SKILL.md +212 -0
  269. package/skills/core/reg-parser/references/checklist-schema.md +223 -0
  270. package/skills/core/reg-parser/references/checklists/hk-amlo-checklist.json +1306 -0
  271. package/skills/core/reg-parser/references/checklists/hk-amlo-checklist.md +469 -0
  272. package/skills/core/reg-parser/references/checklists/hk-fi-corporate-onboarding-cdd-checklist.json +634 -0
  273. package/skills/core/reg-parser/references/checklists/hk-fi-corporate-onboarding-cdd-checklist.md +233 -0
  274. package/skills/core/reg-parser/references/checklists/hk-mso-guideline-checklist.json +2194 -0
  275. package/skills/core/reg-parser/references/checklists/hk-mso-guideline-checklist.md +771 -0
  276. package/skills/core/reg-parser/references/checklists/kyc-aml-checklist.md +258 -0
  277. package/skills/core/reg-parser/references/checklists/visa-vars-checklist.md +1058 -0
  278. package/skills/core/reg-parser/references/mandates/hk-amlo-cap615.md +389 -0
  279. package/skills/core/reg-parser/references/mandates/visa-vars.md +205 -0
  280. package/skills/core/reg-parser/release-check.mjs +93 -0
  281. package/skills/core/reg-parser/scripts/compare_checklist.py +230 -0
  282. package/skills/core/reg-parser/scripts/dump_checklist.py +361 -0
  283. package/skills/core/reg-parser/scripts/preprocess-mandate.sh +187 -0
  284. package/skills/core/reg-parser/scripts/reg-parser.test.mjs +165 -0
  285. package/skills/core/reg-parser/scripts/test_quarantine.sh +105 -0
  286. package/skills/core/reg-parser/scripts/validate_checklist.py +563 -0
  287. package/skills/core/reg-parser/scripts/validate_mandate.py +273 -0
  288. package/skills/core/terminology/LICENSE +3 -0
  289. package/skills/core/terminology/SKILL.md +62 -0
  290. package/skills/core/terminology/references/format.md +50 -0
  291. package/skills/core/terminology/references/init.md +32 -0
  292. package/skills/core/terminology/release-check.mjs +93 -0
  293. package/skills/core/write-doc/LICENSE +3 -0
  294. package/skills/core/write-doc/SKILL.md +141 -0
  295. package/skills/core/write-doc/references/bilingual.md +60 -0
  296. package/skills/core/write-doc/release-check.mjs +93 -0
  297. package/skills/engineering/better-review/LICENSE +3 -0
  298. package/skills/engineering/better-review/SKILL.md +249 -0
  299. package/skills/engineering/better-review/agents/openai.yaml +9 -0
  300. package/skills/engineering/better-review/references/domain-hazards.md +53 -0
  301. package/skills/engineering/better-review/references/passes.md +147 -0
  302. package/skills/engineering/better-review/references/result.md +151 -0
  303. package/skills/engineering/better-review/release-check.mjs +93 -0
  304. package/skills/engineering/better-review/scripts/pr-context.mjs +212 -0
  305. package/skills/engineering/better-review/scripts/pr-context.test.mjs +168 -0
  306. package/skills/engineering/better-review/scripts/rereview-scope.mjs +503 -0
  307. package/skills/engineering/better-review/scripts/rereview-scope.test.mjs +587 -0
  308. package/skills/engineering/better-review/scripts/scan-diff.mjs +365 -0
  309. package/skills/engineering/better-review/scripts/scan-diff.test.mjs +414 -0
  310. package/skills/engineering/better-review/scripts/vendor-sync.test.mjs +96 -0
  311. package/skills/engineering/e2e-test/LICENSE +3 -0
  312. package/skills/engineering/e2e-test/SKILL.md +98 -0
  313. package/skills/engineering/e2e-test/assets/ci-gates.cloudbuild.yaml +24 -0
  314. package/skills/engineering/e2e-test/references/authoring/auth-flows.md +159 -0
  315. package/skills/engineering/e2e-test/references/authoring/playwright-config.md +73 -0
  316. package/skills/engineering/e2e-test/references/authoring/playwright-patterns.md +144 -0
  317. package/skills/engineering/e2e-test/references/ci-integration.md +25 -0
  318. package/skills/engineering/e2e-test/references/ci-playwright-container.md +290 -0
  319. package/skills/engineering/e2e-test/references/presentation-sweep.md +104 -0
  320. package/skills/engineering/e2e-test/references/reviewing.md +41 -0
  321. package/skills/engineering/e2e-test/references/route-manifest.md +51 -0
  322. package/skills/engineering/e2e-test/release-check.mjs +93 -0
  323. package/skills/engineering/e2e-test/scripts/detect-routes-nextjs.mjs +200 -0
  324. package/skills/engineering/e2e-test/scripts/presentation-checks.mjs +171 -0
  325. package/skills/engineering/e2e-test/scripts/presentation-checks.test.mjs +106 -0
  326. package/skills/engineering/e2e-test/scripts/presentation-perceivability.mjs +179 -0
  327. package/skills/engineering/e2e-test/scripts/presentation-perceivability.test.mjs +117 -0
  328. package/skills/engineering/e2e-test/scripts/presentation-reachability.mjs +154 -0
  329. package/skills/engineering/e2e-test/scripts/presentation-reachability.test.mjs +69 -0
  330. package/skills/engineering/e2e-test/scripts/presentation-render-health.mjs +141 -0
  331. package/skills/engineering/e2e-test/scripts/presentation-render-health.test.mjs +98 -0
  332. package/skills/engineering/e2e-test/scripts/presentation-sweep.mjs +147 -0
  333. package/skills/engineering/e2e-test/scripts/presentation-sweep.test.mjs +71 -0
  334. package/skills/engineering/e2e-test/scripts/presentation-temporal.mjs +127 -0
  335. package/skills/engineering/e2e-test/scripts/presentation-temporal.test.mjs +59 -0
  336. package/skills/engineering/e2e-test/scripts/project-route-manifest.mjs +82 -0
  337. package/skills/engineering/e2e-test/scripts/project-route-manifest.test.mjs +76 -0
  338. package/skills/engineering/e2e-test/scripts/validate-manifest.mjs +106 -0
  339. package/skills/engineering/engineering-runtime/LICENSE +3 -0
  340. package/skills/engineering/engineering-runtime/SKILL.md +11 -0
  341. package/skills/engineering/engineering-runtime/agents/openai.yaml +6 -0
  342. package/skills/engineering/engineering-runtime/coherence/workflow.json +597 -0
  343. package/skills/engineering/engineering-runtime/engineering-runtime.test.mjs +68 -0
  344. package/skills/engineering/engineering-runtime/release-check.mjs +93 -0
  345. package/skills/engineering/engineering-runtime/scripts/exact-head-artifact.mjs +131 -0
  346. package/skills/engineering/engineering-runtime/scripts/head-check-set.mjs +398 -0
  347. package/skills/engineering/engineering-runtime/scripts/invocation-policy.mjs +187 -0
  348. package/skills/engineering/engineering-runtime/scripts/invocation-policy.test.mjs +95 -0
  349. package/skills/engineering/engineering-runtime/scripts/main-module.mjs +79 -0
  350. package/skills/engineering/engineering-runtime/scripts/main-module.test.mjs +288 -0
  351. package/skills/engineering/engineering-runtime/scripts/mergify-yaml.mjs +11 -0
  352. package/skills/engineering/engineering-runtime/scripts/package-lock.json +43 -0
  353. package/skills/engineering/engineering-runtime/scripts/package.json +10 -0
  354. package/skills/engineering/engineering-runtime/scripts/required-check-plan.mjs +223 -0
  355. package/skills/engineering/engineering-runtime/scripts/required-check-plan.test.mjs +96 -0
  356. package/skills/engineering/engineering-runtime/scripts/review-completion.mjs +56 -0
  357. package/skills/engineering/engineering-runtime/scripts/workflow-coherence.mjs +595 -0
  358. package/skills/engineering/engineering-runtime/scripts/workflow-policy.mjs +189 -0
  359. package/skills/engineering/engineering-runtime/scripts/yaml-mapping.mjs +18 -0
  360. package/skills/engineering/ensure-coverage/LICENSE +3 -0
  361. package/skills/engineering/ensure-coverage/SKILL.md +129 -0
  362. package/skills/engineering/ensure-coverage/references/breadth/coverage-ledger.md +92 -0
  363. package/skills/engineering/ensure-coverage/references/breadth/inventory-contract.md +85 -0
  364. package/skills/engineering/ensure-coverage/references/breadth/surface-baseline.md +44 -0
  365. package/skills/engineering/ensure-coverage/references/breadth/surface-discovery.md +16 -0
  366. package/skills/engineering/ensure-coverage/references/depth/characterization.md +68 -0
  367. package/skills/engineering/ensure-coverage/references/depth/coverage.config.example.json +19 -0
  368. package/skills/engineering/ensure-coverage/references/depth/grading.md +35 -0
  369. package/skills/engineering/ensure-coverage/references/depth/mock-policy.md +57 -0
  370. package/skills/engineering/ensure-coverage/references/depth/test-smells.md +39 -0
  371. package/skills/engineering/ensure-coverage/references/enforcement/ci-contract.md +44 -0
  372. package/skills/engineering/ensure-coverage/references/examples/coverage-ledger.md +110 -0
  373. package/skills/engineering/ensure-coverage/references/examples/refund-flow.md +35 -0
  374. package/skills/engineering/ensure-coverage/references/presentation/axis.md +64 -0
  375. package/skills/engineering/ensure-coverage/references/process/audit-mode.md +27 -0
  376. package/skills/engineering/ensure-coverage/references/process/output-template.md +139 -0
  377. package/skills/engineering/ensure-coverage/references/process/test-strategy.md +56 -0
  378. package/skills/engineering/ensure-coverage/release-check.mjs +93 -0
  379. package/skills/engineering/ensure-coverage/schemas/coverage-config.schema.json +67 -0
  380. package/skills/engineering/ensure-coverage/schemas/coverage-file.schema.json +140 -0
  381. package/skills/engineering/ensure-coverage/scripts/README.md +99 -0
  382. package/skills/engineering/ensure-coverage/scripts/adapters/nextjs-inventory.mjs +182 -0
  383. package/skills/engineering/ensure-coverage/scripts/adapters/nextjs-inventory.test.mjs +96 -0
  384. package/skills/engineering/ensure-coverage/scripts/check-quarantine-expiry.mjs +105 -0
  385. package/skills/engineering/ensure-coverage/scripts/check-quarantine-expiry.test.mjs +47 -0
  386. package/skills/engineering/ensure-coverage/scripts/ci-audit.mjs +137 -0
  387. package/skills/engineering/ensure-coverage/scripts/ci-audit.test.mjs +86 -0
  388. package/skills/engineering/ensure-coverage/scripts/coverage-ledger.mjs +674 -0
  389. package/skills/engineering/ensure-coverage/scripts/coverage-ledger.test.mjs +447 -0
  390. package/skills/engineering/ensure-coverage/scripts/design-parity.mjs +591 -0
  391. package/skills/engineering/ensure-coverage/scripts/design-parity.test.mjs +552 -0
  392. package/skills/engineering/ensure-coverage/scripts/lint-tests.mjs +282 -0
  393. package/skills/engineering/ensure-coverage/scripts/lint-tests.test.mjs +289 -0
  394. package/skills/engineering/ensure-coverage/scripts/mock-policy-config.mjs +176 -0
  395. package/skills/engineering/ensure-coverage/scripts/mock-policy-config.test.mjs +119 -0
  396. package/skills/engineering/ensure-coverage/scripts/package.json +19 -0
  397. package/skills/engineering/golden-path/LICENSE +3 -0
  398. package/skills/engineering/golden-path/SKILL.md +230 -0
  399. package/skills/engineering/golden-path/agents/openai.yaml +3 -0
  400. package/skills/engineering/golden-path/assets/golden-paths.example.json +57 -0
  401. package/skills/engineering/golden-path/references/contract.md +239 -0
  402. package/skills/engineering/golden-path/references/migration.md +111 -0
  403. package/skills/engineering/golden-path/release-check.mjs +93 -0
  404. package/skills/engineering/golden-path/scripts/golden-path-core.mjs +1779 -0
  405. package/skills/engineering/golden-path/scripts/golden-path.mjs +6 -0
  406. package/skills/engineering/golden-path/scripts/golden-path.test.mjs +1457 -0
  407. package/skills/engineering/harness-runtime/LICENSE +3 -0
  408. package/skills/engineering/harness-runtime/SKILL.md +19 -0
  409. package/skills/engineering/harness-runtime/agents/openai.yaml +6 -0
  410. package/skills/engineering/harness-runtime/bin/discover-models.mjs +4 -0
  411. package/skills/engineering/harness-runtime/bin/model-catalog.mjs +4 -0
  412. package/skills/engineering/harness-runtime/contracts.md +15 -0
  413. package/skills/engineering/harness-runtime/discover-models.mjs +392 -0
  414. package/skills/engineering/harness-runtime/discover-models.test.mjs +363 -0
  415. package/skills/engineering/harness-runtime/fixtures/native-question-schemas.json +33 -0
  416. package/skills/engineering/harness-runtime/fixtures/question-responses.json +54 -0
  417. package/skills/engineering/harness-runtime/harness-runtime.test.mjs +967 -0
  418. package/skills/engineering/harness-runtime/index.mjs +767 -0
  419. package/skills/engineering/harness-runtime/model-catalog-seed.test.mjs +829 -0
  420. package/skills/engineering/harness-runtime/model-catalog.mjs +787 -0
  421. package/skills/engineering/harness-runtime/model-catalog.test.mjs +366 -0
  422. package/skills/engineering/harness-runtime/native-question-contracts.md +37 -0
  423. package/skills/engineering/harness-runtime/references/model-catalog-seed.json +408 -0
  424. package/skills/engineering/harness-runtime/references/model-catalog.md +57 -0
  425. package/skills/engineering/harness-runtime/release-check.mjs +93 -0
  426. package/skills/engineering/resolve-issues/LICENSE +3 -0
  427. package/skills/engineering/resolve-issues/SKILL.md +250 -0
  428. package/skills/engineering/resolve-issues/agents/openai.yaml +9 -0
  429. package/skills/engineering/resolve-issues/plugin-hooks.json +17 -0
  430. package/skills/engineering/resolve-issues/references/canary.md +28 -0
  431. package/skills/engineering/resolve-issues/references/ci.md +105 -0
  432. package/skills/engineering/resolve-issues/references/done.md +25 -0
  433. package/skills/engineering/resolve-issues/references/dropbox.md +90 -0
  434. package/skills/engineering/resolve-issues/references/expire.md +318 -0
  435. package/skills/engineering/resolve-issues/references/exploration.md +202 -0
  436. package/skills/engineering/resolve-issues/references/implementation.md +303 -0
  437. package/skills/engineering/resolve-issues/references/preflight.md +445 -0
  438. package/skills/engineering/resolve-issues/references/review.md +228 -0
  439. package/skills/engineering/resolve-issues/references/shared-modules.md +44 -0
  440. package/skills/engineering/resolve-issues/references/task-plan.md +264 -0
  441. package/skills/engineering/resolve-issues/release-check.mjs +93 -0
  442. package/skills/engineering/resolve-issues/scripts/cleanup-runs.mjs +364 -0
  443. package/skills/engineering/resolve-issues/scripts/cleanup-runs.test.mjs +280 -0
  444. package/skills/engineering/resolve-issues/scripts/discover-models.mjs +9 -0
  445. package/skills/engineering/resolve-issues/scripts/dropbox.mjs +473 -0
  446. package/skills/engineering/resolve-issues/scripts/dropbox.test.mjs +346 -0
  447. package/skills/engineering/resolve-issues/scripts/findings-reuse.mjs +98 -0
  448. package/skills/engineering/resolve-issues/scripts/findings-reuse.test.mjs +88 -0
  449. package/skills/engineering/resolve-issues/scripts/github-reviews.mjs +384 -0
  450. package/skills/engineering/resolve-issues/scripts/github-reviews.test.mjs +264 -0
  451. package/skills/engineering/resolve-issues/scripts/install-hooks.mjs +135 -0
  452. package/skills/engineering/resolve-issues/scripts/install-hooks.test.mjs +79 -0
  453. package/skills/engineering/resolve-issues/scripts/issue-tree.mjs +162 -0
  454. package/skills/engineering/resolve-issues/scripts/issue-tree.test.mjs +107 -0
  455. package/skills/engineering/resolve-issues/scripts/manual-invocation.test.mjs +14 -0
  456. package/skills/engineering/resolve-issues/scripts/model-catalog.mjs +9 -0
  457. package/skills/engineering/resolve-issues/scripts/next-actions-capacity.test.mjs +149 -0
  458. package/skills/engineering/resolve-issues/scripts/next-actions.mjs +856 -0
  459. package/skills/engineering/resolve-issues/scripts/next-actions.test.mjs +915 -0
  460. package/skills/engineering/resolve-issues/scripts/plan-sync.mjs +269 -0
  461. package/skills/engineering/resolve-issues/scripts/plan-sync.test.mjs +156 -0
  462. package/skills/engineering/resolve-issues/scripts/preflight-models.mjs +736 -0
  463. package/skills/engineering/resolve-issues/scripts/preflight-models.test.mjs +448 -0
  464. package/skills/engineering/resolve-issues/scripts/ready-check.mjs +185 -0
  465. package/skills/engineering/resolve-issues/scripts/ready-check.test.mjs +217 -0
  466. package/skills/engineering/resolve-issues/scripts/rehydrate.mjs +98 -0
  467. package/skills/engineering/resolve-issues/scripts/rehydrate.test.mjs +91 -0
  468. package/skills/engineering/resolve-issues/scripts/review-verdict.mjs +509 -0
  469. package/skills/engineering/resolve-issues/scripts/review-verdict.test.mjs +1060 -0
  470. package/skills/engineering/resolve-issues/scripts/size-check.mjs +492 -0
  471. package/skills/engineering/resolve-issues/scripts/size-check.test.mjs +458 -0
  472. package/skills/engineering/resolve-release/LICENSE +3 -0
  473. package/skills/engineering/resolve-release/SKILL.md +215 -0
  474. package/skills/engineering/resolve-release/agents/openai.yaml +8 -0
  475. package/skills/engineering/resolve-release/flows/cloud-run-canary.md +13 -0
  476. package/skills/engineering/resolve-release/flows/cloud-run.md +7 -0
  477. package/skills/engineering/resolve-release/flows/root-tag-npm.md +13 -0
  478. package/skills/engineering/resolve-release/flows/workspace-npm.md +22 -0
  479. package/skills/engineering/resolve-release/references/canary.md +51 -0
  480. package/skills/engineering/resolve-release/references/candidate.md +41 -0
  481. package/skills/engineering/resolve-release/references/cut.md +131 -0
  482. package/skills/engineering/resolve-release/references/dark-launch.md +66 -0
  483. package/skills/engineering/resolve-release/references/flows.md +150 -0
  484. package/skills/engineering/resolve-release/references/preflight.md +154 -0
  485. package/skills/engineering/resolve-release/references/prepared-metadata.md +260 -0
  486. package/skills/engineering/resolve-release/references/promotion.md +82 -0
  487. package/skills/engineering/resolve-release/references/publish.md +232 -0
  488. package/skills/engineering/resolve-release/references/workspace-npm.md +103 -0
  489. package/skills/engineering/resolve-release/release-check.mjs +93 -0
  490. package/skills/engineering/resolve-release/scripts/apply.mjs +212 -0
  491. package/skills/engineering/resolve-release/scripts/apply.test.mjs +99 -0
  492. package/skills/engineering/resolve-release/scripts/dark-flags.mjs +134 -0
  493. package/skills/engineering/resolve-release/scripts/dark-flags.test.mjs +100 -0
  494. package/skills/engineering/resolve-release/scripts/flow.mjs +500 -0
  495. package/skills/engineering/resolve-release/scripts/flow.test.mjs +340 -0
  496. package/skills/engineering/resolve-release/scripts/green-head.mjs +231 -0
  497. package/skills/engineering/resolve-release/scripts/green-head.test.mjs +101 -0
  498. package/skills/engineering/resolve-release/scripts/npm-version-absence.mjs +138 -0
  499. package/skills/engineering/resolve-release/scripts/npm-version-absence.test.mjs +426 -0
  500. package/skills/engineering/resolve-release/scripts/plan-npm.test.mjs +659 -0
  501. package/skills/engineering/resolve-release/scripts/plan-toml-boundary.test.mjs +317 -0
  502. package/skills/engineering/resolve-release/scripts/plan-uv.test.mjs +291 -0
  503. package/skills/engineering/resolve-release/scripts/plan.mjs +806 -0
  504. package/skills/engineering/resolve-release/scripts/plan.test.mjs +428 -0
  505. package/skills/engineering/rush-issues/LICENSE +3 -0
  506. package/skills/engineering/rush-issues/SKILL.md +58 -0
  507. package/skills/engineering/rush-issues/agents/openai.yaml +8 -0
  508. package/skills/engineering/rush-issues/rehydrate.mjs +10 -0
  509. package/skills/engineering/rush-issues/release-check.mjs +93 -0
  510. package/skills/engineering/rush-release/LICENSE +3 -0
  511. package/skills/engineering/rush-release/SKILL.md +35 -0
  512. package/skills/engineering/rush-release/agents/openai.yaml +8 -0
  513. package/skills/engineering/rush-release/release-check.mjs +93 -0
  514. package/skills/engineering/test-quality/LICENSE +3 -0
  515. package/skills/engineering/test-quality/SKILL.md +79 -0
  516. package/skills/engineering/test-quality/references/audit.md +80 -0
  517. package/skills/engineering/test-quality/references/lint.md +24 -0
  518. package/skills/engineering/test-quality/references/principles.md +143 -0
  519. package/skills/engineering/test-quality/references/testing-conventions.md +9 -0
  520. package/skills/engineering/test-quality/release-check.mjs +93 -0
  521. package/skills/engineering/test-quality/scripts/lint-tests.mjs +574 -0
  522. package/skills/engineering/test-quality/scripts/lint-tests.test.mjs +591 -0
  523. package/skills/engineering/test-quality/scripts/mock-policy-config.mjs +176 -0
  524. package/skills/engineering/test-quality/scripts/mock-policy-config.test.mjs +119 -0
  525. package/skills/engineering/test-quality/scripts/persist-conventions-core.mjs +117 -0
  526. package/skills/engineering/test-quality/scripts/persist-conventions.mjs +17 -0
  527. package/skills/engineering/test-quality/scripts/persist-conventions.test.mjs +104 -0
  528. package/skills/risk-compliance/compliance-audit/LICENSE +3 -0
  529. package/skills/risk-compliance/compliance-audit/SKILL.md +439 -0
  530. package/skills/risk-compliance/compliance-audit/references/findings-schema.md +293 -0
  531. package/skills/risk-compliance/compliance-audit/references/normalization-rules.md +45 -0
  532. package/skills/risk-compliance/compliance-audit/references/vars-checklist.md +1068 -0
  533. package/skills/risk-compliance/compliance-audit/references/vars-findings-schema.md +398 -0
  534. package/skills/risk-compliance/compliance-audit/release-check.mjs +93 -0
  535. package/skills/risk-compliance/compliance-audit/scripts/compliance-audit.test.mjs +14 -0
  536. package/skills/risk-compliance/compliance-audit/scripts/export_tracker_xlsx.py +221 -0
  537. package/skills/risk-compliance/compliance-audit/scripts/reconcile_tracker.py +458 -0
  538. package/skills/risk-compliance/compliance-audit/scripts/test_export_tracker_xlsx.py +97 -0
  539. package/skills/risk-compliance/compliance-audit/scripts/test_validate_tracker.py +157 -0
  540. package/skills/risk-compliance/compliance-audit/scripts/validate_tracker.py +829 -0
  541. package/skills/risk-compliance/contract-compare/LICENSE +3 -0
  542. package/skills/risk-compliance/contract-compare/SKILL.md +199 -0
  543. package/skills/risk-compliance/contract-compare/references/comparison-dimensions.md +209 -0
  544. package/skills/risk-compliance/contract-compare/release-check.mjs +93 -0
  545. package/skills/risk-compliance/contract-review/LICENSE +3 -0
  546. package/skills/risk-compliance/contract-review/SKILL.md +240 -0
  547. package/skills/risk-compliance/contract-review/references/review-criteria.md +223 -0
  548. package/skills/risk-compliance/contract-review/release-check.mjs +93 -0
  549. package/skills/risk-compliance/doc-authenticity/LICENSE +3 -0
  550. package/skills/risk-compliance/doc-authenticity/SKILL.md +160 -0
  551. package/skills/risk-compliance/doc-authenticity/agents/openai.yaml +8 -0
  552. package/skills/risk-compliance/doc-authenticity/manual-invocation.test.mjs +12 -0
  553. package/skills/risk-compliance/doc-authenticity/references/agreement.md +66 -0
  554. package/skills/risk-compliance/doc-authenticity/references/bank-statement.md +150 -0
  555. package/skills/risk-compliance/doc-authenticity/references/forensic-signals.md +157 -0
  556. package/skills/risk-compliance/doc-authenticity/references/image-signals.md +114 -0
  557. package/skills/risk-compliance/doc-authenticity/references/invoice.md +66 -0
  558. package/skills/risk-compliance/doc-authenticity/references/issuer-profiles.md +86 -0
  559. package/skills/risk-compliance/doc-authenticity/references/verdict-and-report.md +95 -0
  560. package/skills/risk-compliance/doc-authenticity/references/verdict.schema.json +81 -0
  561. package/skills/risk-compliance/doc-authenticity/release-check.mjs +93 -0
  562. package/skills/risk-compliance/doc-authenticity/scripts/image_forensics.py +294 -0
  563. package/skills/risk-compliance/doc-authenticity/scripts/pdf_forensics.py +401 -0
  564. package/skills/risk-compliance/doc-authenticity/scripts/validate_codes.py +224 -0
  565. package/skills/risk-compliance/doc-authenticity/scripts/validate_verdict.py +308 -0
  566. package/skills/risk-compliance/doc-authenticity/scripts/validate_verdict.test.mjs +212 -0
  567. package/skills/risk-compliance/fraud-analysis/LICENSE +3 -0
  568. package/skills/risk-compliance/fraud-analysis/SKILL.md +114 -0
  569. package/skills/risk-compliance/fraud-analysis/references/archetypes/authorized-payment-scam.md +41 -0
  570. package/skills/risk-compliance/fraud-analysis/references/archetypes/first-party-fraud.md +44 -0
  571. package/skills/risk-compliance/fraud-analysis/references/archetypes/third-party-fraud.md +27 -0
  572. package/skills/risk-compliance/fraud-analysis/references/contexts/bank-transfer.md +24 -0
  573. package/skills/risk-compliance/fraud-analysis/references/contexts/card-payment.md +30 -0
  574. package/skills/risk-compliance/fraud-analysis/references/contexts/payment-collection.md +20 -0
  575. package/skills/risk-compliance/fraud-analysis/references/contexts/payout.md +20 -0
  576. package/skills/risk-compliance/fraud-analysis/references/feature-engineering.md +158 -0
  577. package/skills/risk-compliance/fraud-analysis/references/mechanisms/account-takeover.md +36 -0
  578. package/skills/risk-compliance/fraud-analysis/references/report-rationale.md +45 -0
  579. package/skills/risk-compliance/fraud-analysis/references/report-template.md +190 -0
  580. package/skills/risk-compliance/fraud-analysis/references/review-checklist.md +175 -0
  581. package/skills/risk-compliance/fraud-analysis/references/taxonomy.md +79 -0
  582. package/skills/risk-compliance/fraud-analysis/references/terminology.md +108 -0
  583. package/skills/risk-compliance/fraud-analysis/references/workflow.md +175 -0
  584. package/skills/risk-compliance/fraud-analysis/release-check.mjs +93 -0
  585. package/skills/risk-compliance/payment-analysis/LICENSE +3 -0
  586. package/skills/risk-compliance/payment-analysis/SKILL.md +180 -0
  587. package/skills/risk-compliance/payment-analysis/references/auth-rate-actions.md +30 -0
  588. package/skills/risk-compliance/payment-analysis/references/chargebacks.md +208 -0
  589. package/skills/risk-compliance/payment-analysis/references/chinese-polish.md +51 -0
  590. package/skills/risk-compliance/payment-analysis/references/event-layers.md +127 -0
  591. package/skills/risk-compliance/payment-analysis/references/fx.md +59 -0
  592. package/skills/risk-compliance/payment-analysis/references/journey.md +79 -0
  593. package/skills/risk-compliance/payment-analysis/references/metrics.md +67 -0
  594. package/skills/risk-compliance/payment-analysis/references/report-template.md +119 -0
  595. package/skills/risk-compliance/payment-analysis/references/terminology.md +95 -0
  596. package/skills/risk-compliance/payment-analysis/references/visualization.md +56 -0
  597. package/skills/risk-compliance/payment-analysis/release-check.mjs +93 -0
  598. package/skills/risk-compliance/report-writing/LICENSE +3 -0
  599. package/skills/risk-compliance/report-writing/SKILL.md +220 -0
  600. package/skills/risk-compliance/report-writing/references/audit-report-template.md +121 -0
  601. package/skills/risk-compliance/report-writing/references/external-assessment-template.md +167 -0
  602. package/skills/risk-compliance/report-writing/references/management-report-template.md +145 -0
  603. package/skills/risk-compliance/report-writing/references/vars-report-template.md +224 -0
  604. package/skills/risk-compliance/report-writing/release-check.mjs +93 -0
  605. package/skills/risk-compliance/similar-domain/LICENSE +3 -0
  606. package/skills/risk-compliance/similar-domain/SKILL.md +203 -0
  607. package/skills/risk-compliance/similar-domain/references/entities.md +67 -0
  608. package/skills/risk-compliance/similar-domain/references/fingerprints.md +134 -0
  609. package/skills/risk-compliance/similar-domain/references/pivots.md +82 -0
  610. package/skills/risk-compliance/similar-domain/references/report-template.md +93 -0
  611. package/skills/risk-compliance/similar-domain/references/scoring.md +130 -0
  612. package/skills/risk-compliance/similar-domain/references/terminology.md +41 -0
  613. package/skills/risk-compliance/similar-domain/references/workflow.md +85 -0
  614. package/skills/risk-compliance/similar-domain/release-check.mjs +93 -0
  615. package/skills/risk-compliance/tld-detection/LICENSE +3 -0
  616. package/skills/risk-compliance/tld-detection/SKILL.md +245 -0
  617. package/skills/risk-compliance/tld-detection/agents/openai.yaml +9 -0
  618. package/skills/risk-compliance/tld-detection/references/chinese-polish.md +55 -0
  619. package/skills/risk-compliance/tld-detection/references/clean.md +51 -0
  620. package/skills/risk-compliance/tld-detection/references/clustering.md +235 -0
  621. package/skills/risk-compliance/tld-detection/references/decision.md +189 -0
  622. package/skills/risk-compliance/tld-detection/references/fx-conversion.md +232 -0
  623. package/skills/risk-compliance/tld-detection/references/report-template.md +272 -0
  624. package/skills/risk-compliance/tld-detection/references/streams.md +141 -0
  625. package/skills/risk-compliance/tld-detection/references/terminology.md +95 -0
  626. package/skills/risk-compliance/tld-detection/references/workflow.md +95 -0
  627. package/skills/risk-compliance/tld-detection/release-check.mjs +93 -0
  628. package/skills/risk-compliance/tld-detection/scripts/detect_ladders.py +390 -0
  629. package/skills/risk-compliance/tld-detection/scripts/detect_ladders.test.mjs +14 -0
  630. package/skills/risk-compliance/tld-detection/scripts/detect_streams.py +650 -0
  631. package/skills/risk-compliance/tld-detection/scripts/detect_streams.test.mjs +14 -0
  632. package/skills/risk-compliance/tld-detection/tests/test_detect_ladders.py +134 -0
  633. package/skills/risk-compliance/tld-detection/tests/test_detect_streams.py +520 -0
@@ -0,0 +1,1779 @@
1
+ // golden-path-core — the golden-path contract engine, import-only. `golden-path.mjs`
2
+ // beside it is the CLI. `init` copies both into each repo at scripts/golden-paths/,
3
+ // so this file imports nothing outside Node's standard library.
4
+ //
5
+ // The contract (golden-paths.json) is the single source. Everything else is
6
+ // generated from it and checked against it:
7
+ // GOLDEN_PATHS.md the human view (render)
8
+ // .github/workflows/golden-paths.yml the CI job (ci)
9
+ // golden-path-results.json one run's observations (run)
10
+ // golden-path-verdict.json ALIVE / DEAD / ... (verdict)
11
+ //
12
+ // node golden-path.mjs init [--app-dir <dir>] [--write] scaffold or refresh a repo
13
+ // node golden-path.mjs audit [--write] [--remove-legacy] find legacy smoke setups; migrate
14
+ // node golden-path.mjs validate [--contract f] [--journeys dir] contract shape + spec tags
15
+ // node golden-path.mjs plan --profile <name> which paths run, which are excluded
16
+ // node golden-path.mjs run --profile <name> [--target url] [--expect-sha sha] [--out f]
17
+ // node golden-path.mjs verdict --profile <name> [--results f] [--target url] [--out f]
18
+ // node golden-path.mjs render [--write] GOLDEN_PATHS.md
19
+ // node golden-path.mjs ci [--write] the workflow
20
+ // node golden-path.mjs check generated files match the contract
21
+ // node golden-path.mjs wait --url <url> [--timeout s] wait for a booted app
22
+ // node golden-path.mjs suggest --inventory <f> candidate paths from a surface inventory
23
+ // node golden-path.mjs version
24
+ //
25
+ // Exit codes: 0 ok / ALIVE, 1 failed / not ALIVE / drift, 2 usage error.
26
+
27
+ import fs from 'node:fs'
28
+ import path from 'node:path'
29
+ import os from 'node:os'
30
+ import crypto from 'node:crypto'
31
+ import { spawn, spawnSync } from 'node:child_process'
32
+ import { fileURLToPath } from 'node:url'
33
+
34
+ export const ENGINE_VERSION = '1.0.0'
35
+ export const CONTRACT_VERSION = 3
36
+
37
+ export const CONTRACT_FILE = 'golden-paths.json'
38
+ export const VIEW_FILE = 'GOLDEN_PATHS.md'
39
+ export const WORKFLOW_FILE = '.github/workflows/golden-paths.yml'
40
+ const GENERATED_MARK = 'GENERATED by the golden-path skill'
41
+
42
+ // One workflow per app: the root app keeps the plain name, so a monorepo with
43
+ // several contracts never has two apps overwrite one file.
44
+ export function workflowFile(appRel = '.') {
45
+ if (appRel === '.') return WORKFLOW_FILE
46
+ const slug = appRel.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
47
+ const tag = crypto.createHash('sha256').update(appRel).digest('hex').slice(0, 6)
48
+ return `.github/workflows/golden-paths-${slug}-${tag}.yml`
49
+ }
50
+ export const ENGINE_FILE = 'scripts/golden-paths/golden-path.mjs'
51
+ export const ENGINE_CORE_FILE = 'scripts/golden-paths/golden-path-core.mjs'
52
+ export const RESULTS_FILE = 'golden-path-results.json'
53
+ export const VERDICT_FILE = 'golden-path-verdict.json'
54
+ export const SERVER_LOG = 'golden-paths-server.log'
55
+ export const BROWSER_REPORT = 'golden-path-playwright.json'
56
+ export const LEGACY_CONTRACT_FILE = 'smoke.manifest.json'
57
+
58
+ export const SURFACES = ['browser', 'api', 'cli']
59
+ export const GATES = ['pull-request', 'merge-queue', 'trunk-integration', 'pre-promotion', 'post-promotion']
60
+ export const ENVIRONMENTS = ['local', 'dev', 'prod']
61
+ export const ENDPOINTS = ['local', 'preview', 'active']
62
+ export const MUTATION_POLICIES = ['isolated-writes', 'synthetic-tenant', 'read-only']
63
+ export const QUEUES = ['mergify', 'github', 'none']
64
+ const TITLE_MAX = 80
65
+ // Values that land in generated YAML or shell must be plain, so a contract can never
66
+ // inject a command or a YAML key. Commands (boot, install, ...) are commands by design.
67
+ const ENV_NAME = /^[A-Z_][A-Z0-9_]*$/
68
+ const URL_SAFE = /^https?:\/\/[A-Za-z0-9.-]+(?::\d+)?(?:\/[A-Za-z0-9._~%/-]*)?$/
69
+ const PATH_SAFE = /^\/(?!\/)[A-Za-z0-9._~%/?=&-]*$/
70
+ const LABEL_SAFE = /^[A-Za-z0-9._ ,[\]-]+$/
71
+ const ENGINE_ENV = ['GOLDEN_PATH_PROFILE', 'BASE_URL']
72
+ const OBSERVABLE_MAX = 300
73
+
74
+ // Each gate pins one (environment, endpoint) pair: PR and queue gates run a local
75
+ // build; trunk-integration the dev service at 100% traffic; pre-promotion the
76
+ // production candidate at 0% traffic; post-promotion the live production service.
77
+ const GATE_AXES = {
78
+ 'pull-request': { environment: 'local', endpoint: 'local' },
79
+ 'merge-queue': { environment: 'local', endpoint: 'local' },
80
+ 'trunk-integration': { environment: 'dev', endpoint: 'active' },
81
+ 'pre-promotion': { environment: 'prod', endpoint: 'preview' },
82
+ 'post-promotion': { environment: 'prod', endpoint: 'active' },
83
+ }
84
+
85
+ // Other lanes (rush-release, cloud-build) select these names by hardcoded string,
86
+ // so each name is pinned to its gate; the gate then forces environment, endpoint,
87
+ // and production read-only-ness. A renamed-and-rebound `prod-preview` fails closed.
88
+ export const RESERVED_PROFILE_GATES = {
89
+ 'pr-local': 'pull-request',
90
+ 'queue-local': 'merge-queue',
91
+ 'dev-active': 'trunk-integration',
92
+ 'prod-preview': 'pre-promotion',
93
+ 'prod-active': 'post-promotion',
94
+ }
95
+
96
+ export const STANDARD_PROFILES = {
97
+ 'pr-local': { gate: 'pull-request', environment: 'local', endpoint: 'local', prerequisites: ['boot'], mutationPolicy: 'isolated-writes' },
98
+ 'queue-local': { gate: 'merge-queue', environment: 'local', endpoint: 'local', prerequisites: ['boot'], mutationPolicy: 'isolated-writes' },
99
+ 'dev-active': { gate: 'trunk-integration', environment: 'dev', endpoint: 'active', prerequisites: ['deployed-revision'], mutationPolicy: 'synthetic-tenant' },
100
+ 'prod-preview': { gate: 'pre-promotion', environment: 'prod', endpoint: 'preview', prerequisites: ['candidate-revision-at-0pct'], mutationPolicy: 'read-only' },
101
+ 'prod-active': { gate: 'post-promotion', environment: 'prod', endpoint: 'active', prerequisites: ['live-service-at-100pct'], mutationPolicy: 'read-only' },
102
+ }
103
+
104
+ // Where each gate runs, for the human view. The generated workflow owns only the
105
+ // two local gates; deployed gates belong to the deploy and release pipelines.
106
+ const GATE_WHEN = {
107
+ 'pull-request': 'Every pull request',
108
+ 'merge-queue': 'Merge queue, before merge',
109
+ 'trunk-integration': 'After each deploy to dev',
110
+ 'pre-promotion': 'Production candidate at 0% traffic, before promotion',
111
+ 'post-promotion': 'Live production, after promotion',
112
+ }
113
+ const POLICY_WORDS = {
114
+ 'isolated-writes': 'yes, to a throwaway local store',
115
+ 'synthetic-tenant': 'only paths with a synthetic tenant',
116
+ 'read-only': 'never',
117
+ }
118
+
119
+ // ---------------------------------------------------------------------------
120
+ // Validation
121
+ // ---------------------------------------------------------------------------
122
+
123
+ export function validateProfile(name, profile) {
124
+ const at = `profiles.${name}`
125
+ if (!profile || typeof profile !== 'object' || Array.isArray(profile)) return [`${at}: must be an object`]
126
+ const errors = []
127
+ if (!GATES.includes(profile.gate)) errors.push(`${at}: gate must be one of ${GATES.join('/')}`)
128
+ if (!ENVIRONMENTS.includes(profile.environment)) errors.push(`${at}: environment must be one of ${ENVIRONMENTS.join('/')}`)
129
+ if (!ENDPOINTS.includes(profile.endpoint)) errors.push(`${at}: endpoint must be one of ${ENDPOINTS.join('/')}`)
130
+ if (!MUTATION_POLICIES.includes(profile.mutationPolicy)) errors.push(`${at}: mutationPolicy must be one of ${MUTATION_POLICIES.join('/')}`)
131
+ const reservedGate = RESERVED_PROFILE_GATES[name]
132
+ if (reservedGate && profile.gate !== reservedGate) {
133
+ errors.push(`${at}: "${name}" is a reserved name other lanes select by string; it must bind gate "${reservedGate}", not "${profile.gate}"`)
134
+ }
135
+ const axes = GATE_AXES[profile.gate]
136
+ if (axes) {
137
+ if (ENVIRONMENTS.includes(profile.environment) && profile.environment !== axes.environment) {
138
+ errors.push(`${at}: gate "${profile.gate}" runs in environment "${axes.environment}", not "${profile.environment}"`)
139
+ }
140
+ if (ENDPOINTS.includes(profile.endpoint) && profile.endpoint !== axes.endpoint) {
141
+ errors.push(`${at}: gate "${profile.gate}" targets the "${axes.endpoint}" endpoint, not "${profile.endpoint}"`)
142
+ }
143
+ }
144
+ if (profile.environment === 'prod' && MUTATION_POLICIES.includes(profile.mutationPolicy) && profile.mutationPolicy !== 'read-only') {
145
+ errors.push(`${at}: a prod profile must be read-only, not "${profile.mutationPolicy}"; a synthetic tenant still writes to the production database`)
146
+ }
147
+ if (profile.mutationPolicy === 'isolated-writes' && ENVIRONMENTS.includes(profile.environment) && profile.environment !== 'local') {
148
+ errors.push(`${at}: mutationPolicy "isolated-writes" is only valid in the local environment`)
149
+ }
150
+ if (profile.mutationPolicy === 'synthetic-tenant' && ENVIRONMENTS.includes(profile.environment) && profile.environment !== 'dev') {
151
+ errors.push(`${at}: mutationPolicy "synthetic-tenant" is only valid in the dev environment`)
152
+ }
153
+ if (profile.prerequisites !== undefined && (!Array.isArray(profile.prerequisites) || profile.prerequisites.some((x) => typeof x !== 'string'))) {
154
+ errors.push(`${at}: prerequisites must be an array of strings`)
155
+ }
156
+ if (profile.forbidEnv !== undefined && (!isStringArray(profile.forbidEnv) || profile.forbidEnv.some((n) => !ENV_NAME.test(n)))) errors.push(`${at}: forbidEnv must be a list of environment variable names`)
157
+ if (profile.evidencePolicy !== undefined && typeof profile.evidencePolicy !== 'string') {
158
+ errors.push(`${at}: evidencePolicy must be a string`)
159
+ }
160
+ return errors
161
+ }
162
+
163
+ function validateProfiles(contract, paths, errors, warnings) {
164
+ const registry = contract.profiles
165
+ if (registry === undefined) {
166
+ if (contract.version >= CONTRACT_VERSION) errors.push('profiles: required; start from the five standard profiles (references/contract.md)')
167
+ else warnings.push('no `profiles` registry; plan, run, and verdict need one')
168
+ return
169
+ }
170
+ if (!registry || typeof registry !== 'object' || Array.isArray(registry)) { errors.push('profiles: must be an object of name -> binding'); return }
171
+ const names = new Set(Object.keys(registry))
172
+ if (names.size === 0) errors.push('profiles: declare at least one profile')
173
+ for (const name of names) errors.push(...validateProfile(name, registry[name]))
174
+ const literal = contract.setup?.env && !Array.isArray(contract.setup.env) && typeof contract.setup.env === 'object' ? Object.keys(contract.setup.env) : []
175
+ for (const name of names) {
176
+ const clash = (isStringArray(registry[name]?.forbidEnv) ? registry[name].forbidEnv : []).filter((n) => literal.includes(n))
177
+ if (clash.length) errors.push(`profiles.${name}: forbidEnv ${clash.join(', ')} is set in setup.env, so every run would carry it`)
178
+ }
179
+ for (const p of paths) {
180
+ if (!p || !p.id) continue
181
+ if (!Array.isArray(p.profiles) || p.profiles.length === 0) {
182
+ errors.push(`paths (${p.id}): declare a non-empty "profiles" array, or the path never runs`)
183
+ continue
184
+ }
185
+ for (const ref of p.profiles) if (!names.has(ref)) errors.push(`paths (${p.id}): profile "${ref}" is not declared in profiles`)
186
+ }
187
+ }
188
+
189
+ function isStringArray(v) { return Array.isArray(v) && v.every((x) => typeof x === 'string') }
190
+
191
+ function validateExpect(at, p, errors) {
192
+ const e = p.expect
193
+ if (e === undefined) return
194
+ if (!e || typeof e !== 'object' || Array.isArray(e)) { errors.push(`${at}: expect must be an object`); return }
195
+ if (p.surface === 'api') {
196
+ if (e.status !== undefined && !Number.isInteger(e.status) && !(Array.isArray(e.status) && e.status.every(Number.isInteger))) errors.push(`${at}: expect.status must be an integer or an array of integers`)
197
+ if (e.bodyIncludes !== undefined && typeof e.bodyIncludes !== 'string' && !isStringArray(e.bodyIncludes)) errors.push(`${at}: expect.bodyIncludes must be a string or an array of strings`)
198
+ if (e.json !== undefined && (typeof e.json !== 'object' || e.json === null || Array.isArray(e.json))) errors.push(`${at}: expect.json must be an object (a subset the response JSON must contain)`)
199
+ if (e.headers !== undefined && (typeof e.headers !== 'object' || e.headers === null || Object.values(e.headers).some((v) => typeof v !== 'string'))) errors.push(`${at}: expect.headers must map header names to text the value must include`)
200
+ if (e.jsonNonEmpty !== undefined && !isStringArray(e.jsonNonEmpty)) errors.push(`${at}: expect.jsonNonEmpty must be a list of dotted JSON paths`)
201
+ }
202
+ if (p.surface === 'cli') {
203
+ if (e.exitCode !== undefined && !Number.isInteger(e.exitCode)) errors.push(`${at}: expect.exitCode must be an integer`)
204
+ if (e.stdoutIncludes !== undefined && typeof e.stdoutIncludes !== 'string' && !isStringArray(e.stdoutIncludes)) errors.push(`${at}: expect.stdoutIncludes must be a string or an array of strings`)
205
+ }
206
+ }
207
+
208
+ function validateSetup(contract, paths, errors, warnings) {
209
+ const setup = contract.setup
210
+ const v3 = contract.version >= CONTRACT_VERSION
211
+ if (setup === undefined) {
212
+ if (v3) errors.push('setup: required; at least setup.boot')
213
+ else warnings.push('no `setup` block; the contract does not say how to boot the app')
214
+ return
215
+ }
216
+ if (!setup || typeof setup !== 'object' || Array.isArray(setup)) { errors.push('setup: must be an object'); return }
217
+ if (!setup.boot || typeof setup.boot !== 'string') errors.push('setup.boot: needs the command that starts the app')
218
+ for (const f of ['install', 'build', 'seed', 'baseUrl', 'healthPath', 'journeys', 'authBypass', 'fixtures']) {
219
+ if (f in setup && typeof setup[f] !== 'string') errors.push(`setup.${f}: must be a string`)
220
+ }
221
+ if (setup.baseUrl && !URL_SAFE.test(setup.baseUrl)) errors.push('setup.baseUrl: must be a plain http(s) URL (letters, digits, . - / : only)')
222
+ if (setup.healthPath && !PATH_SAFE.test(setup.healthPath)) errors.push('setup.healthPath: must be a plain path starting with a single /')
223
+ const reserved = new Set([...ENGINE_ENV, ...(setup.database ? [setup.database.urlEnv || 'DATABASE_URL'] : [])])
224
+ const names = [
225
+ ...(setup.env && !Array.isArray(setup.env) && typeof setup.env === 'object' ? Object.keys(setup.env) : []),
226
+ ...(isStringArray(setup.secrets?.generate) ? setup.secrets.generate : []), ...(isStringArray(setup.secrets?.fromCi) ? setup.secrets.fromCi : []),
227
+ ]
228
+ for (const n of names) {
229
+ if (typeof n !== 'string') continue
230
+ if (!ENV_NAME.test(n)) errors.push(`setup: "${n}" is not a valid environment variable name (A-Z, 0-9, _)`)
231
+ else if (reserved.has(n)) errors.push(`setup: ${n} is set by the generated workflow; do not declare it`)
232
+ }
233
+ if (new Set(names).size !== names.length) errors.push('setup: an environment variable is declared more than once across env and secrets')
234
+ if ('env' in setup) {
235
+ const env = setup.env
236
+ if (isStringArray(env)) {
237
+ if (v3) errors.push('setup.env: in version 3 this is an object of literal values; move secret names to setup.secrets')
238
+ } else if (!env || typeof env !== 'object' || Array.isArray(env) || Object.values(env).some((x) => typeof x !== 'string')) {
239
+ errors.push('setup.env: must be an object of NAME -> literal string value')
240
+ }
241
+ }
242
+ if ('secrets' in setup) {
243
+ const s = setup.secrets
244
+ if (!s || typeof s !== 'object' || Array.isArray(s)) errors.push('setup.secrets: must be an object { generate?: [...], fromCi?: [...] }')
245
+ else for (const k of ['generate', 'fromCi']) if (k in s && !isStringArray(s[k])) errors.push(`setup.secrets.${k}: must be an array of names`)
246
+ }
247
+ if ('tenants' in setup && !isStringArray(setup.tenants)) errors.push('setup.tenants: must be an array of strings')
248
+ if ('database' in setup) {
249
+ const d = setup.database
250
+ if (!d || typeof d !== 'object' || d.engine !== 'postgres') errors.push('setup.database: only { "engine": "postgres", "version"?, "urlEnv"? } is supported')
251
+ else {
252
+ if (d.urlEnv !== undefined && (typeof d.urlEnv !== 'string' || !ENV_NAME.test(d.urlEnv))) errors.push('setup.database.urlEnv: must be an environment variable name')
253
+ else if (ENGINE_ENV.includes(d.urlEnv)) errors.push(`setup.database.urlEnv: ${d.urlEnv} is set by the generated workflow`)
254
+ if (d.version !== undefined && !/^[\w.-]+$/.test(String(d.version))) errors.push('setup.database.version: must be a plain version like "17"')
255
+ }
256
+ }
257
+ if ('browser' in setup) {
258
+ const b = setup.browser
259
+ if (!b || typeof b !== 'object' || Array.isArray(b)) errors.push('setup.browser: must be an object { command?, install? }')
260
+ else for (const k of ['command', 'install']) if (k in b && typeof b[k] !== 'string') errors.push(`setup.browser.${k}: must be a string`)
261
+ }
262
+ if ('attestation' in setup) {
263
+ const a = setup.attestation
264
+ if (!a || typeof a.path !== 'string' || !PATH_SAFE.test(a.path) || typeof a.field !== 'string') errors.push('setup.attestation: must be { "path": "/api/version", "field": "sha" } with a plain path')
265
+ }
266
+ const declared = new Set(isStringArray(setup.tenants) ? setup.tenants : [])
267
+ for (const p of paths) {
268
+ if (p && p.tenant && !declared.has(p.tenant)) {
269
+ const msg = `paths (${p.id}): tenant "${p.tenant}" is not listed in setup.tenants`
270
+ if (v3) errors.push(msg); else warnings.push(msg)
271
+ }
272
+ }
273
+ const needsSeed = Object.values(contract.profiles || {}).some((pr) => pr && pr.environment === 'local' && Array.isArray(pr.prerequisites) && pr.prerequisites.includes('seed'))
274
+ if (needsSeed && !setup.seed) warnings.push('setup.seed: a local profile lists the "seed" prerequisite, but setup.seed is unset; add the seed command or drop the prerequisite')
275
+ if (paths.some((p) => p && p.surface === 'browser') && !setup.journeys) {
276
+ warnings.push('setup.journeys: name the specs directory so browser paths can be matched to their tagged specs')
277
+ }
278
+ }
279
+
280
+ function validateCi(contract, errors) {
281
+ const ci = contract.ci
282
+ if (ci === undefined) return
283
+ if (!ci || typeof ci !== 'object' || Array.isArray(ci)) { errors.push('ci: must be an object'); return }
284
+ if ('enabled' in ci && typeof ci.enabled !== 'boolean') errors.push('ci.enabled: must be true or false')
285
+ if ('queue' in ci && !QUEUES.includes(ci.queue)) errors.push(`ci.queue: must be one of ${QUEUES.join('/')}`)
286
+ for (const k of ['runner', 'node', 'packageManager']) if (k in ci && typeof ci[k] !== 'string') errors.push(`ci.${k}: must be a string`)
287
+ if (typeof ci.runner === 'string' && !LABEL_SAFE.test(ci.runner)) errors.push('ci.runner: must be a runner label, or a [list] of labels, on one line')
288
+ if (typeof ci.node === 'string' && !/^[\w.-]+$/.test(ci.node)) errors.push('ci.node: must be a plain version like "22"')
289
+ if ('lockfile' in ci && (typeof ci.lockfile !== 'string' || !/^[\w./-]+$/.test(ci.lockfile) || ci.lockfile.includes('..'))) errors.push('ci.lockfile: must be a repo-relative path')
290
+ if ('packageManager' in ci && !['pnpm', 'npm', 'yarn'].includes(ci.packageManager)) errors.push('ci.packageManager: must be pnpm, npm, or yarn')
291
+ if ('timeoutMinutes' in ci && !(Number.isInteger(ci.timeoutMinutes) && ci.timeoutMinutes > 0)) errors.push('ci.timeoutMinutes: must be a positive integer')
292
+ if ('cache' in ci && typeof ci.cache !== 'boolean') errors.push('ci.cache: must be true or false')
293
+ }
294
+
295
+ export function validateContract(contract) {
296
+ const errors = []
297
+ const warnings = []
298
+ if (!contract || typeof contract !== 'object' || Array.isArray(contract)) return { ok: false, errors: ['the contract must be a JSON object'], warnings }
299
+ const v3 = contract.version >= CONTRACT_VERSION
300
+ if (contract.version !== undefined && !Number.isInteger(contract.version)) errors.push('version: must be an integer')
301
+ if (!v3) warnings.push(`version ${contract.version ?? 'unset'}: a legacy smoke manifest; run \`audit --write\` to migrate to version ${CONTRACT_VERSION}`)
302
+ const paths = contract.paths
303
+ if (!Array.isArray(paths) || paths.length === 0) {
304
+ errors.push('paths: needs at least one golden path; a contract with none proves nothing')
305
+ return { ok: false, errors, warnings }
306
+ }
307
+ errors.push(...validatePathDocumentation(paths))
308
+ const seen = new Set()
309
+ for (const [i, p] of paths.entries()) {
310
+ const at = `paths[${i}]${p && p.id ? ` (${p.id})` : ''}`
311
+ if (!p || typeof p !== 'object') { errors.push(`${at}: not an object`); continue }
312
+ if (!p.id || typeof p.id !== 'string') errors.push(`${at}: missing id`)
313
+ else if (!/^[a-z0-9][a-z0-9/_-]*$/.test(p.id)) errors.push(`${at}: id must be a lowercase slug`)
314
+ else if (seen.has(p.id)) errors.push(`${at}: duplicate id`)
315
+ else seen.add(p.id)
316
+ if (!SURFACES.includes(p.surface)) errors.push(`${at}: surface must be one of ${SURFACES.join('/')}`)
317
+ if (v3) {
318
+ if (!p.title || typeof p.title !== 'string') errors.push(`${at}: needs a "title", one line on what the user achieves`)
319
+ else if (p.title.length > TITLE_MAX) errors.push(`${at}: title is ${p.title.length} chars; keep it under ${TITLE_MAX}`)
320
+ }
321
+ if (p.surface === 'browser') {
322
+ if (!p.journey || typeof p.journey !== 'string') errors.push(`${at}: a browser path needs "journey", the @covers id of the tagged spec that drives it`)
323
+ if (p.config !== undefined && (typeof p.config !== 'string' || !/^[\w./-]+$/.test(p.config) || p.config.includes('..'))) errors.push(`${at}: config must be a Playwright config path inside the app`)
324
+ } else if (SURFACES.includes(p.surface)) {
325
+ if (p.surface === 'api' && !p.start && !p.request) errors.push(`${at}: an api path needs "start" ("GET /path") or "request"`)
326
+ else if (v3 && p.surface === 'api' && !p.request && !parseStart(p.start) && !/^\s*TODO\b/.test(p.start)) errors.push(`${at}: start "${p.start}" is not one "METHOD /path" request; set "request", split the path, or make it a cli path`)
327
+ if (p.surface === 'cli' && !p.command) errors.push(`${at}: a cli path needs "command"`)
328
+ else if (p.surface === 'cli' && /<[\w|. -]+>/.test(p.command)) errors.push(`${at}: command still holds a <placeholder>; replace it with an environment variable`)
329
+ if (!p.observable || typeof p.observable !== 'string') errors.push(`${at}: needs "observable", the concrete fact that proves it worked`)
330
+ if (v3 && p.expect === undefined) warnings.push(`${at}: no "expect"; run checks only for a 2xx (api) or exit 0 (cli)`)
331
+ }
332
+ if (typeof p.observable === 'string' && p.observable.length > OBSERVABLE_MAX) {
333
+ const msg = `${at}: observable is ${p.observable.length} chars; keep it under ${OBSERVABLE_MAX} and move setup and cleanup detail out`
334
+ if (v3) errors.push(msg); else warnings.push(msg)
335
+ }
336
+ validateExpect(at, p, errors)
337
+ if (p.mutates !== undefined && typeof p.mutates !== 'boolean') errors.push(`${at}: mutates must be true or false`)
338
+ if (p.request !== undefined && (!p.request || typeof p.request.path !== 'string' || !PATH_SAFE.test(p.request.path))) {
339
+ errors.push(`${at}: request needs a "path" starting with a single /`)
340
+ }
341
+ if (p.surface === 'api' && p.start && parseStart(p.start) && !PATH_SAFE.test(parseStart(p.start).path)) errors.push(`${at}: start path must start with a single /`)
342
+ // mutates:false is allowed for a write only while the path stays on a throwaway local store.
343
+ const method = p.surface === 'api' ? (p.request ? (p.request.method || 'GET') : parseStart(p.start)?.method || 'GET').toUpperCase() : 'GET'
344
+ const shared = (p.profiles || []).filter((n) => contract.profiles?.[n] && contract.profiles[n].environment !== 'local')
345
+ if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && p.mutates !== true && shared.length && !(typeof p.nonWriting === 'string' && p.nonWriting.trim().length >= 20)) {
346
+ errors.push(`${at}: a ${method} path marked as not writing runs in ${shared.join(', ')}; set mutates true with a tenant and cleanup, keep it in local profiles, or explain in "nonWriting" why the server cannot write (for a probe that must be refused)`)
347
+ }
348
+ if (p.mutates === true) {
349
+ if (!p.tenant) errors.push(`${at}: mutates:true needs "tenant", a synthetic tenant, so it is safe off-local`)
350
+ if (v3 && (!p.cleanup || typeof p.cleanup !== 'string')) errors.push(`${at}: mutates:true needs "cleanup", how its writes are removed`)
351
+ }
352
+ }
353
+ validateSetup(contract, paths, errors, warnings)
354
+ validateProfiles(contract, paths, errors, warnings)
355
+ validateCi(contract, errors)
356
+ for (const at of placeholders(contract)) errors.push(`${at}: still a TODO placeholder; replace it`)
357
+ const tenants = new Set([
358
+ ...paths.filter((p) => p && typeof p.tenant === 'string').map((p) => p.tenant),
359
+ ...(contract.setup && isStringArray(contract.setup.tenants) ? contract.setup.tenants : []),
360
+ ])
361
+ for (const t of tenants) if (!t.startsWith('e2e-')) warnings.push(`tenant "${t}": prefix synthetic tenants with e2e- so test data is never mistaken for live data`)
362
+ return { ok: errors.length === 0, errors, warnings }
363
+ }
364
+
365
+ function validatePathDocumentation(paths) {
366
+ const errors = []
367
+ const references = new Set()
368
+ for (const [i, p] of paths.entries()) {
369
+ const at = `paths[${i}]${p?.id ? ` (${p.id})` : ''}`
370
+ validateDocumentation(at, p?.documentation, errors)
371
+ const reference = p?.documentation?.reference
372
+ if (typeof reference === 'string') {
373
+ if (references.has(reference)) errors.push(`${at}: duplicate documentation.reference "${reference}"`)
374
+ references.add(reference)
375
+ }
376
+ }
377
+ return errors
378
+ }
379
+
380
+ function validateDocumentation(at, doc, errors) {
381
+ if (doc === undefined) return
382
+ const object = (value) => value && typeof value === 'object' && !Array.isArray(value)
383
+ if (!object(doc)) { errors.push(`${at}: documentation must be an object`); return }
384
+ const nonempty = (value) => typeof value === 'string' && Boolean(value.trim())
385
+ const localized = (value, field) => {
386
+ if (!object(value) || !nonempty(value.en) ||
387
+ (value.zh !== undefined && !nonempty(value.zh))) {
388
+ errors.push(`${at}: documentation.${field} needs nonempty en and optional nonempty zh text`)
389
+ }
390
+ }
391
+ if (doc.reference !== undefined && (typeof doc.reference !== 'string' || !/^GP-[A-Z0-9]+(?:-[A-Z0-9]+)*$/.test(doc.reference))) {
392
+ errors.push(`${at}: documentation.reference must be a stable uppercase GP- slug, such as GP-IDENTITY-LOGIN`)
393
+ }
394
+ if (doc.title !== undefined) localized(doc.title, 'title')
395
+ if (doc.group !== undefined) {
396
+ localized(doc.group, 'group')
397
+ if (doc.group?.order !== undefined && (!Number.isInteger(doc.group.order) || doc.group.order < 0)) {
398
+ errors.push(`${at}: documentation.group.order must be a nonnegative integer`)
399
+ }
400
+ }
401
+ if (doc.precondition !== undefined) localized(doc.precondition, 'precondition')
402
+ if (doc.summary !== undefined) {
403
+ if (!object(doc.summary)) errors.push(`${at}: documentation.summary must be an object`)
404
+ else {
405
+ localized(doc.summary.route, 'summary.route')
406
+ localized(doc.summary.outcome, 'summary.outcome')
407
+ if ((doc.summary.route?.zh !== undefined || doc.summary.outcome?.zh !== undefined) &&
408
+ (!nonempty(doc.summary.route?.zh) || !nonempty(doc.summary.outcome?.zh))) {
409
+ errors.push(`${at}: documentation.summary needs paired zh route and outcome text`)
410
+ }
411
+ }
412
+ }
413
+ if (!Array.isArray(doc.steps) || !doc.steps.length) {
414
+ errors.push(`${at}: documentation.steps needs at least one action and expected result`)
415
+ return
416
+ }
417
+ const chinese = doc.title?.zh !== undefined || doc.precondition?.zh !== undefined ||
418
+ doc.steps.some((step) => step?.action?.zh !== undefined || step?.expected?.zh !== undefined)
419
+ for (const [i, step] of doc.steps.entries()) {
420
+ localized(step?.action, `steps[${i}].action`)
421
+ localized(step?.expected, `steps[${i}].expected`)
422
+ if (chinese && (!nonempty(step?.action?.zh) || !nonempty(step?.expected?.zh))) {
423
+ errors.push(`${at}: documentation.steps[${i}] needs paired zh action and expected text`)
424
+ }
425
+ }
426
+ }
427
+
428
+ // Where the contract still holds a "TODO" value left by init or a migration.
429
+ export function placeholders(value, at = '') {
430
+ if (typeof value === 'string') return /^\s*TODO\b/.test(value) ? [at || '(root)'] : []
431
+ if (Array.isArray(value)) return value.flatMap((v, i) => placeholders(v, `${at}[${i}]`))
432
+ // Keys starting with "_" are parking space (notes, paths without a driver yet): never read.
433
+ if (value && typeof value === 'object') return Object.entries(value).filter(([k]) => !k.startsWith('_')).flatMap(([k, v]) => placeholders(v, at ? `${at}.${k}` : k))
434
+ return []
435
+ }
436
+
437
+ // ---------------------------------------------------------------------------
438
+ // Selection and verdict
439
+ // ---------------------------------------------------------------------------
440
+
441
+ // A path runs iff it declares the profile and the profile's mutationPolicy admits
442
+ // it. Selection is a pure function of (contract, profile name), so run and verdict
443
+ // cannot disagree about the set.
444
+ // `surfaces` narrows the run to some surfaces (a deploy step with no browser); the
445
+ // run records it and the verdict must use the same narrowing.
446
+ export function selectPathsForProfile(contract, profileName, { surfaces, ids } = {}) {
447
+ const registry = (contract && contract.profiles) || {}
448
+ const profile = registry[profileName]
449
+ if (!profile) throw new Error(`unknown profile "${profileName}" (declared: ${Object.keys(registry).join(', ') || 'none'})`)
450
+ const bad = (surfaces || []).filter((x) => !SURFACES.includes(x))
451
+ if (bad.length) throw new Error(`unknown surface ${bad.join(', ')} (use ${SURFACES.join(', ')})`)
452
+ const known = new Set((contract.paths || []).map((p) => p.id))
453
+ const missing = (ids || []).filter((id) => !known.has(id))
454
+ if (missing.length) throw new Error(`unknown path ${missing.join(', ')}`)
455
+ const run = []
456
+ const excluded = []
457
+ for (const p of contract.paths || []) {
458
+ if (!Array.isArray(p.profiles) || !p.profiles.includes(profileName)) { excluded.push({ id: p.id, reason: `not declared for ${profileName}` }); continue }
459
+ if (surfaces && !surfaces.includes(p.surface)) { excluded.push({ id: p.id, reason: `surface ${p.surface} not selected (--surfaces ${surfaces.join(',')})` }); continue }
460
+ if (ids && !ids.includes(p.id)) { excluded.push({ id: p.id, reason: 'not in --paths (another shard)' }); continue }
461
+ // Anything but an explicit false is treated as writing, so a malformed flag fails safe.
462
+ const writes = p.mutates !== undefined && p.mutates !== false
463
+ if (writes && profile.mutationPolicy === 'read-only') excluded.push({ id: p.id, reason: `writes data; ${profileName} is read-only` })
464
+ else if (writes && profile.mutationPolicy === 'synthetic-tenant' && !p.tenant) excluded.push({ id: p.id, reason: `writes data without a synthetic tenant` })
465
+ else run.push(p)
466
+ }
467
+ return { profile: { name: profileName, ...profile, ...(surfaces ? { surfaces } : {}), ...(ids ? { paths: ids } : {}) }, run, excluded }
468
+ }
469
+
470
+ // Only `fail` means the app is broken (DEAD). `blocked`, `cannot-run`, and a
471
+ // missing result mean the gate could not observe, so the verdict is CANNOT-RUN.
472
+ // An empty selection is EMPTY, never a vacuous ALIVE.
473
+ export function computeVerdict(selected, results) {
474
+ const byId = new Map((results || []).map((r) => [r.id, r]))
475
+ const rows = selected.map((p) => {
476
+ const r = byId.get(p.id)
477
+ return { id: p.id, surface: p.surface, status: r ? r.status : 'missing', evidence: r && r.evidence, note: r ? r.note : 'no result reported; the path was not driven' }
478
+ })
479
+ if (rows.length === 0) {
480
+ return { verdict: 'EMPTY', ok: false, total: 0, broken: [], rows, note: 'no paths selected, so nothing was proven; check the profile and the paths that declare it' }
481
+ }
482
+ const failed = rows.filter((r) => r.status === 'fail')
483
+ const cannot = rows.filter((r) => r.status !== 'pass' && r.status !== 'fail')
484
+ // A path that was reached and failed proves the app broken, whatever else could not run.
485
+ if (failed.length > 0) {
486
+ return { verdict: 'DEAD', ok: false, total: rows.length, broken: [...failed, ...cannot].map(({ id, status, note }) => ({ id, status, note })), rows }
487
+ }
488
+ if (cannot.length > 0) {
489
+ return { verdict: 'CANNOT-RUN', ok: false, total: rows.length, broken: cannot.map(({ id, status, note }) => ({ id, status, note })), rows, note: 'the gate could not observe at least one path (boot, secret, driver, or a missing result); repair the gate, the app was not judged' }
490
+ }
491
+ return { verdict: 'ALIVE', ok: true, total: rows.length, broken: [], rows }
492
+ }
493
+
494
+ // `run` writes its results inside an envelope naming the profile and target they
495
+ // were observed under, so a verdict can never reuse one profile's observations
496
+ // for another (a local run must not become a production ALIVE).
497
+ export function resultsEnvelope(results, { profile, target, surfaces, ids }) {
498
+ return { profile, target, ...(surfaces ? { surfaces } : {}), ...(ids ? { paths: ids } : {}), observedAt: new Date().toISOString(), results }
499
+ }
500
+
501
+ // Returns { results, error }. A bare array (results driven by hand) is accepted.
502
+ export function openResults(data, { profile, target, surfaces, ids, deployed = false }) {
503
+ // A deployed profile gates real traffic, so its evidence must name what it observed.
504
+ if (deployed && (Array.isArray(data) || !data?.target || !data?.observedAt)) return { error: `a ${profile} verdict needs results from \`run\` (profile, target, observedAt); hand-made results are accepted for local profiles only` }
505
+ if (Array.isArray(data)) return { results: data }
506
+ if (!data || !Array.isArray(data.results)) return { error: 'results file is neither a list nor a run envelope' }
507
+ if (data.profile !== profile) return { error: `results were observed under profile "${data.profile}", not "${profile}"; run again with --profile ${profile}` }
508
+ if (target && data.target && data.target !== target) return { error: `results were observed against ${data.target}, not ${target}; run again against this target` }
509
+ const ran = (data.surfaces || []).join(',')
510
+ if (surfaces !== undefined && surfaces.join(',') !== ran) return { error: `results were observed with --surfaces ${ran || '(all)'}, not ${surfaces.join(',') || '(all)'}` }
511
+ const ranIds = (data.paths || []).join(',')
512
+ if (ids !== undefined && ids.join(',') !== ranIds) return { error: `results were observed with --paths ${ranIds || '(all)'}, not ${ids.join(',') || '(all)'}` }
513
+ return { results: data.results, observedAt: data.observedAt, target: data.target, surfaces: data.surfaces, ids: data.paths }
514
+ }
515
+
516
+ // `generatedAt` dates the verdict, not the observations: re-running `verdict` on
517
+ // an old results file mints a fresh stamp. Re-drive with `run` for fresh evidence.
518
+ export function stampTarget(verdict, target, extra = {}) {
519
+ return { ...verdict, target: target || 'local', ...extra, engine: ENGINE_VERSION, generatedAt: new Date().toISOString() }
520
+ }
521
+
522
+ // ---------------------------------------------------------------------------
523
+ // Journeys: browser paths <-> tagged specs
524
+ // ---------------------------------------------------------------------------
525
+
526
+ const TAG = /@(?:golden-path|smoke)\b/
527
+
528
+ export function journeyCoversId(journey) {
529
+ if (!journey || typeof journey !== 'string') return null
530
+ const id = journey.trim().replace(/^@(?:golden-path|smoke)\b[:\s]*/i, '').replace(/^route:/, '').trim()
531
+ return id || null
532
+ }
533
+
534
+ // Every spec file carrying @golden-path (or the legacy @smoke) contributes its
535
+ // @covers ids. Returns id -> [files] so `run` can find what to execute.
536
+ export function isJourneyId(id) { return !/^\//.test(id) && !/^[a-z]+:/i.test(id) }
537
+
538
+ export function scanJourneyTags(dir) {
539
+ const byId = new Map()
540
+ const byFile = new Map()
541
+ const noCovers = []
542
+ const walk = (d) => {
543
+ for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
544
+ const full = path.join(d, ent.name)
545
+ if (ent.isDirectory()) { if (ent.name !== 'node_modules' && !ent.name.startsWith('.')) walk(full); continue }
546
+ if (!/\.(spec|test)\.[cm]?[jt]sx?$/.test(ent.name)) continue
547
+ const text = fs.readFileSync(full, 'utf8')
548
+ if (!TAG.test(text)) continue
549
+ // e2e-test tags surfaces with @covers too (`/cases/[id]`, `api:...`); only ids that
550
+ // are not surface ids name a golden-path journey.
551
+ const covers = [...text.matchAll(/@covers\s+(\S+)/g)].map((m) => m[1]).filter(isJourneyId)
552
+ if (covers.length === 0) noCovers.push(full)
553
+ byFile.set(full, [...new Set(covers)])
554
+ for (const c of new Set(covers)) byId.set(c, [...(byId.get(c) || []), full])
555
+ }
556
+ }
557
+ if (dir && fs.existsSync(dir)) walk(dir)
558
+ return { byId, byFile, noCovers }
559
+ }
560
+
561
+ // Both directions are errors: a path whose journey is not tagged cannot be driven,
562
+ // and a tagged journey no path references silently never runs (a false ALIVE).
563
+ export function reconcileJourneys(contract, taggedIds) {
564
+ const errors = []
565
+ const warnings = []
566
+ const tagged = new Set(taggedIds || [])
567
+ const referenced = new Set()
568
+ for (const p of (contract && contract.paths) || []) {
569
+ if (!p || p.surface !== 'browser') continue
570
+ const id = journeyCoversId(p.journey)
571
+ if (!id) { warnings.push(`paths (${p.id}): cannot read a @covers id from journey "${p.journey}"`); continue }
572
+ referenced.add(id)
573
+ if (!tagged.has(id)) errors.push(`paths (${p.id}): no spec is tagged @golden-path with @covers ${id}`)
574
+ }
575
+ for (const id of tagged) if (!referenced.has(id)) errors.push(`spec tagged @golden-path @covers ${id} is not in the contract; add a browser path or drop the tag`)
576
+ return { errors, warnings }
577
+ }
578
+
579
+ function reconcileAt(contract, journeysDir) {
580
+ const hasBrowser = (contract.paths || []).some((p) => p && p.surface === 'browser')
581
+ if (!journeysDir) return { errors: [], warnings: hasBrowser ? ['browser paths not reconciled; set setup.journeys or pass --journeys'] : [] }
582
+ if (!fs.existsSync(journeysDir)) return { errors: [`journeys directory not found: ${journeysDir}`], warnings: [] }
583
+ const { byId, byFile, noCovers } = scanJourneyTags(journeysDir)
584
+ const r = reconcileJourneys(contract, [...byId.keys()])
585
+ for (const f of noCovers) r.warnings.push(`tagged spec has no @covers id: ${f}`)
586
+ // `run` executes whole spec files, so a file holding two journeys would run both
587
+ // whenever either is selected, including a writing one under a read-only profile.
588
+ for (const [f, ids] of byFile) if (ids.length > 1) r.errors.push(`tagged spec ${f} covers ${ids.join(', ')}; keep one golden-path journey per spec file`)
589
+ return r
590
+ }
591
+
592
+ // ---------------------------------------------------------------------------
593
+ // Run: drive each selected path and record what was observed
594
+ // ---------------------------------------------------------------------------
595
+
596
+ export function parseStart(start) {
597
+ const m = /^\s*(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\/\S*)\s*$/i.exec(String(start || ''))
598
+ return m ? { method: m[1].toUpperCase(), path: m[2] } : null
599
+ }
600
+
601
+ function asList(v) { return v === undefined ? [] : Array.isArray(v) ? v : [v] }
602
+
603
+ function subsetMatches(actual, expected) {
604
+ if (expected === null || typeof expected !== 'object') return actual === expected
605
+ if (!actual || typeof actual !== 'object') return false
606
+ return Object.entries(expected).every(([k, v]) => subsetMatches(actual[k], v))
607
+ }
608
+
609
+ // Pure: judge one HTTP response against a path's expect block.
610
+ export function judgeHttp(p, status, body, headers = {}) {
611
+ const e = p.expect || {}
612
+ const okStatus = e.status === undefined ? status >= 200 && status < 300 : asList(e.status).includes(status)
613
+ if (!okStatus) return { status: 'fail', note: `HTTP ${status}, expected ${e.status === undefined ? '2xx' : asList(e.status).join(' or ')}` }
614
+ for (const s of asList(e.bodyIncludes)) if (!body.includes(s)) return { status: 'fail', note: `body does not include ${JSON.stringify(s)}` }
615
+ for (const [name, want] of Object.entries(e.headers || {})) {
616
+ const got = headers[name.toLowerCase()] ?? ''
617
+ if (!String(got).includes(want)) return { status: 'fail', note: `header ${name} is "${got}", expected it to include "${want}"` }
618
+ }
619
+ if (e.json !== undefined || e.jsonNonEmpty !== undefined) {
620
+ let parsed
621
+ try { parsed = JSON.parse(body) } catch { return { status: 'fail', note: 'body is not JSON' } }
622
+ if (e.json !== undefined && !subsetMatches(parsed, e.json)) return { status: 'fail', note: `JSON does not contain ${JSON.stringify(e.json)}` }
623
+ for (const at of e.jsonNonEmpty || []) {
624
+ const v = at.split('.').reduce((o, k) => (o == null ? o : o[k]), parsed)
625
+ const empty = v == null || v === '' || (Array.isArray(v) && v.length === 0) || (typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 0)
626
+ if (empty) return { status: 'fail', note: `JSON ${at} is empty` }
627
+ }
628
+ }
629
+ return { status: 'pass', evidence: `HTTP ${status}` }
630
+ }
631
+
632
+ // Pure: judge one command result against a path's expect block.
633
+ export function judgeCli(p, exitCode, stdout, stderr = '') {
634
+ const e = p.expect || {}
635
+ const want = e.exitCode ?? 0
636
+ if (exitCode !== want) return { status: 'fail', note: `exit ${exitCode}, expected ${want}` }
637
+ for (const s of asList(e.stdoutIncludes)) if (!stdout.includes(s)) return { status: 'fail', note: `stdout does not include ${JSON.stringify(s)}${stderr.includes(s) ? ' (it is on stderr)' : ''}` }
638
+ return { status: 'pass', evidence: `exit ${exitCode}` }
639
+ }
640
+
641
+ async function driveApi(p, target) {
642
+ const req = p.request || parseStart(p.start)
643
+ if (!req) return { id: p.id, status: 'cannot-run', note: `start "${p.start}" is not one "METHOD /path" request; set "request" to drive it` }
644
+ const url = new URL(req.path, target)
645
+ if (url.origin !== new URL(target).origin) return { id: p.id, status: 'cannot-run', note: `request path ${req.path} leaves the target origin ${new URL(target).origin}` }
646
+ try {
647
+ const res = await fetch(url, {
648
+ method: (req.method || 'GET').toUpperCase(),
649
+ headers: req.headers,
650
+ body: req.body === undefined ? undefined : typeof req.body === 'string' ? req.body : JSON.stringify(req.body),
651
+ redirect: 'manual',
652
+ signal: AbortSignal.timeout(30_000),
653
+ })
654
+ return { id: p.id, ...judgeHttp(p, res.status, await res.text(), Object.fromEntries(res.headers)) }
655
+ } catch (err) {
656
+ return { id: p.id, status: 'cannot-run', note: `request failed: ${err.message}` }
657
+ }
658
+ }
659
+
660
+ function driveCli(p, cwd, env) {
661
+ const r = spawnSync(p.command, { shell: true, cwd, env, encoding: 'utf8', timeout: 300_000 })
662
+ if (r.error) return { id: p.id, status: 'cannot-run', note: `could not run: ${r.error.message}` }
663
+ return { id: p.id, ...judgeCli(p, r.status, r.stdout || '', r.stderr || '') }
664
+ }
665
+
666
+ // Fold one Playwright JSON report into file -> passed?
667
+ // One test's outcome. Only a test whose final attempt passed is a pass: a skipped
668
+ // test observed nothing, and an expected failure (test.fail) is not a working flow.
669
+ export function testOutcome(t) {
670
+ const last = (t.results || []).at(-1)
671
+ if (t.status === 'skipped' || last?.status === 'skipped') return 'skipped'
672
+ return (t.status === 'expected' || t.status === 'flaky') && last?.status === 'passed' ? 'pass' : 'fail'
673
+ }
674
+
675
+ // The same file reached through a symlinked directory must compare equal.
676
+ function realPath(p) { try { return fs.realpathSync(p) } catch { return path.resolve(p) } }
677
+
678
+ const worst = (a, b) => (a === 'fail' || b === 'fail' ? 'fail' : a === 'skipped' || b === 'skipped' ? 'skipped' : 'pass')
679
+
680
+ // Fold a Playwright JSON report into absolute spec path -> 'pass' | 'fail' | 'skipped'.
681
+ // Report file names are relative to config.rootDir, so they are resolved against it
682
+ // and compared exactly; a suffix match would lend one file's result to another.
683
+ export function playwrightFileResults(report, { appDir = process.cwd() } = {}) {
684
+ const root = path.resolve(appDir, report?.config?.rootDir || '.')
685
+ const out = new Map()
686
+ const visit = (suite, file) => {
687
+ const f = suite.file || file
688
+ for (const spec of suite.specs || []) {
689
+ if (!f) continue
690
+ const key = realPath(path.resolve(root, f))
691
+ const tests = spec.tests || []
692
+ const outcome = tests.length ? tests.map(testOutcome).reduce(worst) : spec.ok === false ? 'fail' : 'skipped'
693
+ out.set(key, worst(out.get(key) ?? 'pass', outcome))
694
+ }
695
+ for (const child of suite.suites || []) visit(child, f)
696
+ }
697
+ for (const s of (report && report.suites) || []) visit(s, s.file)
698
+ return out
699
+ }
700
+
701
+ function driveBrowser(paths, contract, appDir, target, env) {
702
+ const setup = contract.setup || {}
703
+ const journeysDir = setup.journeys ? path.resolve(appDir, setup.journeys) : null
704
+ if (!journeysDir) return paths.map((p) => ({ id: p.id, status: 'cannot-run', note: 'setup.journeys is not set; cannot find the spec' }))
705
+ const { byId, byFile } = scanJourneyTags(journeysDir)
706
+ const files = new Map()
707
+ const results = []
708
+ for (const p of paths) {
709
+ const id = journeyCoversId(p.journey)
710
+ const specs = byId.get(id)
711
+ const shared = (specs || []).flatMap((f) => byFile.get(f).filter((x) => x !== id))
712
+ if (!specs) results.push({ id: p.id, status: 'cannot-run', note: `no spec tagged @golden-path with @covers ${id}` })
713
+ else if (shared.length) results.push({ id: p.id, status: 'cannot-run', note: `its spec also covers ${shared.join(', ')}; keep one journey per spec file` })
714
+ else files.set(p.id, specs)
715
+ }
716
+ if (files.size === 0) return results
717
+ // One Playwright run per config: a path may name its own config file.
718
+ const byConfig = new Map()
719
+ for (const p of paths) if (files.has(p.id)) byConfig.set(p.config || '', [...(byConfig.get(p.config || '') || []), p.id])
720
+ for (const [config, ids] of byConfig) {
721
+ results.push(...runPlaywright(new Map(ids.map((id) => [id, files.get(id)])), config, contract, appDir, target, env))
722
+ }
723
+ return results
724
+ }
725
+
726
+ function runPlaywright(files, config, contract, appDir, target, env) {
727
+ const setup = contract.setup || {}
728
+ const results = []
729
+ const pm = contract.ci?.packageManager || detectPackageManager(appDir)
730
+ const command = `${setup.browser?.command || `${pmExec(pm)} playwright test`}${config ? ` --config ${shellQuote(config)}` : ''}`
731
+ // Inside the app, so a wrapper that runs Playwright in a container sees it.
732
+ const report = path.join(appDir, BROWSER_REPORT)
733
+ fs.rmSync(report, { force: true })
734
+ const all = [...new Set([...files.values()].flat())].map((f) => path.relative(appDir, f))
735
+ const r = spawnSync(`${command} ${all.map(shellQuote).join(' ')} --reporter=list,json`, {
736
+ shell: true, cwd: appDir, encoding: 'utf8', stdio: ['ignore', 'inherit', 'inherit'], timeout: 1_800_000,
737
+ env: { ...env, BASE_URL: target, PLAYWRIGHT_BASE_URL: target, PLAYWRIGHT_JSON_OUTPUT_NAME: report, PLAYWRIGHT_JSON_OUTPUT_FILE: report },
738
+ })
739
+ if (r.error || !fs.existsSync(report)) {
740
+ for (const id of files.keys()) results.push({ id, status: 'cannot-run', note: `browser run produced no report: ${r.error?.message || `exit ${r.status}`}` })
741
+ return results
742
+ }
743
+ let parsed
744
+ try { parsed = JSON.parse(fs.readFileSync(report, 'utf8')) } catch (e) { parsed = null }
745
+ if (!parsed) {
746
+ for (const id of files.keys()) results.push({ id, status: 'cannot-run', note: 'browser report is not valid JSON' })
747
+ return results
748
+ }
749
+ const outcomes = playwrightFileResults(parsed, { appDir })
750
+ // A report-level error (global setup, teardown, a crash), or a failing exit that no
751
+ // failed test explains, means the run itself broke: no pass can be trusted.
752
+ const ours = new Set([...files.values()].flat().map(realPath))
753
+ const explained = [...outcomes].some(([f, o]) => o === 'fail' && ours.has(f))
754
+ const runBroke = (parsed.errors || []).length > 0 || (r.status !== 0 && !explained)
755
+ const why = (parsed.errors || []).map((e) => e.message).filter(Boolean)[0] || `playwright exited ${r.status}`
756
+ for (const [id, specs] of files) {
757
+ const rel = specs.map((s) => path.relative(appDir, s)).join(', ')
758
+ const got = specs.map((abs) => outcomes.get(realPath(abs)))
759
+ if (got.some((v) => v === undefined)) results.push({ id, status: 'cannot-run', note: `spec did not appear in the browser report: ${rel}` })
760
+ else if (got.includes('fail')) results.push({ id, status: 'fail', note: `journey failed: ${rel}` })
761
+ else if (got.includes('skipped')) results.push({ id, status: 'cannot-run', note: `journey was skipped: ${rel}` })
762
+ else if (runBroke) results.push({ id, status: 'cannot-run', note: `journey passed but the browser run broke: ${why}` })
763
+ else results.push({ id, status: 'pass', evidence: rel })
764
+ }
765
+ return results
766
+ }
767
+
768
+ function shellQuote(s) { return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'` }
769
+
770
+ async function checkAttestation(contract, target, sha) {
771
+ const a = contract.setup?.attestation
772
+ if (!a) return `--expect-sha needs setup.attestation { path, field } in the contract`
773
+ try {
774
+ const res = await fetch(new URL(a.path, target), { signal: AbortSignal.timeout(30_000) })
775
+ const body = await res.json()
776
+ const got = String(a.field.split('.').reduce((o, k) => (o == null ? o : o[k]), body) ?? '')
777
+ // Both sides need at least 7 hex characters before a prefix match identifies a commit.
778
+ if (!/^[0-9a-f]{7,}$/i.test(sha)) return `--expect-sha needs at least 7 hex characters, got "${sha}"`
779
+ if (!/^[0-9a-f]{7,}$/i.test(got)) return `target attests "${got || 'nothing'}", not a commit sha of 7+ hex characters`
780
+ if (!(got.toLowerCase().startsWith(sha.toLowerCase()) || sha.toLowerCase().startsWith(got.toLowerCase()))) return `target serves ${got}, expected ${sha}`
781
+ return null
782
+ } catch (err) {
783
+ return `attestation check failed: ${err.message}`
784
+ }
785
+ }
786
+
787
+ // Poll a URL until it answers below 500. Returns null when up, else the last error.
788
+ export async function waitFor(url, timeoutSec = 120) {
789
+ const until = Date.now() + timeoutSec * 1000
790
+ let last = 'no answer'
791
+ while (Date.now() < until) {
792
+ try {
793
+ const res = await fetch(url, { signal: AbortSignal.timeout(5000), redirect: 'manual' })
794
+ if (res.status < 500) return null
795
+ last = `HTTP ${res.status}`
796
+ } catch (e) { last = e.message }
797
+ await new Promise((r) => setTimeout(r, 1000))
798
+ }
799
+ return last
800
+ }
801
+
802
+ // Start setup.boot in its own process group, logging to the server log. The caller
803
+ // stops it with stopApp, which ends the whole group (npm start spawns a child).
804
+ export function bootApp(contract, appDir, env = process.env) {
805
+ const literal = isStringArray(contract.setup?.env) ? {} : contract.setup?.env || {}
806
+ const log = fs.openSync(path.join(appDir, SERVER_LOG), 'w')
807
+ const child = spawn('sh', ['-c', contract.setup.boot], { cwd: appDir, env: { ...env, ...literal }, stdio: ['ignore', log, log], detached: true })
808
+ fs.closeSync(log)
809
+ child.exited = null
810
+ child.on('exit', (code, signal) => { child.exited = signal || `exit ${code}` })
811
+ child.unref()
812
+ return child
813
+ }
814
+
815
+ function groupAlive(pid) { try { process.kill(-pid, 0); return true } catch { return false } }
816
+
817
+ // SIGTERM the whole group, then SIGKILL whatever ignores it, so no server outlives the run.
818
+ export async function stopApp(child, graceMs = 5000) {
819
+ try { process.kill(-child.pid, 'SIGTERM') } catch { return }
820
+ const until = Date.now() + graceMs
821
+ while (groupAlive(child.pid) && Date.now() < until) await new Promise((r) => setTimeout(r, 100))
822
+ if (groupAlive(child.pid)) { try { process.kill(-child.pid, 'SIGKILL') } catch { /* gone */ } }
823
+ }
824
+
825
+ // Wait for the booted app; fail as soon as the boot process itself has exited.
826
+ export async function waitForBoot(child, url, timeoutSec) {
827
+ const until = Date.now() + timeoutSec * 1000
828
+ let last = 'no answer'
829
+ while (Date.now() < until) {
830
+ if (child.exited) return `the boot command ended (${child.exited}) before the app answered`
831
+ const down = await waitFor(url, 1)
832
+ if (!down) return child.exited ? `the boot command ended (${child.exited}); something else answers at ${url}` : null
833
+ last = down
834
+ }
835
+ return last
836
+ }
837
+
838
+ // Why this profile must not run against this target with this environment, or null.
839
+ // A local profile writes freely, so it only ever drives a loopback build; a deployed
840
+ // profile drives real traffic over https; forbidEnv keeps credentials out of a run.
841
+ export function targetProblem(profile, target, env = {}) {
842
+ let url
843
+ try { url = new URL(target) } catch { return `target ${target} is not a URL` }
844
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
845
+ if (profile.environment === 'local' && !loopback) return `profile ${profile.name} drives a local build; ${target} is not a loopback address`
846
+ if (profile.environment !== 'local' && url.protocol !== 'https:') return `profile ${profile.name} drives a deployed target; use https, not ${target}`
847
+ const set = (profile.forbidEnv || []).filter((n) => env[n])
848
+ if (set.length) return `profile ${profile.name} forbids ${set.join(', ')} in the environment; unset them for this run`
849
+ return null
850
+ }
851
+
852
+ export async function runPaths(contract, { profile, target, appDir, expectSha, surfaces, ids, env = process.env }) {
853
+ const { run, profile: prof } = selectPathsForProfile(contract, profile, { surfaces, ids })
854
+ // Judge the environment the paths will actually get, contract literals included.
855
+ // setup.env describes the local build; a deployed target keeps the runner's own env.
856
+ const literal = prof.environment === 'local' && !isStringArray(contract.setup?.env) ? contract.setup?.env || {} : {}
857
+ const refused = targetProblem(prof, target, { ...env, ...literal })
858
+ if (refused) return run.map((p) => ({ id: p.id, status: 'cannot-run', note: refused }))
859
+ if (expectSha) {
860
+ const problem = await checkAttestation(contract, target, expectSha)
861
+ if (problem) return run.map((p) => ({ id: p.id, status: 'cannot-run', note: problem }))
862
+ }
863
+ const runEnv = { ...env, ...literal, BASE_URL: target }
864
+ const results = []
865
+ for (const p of run) {
866
+ if (p.surface === 'api') results.push(await driveApi(p, target))
867
+ else if (p.surface === 'cli') results.push(driveCli(p, appDir, runEnv))
868
+ }
869
+ results.push(...driveBrowser(run.filter((p) => p.surface === 'browser'), contract, appDir, target, runEnv))
870
+ const order = new Map(run.map((p, i) => [p.id, i]))
871
+ return results.sort((a, b) => order.get(a.id) - order.get(b.id))
872
+ }
873
+
874
+ // ---------------------------------------------------------------------------
875
+ // Repo layout helpers
876
+ // ---------------------------------------------------------------------------
877
+
878
+ export function findRepoRoot(start) {
879
+ let dir = path.resolve(start)
880
+ for (;;) {
881
+ if (fs.existsSync(path.join(dir, '.git'))) return dir
882
+ const up = path.dirname(dir)
883
+ if (up === dir) return path.resolve(start)
884
+ dir = up
885
+ }
886
+ }
887
+
888
+ export function detectPackageManager(dir) {
889
+ if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm'
890
+ if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn'
891
+ if (fs.existsSync(path.join(dir, 'package-lock.json'))) return 'npm'
892
+ const root = findRepoRoot(dir)
893
+ return root !== path.resolve(dir) ? detectPackageManager(root) : 'npm'
894
+ }
895
+
896
+ const LOCKFILES = { pnpm: 'pnpm-lock.yaml', yarn: 'yarn.lock', npm: 'package-lock.json' }
897
+
898
+ // The lockfile for this package manager, in the app dir or at the repo root.
899
+ export function hasLockfile(appDir, pm) {
900
+ return fs.existsSync(path.join(appDir, LOCKFILES[pm])) || fs.existsSync(path.join(findRepoRoot(appDir), LOCKFILES[pm]))
901
+ }
902
+
903
+ // ci fields for the lockfile: no cache without one, and the workspace-root path when
904
+ // a monorepo app has none of its own (setup-node needs a file that exists).
905
+ function lockfileCi(appDir, pm) {
906
+ if (fs.existsSync(path.join(appDir, LOCKFILES[pm]))) return {}
907
+ const root = findRepoRoot(appDir)
908
+ if (root !== path.resolve(appDir) && fs.existsSync(path.join(root, LOCKFILES[pm]))) return { lockfile: LOCKFILES[pm] }
909
+ return { cache: false }
910
+ }
911
+
912
+ function pmExec(pm) { return pm === 'npm' ? 'npx' : `${pm} exec` }
913
+ function pmRun(pm, script) {
914
+ if (pm === 'npm') return script === 'start' ? 'npm start' : `npm run ${script}`
915
+ return `${pm} run ${script}`
916
+ }
917
+ function pmInstall(pm, locked = true) {
918
+ if (!locked) return pm === 'npm' ? 'npm install' : `${pm} install`
919
+ return pm === 'pnpm' ? 'pnpm install --frozen-lockfile' : pm === 'yarn' ? 'yarn install --immutable' : 'npm ci'
920
+ }
921
+
922
+ function posix(p) { return p.split(path.sep).join('/') }
923
+
924
+ // Paths relative to the repo root for one contract file.
925
+ export function layout(contractFile) {
926
+ const contractPath = path.resolve(contractFile)
927
+ const appDir = path.dirname(contractPath)
928
+ const repoRoot = findRepoRoot(appDir)
929
+ const rel = posix(path.relative(repoRoot, appDir)) || '.'
930
+ return { repoRoot, appDir, appRel: rel, contractPath, viewPath: path.join(appDir, VIEW_FILE), workflowPath: path.join(repoRoot, workflowFile(rel)), enginePath: path.join(appDir, ENGINE_FILE), coreEnginePath: path.join(appDir, ENGINE_CORE_FILE) }
931
+ }
932
+
933
+ function inApp(appRel, file) { return appRel === '.' ? file : `${appRel}/${file}` }
934
+
935
+ // ---------------------------------------------------------------------------
936
+ // Render: GOLDEN_PATHS.md
937
+ // ---------------------------------------------------------------------------
938
+
939
+ function cell(s) { return String(s ?? '').replace(/\|/g, '\\|').replace(/\s*\n\s*/g, ' ').trim() }
940
+
941
+ function documentationText(s) {
942
+ const literal = cell(String(s ?? '').replace(/[\\`*_\[\]~]/g, '\\$&'))
943
+ .replace(/^([#+-])/, '\\$1')
944
+ .replace(/^(\d+)([.)])(?=\s)/, '$1\\$2')
945
+ return literal.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
946
+ }
947
+
948
+ function firstSentence(s) {
949
+ const t = String(s || '').trim()
950
+ const m = /^(.+?[.;])(\s|$)/.exec(t)
951
+ const one = m ? m[1] : t
952
+ return one.length > 140 ? `${one.slice(0, 137)}...` : one
953
+ }
954
+
955
+ function howChecked(p) {
956
+ if (p.surface === 'browser') return `Browser journey \`${journeyCoversId(p.journey)}\``
957
+ if (p.surface === 'api') {
958
+ const req = p.request ? `${(p.request.method || 'GET').toUpperCase()} ${p.request.path}` : p.start
959
+ return `API \`${req}\``
960
+ }
961
+ return `Command \`${p.command}\``
962
+ }
963
+
964
+ // A GET api path that looks like a health check, used when setup.healthPath is unset.
965
+ export function inferHealthPath(contract) {
966
+ for (const p of contract.paths || []) {
967
+ if (p.surface !== 'api') continue
968
+ const req = p.request ? { method: (p.request.method || 'GET').toUpperCase(), path: p.request.path } : parseStart(p.start)
969
+ if (req && req.method === 'GET' && /health|ready|live|status/i.test(req.path)) return req.path
970
+ }
971
+ return null
972
+ }
973
+
974
+ // The workflow runs the local profiles that a trigger exists for.
975
+ export function ciProfiles(contract) {
976
+ const ci = contract.ci || {}
977
+ if (ci.enabled === false) return []
978
+ const names = Object.keys(contract.profiles || {})
979
+ const out = []
980
+ if (names.includes('pr-local')) out.push('pr-local')
981
+ if (names.includes('queue-local') && (ci.queue || 'none') !== 'none') out.push('queue-local')
982
+ return out
983
+ }
984
+
985
+ function journeyGroups(paths, label) {
986
+ const groups = new Map()
987
+ for (const p of paths.filter((p) => p.surface === 'browser')) {
988
+ const group = p.documentation?.group
989
+ const name = group?.en || 'User journeys'
990
+ if (!groups.has(name)) groups.set(name, {
991
+ title: group ? (group.zh ? label(group.en, group.zh) : group.en) : label('User journeys', '用户旅程'),
992
+ order: group?.order ?? Number.MAX_SAFE_INTEGER,
993
+ paths: [],
994
+ })
995
+ groups.get(name).paths.push(p)
996
+ }
997
+ const result = [...groups.values()].sort((a, b) => a.order - b.order)
998
+ const services = paths.filter((p) => p.surface !== 'browser')
999
+ if (services.length) result.push({ title: label('Service checks', '服务检查'), paths: services })
1000
+ return result
1001
+ }
1002
+
1003
+ export function renderView(contract, { appRel = '.' } = {}) {
1004
+ const engine = inApp(appRel, ENGINE_FILE)
1005
+ const contractRel = inApp(appRel, CONTRACT_FILE)
1006
+ const inCi = new Set(validateContract(contract).ok ? ciProfiles(contract) : [])
1007
+ const localProfile = Object.entries(contract.profiles || {}).find(([, p]) => p && p.environment === 'local')?.[0] || 'pr-local'
1008
+ const paths = contract.paths || []
1009
+ const documentationErrors = validatePathDocumentation(paths)
1010
+ if (documentationErrors.length) throw new Error(`golden-path: invalid documentation:\n${documentationErrors.join('\n')}`)
1011
+ const bilingual = paths.some((p) => p.documentation?.summary?.route?.zh || p.documentation?.summary?.outcome?.zh || p.documentation?.group?.zh || p.documentation?.title?.zh || p.documentation?.precondition?.zh || p.documentation?.steps?.some((s) => s.action?.zh || s.expected?.zh))
1012
+ const label = (en, zh) => bilingual ? `${en} / ${zh}` : en
1013
+ const lines = [
1014
+ `# ${label('Golden paths', '黄金路径')}`,
1015
+ '',
1016
+ `<!-- GENERATED by the golden-path skill from ${CONTRACT_FILE}. Do not edit: change ${CONTRACT_FILE}, then run \`node ${ENGINE_FILE} init --write\`. -->`,
1017
+ '',
1018
+ 'The user flows whose failure blocks a release. A run is **ALIVE** only when every path it selects passes; one failure makes it **DEAD**.',
1019
+ '',
1020
+ ...(bilingual ? ['这些流程一旦失败,就会阻止发布。只有本次运行选中的所有路径均通过,结果才是 **ALIVE**;任一路径失败,结果即为 **DEAD**。', ''] : []),
1021
+ ]
1022
+ const documented = paths.some((p) => p.documentation)
1023
+ if (paths.length === 0) {
1024
+ lines.push(`No golden paths yet. Add them to \`${contractRel}\`.`, '')
1025
+ } else if (!documented) {
1026
+ lines.push('| Path | What it proves | How it is checked | Runs in | Writes data |', '|---|---|---|---|---|')
1027
+ for (const p of paths) {
1028
+ const proves = p.title || firstSentence(p.intent || p.observable)
1029
+ const writes = p.mutates ? `yes (tenant \`${p.tenant}\`)` : 'no'
1030
+ lines.push(`| \`${cell(p.id)}\` | ${cell(proves)} | ${cell(howChecked(p))} | ${cell((p.profiles || []).join(', '))} | ${cell(writes)} |`)
1031
+ }
1032
+ lines.push('')
1033
+ } else {
1034
+ const groups = journeyGroups(paths, label)
1035
+ const referenceOf = (p) => p.documentation?.reference || p.id
1036
+ const titleOf = (p) => p.documentation?.title || { en: p.title || firstSentence(p.intent || p.observable) }
1037
+ lines.push(`## ${label('Contents', '目录')}`, '')
1038
+ for (const group of groups) {
1039
+ lines.push(`**${documentationText(group.title)}**`, '')
1040
+ for (const p of group.paths) {
1041
+ const title = titleOf(p)
1042
+ const text = `${documentationText(referenceOf(p))}: ${documentationText(title.en)}${title.zh ? ` / ${documentationText(title.zh)}` : ''}`
1043
+ lines.push(`- [${text}](#golden-path-${p.id})`)
1044
+ }
1045
+ lines.push('')
1046
+ }
1047
+ for (const group of groups) {
1048
+ lines.push(`## ${documentationText(group.title)}`, '')
1049
+ for (const p of group.paths) {
1050
+ const doc = p.documentation
1051
+ const title = titleOf(p)
1052
+ lines.push(`<a id="golden-path-${p.id}"></a>`, '',
1053
+ `### ${documentationText(referenceOf(p))}: ${documentationText(title.en)}`, '')
1054
+ if (title.zh) lines.push(`**${documentationText(title.zh)}**`, '')
1055
+ if (doc?.summary) {
1056
+ const { route, outcome } = doc.summary
1057
+ lines.push(`**${label('Route', '路径')}:** ${documentationText(route.en)}${route.zh ? '<br>' : ''}`)
1058
+ if (route.zh) lines.push(documentationText(route.zh))
1059
+ lines.push('', `**${label('Result', '结果')}:** ${documentationText(outcome.en)}${outcome.zh ? '<br>' : ''}`)
1060
+ if (outcome.zh) lines.push(documentationText(outcome.zh))
1061
+ lines.push('', '<details>', `<summary>${label('Full steps', '完整步骤')}</summary>`, '')
1062
+ }
1063
+ if (doc?.precondition) {
1064
+ lines.push(`**${label('Starting point', '开始前')}**`, '', documentationText(doc.precondition.en), '')
1065
+ if (doc.precondition.zh) lines.push(documentationText(doc.precondition.zh), '')
1066
+ }
1067
+ for (const [i, step] of (doc?.steps || []).entries()) {
1068
+ lines.push(`${i + 1}. **${documentationText(step.action.en)}**${step.action.zh ? '<br>' : ''}`)
1069
+ if (step.action.zh) lines.push(` **${documentationText(step.action.zh)}**`)
1070
+ lines.push('', ` Expected: ${documentationText(step.expected.en)}${step.expected.zh ? '<br>' : ''}`)
1071
+ if (step.expected.zh) lines.push(` 预期:${documentationText(step.expected.zh)}`)
1072
+ lines.push('')
1073
+ }
1074
+ lines.push(`**${label('Verified by', '自动验证')}**`, '',
1075
+ `\`${p.id}\` · ${howChecked(p)}`, '',
1076
+ `${label('Runs in', '运行环境')}: ${cell((p.profiles || []).join(', '))}`, '',
1077
+ `${label('Writes to shared data', '写入共享数据')}: ${p.mutates ? `${label('yes', '是')} (tenant \`${p.tenant}\`)` : label('no', '否')}`, '')
1078
+ if (doc?.summary) lines.push('</details>', '')
1079
+ lines.push('---', '')
1080
+ }
1081
+ }
1082
+ lines.push(
1083
+ 'Shared-data writes outlive the run. Local journeys may write to a disposable test database.',
1084
+ ...(bilingual ? ['共享数据写入在运行结束后仍保留。本地旅程可能写入一次性测试数据库。'] : []), '',
1085
+ )
1086
+ }
1087
+ const profiles = Object.entries(contract.profiles || {})
1088
+ if (profiles.length) {
1089
+ lines.push(`## ${label('Where they run', '运行环境')}`, '', `| ${label('Profile', '配置')} | ${label('When', '时机')} | ${label('Writes data', '写入策略')} | ${label('Paths', '路径数')} | ${label('Run by', '执行方')} |`, '|---|---|---|---|---|')
1090
+ for (const [name, prof] of profiles) {
1091
+ let count = '-'
1092
+ try { count = String(selectPathsForProfile(contract, name).run.length) } catch { /* invalid profile */ }
1093
+ const by = inCi.has(name) ? `\`${workflowFile(appRel)}\`` : prof.environment === 'local' ? (contract.ci?.enabled === false ? "the repo's own CI job, or locally" : 'locally') : 'the deploy or release pipeline'
1094
+ lines.push(`| \`${name}\` | ${cell(GATE_WHEN[prof.gate] || prof.gate)} | ${cell(POLICY_WORDS[prof.mutationPolicy] || prof.mutationPolicy)} | ${count} | ${by} |`)
1095
+ }
1096
+ lines.push('')
1097
+ }
1098
+ lines.push(
1099
+ `## ${label('Run them locally', '本地运行')}`,
1100
+ '',
1101
+ bilingual ? 'Start the app, then / 启动应用后运行:' : 'Start the app, then:',
1102
+ '',
1103
+ '```sh',
1104
+ `node ${engine} run --profile ${localProfile}`,
1105
+ `node ${engine} verdict --profile ${localProfile}`,
1106
+ '```',
1107
+ '',
1108
+ `## ${label('Change them', '修改方式')}`,
1109
+ '',
1110
+ `Edit \`${contractRel}\`, then run \`node ${engine} init --write\` to refresh this file and the workflow. CI fails while they are out of date.`,
1111
+ '',
1112
+ ...(bilingual ? [`修改 \`${contractRel}\`,然后运行上述 init --write 命令重新生成本文及工作流。生成文件未同步时,CI 检查会失败。`, ''] : []),
1113
+ )
1114
+ return lines.join('\n')
1115
+ }
1116
+
1117
+ // ---------------------------------------------------------------------------
1118
+ // CI: .github/workflows/golden-paths.yml
1119
+ // ---------------------------------------------------------------------------
1120
+
1121
+ function yamlStr(s) { return JSON.stringify(String(s)) }
1122
+ // The postgres:18 image keeps PGDATA under /var/lib/postgresql/18/docker and declares
1123
+ // its volume at /var/lib/postgresql; 17 and older use /var/lib/postgresql/data. A tmpfs
1124
+ // on the wrong path leaves the real data dir on an anonymous disk volume.
1125
+ function pgDataDir(version = '17') {
1126
+ return parseInt(String(version), 10) >= 18 ? '/var/lib/postgresql' : '/var/lib/postgresql/data'
1127
+ }
1128
+
1129
+ export function renderWorkflow(contract, { appRel = '.' } = {}) {
1130
+ // Contract values land in YAML and shell: never render from an unvalidated contract.
1131
+ if (!validateContract(contract).ok) return null
1132
+ const profiles = ciProfiles(contract)
1133
+ if (profiles.length === 0) return null
1134
+ const ci = contract.ci || {}
1135
+ const setup = contract.setup || {}
1136
+ const pm = ci.packageManager || 'npm'
1137
+ const baseUrl = setup.baseUrl || 'http://127.0.0.1:3000'
1138
+ const health = `${baseUrl.replace(/\/$/, '')}${setup.healthPath || inferHealthPath(contract) || '/'}`
1139
+ const hasBrowser = (contract.paths || []).some((p) => p.surface === 'browser' && (p.profiles || []).some((x) => profiles.includes(x)))
1140
+ const db = setup.database
1141
+ const dbUrlEnv = db?.urlEnv || 'DATABASE_URL'
1142
+ const engine = ENGINE_FILE
1143
+ const watch = appRel === '.' ? null : appRel
1144
+ const L = []
1145
+ L.push(`# GENERATED by the golden-path skill from ${inApp(appRel, CONTRACT_FILE)}. Do not edit:`)
1146
+ L.push(`# change the contract, then run \`node ${inApp(appRel, ENGINE_FILE)} init --write\`.`)
1147
+ const label = yamlStr(watch ? `Golden paths (${watch})` : 'Golden paths')
1148
+ L.push(`name: ${label}`)
1149
+ L.push('on:')
1150
+ if (profiles.includes('pr-local')) L.push(' pull_request:')
1151
+ if (profiles.includes('queue-local')) {
1152
+ if (ci.queue === 'github') L.push(' merge_group:')
1153
+ else L.push(' push:', " branches: ['mergify/merge-queue/**']")
1154
+ }
1155
+ L.push(' workflow_dispatch:', ' inputs:', ' profile:', ' type: choice', ` default: ${profiles[0]}`, ` options: [${profiles.join(', ')}]`)
1156
+ L.push('permissions:', ' contents: read')
1157
+ L.push('concurrency:', ` group: ${path.basename(workflowFile(appRel), '.yml')}-\${{ github.ref }}`, ' cancel-in-progress: true')
1158
+ L.push('jobs:', ' golden-paths:', ` name: ${label}`)
1159
+ L.push(` runs-on: ${ci.runner || 'ubuntu-latest'}`)
1160
+ L.push(` timeout-minutes: ${ci.timeoutMinutes || 20}`)
1161
+ if (watch) L.push(' defaults:', ' run:', ` working-directory: ${yamlStr(watch)}`)
1162
+ if (db) {
1163
+ L.push(' services:', ' postgres:', ` image: postgres:${db.version || '17'}`)
1164
+ L.push(' env: { POSTGRES_USER: postgres, POSTGRES_PASSWORD: postgres, POSTGRES_DB: golden_paths }')
1165
+ L.push(" ports: ['5432/tcp']")
1166
+ L.push(' options: >-', ` --tmpfs ${pgDataDir(db.version)}:rw,noexec,nosuid,size=1g`, ' --health-cmd "pg_isready -U postgres" --health-interval 2s --health-timeout 5s --health-retries 30')
1167
+ }
1168
+ const queueExpr = profiles.includes('queue-local') ? "(github.event_name != 'pull_request' && 'queue-local')" : null
1169
+ const prExpr = profiles.includes('pr-local') ? "'pr-local'" : `'${profiles[0]}'`
1170
+ const profileExpr = `\${{ inputs.profile || ${queueExpr ? `${queueExpr} || ` : ''}${prExpr} }}`
1171
+ L.push(' env:', ` GOLDEN_PATH_PROFILE: ${profileExpr}`, ` BASE_URL: ${yamlStr(baseUrl)}`)
1172
+ if (db) L.push(` ${dbUrlEnv}: postgres://postgres:postgres@127.0.0.1:\${{ job.services.postgres.ports['5432'] }}/golden_paths`)
1173
+ for (const [k, v] of Object.entries(isStringArray(setup.env) ? {} : setup.env || {})) L.push(` ${k}: ${yamlStr(v)}`)
1174
+ for (const k of setup.secrets?.fromCi || []) L.push(` ${k}: \${{ secrets.${k} }}`)
1175
+ L.push(' steps:', ' - uses: actions/checkout@v4')
1176
+ if (pm !== 'npm') L.push(' - run: corepack enable')
1177
+ const cache = ci.cache !== false
1178
+ L.push(' - uses: actions/setup-node@v4', ' with:', ` node-version: ${yamlStr(ci.node || '22')}`)
1179
+ if (cache) L.push(` cache: ${pm}`)
1180
+ if (cache && (ci.lockfile || watch)) L.push(` cache-dependency-path: ${yamlStr(ci.lockfile || `${watch}/${LOCKFILES[pm]}`)}`)
1181
+ L.push(' - name: Check generated files', ` run: node ${engine} check`)
1182
+ const gen = setup.secrets?.generate || []
1183
+ if (gen.length) {
1184
+ L.push(' - name: Generate per-run secrets', ' run: |')
1185
+ L.push(` for name in ${gen.join(' ')}; do`)
1186
+ L.push(` value=$(node -e "process.stdout.write(require('crypto').randomBytes(32).toString('hex'))")`)
1187
+ L.push(' echo "::add-mask::$value"', ' echo "$name=$value" >> "$GITHUB_ENV"', ' done')
1188
+ }
1189
+ L.push(` - run: ${yamlStr(setup.install || pmInstall(pm, cache))}`)
1190
+ if (hasBrowser) L.push(` - run: ${yamlStr(setup.browser?.install || `${pmExec(pm)} playwright install --with-deps chromium`)}`)
1191
+ if (setup.build) L.push(` - run: ${yamlStr(setup.build)}`)
1192
+ if (setup.seed) L.push(` - run: ${yamlStr(setup.seed)}`)
1193
+ L.push(' - name: Boot the app', ' run: |', ` nohup sh -c ${shellQuote(setup.boot)} > ${SERVER_LOG} 2>&1 &`)
1194
+ L.push(` node ${engine} wait --url ${yamlStr(health)} --timeout 180`)
1195
+ L.push(` - run: node ${engine} run --profile "$GOLDEN_PATH_PROFILE" --target "$BASE_URL"`)
1196
+ L.push(` - run: node ${engine} verdict --profile "$GOLDEN_PATH_PROFILE" --target "$BASE_URL"`)
1197
+ L.push(' - if: failure()', ' uses: actions/upload-artifact@v4', ' with:', ' name: golden-paths', ' retention-days: 7', ' if-no-files-found: ignore', ' path: |')
1198
+ for (const f of [SERVER_LOG, RESULTS_FILE, VERDICT_FILE, 'playwright-report/', 'test-results/']) L.push(` ${watch ? `${watch}/` : ''}${f}`)
1199
+ L.push('')
1200
+ return L.join('\n')
1201
+ }
1202
+
1203
+ // ---------------------------------------------------------------------------
1204
+ // init / check / audit
1205
+ // ---------------------------------------------------------------------------
1206
+
1207
+ function pointerMarks(appRel = '.') {
1208
+ const id = appRel === '.' ? 'golden-path' : `golden-path:${appRel}`
1209
+ return [`<!-- ${id}:start -->`, `<!-- ${id}:end -->`]
1210
+ }
1211
+
1212
+ export function pointerBlock(appRel = '.') {
1213
+ const [POINTER_START, POINTER_END] = pointerMarks(appRel)
1214
+ const view = inApp(appRel, VIEW_FILE)
1215
+ const contract = inApp(appRel, CONTRACT_FILE)
1216
+ return [
1217
+ POINTER_START,
1218
+ '## Golden paths',
1219
+ '',
1220
+ `The user flows that must work before a release are listed in [${view}](${view}). Their contract is \`${contract}\`: edit the contract, never the generated files, and use the golden-path skill to change, run, or check them.`,
1221
+ POINTER_END,
1222
+ '',
1223
+ ].join('\n')
1224
+ }
1225
+
1226
+ export function upsertBlock(current, block, appRel = '.') {
1227
+ const [POINTER_START, POINTER_END] = pointerMarks(appRel)
1228
+ if (current == null) return `# AGENTS.md\n\n${block}`
1229
+ const from = current.indexOf(POINTER_START)
1230
+ const to = current.indexOf(POINTER_END)
1231
+ if (from !== -1 && to > from) return current.slice(0, from) + block + current.slice(to + POINTER_END.length).replace(/^\r?\n/, '')
1232
+ return `${current.replace(/\s*$/, '')}\n\n${block}`
1233
+ }
1234
+
1235
+ const IGNORED = [RESULTS_FILE, VERDICT_FILE, SERVER_LOG, BROWSER_REPORT]
1236
+
1237
+ export function starterContract(appDir) {
1238
+ const pm = detectPackageManager(appDir)
1239
+ let scripts = {}
1240
+ try { scripts = JSON.parse(fs.readFileSync(path.join(appDir, 'package.json'), 'utf8')).scripts || {} } catch { /* no package.json */ }
1241
+ const setup = { boot: scripts.start ? pmRun(pm, 'start') : 'TODO: the command that starts the app', baseUrl: 'http://127.0.0.1:3000' }
1242
+ if (scripts.build) setup.build = pmRun(pm, 'build')
1243
+ for (const dir of ['e2e/journeys', 'e2e', 'tests/e2e']) if (fs.existsSync(path.join(appDir, dir))) { setup.journeys = dir; break }
1244
+ setup.tenants = []
1245
+ return {
1246
+ version: CONTRACT_VERSION,
1247
+ profiles: STANDARD_PROFILES,
1248
+ setup,
1249
+ ci: { queue: fs.existsSync(path.join(findRepoRoot(appDir), '.mergify.yml')) ? 'mergify' : 'none', packageManager: pm, node: '22', ...lockfileCi(appDir, pm) },
1250
+ paths: [],
1251
+ }
1252
+ }
1253
+
1254
+ function json(o) { return `${JSON.stringify(o, null, 2)}\n` }
1255
+
1256
+ // The version plus a hash of both engine files: two copies agree only when identical.
1257
+ export function engineIdentity() {
1258
+ return identityOf(engineSource('golden-path.mjs'), engineSource('golden-path-core.mjs'))
1259
+ }
1260
+
1261
+ function identityOf(launcher, core) {
1262
+ const h = crypto.createHash('sha256').update(launcher).update(core)
1263
+ return `${/ENGINE_VERSION = '([^']+)'/.exec(core)?.[1] || '?'}+${h.digest('hex').slice(0, 12)}`
1264
+ }
1265
+
1266
+ function copyIdentity(launcherFile, coreFile) {
1267
+ return identityOf(fs.readFileSync(launcherFile, 'utf8'), fs.readFileSync(coreFile, 'utf8'))
1268
+ }
1269
+
1270
+ function engineSource(name) { return fs.readFileSync(fileURLToPath(new URL(`./${name}`, import.meta.url)), 'utf8') }
1271
+
1272
+ // Every file init owns, with the text it should hold (null = leave alone).
1273
+ export function initPlan(contractFile, { contract, origin } = {}) {
1274
+ const L = layout(contractFile)
1275
+ const exists = fs.existsSync(L.contractPath)
1276
+ const c = contract || (exists ? JSON.parse(fs.readFileSync(L.contractPath, 'utf8')) : starterContract(L.appDir))
1277
+ const valid = validateContract(c).ok
1278
+ const plan = []
1279
+ plan.push({ file: L.contractPath, next: exists && !contract ? null : json(c), why: exists && !contract ? 'kept: the contract is yours' : origin ? `migrated from ${origin}` : 'starter contract; add the golden paths' })
1280
+ plan.push({ file: L.enginePath, next: engineSource('golden-path.mjs'), why: `engine ${ENGINE_VERSION}` })
1281
+ plan.push({ file: L.coreEnginePath, next: engineSource('golden-path-core.mjs'), why: `engine ${ENGINE_VERSION}` })
1282
+ plan.push({ file: L.viewPath, next: renderView(c, { appRel: L.appRel }), why: 'generated view' })
1283
+ const wf = valid ? renderWorkflow(c, { appRel: L.appRel }) : null
1284
+ const wfNow = fs.existsSync(L.workflowPath) ? fs.readFileSync(L.workflowPath, 'utf8') : null
1285
+ if (!wf && valid && wfNow?.includes(GENERATED_MARK)) plan.push({ file: L.workflowPath, remove: true, why: 'the contract no longer generates a workflow' })
1286
+ else plan.push({ file: L.workflowPath, next: wf, why: wf ? 'generated workflow' : valid ? 'skipped: ci.enabled is false or no local profile has a trigger' : 'skipped until `validate` passes' })
1287
+ const agents = path.join(L.repoRoot, 'AGENTS.md')
1288
+ const agentsText = fs.existsSync(agents) ? fs.readFileSync(agents, 'utf8') : null
1289
+ plan.push({ file: agents, next: upsertBlock(agentsText, pointerBlock(L.appRel), L.appRel), why: 'pointer for agents' })
1290
+ const readme = path.join(L.repoRoot, 'README.md')
1291
+ const readmeText = fs.existsSync(readme) ? fs.readFileSync(readme, 'utf8') : '# README.md\n'
1292
+ plan.push({ file: readme, next: upsertBlock(readmeText, pointerBlock(L.appRel), L.appRel), why: 'pointer for people' })
1293
+ const claude = path.join(L.repoRoot, 'CLAUDE.md')
1294
+ const st = fs.lstatSync(claude, { throwIfNoEntry: false })
1295
+ if (!st) plan.push({ file: claude, link: 'AGENTS.md', why: 'symlink to AGENTS.md' })
1296
+ else if (!st.isSymbolicLink()) {
1297
+ const t = fs.readFileSync(claude, 'utf8')
1298
+ plan.push({ file: claude, next: /(?:^|[^\w-])AGENTS\.md/.test(t) ? t : upsertBlock(t, pointerBlock(L.appRel), L.appRel), why: 'pointer for Claude Code' })
1299
+ }
1300
+ const gi = path.join(L.appDir, '.gitignore')
1301
+ const giText = fs.existsSync(gi) ? fs.readFileSync(gi, 'utf8') : ''
1302
+ const missing = IGNORED.filter((f) => !giText.split(/\r?\n/).includes(f))
1303
+ plan.push({ file: gi, next: missing.length ? `${giText.replace(/\s*$/, '')}${giText.trim() ? '\n\n' : ''}# golden-path run output\n${missing.join('\n')}\n` : giText, why: 'ignore run output' })
1304
+ return { layout: L, plan, valid }
1305
+ }
1306
+
1307
+ export function applyPlan(plan, { write }) {
1308
+ return plan.map((step) => {
1309
+ const rel = step.file
1310
+ if (step.link) {
1311
+ if (write) fs.symlinkSync(step.link, step.file)
1312
+ return { file: rel, action: 'link', why: step.why }
1313
+ }
1314
+ if (step.remove) {
1315
+ if (write) fs.rmSync(step.file, { force: true })
1316
+ return { file: rel, action: 'delete', why: step.why }
1317
+ }
1318
+ if (step.next == null) return { file: rel, action: 'skip', why: step.why }
1319
+ const current = fs.existsSync(step.file) ? fs.readFileSync(step.file, 'utf8') : null
1320
+ const action = current == null ? 'create' : current === step.next ? 'unchanged' : 'update'
1321
+ if (write && action !== 'unchanged') {
1322
+ fs.mkdirSync(path.dirname(step.file), { recursive: true })
1323
+ fs.writeFileSync(step.file, step.next)
1324
+ }
1325
+ return { file: rel, action, why: step.why }
1326
+ })
1327
+ }
1328
+
1329
+ // Generated files that differ from what the contract renders today.
1330
+ export function checkDrift(contract, contractFile) {
1331
+ const L = layout(contractFile)
1332
+ const drift = []
1333
+ const view = renderView(contract, { appRel: L.appRel })
1334
+ const viewNow = fs.existsSync(L.viewPath) ? fs.readFileSync(L.viewPath, 'utf8') : null
1335
+ if (viewNow !== view) drift.push(`${posix(path.relative(L.repoRoot, L.viewPath))} is ${viewNow == null ? 'missing' : 'out of date'}`)
1336
+ const WORKFLOW_FILE = workflowFile(L.appRel)
1337
+ const wf = renderWorkflow(contract, { appRel: L.appRel })
1338
+ const wfNow = fs.existsSync(L.workflowPath) ? fs.readFileSync(L.workflowPath, 'utf8') : null
1339
+ if (wf != null && wfNow !== wf) drift.push(`${WORKFLOW_FILE} is ${wfNow == null ? 'missing' : 'out of date'}`)
1340
+ if (wf == null && wfNow?.includes(GENERATED_MARK)) drift.push(`${WORKFLOW_FILE} exists but the contract generates no workflow; init --write removes it`)
1341
+ return drift
1342
+ }
1343
+
1344
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'coverage', '.turbo', '.worktrees', 'vendor'])
1345
+
1346
+ function walkFiles(root, visit, depth = 0) {
1347
+ if (depth > 6) return
1348
+ for (const ent of fs.readdirSync(root, { withFileTypes: true })) {
1349
+ if (ent.isDirectory()) { if (!SKIP_DIRS.has(ent.name) && !(ent.name.startsWith('.') && ent.name !== '.github')) walkFiles(path.join(root, ent.name), visit, depth + 1) }
1350
+ else visit(path.join(root, ent.name), ent.name)
1351
+ }
1352
+ }
1353
+
1354
+ // Test names from tagged spec files, without tags or an "@smoke id:" prefix, sentence-cased.
1355
+ export function specTitles(files) {
1356
+ const out = []
1357
+ for (const f of files) {
1358
+ const text = fs.readFileSync(f, 'utf8')
1359
+ for (const m of text.matchAll(/\btest(?:\.only)?\(\s*(["'`])((?:(?!\1).)+)\1/g)) {
1360
+ const t = m[2].replace(/@[\w/-]+(?:\s+[\w/-]+:)?/g, '').replace(/\s+/g, ' ').trim()
1361
+ if (t) out.push(t[0].toUpperCase() + t.slice(1))
1362
+ }
1363
+ }
1364
+ return out
1365
+ }
1366
+
1367
+ // Mechanical v2 -> v3 conversion. Returns the contract plus what still needs a person.
1368
+ export function migrateLegacy(legacy, { appDir }) {
1369
+ const todo = []
1370
+ const c = { version: CONTRACT_VERSION }
1371
+ for (const [k, v] of Object.entries(legacy)) if (!['version', 'profiles', 'setup', 'ci', 'paths'].includes(k)) c[k] = v
1372
+ c.profiles = legacy.profiles || STANDARD_PROFILES
1373
+ if (!legacy.profiles) todo.push('profiles: none declared; the five standard profiles were added. Remove the ones this app does not use.')
1374
+ const s = { ...(legacy.setup || {}) }
1375
+ if (!s.boot) { s.boot = 'TODO: the command that starts the app'; todo.push('setup.boot: write the command that starts the app.') }
1376
+ else { s.boot = `TODO: make this one shell command: ${s.boot}`; todo.push('setup.boot: the old value may be prose; replace it with the one shell command that starts the app.') }
1377
+ todo.push('setup: add install, build, seed, database ({ "engine": "postgres" }), and secrets.generate if a local run needs them; the generated workflow uses them.')
1378
+ if (isStringArray(s.env)) {
1379
+ if (s.env.length) {
1380
+ s.secrets = { ...(s.secrets || {}), fromCi: [...new Set([...(s.secrets?.fromCi || []), ...s.env])] }
1381
+ todo.push(`setup.env: the names ${s.env.join(', ')} moved to setup.secrets.fromCi. Move non-secret ones to setup.env with their value, and per-run secrets to setup.secrets.generate.`)
1382
+ }
1383
+ delete s.env
1384
+ }
1385
+ if (!s.baseUrl) { s.baseUrl = 'http://127.0.0.1:3000'; todo.push('setup.baseUrl: check the URL the booted app listens on (default http://127.0.0.1:3000 was set).') }
1386
+ if (!s.journeys) for (const dir of ['e2e/journeys', 'e2e', 'tests/e2e']) if (fs.existsSync(path.join(appDir, dir))) { s.journeys = dir; break }
1387
+ const tenants = new Set(isStringArray(s.tenants) ? s.tenants : [])
1388
+ const specs = s.journeys ? scanJourneyTags(path.resolve(appDir, s.journeys)).byId : new Map()
1389
+ c.setup = s
1390
+ const pm = detectPackageManager(appDir)
1391
+ c.ci = { queue: fs.existsSync(path.join(findRepoRoot(appDir), '.mergify.yml')) ? 'mergify' : 'none', packageManager: pm, node: '22', ...lockfileCi(appDir, pm), ...(legacy.ci || {}) }
1392
+ c.paths = (legacy.paths || []).map((p) => {
1393
+ const q = { ...p }
1394
+ if (q.surface === 'browser' && q.journey) q.journey = journeyCoversId(q.journey)
1395
+ if (!q.title) {
1396
+ // A spec with several tests does not say which one is the path, so only a lone test name is used.
1397
+ const named = specTitles(specs.get(journeyCoversId(q.journey)) || [])
1398
+ const candidates = [firstSentence(q.intent || q.observable || ''), ...(named.length === 1 ? named : [])].filter(Boolean)
1399
+ const fit = candidates.find((t) => t.length <= TITLE_MAX)
1400
+ q.title = fit || 'TODO: one line on what this path proves'
1401
+ todo.push(fit ? `paths (${q.id}): check the title "${fit}".` : `paths (${q.id}): write a title under ${TITLE_MAX} characters${candidates[0] ? `; the spec says "${candidates[0]}"` : ''}.`)
1402
+ }
1403
+ if (typeof q.observable === 'string' && q.observable.length > OBSERVABLE_MAX) todo.push(`paths (${q.id}): shorten observable (${q.observable.length} chars) under ${OBSERVABLE_MAX}; move setup and cleanup detail out.`)
1404
+ if (q.mutates === true && !q.cleanup) { q.cleanup = 'TODO: how this path removes what it writes'; todo.push(`paths (${q.id}): write cleanup for a path that writes data.`) }
1405
+ if (q.tenant && !tenants.has(q.tenant)) { tenants.add(q.tenant); }
1406
+ if (q.surface === 'api' && !q.request && !parseStart(q.start)) todo.push(`paths (${q.id}): start "${q.start}" is not one request; split the path or set "request" so run can drive it.`)
1407
+ if (q.surface !== 'browser' && q.expect === undefined) todo.push(`paths (${q.id}): add "expect" so run checks more than a 2xx or exit 0.`)
1408
+ return q
1409
+ })
1410
+ c.setup.tenants = [...tenants]
1411
+ return { contract: c, todo }
1412
+ }
1413
+
1414
+ // What a CI file does with smoke, judged by its commands (not comments) and triggers.
1415
+ // Returns null when it only mentions smoke.
1416
+ export function classifyWorkflow(rel, text) {
1417
+ // Commands only: drop comments and display names (`name: smoke.mjs verdict` runs nothing).
1418
+ const code = text.split(/\r?\n/).map((l) => l.replace(/(^|\s)#.*$/, '').replace(/\b(?:echo|printf)\s+(["']).*?\1/g, '')).filter((l) => !/^\s*-?\s*name:/.test(l)).join('\n')
1419
+ const script = /\b(?:pnpm|npm run|yarn)\s+(?:run\s+)?([\w:-]*smoke[\w:-]*)/i.exec(code)?.[1]
1420
+ if (!script && !/smoke\.mjs|smoke\.manifest|@smoke|validation-profile/i.test(code)) return null
1421
+ const gate = /verdict|smoke\.mjs["']?[\s,]+["']?run\b|--grep[= ]["']?@smoke/i.test(code) || (!!script && !/validate/i.test(script))
1422
+ let lane
1423
+ if (/^cloudbuild/.test(path.basename(rel)) || rel.includes('/cloudbuild')) lane = 'deploy'
1424
+ else {
1425
+ const on = /^(?:on|"on"|'on'):[ \t]*(\[[^\]]*\]|\S[^\n]*|\n(?:(?:[ \t]+[^\n]*)?\n)*)/m.exec(code)?.[1] || ''
1426
+ if (/\bpull_request\b/.test(on)) lane = 'pr'
1427
+ else if (/merge_group|mergify\/merge-queue/.test(on)) lane = 'queue'
1428
+ else if (/\b(push|workflow_run|deployment|deployment_status|schedule)\b/.test(on)) lane = 'deploy'
1429
+ else lane = 'manual'
1430
+ }
1431
+ return { file: rel, lane, gate }
1432
+ }
1433
+
1434
+ function workflowNote(w, engineAt, generated = WORKFLOW_FILE, ciOff = false) {
1435
+ if (!w.gate) return `only validates the old manifest (${w.lane}); switch it to \`node ${engineAt} validate\` or drop it, since the generated workflow runs \`check\``
1436
+ if ((w.lane === 'pr' || w.lane === 'queue') && ciOff) return `runs smoke from a ${w.lane === 'pr' ? 'pull_request' : 'merge-queue'} trigger, and the contract sets ci.enabled false: keep this job and call \`node ${engineAt} run\` then \`verdict\` (--paths for a shard)`
1437
+ if (w.lane === 'pr' || w.lane === 'queue') return `runs smoke from a ${w.lane === 'pr' ? 'pull_request' : 'merge-queue'} trigger (job conditions may narrow it); the generated ${generated} can replace this job, or keep it and call \`node ${engineAt} run\` then \`verdict\`. If a required check names it, moving that is a merge-rule change: ask first`
1438
+ if (w.lane === 'deploy') return `runs smoke after a deploy or on a schedule; keep the step and call \`node ${engineAt} run\` then \`verdict\` with the deployed profile, --target, and --surfaces when that runner has no browser`
1439
+ return `manual-only (workflow_dispatch); repoint it at \`node ${engineAt} run\` and \`verdict\`, or leave it`
1440
+ }
1441
+
1442
+ export function audit(repoRoot) {
1443
+ const legacy = []
1444
+ const contracts = []
1445
+ const engines = []
1446
+ const workflows = []
1447
+ let smokeTags = 0
1448
+ let goldenTags = 0
1449
+ walkFiles(repoRoot, (full, name) => {
1450
+ const rel = posix(path.relative(repoRoot, full))
1451
+ if (name === LEGACY_CONTRACT_FILE) legacy.push(rel)
1452
+ else if (name === CONTRACT_FILE) contracts.push(rel)
1453
+ else if (/smoke.*\.mjs$|golden-path-core\.mjs$/.test(name) && !/\.test\.mjs$/.test(name)) {
1454
+ const text = fs.readFileSync(full, 'utf8')
1455
+ const launcher = path.join(path.dirname(full), 'golden-path.mjs')
1456
+ const v = /ENGINE_VERSION = '([^']+)'/.exec(text) && fs.existsSync(launcher) ? copyIdentity(launcher, full) : /ENGINE_VERSION = '([^']+)'/.exec(text)?.[1]
1457
+ // A gate engine reads the manifest or reduces a verdict; a one-off probe does neither.
1458
+ if (v || /smoke\.manifest|\bALIVE\b|\bverdict\b/.test(text)) engines.push({ file: rel, lines: text.split('\n').length, version: v || null })
1459
+ } else if (/\.(spec|test)\.[cm]?[jt]sx?$/.test(name)) {
1460
+ const text = fs.readFileSync(full, 'utf8')
1461
+ const journeys = /\.spec\./.test(name) && [...text.matchAll(/@covers\s+(\S+)/g)].some((m) => isJourneyId(m[1]))
1462
+ if (journeys && /@golden-path\b/.test(text)) goldenTags++
1463
+ else if (journeys && /@smoke\b/.test(text)) smokeTags++
1464
+ } else if ((rel.startsWith('.github/workflows/') && /\.ya?ml$/.test(name)) || /^cloudbuild.*\.ya?ml$/.test(name)) {
1465
+ const text = fs.readFileSync(full, 'utf8')
1466
+ const w = text.includes(GENERATED_MARK) ? null : classifyWorkflow(rel, text)
1467
+ if (w) workflows.push(w)
1468
+ }
1469
+ })
1470
+ const findings = []
1471
+ for (const f of legacy) {
1472
+ const appDir = path.join(repoRoot, path.dirname(f))
1473
+ const hasNew = fs.existsSync(path.join(appDir, CONTRACT_FILE))
1474
+ let declared = []
1475
+ try { declared = Object.keys(JSON.parse(fs.readFileSync(path.join(repoRoot, f), 'utf8')).profiles || {}) } catch { findings.push({ kind: 'legacy', file: f, note: 'not valid JSON' }); continue }
1476
+ findings.push({ kind: 'legacy', file: f, note: hasNew ? `${CONTRACT_FILE} already exists beside it; remove the legacy file once nothing reads it` : 'migrate with `audit --write`' })
1477
+ if (declared.includes('pr-local') && !workflows.some((w) => w.lane === 'pr' && w.gate)) findings.push({ kind: 'drift', file: f, note: 'declares pr-local, but no workflow runs smoke on pull_request. Keep it and the generated workflow runs it on PRs, or drop pr-local if PRs should not run it' })
1478
+ }
1479
+ for (const e of engines) {
1480
+ if (e.version === engineIdentity()) continue
1481
+ findings.push({ kind: 'engine', file: e.file, note: e.version ? `engine ${e.version} differs from this skill's ${engineIdentity()} (an older or edited copy); refresh with init --write` : `${e.lines}-line smoke script; the copied engine replaces it. Check it for repo-only features before deleting it` })
1482
+ }
1483
+ const appRel = legacy[0] ? posix(path.dirname(legacy[0])) : contracts[0] ? posix(path.dirname(contracts[0])) : '.'
1484
+ const engineAt = inApp(appRel, ENGINE_FILE)
1485
+ let ciOff = false
1486
+ try { ciOff = JSON.parse(fs.readFileSync(path.join(repoRoot, appRel, CONTRACT_FILE), 'utf8')).ci?.enabled === false } catch { /* no contract yet */ }
1487
+ for (const w of workflows) findings.push({ kind: 'workflow', file: w.file, note: workflowNote(w, engineAt, workflowFile(appRel), ciOff) })
1488
+ if (smokeTags) findings.push({ kind: 'tags', file: '(specs)', note: `${smokeTags} spec file(s) tagged @smoke; still read by golden-path. Retag to @golden-path only after the old smoke scripts are retired, since they read @smoke` })
1489
+ return { legacy, contracts, engines, workflows, smokeTags, goldenTags, findings }
1490
+ }
1491
+
1492
+ // ---------------------------------------------------------------------------
1493
+ // suggest (candidates from a surface inventory; a person decides)
1494
+ // ---------------------------------------------------------------------------
1495
+
1496
+ const GOLDEN_KEYWORDS = ['checkout', 'pay', 'payment', 'billing', 'invoice', 'subscribe', 'order', 'purchase', 'refund', 'login', 'signin', 'sign-in', 'signup', 'sign-up', 'register', 'sso', 'oauth', 'auth', 'onboard', 'invite', 'settings', 'connect', 'create', 'new']
1497
+
1498
+ function normalizeInventory(inv) {
1499
+ if (!inv || typeof inv !== 'object') return []
1500
+ if (Array.isArray(inv.surfaces)) return inv.surfaces
1501
+ const out = []
1502
+ for (const [key, kind] of [['routes', 'route'], ['apis', 'api']]) for (const id of inv[key] || []) out.push({ id, kind })
1503
+ return out
1504
+ }
1505
+
1506
+ export function suggestCandidates(inventory, { limit = 8 } = {}) {
1507
+ const scored = normalizeInventory(inventory).map((s) => {
1508
+ const id = String(s.id || '').toLowerCase()
1509
+ let score = 0
1510
+ const reasons = []
1511
+ if (s.kind === 'route') { score += 20; reasons.push('route'); if (s.class === 'mutation') { score += 55; reasons.push('mutation') } }
1512
+ if (s.kind === 'api') { if (/health|ready|live/.test(id)) { score += 45; reasons.push('health') } if (s.class === 'mutation') { score += 25; reasons.push('mutation') } }
1513
+ const kw = GOLDEN_KEYWORDS.find((k) => id.includes(k))
1514
+ if (kw) { score += 30; reasons.push(`keyword:${kw}`) }
1515
+ if (/about|help|docs|terms|privacy|status/.test(id)) score -= 60
1516
+ return { s, score, reasons }
1517
+ }).filter((x) => x.score > 0).sort((a, b) => b.score - a.score || String(a.s.id).localeCompare(String(b.s.id))).slice(0, limit)
1518
+ return {
1519
+ _comment: 'CANDIDATES ONLY. A person decides which flows block a release; promote by hand into golden-paths.json paths.',
1520
+ candidates: scored.map(({ s, score, reasons }) => ({
1521
+ id: String(s.id).replace(/^\/+/, '').replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'root',
1522
+ surface: s.kind === 'route' ? 'browser' : 'api', start: s.kind === 'route' ? s.id : `${s.method || 'GET'} ${s.id}`,
1523
+ mutates: s.class === 'mutation', score, reasons,
1524
+ })),
1525
+ }
1526
+ }
1527
+
1528
+ // ---------------------------------------------------------------------------
1529
+ // CLI
1530
+ // ---------------------------------------------------------------------------
1531
+
1532
+ const FLAGS = { '--paths': 'paths', '--surfaces': 'surfaces', '--contract': 'contract', '--profile': 'profile', '--target': 'target', '--results': 'results', '--out': 'out', '--journeys': 'journeys', '--inventory': 'inventory', '--limit': 'limit', '--url': 'url', '--timeout': 'timeout', '--expect-sha': 'expectSha', '--app-dir': 'appDir', '--repo-root': 'repoRoot', '--manifest': 'contract' }
1533
+ const BOOLS = { '--boot': 'boot', '--write': 'write', '--json': 'json', '--remove-legacy': 'removeLegacy' }
1534
+
1535
+ export const USAGE = `usage: node golden-path.mjs <command> [flags]
1536
+
1537
+ init [--app-dir <dir>] [--write] scaffold or refresh: contract, engine copy, view, workflow, pointers
1538
+ audit [--repo-root <dir>] [--write] [--remove-legacy] [--json]
1539
+ find legacy smoke setups; --write migrates them
1540
+ validate [--contract <f>] [--journeys <dir>] check the contract and the spec tags
1541
+ plan --profile <name> [--target <url>] [--surfaces api,cli,browser] [--paths id,id]
1542
+ which paths run and which are skipped
1543
+ run --profile <name> [--target <url>] [--surfaces ...] [--paths ...] [--expect-sha <sha>] [--out <f>]
1544
+ [--boot [--timeout <s>]] drive the paths against a running app; --boot starts
1545
+ setup.boot first and stops it after (local profiles)
1546
+ verdict --profile <name> [--target <url>] [--surfaces ...] [--paths ...] [--results <f>] [--out <f>]
1547
+ ALIVE / DEAD / CANNOT-RUN / EMPTY; exit 0 only on ALIVE
1548
+ render [--write] print or write GOLDEN_PATHS.md
1549
+ ci [--write] print or write the workflow
1550
+ check contract valid and generated files current (CI runs this)
1551
+ wait --url <url> [--timeout <s>] wait until a booted app answers
1552
+ suggest --inventory <f> [--limit <n>] candidate paths from a surface inventory
1553
+ version the engine version
1554
+
1555
+ The contract defaults to ./golden-paths.json.`
1556
+
1557
+ export function parseArgs(argv) {
1558
+ const f = {}
1559
+ for (let i = 0; i < argv.length; i++) {
1560
+ const a = argv[i]
1561
+ if (FLAGS[a]) f[FLAGS[a]] = argv[++i]
1562
+ else if (BOOLS[a]) f[BOOLS[a]] = true
1563
+ else if (a === '--help' || a === '-h') f.cmd = 'help'
1564
+ else if (a.startsWith('--')) return { error: `unknown flag ${a}` }
1565
+ else if (!f.cmd) f.cmd = a
1566
+ else return { error: `unexpected argument ${a}` }
1567
+ }
1568
+ return f
1569
+ }
1570
+
1571
+ function readJson(p) { return JSON.parse(fs.readFileSync(p, 'utf8')) }
1572
+
1573
+ const WOULD = { create: 'would create', update: 'would update', delete: 'would delete', link: 'would link' }
1574
+
1575
+ function report(results, root, write, log) {
1576
+ for (const r of results) log(` ${(write ? r.action : WOULD[r.action] || r.action).padEnd(13)} ${posix(path.relative(root, r.file)) || r.file} (${r.why})`)
1577
+ log(write ? 'golden-path: written' : 'golden-path: preview only; re-run with --write to write')
1578
+ }
1579
+
1580
+ function loadContract(f, log) {
1581
+ const file = f.contract || CONTRACT_FILE
1582
+ if (!fs.existsSync(file)) {
1583
+ const legacy = path.join(path.dirname(file), LEGACY_CONTRACT_FILE)
1584
+ log(fs.existsSync(legacy)
1585
+ ? `golden-path: no ${file}, but ${legacy} exists; migrate it with \`node ${ENGINE_FILE} audit --write\``
1586
+ : `golden-path: no ${file}; create one with \`init --write\`, then add the golden paths`)
1587
+ return null
1588
+ }
1589
+ return { file, contract: readJson(file) }
1590
+ }
1591
+
1592
+ export async function runCli(argv, { log = console.log, err = console.error } = {}) {
1593
+ const f = parseArgs(argv)
1594
+ if (f.error) { err(`golden-path: ${f.error}`); return 2 }
1595
+ if (!f.cmd) { err(USAGE); return 2 }
1596
+ if (f.cmd === 'help') { log(USAGE); return 0 }
1597
+
1598
+ if (f.cmd === 'version') { log(engineIdentity()); return 0 }
1599
+
1600
+ if (f.cmd === 'wait') {
1601
+ if (!f.url) { err('golden-path: wait needs --url'); return 2 }
1602
+ const down = await waitFor(f.url, Number(f.timeout || 120))
1603
+ if (!down) { log(`golden-path: ${f.url} is up`); return 0 }
1604
+ err(`golden-path: ${f.url} did not come up within ${f.timeout || 120}s (${down})`)
1605
+ return 1
1606
+ }
1607
+
1608
+ if (f.cmd === 'suggest') {
1609
+ if (!f.inventory) { err('golden-path: suggest needs --inventory'); return 2 }
1610
+ const out = json(suggestCandidates(readJson(f.inventory), { limit: f.limit ? Number(f.limit) : 8 }))
1611
+ if (f.out) fs.writeFileSync(f.out, out)
1612
+ log(out.trimEnd())
1613
+ return 0
1614
+ }
1615
+
1616
+ if (f.cmd === 'init') {
1617
+ const appDir = path.resolve(f.appDir || '.')
1618
+ const { layout: L, plan, valid } = initPlan(path.join(appDir, CONTRACT_FILE))
1619
+ if (!fs.existsSync(L.contractPath) && fs.existsSync(path.join(appDir, LEGACY_CONTRACT_FILE))) {
1620
+ err(`golden-path: ${LEGACY_CONTRACT_FILE} exists here; run \`audit --write\` to migrate it instead of starting empty`)
1621
+ return 1
1622
+ }
1623
+ report(applyPlan(plan, { write: !!f.write }), L.repoRoot, !!f.write, log)
1624
+ if (plan.some((p) => p.file === L.contractPath && p.next != null)) log(`golden-path: check setup.boot and setup.baseUrl in ${CONTRACT_FILE}; init guessed them`)
1625
+ if (!valid) log('golden-path: the contract is not valid yet (run validate); the workflow is generated once it passes')
1626
+ return 0
1627
+ }
1628
+
1629
+ if (f.cmd === 'audit') {
1630
+ const root = path.resolve(f.repoRoot || findRepoRoot('.'))
1631
+ const a = audit(root)
1632
+ if (f.json && !f.write) { log(json(a).trimEnd()); return 0 }
1633
+ log(`golden-path audit of ${root}`)
1634
+ log(` contracts: ${a.contracts.join(', ') || 'none'}; legacy manifests: ${a.legacy.join(', ') || 'none'}; tagged specs: ${a.goldenTags} @golden-path, ${a.smokeTags} @smoke`)
1635
+ for (const x of a.findings) log(` [${x.kind}] ${x.file}: ${x.note}`)
1636
+ if (!a.findings.length) log(' nothing to migrate')
1637
+ if (!f.write) {
1638
+ if (a.legacy.length) log('golden-path: preview only; `audit --write` converts each legacy manifest and runs init beside it')
1639
+ return a.findings.length ? 1 : 0
1640
+ }
1641
+ for (const rel of a.legacy) {
1642
+ const appDir = path.join(root, path.dirname(rel))
1643
+ if (fs.existsSync(path.join(appDir, CONTRACT_FILE))) continue
1644
+ const { contract, todo } = migrateLegacy(readJson(path.join(root, rel)), { appDir })
1645
+ log(`\nmigrating ${rel}`)
1646
+ const migrated = initPlan(path.join(appDir, CONTRACT_FILE), { contract, origin: path.basename(rel) })
1647
+ report(applyPlan(migrated.plan, { write: true }), root, true, log)
1648
+ if (!migrated.valid) log(' the contract is not valid yet; finish the lines below, then validate and init --write')
1649
+ if (f.removeLegacy) { fs.rmSync(path.join(root, rel)); log(` removed ${rel}`) }
1650
+ if (todo.length) {
1651
+ const kinds = { title: /title/, observable: /observable/, cleanup: /cleanup/, expect: /"expect"/, request: /not one request/, setup: /^setup/ }
1652
+ const counts = Object.entries(kinds).map(([k, re]) => [k, todo.filter((t) => re.test(t)).length]).filter(([, n]) => n)
1653
+ log(` needs a person (${todo.length}: ${counts.map(([k, n]) => `${n} ${k}`).join(', ')}):`)
1654
+ for (const t of todo) log(` - ${t}`)
1655
+ }
1656
+ }
1657
+ return 0
1658
+ }
1659
+
1660
+ const loaded = loadContract(f, err)
1661
+ if (!loaded) return 2
1662
+ const { file, contract } = loaded
1663
+ const L = layout(file)
1664
+ const journeys = f.journeys || (contract.setup?.journeys ? path.resolve(L.appDir, contract.setup.journeys) : null)
1665
+
1666
+ if (f.cmd === 'ci' && !validateContract(contract).ok) { err('golden-path: the contract is not valid; run validate. No workflow is generated from an invalid contract'); return 1 }
1667
+ if (f.cmd === 'render' || f.cmd === 'ci') {
1668
+ const next = f.cmd === 'render' ? renderView(contract, { appRel: L.appRel }) : renderWorkflow(contract, { appRel: L.appRel })
1669
+ const target = f.cmd === 'render' ? L.viewPath : L.workflowPath
1670
+ if (next == null) { log('golden-path: the contract generates no workflow (ci.enabled is false, or no local profile has a trigger)'); return 0 }
1671
+ if (!f.write) { log(next.trimEnd()); return 0 }
1672
+ report(applyPlan([{ file: target, next, why: 'generated' }], { write: true }), L.repoRoot, true, log)
1673
+ return 0
1674
+ }
1675
+
1676
+ const v = validateContract(contract)
1677
+ const rec = reconcileAt(contract, journeys)
1678
+ const errors = [...v.errors, ...rec.errors]
1679
+ const warnings = [...v.warnings, ...rec.warnings]
1680
+ const pmName = contract.ci?.packageManager || detectPackageManager(L.appDir)
1681
+ if (contract.ci?.cache !== false && !contract.setup?.install && !hasLockfile(L.appDir, pmName)) {
1682
+ warnings.push(`no ${LOCKFILES[pmName]}: the workflow's ${pmInstall(pmName)} and dependency cache need one; commit it, or set ci.cache to false`)
1683
+ }
1684
+
1685
+ if (f.cmd === 'validate') {
1686
+ if (f.json) log(json({ ok: !errors.length, errors, warnings }).trimEnd())
1687
+ else {
1688
+ log(errors.length ? 'golden-path: contract invalid:' : `golden-path: contract valid (${contract.paths.length} golden path(s))`)
1689
+ for (const e of errors) log(` - ${e}`)
1690
+ for (const w of warnings) log(` ! ${w}`)
1691
+ }
1692
+ return errors.length ? 1 : 0
1693
+ }
1694
+
1695
+ if (f.cmd === 'check') {
1696
+ const drift = errors.length ? [] : checkDrift(contract, file)
1697
+ for (const e of errors) log(` - ${e}`)
1698
+ for (const d of drift) log(` - ${d}`)
1699
+ if (errors.length || drift.length) { log(`golden-path: check failed; fix the contract, then run \`node ${ENGINE_FILE} init --write\``); return 1 }
1700
+ log('golden-path: contract valid and generated files current')
1701
+ return 0
1702
+ }
1703
+
1704
+ if (errors.length) { err('golden-path: contract invalid; run validate'); for (const e of errors) err(` - ${e}`); return 1 }
1705
+ if (!f.profile) { err(`golden-path: ${f.cmd} needs --profile`); return 2 }
1706
+ let surfaces = f.surfaces ? f.surfaces.split(',').map((x) => x.trim()).filter(Boolean) : undefined
1707
+ let ids = f.paths ? f.paths.split(',').map((x) => x.trim()).filter(Boolean) : undefined
1708
+ const target = f.target || contract.setup?.baseUrl || 'http://127.0.0.1:3000'
1709
+ let opened = null
1710
+ if (f.cmd === 'verdict') {
1711
+ const resultsFile = f.results || path.join(L.appDir, RESULTS_FILE)
1712
+ if (!fs.existsSync(resultsFile)) { err(`golden-path: no results at ${resultsFile}; run \`run --profile ${f.profile}\` first`); return 1 }
1713
+ const deployed = (contract.profiles?.[f.profile]?.environment || 'local') !== 'local'
1714
+ opened = openResults(readJson(resultsFile), { profile: f.profile, target: f.target ? target : null, surfaces, ids, deployed })
1715
+ if (opened.error) { err(`golden-path: ${opened.error}`); return 1 }
1716
+ surfaces = surfaces ?? opened.surfaces
1717
+ ids = ids ?? opened.ids
1718
+ }
1719
+ let sel
1720
+ try { sel = selectPathsForProfile(contract, f.profile, { surfaces, ids }) } catch (e) { err(`golden-path: ${e.message}`); return 1 }
1721
+
1722
+ if (f.cmd === 'plan') {
1723
+ const plan = { profile: sel.profile, target, run: sel.run.map((p) => ({ id: p.id, surface: p.surface, drive: p.journey || p.command || p.start || p.request?.path })), excluded: sel.excluded }
1724
+ if (f.json) log(json(plan).trimEnd())
1725
+ else {
1726
+ log(`golden-path plan: ${f.profile} (${sel.profile.gate}, ${sel.profile.mutationPolicy}) against ${target}`)
1727
+ for (const p of plan.run) log(` run ${p.id} [${p.surface}] ${p.drive}`)
1728
+ for (const x of plan.excluded) log(` skip ${x.id}: ${x.reason}`)
1729
+ }
1730
+ return 0
1731
+ }
1732
+
1733
+ if (f.cmd === 'run') {
1734
+ let app = null
1735
+ if (f.boot) {
1736
+ if (sel.profile.environment !== 'local') { err(`golden-path: --boot starts a local build; profile ${f.profile} targets ${sel.profile.environment}`); return 2 }
1737
+ if (contract.setup?.seed) {
1738
+ const literal = isStringArray(contract.setup?.env) ? {} : contract.setup?.env || {}
1739
+ const seeded = spawnSync(contract.setup.seed, { shell: true, cwd: L.appDir, stdio: 'inherit', env: { ...process.env, ...literal } })
1740
+ if (seeded.status !== 0) { err(`golden-path: setup.seed failed (exit ${seeded.status}); fix it before running`); return 1 }
1741
+ }
1742
+ const health = `${target.replace(/\/$/, '')}${contract.setup?.healthPath || inferHealthPath(contract) || '/'}`
1743
+ // A server already answering would be judged instead of the build we start.
1744
+ if (!(await waitFor(health, 1))) { err(`golden-path: something already answers at ${health}; stop it, or run without --boot`); return 1 }
1745
+ app = bootApp(contract, L.appDir)
1746
+ const down = await waitForBoot(app, health, Number(f.timeout || 180))
1747
+ if (down) {
1748
+ await stopApp(app)
1749
+ const results = sel.run.map((p) => ({ id: p.id, status: 'cannot-run', note: `the app did not come up at ${health} (${down}); see ${SERVER_LOG}` }))
1750
+ fs.writeFileSync(f.out || path.join(L.appDir, RESULTS_FILE), json(resultsEnvelope(results, { profile: f.profile, target, surfaces, ids })))
1751
+ err(`golden-path: the app did not come up at ${health} (${down}); see ${SERVER_LOG}`)
1752
+ return 0
1753
+ }
1754
+ }
1755
+ let results
1756
+ try { results = await runPaths(contract, { profile: f.profile, target, appDir: L.appDir, expectSha: f.expectSha, surfaces, ids }) } finally { if (app) await stopApp(app) }
1757
+ const out = f.out || path.join(L.appDir, RESULTS_FILE)
1758
+ fs.writeFileSync(out, json(resultsEnvelope(results, { profile: f.profile, target, surfaces, ids })))
1759
+ for (const r of results) log(` ${r.status.padEnd(10)} ${r.id}${r.note ? `: ${r.note}` : ''}`)
1760
+ log(`golden-path: ${results.length} path(s) driven; results in ${posix(path.relative(process.cwd(), out)) || out}`)
1761
+ return 0
1762
+ }
1763
+
1764
+ if (f.cmd === 'verdict') {
1765
+ const verdict = stampTarget(computeVerdict(sel.run, opened.results), opened.target || target, { profile: f.profile, noMutations: sel.profile.mutationPolicy === 'read-only', ...(surfaces ? { surfaces } : {}), ...(ids ? { paths: ids } : {}), ...(opened.observedAt ? { observedAt: opened.observedAt } : {}) })
1766
+ fs.writeFileSync(f.out || path.join(L.appDir, VERDICT_FILE), json(verdict))
1767
+ if (f.json) log(json(verdict).trimEnd())
1768
+ else {
1769
+ // The report shape SKILL.md asks for, ready to paste.
1770
+ log(`Golden paths: ${verdict.verdict} (profile ${f.profile}, target ${verdict.target})`)
1771
+ for (const r of verdict.rows) log(`- ${r.status.padEnd(10)} ${r.id}${r.status === 'pass' ? (r.evidence ? ` (${r.evidence})` : '') : r.note ? `: ${r.note}` : ''}`)
1772
+ if (verdict.note) log(verdict.note)
1773
+ }
1774
+ return verdict.ok ? 0 : 1
1775
+ }
1776
+
1777
+ err(`golden-path: unknown command ${f.cmd}`)
1778
+ return 2
1779
+ }