@yiyi_zhang/laoshi 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (351) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +21 -0
  3. package/README.md +60 -2
  4. package/SCOPE.md +13 -0
  5. package/adapters/dsh/adapter.ts +75 -0
  6. package/adapters/dsh/dsh-runtime.ts +242 -0
  7. package/adapters/dsh/install.mjs +97 -0
  8. package/adapters/dsh/intranet/install.mjs +15 -0
  9. package/adapters/dsh/intranet/make-sample.mjs +52 -0
  10. package/adapters/dsh/plugin/channel.d.mts +2 -0
  11. package/adapters/dsh/plugin/channel.mjs +31 -0
  12. package/adapters/dsh/plugin/index.d.mts +3 -0
  13. package/adapters/dsh/plugin/index.mjs +292 -0
  14. package/adapters/dsh/plugin/package.json +18 -0
  15. package/adapters/paseo/adapter.ts +96 -0
  16. package/adapters/paseo/daemon-check.ts +80 -0
  17. package/adapters/paseo/daemon-version.ts +64 -0
  18. package/adapters/paseo/doctor.ts +161 -0
  19. package/adapters/paseo/install.mjs +30 -0
  20. package/adapters/paseo/paseo-json.ts +73 -0
  21. package/adapters/paseo/paseo-profiles.ts +127 -0
  22. package/adapters/paseo/paseo-runtime.ts +507 -0
  23. package/adapters/paseo/settings.ts +22 -0
  24. package/adapters/paseo/skill/setup.md +26 -0
  25. package/adapters/paseo/skill/templates/copy-local-files.mjs +32 -0
  26. package/adapters/paseo/skill/templates/with-port.mjs +36 -0
  27. package/adapters/paseo/smoke-test.ts +203 -0
  28. package/bin/bootstrap.mjs +170 -0
  29. package/bin/install.mjs +245 -0
  30. package/bin/locate.mjs +22 -0
  31. package/bin/req-docs.d.mts +5 -0
  32. package/bin/req-docs.mjs +167 -0
  33. package/bin/req-doctor.mjs +21 -0
  34. package/bin/req.mjs +236 -0
  35. package/bin/start-pipeline +21 -0
  36. package/bin/start-pipeline.mjs +22 -0
  37. package/config.example.json +134 -0
  38. package/contracts/README.md +21 -0
  39. package/contracts/agent-runtime.md +83 -0
  40. package/contracts/cli-json.md +76 -0
  41. package/contracts/feature-files.md +148 -0
  42. package/contracts/notifier-event.md +90 -0
  43. package/contracts/result-file.md +21 -0
  44. package/contracts/spec.md +37 -0
  45. package/contracts/state.md +69 -0
  46. package/contracts/usage-record.md +72 -0
  47. package/contracts/verify.md +41 -0
  48. package/docs/adr/0001-new-repo-core-and-adapters.md +20 -0
  49. package/docs/adr/0002-two-orchestration-modes.md +20 -0
  50. package/docs/adr/0003-generate-once-then-lock.md +20 -0
  51. package/docs/adr/0004-external-contracts-stay-stable.md +19 -0
  52. package/docs/adr/0005-skill-names.md +26 -0
  53. package/docs/adr/0006-deterministic-engine-platform-capabilities.md +42 -0
  54. package/docs/adr/0007-one-install-many-repos.md +63 -0
  55. package/docs/adr/0008-capability-sources-and-platform-plugin.md +81 -0
  56. package/docs/adr/README.md +14 -0
  57. package/docs/design/adapter-guide.md +90 -0
  58. package/docs/design/architecture.md +104 -0
  59. package/docs/design/builtin-capabilities.md +72 -0
  60. package/docs/design/compat-migration.md +65 -0
  61. package/docs/design/dsh-adapter.md +145 -0
  62. package/docs/design/in-chat-orchestration.md +67 -0
  63. package/docs/design/init-bootstrap.md +83 -0
  64. package/docs/design/internal-platform-adapter.md +76 -0
  65. package/docs/design/platform-discovery.md +117 -0
  66. package/docs/design/platform-vocabulary.md +44 -0
  67. package/docs/design/state-v2.md +71 -0
  68. package/docs/guide//344/275/277/347/224/250/350/200/205/346/214/207/345/215/227.md +130 -0
  69. package/docs/guide//345/256/211/350/243/205/344/270/216/345/215/207/347/272/247.md +211 -0
  70. package/docs/guide//347/273/264/346/212/244/350/200/205/346/214/207/345/215/227.md +86 -0
  71. package/docs/guide//351/241/271/347/233/256/345/256/232/345/210/266/344/270/216/350/277/220/350/241/214/350/247/204/345/210/231.md +595 -0
  72. package/docs/intranet/install-verify.md +278 -0
  73. package/engine/prompts/00-shared-context.md +107 -0
  74. package/engine/prompts/02-spec-review.md +46 -0
  75. package/engine/prompts/03-design.md +77 -0
  76. package/engine/prompts/03a-design-proposal.md +30 -0
  77. package/engine/prompts/04-design-review.md +73 -0
  78. package/engine/prompts/04b-design-revise.md +56 -0
  79. package/engine/prompts/05-implement.md +72 -0
  80. package/engine/prompts/06-code-review.md +81 -0
  81. package/engine/prompts/07-review-fix.md +41 -0
  82. package/engine/prompts/07b-handoff.md +45 -0
  83. package/engine/prompts/08-service-start.md +59 -0
  84. package/engine/prompts/09-verify.md +90 -0
  85. package/engine/prompts/10-defect-fix.md +41 -0
  86. package/engine/prompts/10b-reverify.md +43 -0
  87. package/engine/prompts/11-report.md +112 -0
  88. package/engine/prompts/browser-verify.md +14 -0
  89. package/engine/prompts/incremental.md +24 -0
  90. package/engine/prompts/joint.md +55 -0
  91. package/engine/prompts/managed-services.md +9 -0
  92. package/engine/prompts/panel-member.md +38 -0
  93. package/engine/prompts/related-repos.md +7 -0
  94. package/engine/prompts/review-axis-spec.md +10 -0
  95. package/engine/prompts/review-axis-standards.md +11 -0
  96. package/engine/prompts/types/assessment.md +41 -0
  97. package/engine/prompts/types/defect.md +55 -0
  98. package/engine/prompts/types/refactor.md +39 -0
  99. package/engine/prompts/ui-check.md +15 -0
  100. package/engine/prompts/verify-deployed.md +14 -0
  101. package/engine/skill-fragments/setup-builtin.md +24 -0
  102. package/engine/src/activity.ts +131 -0
  103. package/engine/src/api.ts +655 -0
  104. package/engine/src/builtin/index.ts +30 -0
  105. package/engine/src/builtin/project-services.ts +66 -0
  106. package/engine/src/builtin/service-runner.mjs +35 -0
  107. package/engine/src/builtin/services.ts +264 -0
  108. package/engine/src/builtin/setup-runner.mjs +26 -0
  109. package/engine/src/builtin/workspace.ts +139 -0
  110. package/engine/src/card-cmd.ts +505 -0
  111. package/engine/src/card.ts +541 -0
  112. package/engine/src/checklist-cmd.ts +37 -0
  113. package/engine/src/checklist.ts +254 -0
  114. package/engine/src/cli-args.ts +228 -0
  115. package/engine/src/code-review.ts +421 -0
  116. package/engine/src/codeowners.ts +87 -0
  117. package/engine/src/config-view.ts +310 -0
  118. package/engine/src/config.ts +862 -0
  119. package/engine/src/configure.ts +343 -0
  120. package/engine/src/control.ts +257 -0
  121. package/engine/src/danger-guard.ts +180 -0
  122. package/engine/src/digest.ts +141 -0
  123. package/engine/src/doctor.ts +410 -0
  124. package/engine/src/estimate.ts +95 -0
  125. package/engine/src/eval.ts +325 -0
  126. package/engine/src/factory.ts +545 -0
  127. package/engine/src/features.ts +311 -0
  128. package/engine/src/gate.ts +157 -0
  129. package/engine/src/git.ts +30 -0
  130. package/engine/src/identity.ts +72 -0
  131. package/engine/src/index-cmd.ts +34 -0
  132. package/engine/src/integration-cmd.ts +161 -0
  133. package/engine/src/integrations.ts +485 -0
  134. package/engine/src/joint.ts +173 -0
  135. package/engine/src/launch.ts +443 -0
  136. package/engine/src/lessons.ts +74 -0
  137. package/engine/src/locations.ts +83 -0
  138. package/engine/src/main.ts +390 -0
  139. package/engine/src/messages.ts +472 -0
  140. package/engine/src/notifiers.ts +114 -0
  141. package/engine/src/notify-test.ts +108 -0
  142. package/engine/src/outcomes.ts +145 -0
  143. package/engine/src/paths.ts +10 -0
  144. package/engine/src/pipeline.ts +2517 -0
  145. package/engine/src/platform.ts +121 -0
  146. package/engine/src/playbooks.ts +46 -0
  147. package/engine/src/preflight.ts +352 -0
  148. package/engine/src/prompts.ts +76 -0
  149. package/engine/src/queue.ts +61 -0
  150. package/engine/src/records.ts +403 -0
  151. package/engine/src/reply.ts +81 -0
  152. package/engine/src/review-assets/app.css +339 -0
  153. package/engine/src/review-assets/app.html +107 -0
  154. package/engine/src/review-assets/app.js +958 -0
  155. package/engine/src/review-assets/check.css +12 -0
  156. package/engine/src/review-assets/check.html +61 -0
  157. package/engine/src/review-assets/check.js +341 -0
  158. package/engine/src/review-assets/code.css +16 -0
  159. package/engine/src/review-assets/code.html +58 -0
  160. package/engine/src/review-assets/code.js +497 -0
  161. package/engine/src/review-assets/rk-icons.js +98 -0
  162. package/engine/src/review-assets/rk-tokens.css +252 -0
  163. package/engine/src/review-assets/rk.css +254 -0
  164. package/engine/src/review.ts +771 -0
  165. package/engine/src/runtime-loader.ts +110 -0
  166. package/engine/src/runtime.ts +186 -0
  167. package/engine/src/scan-guard.ts +132 -0
  168. package/engine/src/schedule-time.ts +51 -0
  169. package/engine/src/secret-scan.ts +177 -0
  170. package/engine/src/semver.ts +31 -0
  171. package/engine/src/skills-render.ts +104 -0
  172. package/engine/src/spec-review.ts +99 -0
  173. package/engine/src/state.ts +506 -0
  174. package/engine/src/stats.ts +810 -0
  175. package/engine/src/steps.ts +269 -0
  176. package/engine/src/try.ts +135 -0
  177. package/engine/src/ui-check-page.js +208 -0
  178. package/engine/src/ui-check.ts +366 -0
  179. package/engine/src/usage.ts +67 -0
  180. package/engine/src/watchdog.ts +139 -0
  181. package/engine/src/words.ts +95 -0
  182. package/engine/src/worktree.ts +227 -0
  183. package/notifiers/im-template.mjs +86 -0
  184. package/package.json +78 -4
  185. package/principles/INDEX.md +11 -0
  186. package/site-dist/404.html +27 -0
  187. package/site-dist/assets/app.Df99UgrJ.js +1 -0
  188. package/site-dist/assets/changelog.md.Df8vFhjK.js +1 -0
  189. package/site-dist/assets/changelog.md.Df8vFhjK.lean.js +1 -0
  190. package/site-dist/assets/chunks/@localSearchIndexroot.n-0kN-N0.js +1 -0
  191. package/site-dist/assets/chunks/VPLocalSearchBox.IEhP6Gw5.js +9 -0
  192. package/site-dist/assets/chunks/framework.BetZR81g.js +20 -0
  193. package/site-dist/assets/chunks/theme.DHubfO7g.js +2 -0
  194. package/site-dist/assets/guide_dsh.md.0X-eYB87.js +5 -0
  195. package/site-dist/assets/guide_dsh.md.0X-eYB87.lean.js +5 -0
  196. package/site-dist/assets/guide_getting-started.md.BZTWiHhH.js +1 -0
  197. package/site-dist/assets/guide_getting-started.md.BZTWiHhH.lean.js +1 -0
  198. package/site-dist/assets/guide_how-it-works.md.CkvlSgxO.js +25 -0
  199. package/site-dist/assets/guide_how-it-works.md.CkvlSgxO.lean.js +1 -0
  200. package/site-dist/assets/guide_index.md.D67QX_Vi.js +1 -0
  201. package/site-dist/assets/guide_index.md.D67QX_Vi.lean.js +1 -0
  202. package/site-dist/assets/guide_install.md.D7NiiOPu.js +19 -0
  203. package/site-dist/assets/guide_install.md.D7NiiOPu.lean.js +19 -0
  204. package/site-dist/assets/guide_intranet.md.Bz0sAHK0.js +9 -0
  205. package/site-dist/assets/guide_intranet.md.Bz0sAHK0.lean.js +9 -0
  206. package/site-dist/assets/guide_maintainer.md.C-Vt-DdK.js +1 -0
  207. package/site-dist/assets/guide_maintainer.md.C-Vt-DdK.lean.js +1 -0
  208. package/site-dist/assets/guide_phases.md.Cw0A9Vb1.js +1 -0
  209. package/site-dist/assets/guide_phases.md.Cw0A9Vb1.lean.js +1 -0
  210. package/site-dist/assets/guide_project.md.BIcaDhdS.js +77 -0
  211. package/site-dist/assets/guide_project.md.BIcaDhdS.lean.js +77 -0
  212. package/site-dist/assets/guide_user.md.B66TQvIA.js +1 -0
  213. package/site-dist/assets/guide_user.md.B66TQvIA.lean.js +1 -0
  214. package/site-dist/assets/index.md.CrBM3tiI.js +1 -0
  215. package/site-dist/assets/index.md.CrBM3tiI.lean.js +1 -0
  216. package/site-dist/assets/inter-italic-cyrillic-ext.r48I6akx.woff2 +0 -0
  217. package/site-dist/assets/inter-italic-cyrillic.By2_1cv3.woff2 +0 -0
  218. package/site-dist/assets/inter-italic-greek-ext.1u6EdAuj.woff2 +0 -0
  219. package/site-dist/assets/inter-italic-greek.DJ8dCoTZ.woff2 +0 -0
  220. package/site-dist/assets/inter-italic-latin-ext.CN1xVJS-.woff2 +0 -0
  221. package/site-dist/assets/inter-italic-latin.C2AdPX0b.woff2 +0 -0
  222. package/site-dist/assets/inter-italic-vietnamese.BSbpV94h.woff2 +0 -0
  223. package/site-dist/assets/inter-roman-cyrillic-ext.BBPuwvHQ.woff2 +0 -0
  224. package/site-dist/assets/inter-roman-cyrillic.C5lxZ8CY.woff2 +0 -0
  225. package/site-dist/assets/inter-roman-greek-ext.CqjqNYQ-.woff2 +0 -0
  226. package/site-dist/assets/inter-roman-greek.BBVDIX6e.woff2 +0 -0
  227. package/site-dist/assets/inter-roman-latin-ext.4ZJIpNVo.woff2 +0 -0
  228. package/site-dist/assets/inter-roman-latin.Di8DUHzh.woff2 +0 -0
  229. package/site-dist/assets/inter-roman-vietnamese.BjW4sHH5.woff2 +0 -0
  230. package/site-dist/assets/reference_adr_0001-new-repo-core-and-adapters.md.CjNHHmrf.js +1 -0
  231. package/site-dist/assets/reference_adr_0001-new-repo-core-and-adapters.md.CjNHHmrf.lean.js +1 -0
  232. package/site-dist/assets/reference_adr_0002-two-orchestration-modes.md.CHD05agO.js +1 -0
  233. package/site-dist/assets/reference_adr_0002-two-orchestration-modes.md.CHD05agO.lean.js +1 -0
  234. package/site-dist/assets/reference_adr_0003-generate-once-then-lock.md.BaRiZfXT.js +1 -0
  235. package/site-dist/assets/reference_adr_0003-generate-once-then-lock.md.BaRiZfXT.lean.js +1 -0
  236. package/site-dist/assets/reference_adr_0004-external-contracts-stay-stable.md.DUJ7CTV1.js +1 -0
  237. package/site-dist/assets/reference_adr_0004-external-contracts-stay-stable.md.DUJ7CTV1.lean.js +1 -0
  238. package/site-dist/assets/reference_adr_0005-skill-names.md.DuBVd1tl.js +1 -0
  239. package/site-dist/assets/reference_adr_0005-skill-names.md.DuBVd1tl.lean.js +1 -0
  240. package/site-dist/assets/reference_adr_0006-deterministic-engine-platform-capabilities.md.Dcrnx1-L.js +1 -0
  241. package/site-dist/assets/reference_adr_0006-deterministic-engine-platform-capabilities.md.Dcrnx1-L.lean.js +1 -0
  242. package/site-dist/assets/reference_adr_0007-one-install-many-repos.md.C78cd4_P.js +1 -0
  243. package/site-dist/assets/reference_adr_0007-one-install-many-repos.md.C78cd4_P.lean.js +1 -0
  244. package/site-dist/assets/reference_adr_0008-capability-sources-and-platform-plugin.md.B4vBkIDS.js +1 -0
  245. package/site-dist/assets/reference_adr_0008-capability-sources-and-platform-plugin.md.B4vBkIDS.lean.js +1 -0
  246. package/site-dist/assets/reference_adr_index.md.Dx8sPsjs.js +1 -0
  247. package/site-dist/assets/reference_adr_index.md.Dx8sPsjs.lean.js +1 -0
  248. package/site-dist/assets/reference_commands.md.BFJRjNju.js +1 -0
  249. package/site-dist/assets/reference_commands.md.BFJRjNju.lean.js +1 -0
  250. package/site-dist/assets/reference_config.md.Dt_TJ2y9.js +6 -0
  251. package/site-dist/assets/reference_config.md.Dt_TJ2y9.lean.js +1 -0
  252. package/site-dist/assets/reference_contracts_agent-runtime.md.Bu8q-uGl.js +1 -0
  253. package/site-dist/assets/reference_contracts_agent-runtime.md.Bu8q-uGl.lean.js +1 -0
  254. package/site-dist/assets/reference_contracts_cli-json.md.Bonk0m6-.js +1 -0
  255. package/site-dist/assets/reference_contracts_cli-json.md.Bonk0m6-.lean.js +1 -0
  256. package/site-dist/assets/reference_contracts_feature-files.md.9n332kF_.js +26 -0
  257. package/site-dist/assets/reference_contracts_feature-files.md.9n332kF_.lean.js +26 -0
  258. package/site-dist/assets/reference_contracts_index.md.dqNwNs6U.js +1 -0
  259. package/site-dist/assets/reference_contracts_index.md.dqNwNs6U.lean.js +1 -0
  260. package/site-dist/assets/reference_contracts_notifier-event.md.D6we9wWS.js +24 -0
  261. package/site-dist/assets/reference_contracts_notifier-event.md.D6we9wWS.lean.js +24 -0
  262. package/site-dist/assets/reference_contracts_result-file.md.BmCaSlEu.js +1 -0
  263. package/site-dist/assets/reference_contracts_result-file.md.BmCaSlEu.lean.js +1 -0
  264. package/site-dist/assets/reference_contracts_spec.md.CDQYgJz7.js +8 -0
  265. package/site-dist/assets/reference_contracts_spec.md.CDQYgJz7.lean.js +8 -0
  266. package/site-dist/assets/reference_contracts_state.md.DVHC4opX.js +1 -0
  267. package/site-dist/assets/reference_contracts_state.md.DVHC4opX.lean.js +1 -0
  268. package/site-dist/assets/reference_contracts_usage-record.md.CQI2chqh.js +10 -0
  269. package/site-dist/assets/reference_contracts_usage-record.md.CQI2chqh.lean.js +10 -0
  270. package/site-dist/assets/reference_contracts_verify.md.CkJy8LXk.js +29 -0
  271. package/site-dist/assets/reference_contracts_verify.md.CkJy8LXk.lean.js +29 -0
  272. package/site-dist/assets/reference_design_adapter-guide.md.BSziZJSM.js +16 -0
  273. package/site-dist/assets/reference_design_adapter-guide.md.BSziZJSM.lean.js +16 -0
  274. package/site-dist/assets/reference_design_architecture.md.Bfoc-F2B.js +23 -0
  275. package/site-dist/assets/reference_design_architecture.md.Bfoc-F2B.lean.js +23 -0
  276. package/site-dist/assets/reference_design_builtin-capabilities.md.CZYtjo_v.js +7 -0
  277. package/site-dist/assets/reference_design_builtin-capabilities.md.CZYtjo_v.lean.js +7 -0
  278. package/site-dist/assets/reference_design_platform-vocabulary.md.xWGv5QO8.js +3 -0
  279. package/site-dist/assets/reference_design_platform-vocabulary.md.xWGv5QO8.lean.js +3 -0
  280. package/site-dist/assets/reference_scope.md.aUo6vISB.js +1 -0
  281. package/site-dist/assets/reference_scope.md.aUo6vISB.lean.js +1 -0
  282. package/site-dist/assets/style.BX2ZxxqY.css +1 -0
  283. package/site-dist/changelog.html +30 -0
  284. package/site-dist/favicon.svg +10 -0
  285. package/site-dist/guide/dsh.html +34 -0
  286. package/site-dist/guide/getting-started.html +30 -0
  287. package/site-dist/guide/how-it-works.html +54 -0
  288. package/site-dist/guide/index.html +30 -0
  289. package/site-dist/guide/install.html +48 -0
  290. package/site-dist/guide/intranet.html +38 -0
  291. package/site-dist/guide/maintainer.html +30 -0
  292. package/site-dist/guide/phases.html +30 -0
  293. package/site-dist/guide/project.html +106 -0
  294. package/site-dist/guide/user.html +30 -0
  295. package/site-dist/hashmap.json +1 -0
  296. package/site-dist/index.html +30 -0
  297. package/site-dist/logo-light.svg +6 -0
  298. package/site-dist/logo.svg +6 -0
  299. package/site-dist/reference/adr/0001-new-repo-core-and-adapters.html +30 -0
  300. package/site-dist/reference/adr/0002-two-orchestration-modes.html +30 -0
  301. package/site-dist/reference/adr/0003-generate-once-then-lock.html +30 -0
  302. package/site-dist/reference/adr/0004-external-contracts-stay-stable.html +30 -0
  303. package/site-dist/reference/adr/0005-skill-names.html +30 -0
  304. package/site-dist/reference/adr/0006-deterministic-engine-platform-capabilities.html +30 -0
  305. package/site-dist/reference/adr/0007-one-install-many-repos.html +30 -0
  306. package/site-dist/reference/adr/0008-capability-sources-and-platform-plugin.html +30 -0
  307. package/site-dist/reference/adr/index.html +30 -0
  308. package/site-dist/reference/commands.html +30 -0
  309. package/site-dist/reference/config.html +35 -0
  310. package/site-dist/reference/contracts/agent-runtime.html +30 -0
  311. package/site-dist/reference/contracts/cli-json.html +30 -0
  312. package/site-dist/reference/contracts/feature-files.html +55 -0
  313. package/site-dist/reference/contracts/index.html +30 -0
  314. package/site-dist/reference/contracts/notifier-event.html +53 -0
  315. package/site-dist/reference/contracts/result-file.html +30 -0
  316. package/site-dist/reference/contracts/spec.html +37 -0
  317. package/site-dist/reference/contracts/state.html +30 -0
  318. package/site-dist/reference/contracts/usage-record.html +39 -0
  319. package/site-dist/reference/contracts/verify.html +58 -0
  320. package/site-dist/reference/design/adapter-guide.html +45 -0
  321. package/site-dist/reference/design/architecture.html +52 -0
  322. package/site-dist/reference/design/builtin-capabilities.html +36 -0
  323. package/site-dist/reference/design/platform-vocabulary.html +32 -0
  324. package/site-dist/reference/scope.html +30 -0
  325. package/site-dist/vp-icons.css +1 -0
  326. package/skills/acceptance-criteria/SKILL.md +61 -0
  327. package/skills/laoshi/SKILL.md +108 -0
  328. package/skills/laoshi/playbooks/accept.md +65 -0
  329. package/skills/laoshi/playbooks/change.md +51 -0
  330. package/skills/laoshi/playbooks/incident.md +55 -0
  331. package/skills/laoshi/playbooks/new.md +96 -0
  332. package/skills/laoshi/playbooks/small.md +48 -0
  333. package/skills/laoshi/playbooks/status.md +41 -0
  334. package/skills/laoshi/playbooks/takeover.md +51 -0
  335. package/skills/laoshi/playbooks/unattended.md +101 -0
  336. package/skills/laoshi/playbooks/verify.md +57 -0
  337. package/skills/laoshi-doctor/SKILL.md +36 -0
  338. package/skills/laoshi-retro/SKILL.md +81 -0
  339. package/skills/laoshi-setup/SKILL.md +107 -0
  340. package/skills/laoshi-setup/templates/copy-local-files.mjs +32 -0
  341. package/skills/principle-delete-before-add/SKILL.md +33 -0
  342. package/skills/principle-dont-block-on-humans/SKILL.md +35 -0
  343. package/skills/principle-fix-root-cause/SKILL.md +33 -0
  344. package/skills/principle-prove-it-works/SKILL.md +33 -0
  345. package/skills/principle-report-honestly/SKILL.md +33 -0
  346. package/skills/principle-speak-to-reader/SKILL.md +33 -0
  347. package/skills/principle-this-requirement-only/SKILL.md +33 -0
  348. package/skills/requirement-interview/SKILL.md +97 -0
  349. package/skills/result-report/SKILL.md +34 -0
  350. package/skills/spec-writing/SKILL.md +58 -0
  351. package/skills/spec-writing/spec-template.md +109 -0
@@ -0,0 +1,771 @@
1
+ // The prototype review page (1.13): a small web server on this machine where the requester
2
+ // looks at the interface prototype of a requirement, clicks on what they want changed (the page
3
+ // records which element, its text, color, size and position, so nobody has to describe it in
4
+ // technical words), edits texts in place, and then sends the list to the requirement's chat or
5
+ // confirms the design. The requirements plugin links to it; `req review <需求>` opens it from a terminal.
6
+ //
7
+ // One server per machine, started on demand and stopped after a few idle hours. It listens on
8
+ // 127.0.0.1 only and every address carries a random token (a second token gives a read-only
9
+ // page). REQ_KIT_REVIEW_HOST / REQ_KIT_REVIEW_PORT / REQ_KIT_REVIEW_PUBLIC_URL change that, e.g.
10
+ // when people open the platform's web UI from other computers.
11
+ import { spawn, spawnSync } from "node:child_process";
12
+ import crypto from "node:crypto";
13
+ import fs from "node:fs";
14
+ import os from "node:os";
15
+ import http from "node:http";
16
+ import path from "node:path";
17
+ import { ENGINE_DIR, KIT_ROOT, kitHome, kitVersion } from "./locations.js";
18
+ import { buildCodeReview, recordHumanReview, startReviewFix, type Submission } from "./code-review.js";
19
+ import { type Answer, acceptanceFailMessage, acceptanceText, buildChecklist, recordAcceptance, verdictOf } from "./checklist.js";
20
+ import { appendEvent, readIndex, requirementRef } from "./records.js";
21
+ import { readState, statePath } from "./state.js";
22
+ import { scrubOriginEnv, wordsFor } from "./runtime-loader.js";
23
+
24
+ const ASSETS = path.join(ENGINE_DIR, "src", "review-assets");
25
+ /** 1.15: the design system's tokens, component styles and icons, shared by the three pages (copies made by scripts/tokens-build.mjs). */
26
+ const SHARED_ASSETS = new Set(["rk-tokens.css", "rk.css", "rk-icons.js"]);
27
+ const DEFAULT_PORT = 6781;
28
+ const IDLE_EXIT_MS = 4 * 60 * 60_000;
29
+ const MAX_BODY = 2_000_000;
30
+ const MAX_MESSAGE = 7_500;
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // What the page shows
34
+
35
+ export interface Criterion {
36
+ id: string;
37
+ text: string;
38
+ }
39
+
40
+ /** The acceptance criteria in spec.md: "AC-1.2 …" or "**AC-1.2**:…", first mention of each. */
41
+ export function specCriteria(spec: string): Criterion[] {
42
+ const out = new Map<string, string>();
43
+ for (const line of spec.split(/\r?\n/)) {
44
+ const m = /\b(AC-\d+(?:\.\d+)*)\b[\s*_`))\]】::-]*(.*)$/.exec(line);
45
+ if (!m || out.has(m[1])) continue;
46
+ out.set(m[1], m[2].replace(/[*`_]/g, "").replace(/^[\s|::-]+/, "").replace(/[\s|]+$/, "").trim().slice(0, 200));
47
+ }
48
+ return [...out.entries()].map(([id, text]) => ({ id, text }));
49
+ }
50
+
51
+ function specTitle(spec: string, fallback: string): string {
52
+ const h = /^#\s+(.+)$/m.exec(spec);
53
+ return (h?.[1] ?? fallback).replace(/^需求说明[::\s]*/, "").trim() || fallback;
54
+ }
55
+
56
+ /** The HTML pages of a prototype directory (relative, "/"-separated), with their <title>. */
57
+ export function prototypeFiles(dir: string): Array<{ path: string; title: string }> {
58
+ const out: Array<{ path: string; title: string }> = [];
59
+ const walk = (d: string) => {
60
+ let entries: fs.Dirent[] = [];
61
+ try {
62
+ entries = fs.readdirSync(d, { withFileTypes: true });
63
+ } catch {
64
+ return;
65
+ }
66
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
67
+ const full = path.join(d, e.name);
68
+ if (e.isDirectory()) walk(full);
69
+ else if (/\.html?$/i.test(e.name)) {
70
+ const rel = path.relative(dir, full).split(path.sep).join("/");
71
+ const title = /<title>([^<]*)<\/title>/i.exec(fs.readFileSync(full, "utf8"))?.[1]?.trim();
72
+ out.push({ path: rel, title: title || rel });
73
+ }
74
+ }
75
+ };
76
+ walk(dir);
77
+ return out;
78
+ }
79
+
80
+ /** A short fingerprint of everything in a directory (names and contents). */
81
+ export function dirHash(dir: string): string | null {
82
+ if (!fs.existsSync(dir)) return null;
83
+ const h = crypto.createHash("sha256");
84
+ const walk = (d: string) => {
85
+ for (const e of fs.readdirSync(d, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
86
+ const full = path.join(d, e.name);
87
+ if (e.isDirectory()) walk(full);
88
+ else {
89
+ h.update(path.relative(dir, full).split(path.sep).join("/"));
90
+ h.update("\0");
91
+ h.update(fs.readFileSync(full));
92
+ h.update("\0");
93
+ }
94
+ }
95
+ };
96
+ walk(dir);
97
+ return h.digest("hex").slice(0, 12);
98
+ }
99
+
100
+ /**
101
+ * Keeps a copy of each prototype version the page has shown (in .pipeline/review/versions), so
102
+ * a revised prototype can be compared with the one the requester commented on.
103
+ */
104
+ export function snapshotVersion(prototypeDir: string, reviewDir: string, now = new Date()): { current: string | null; previous: string | null } {
105
+ const current = dirHash(prototypeDir);
106
+ if (!current) return { current: null, previous: null };
107
+ const listFile = path.join(reviewDir, "versions.json");
108
+ let list: Array<{ hash: string; at: string }> = [];
109
+ try {
110
+ list = JSON.parse(fs.readFileSync(listFile, "utf8"));
111
+ } catch {
112
+ list = [];
113
+ }
114
+ if (list.at(-1)?.hash !== current) {
115
+ const dest = path.join(reviewDir, "versions", current);
116
+ if (!fs.existsSync(dest)) {
117
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
118
+ fs.cpSync(prototypeDir, dest, { recursive: true });
119
+ }
120
+ list = [...list.filter((v) => v.hash !== current), { hash: current, at: now.toISOString() }];
121
+ fs.mkdirSync(reviewDir, { recursive: true });
122
+ fs.writeFileSync(listFile, JSON.stringify(list, null, 2));
123
+ }
124
+ const i = list.findIndex((v) => v.hash === current);
125
+ return { current, previous: i > 0 ? list[i - 1].hash : null };
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Turning clicks into a list the chat (and the design step) can act on
130
+
131
+ export type CommentKind = "text" | "bigger" | "smaller" | "color" | "move" | "remove" | "add" | "other";
132
+
133
+ export interface ReviewComment {
134
+ id: string;
135
+ file: string;
136
+ state?: string | null;
137
+ width?: number | null;
138
+ kind: CommentKind;
139
+ note?: string;
140
+ newText?: string;
141
+ target?: {
142
+ desc?: string;
143
+ text?: string;
144
+ selector?: string;
145
+ region?: { ac?: string | null; label?: string | null; index?: number | null } | null;
146
+ styles?: { color?: string; background?: string; fontSize?: string; size?: string } | null;
147
+ } | null;
148
+ }
149
+
150
+ const KIND_TEXT: Record<CommentKind, string> = {
151
+ text: "改文字",
152
+ bigger: "放大一点",
153
+ smaller: "缩小一点",
154
+ color: "换颜色",
155
+ move: "换位置",
156
+ remove: "删掉",
157
+ add: "在这里加东西",
158
+ other: "其他修改",
159
+ };
160
+
161
+ const clip = (s: string | undefined | null, n: number) => {
162
+ const t = (s ?? "").replace(/\s+/g, " ").trim();
163
+ return t.length > n ? `${t.slice(0, n)}…` : t;
164
+ };
165
+
166
+ /** Plain text for the chat: where, what was clicked (with its look), what to change. */
167
+ export function composeFeedback(comments: ReviewComment[], general: string | undefined, widths: Record<number, string> = { 1280: "电脑", 768: "平板", 390: "手机" }): string {
168
+ const lines: string[] = [];
169
+ lines.push(`来自原型审查页的修改意见(共 ${comments.length} 条${general?.trim() ? ",另有总体意见" : ""})。`);
170
+ lines.push(
171
+ '请据此修改需求说明(changes.md 中原因写"方案确认时的修改"),把要改的地方讲给用户确认后再继续;元素的颜色、大小等是原型里的现状,供定位用。只有意思不清楚时才追问。',
172
+ );
173
+ if (general?.trim()) lines.push("", `总体意见:${clip(general, 800)}`);
174
+ comments.forEach((c, i) => {
175
+ const where = [`原型 ${c.file}`];
176
+ if (c.state) where.push(`状态"${c.state}"`);
177
+ if (c.width) where.push(`${widths[c.width] ?? ""}宽度 ${c.width}px`.trim());
178
+ const r = c.target?.region;
179
+ if (r && (r.ac || r.label)) where.push(`区域${r.index ? ` ${r.index}` : ""}${r.label ? `「${clip(r.label, 40)}」` : ""}${r.ac ? `(${r.ac})` : ""}`);
180
+ lines.push("", `${i + 1}. 位置:${where.join(",")}`);
181
+ const t = c.target;
182
+ if (t?.desc || t?.text) {
183
+ const look = [
184
+ t.styles?.color ? `文字颜色 ${t.styles.color}` : "",
185
+ t.styles?.background ? `背景 ${t.styles.background}` : "",
186
+ t.styles?.fontSize ? `字号 ${t.styles.fontSize}` : "",
187
+ t.styles?.size ? `大小 ${t.styles.size}` : "",
188
+ ].filter(Boolean);
189
+ lines.push(` 点的是:${clip(t.desc, 30) || "元素"}${t.text ? `"${clip(t.text, 60)}"` : ""}${look.length ? `(${look.join(",")})` : ""}`);
190
+ }
191
+ if (c.kind === "text") lines.push(` 要改:文字改为"${clip(c.newText, 300)}"${t?.text ? `(原来是"${clip(t.text, 120)}")` : ""}`);
192
+ else lines.push(` 要改:${KIND_TEXT[c.kind] ?? KIND_TEXT.other}${c.newText ? `,改为"${clip(c.newText, 300)}"` : ""}`);
193
+ if (c.note?.trim()) lines.push(` 说明:${clip(c.note, 500)}`);
194
+ });
195
+ let text = lines.join("\n");
196
+ if (text.length > MAX_MESSAGE) {
197
+ text = `${text.slice(0, MAX_MESSAGE)}\n……(意见太长,后面的没有转达,完整内容在 .pipeline/review/submitted 中最新的文件里)`;
198
+ }
199
+ return text;
200
+ }
201
+
202
+ // ---------------------------------------------------------------------------
203
+ // The server
204
+
205
+ export interface ReviewServerOptions {
206
+ token: string;
207
+ readToken: string;
208
+ env?: NodeJS.ProcessEnv;
209
+ /** Runs `req approve|reply …` in the requirement's checkout; tests replace it. */
210
+ run?: (command: "approve" | "reply", repo: string, featureDir: string, extra: string[]) => { ok: boolean; message: string };
211
+ /** 1.14: `req review-fix <需求>` after the code review page asked for changes; tests replace it. */
212
+ codeFix?: (repo: string, featureDir: string) => { ok: boolean; message: string };
213
+ /** 1.14: `req try <需求> --json [--stop]` for the checklist page's "试用" button; tests replace it. */
214
+ tryRun?: (repo: string, featureDir: string, stop: boolean) => { ok: boolean; message: string; services?: unknown[]; howTo?: string[] };
215
+ onRequest?: () => void;
216
+ }
217
+
218
+ const TYPES: Record<string, string> = {
219
+ ".html": "text/html; charset=utf-8",
220
+ ".htm": "text/html; charset=utf-8",
221
+ ".js": "text/javascript; charset=utf-8",
222
+ ".css": "text/css; charset=utf-8",
223
+ ".json": "application/json; charset=utf-8",
224
+ ".svg": "image/svg+xml",
225
+ ".png": "image/png",
226
+ ".jpg": "image/jpeg",
227
+ ".jpeg": "image/jpeg",
228
+ ".gif": "image/gif",
229
+ ".webp": "image/webp",
230
+ };
231
+
232
+ function sameToken(a: string, b: string): boolean {
233
+ const x = Buffer.from(a);
234
+ const y = Buffer.from(b);
235
+ return x.length === y.length && crypto.timingSafeEqual(x, y);
236
+ }
237
+
238
+ /** A path inside `base`, or null when the request tries to leave it. */
239
+ function inside(base: string, rel: string): string | null {
240
+ let decoded: string;
241
+ try {
242
+ decoded = decodeURIComponent(rel);
243
+ } catch {
244
+ return null;
245
+ }
246
+ const target = path.resolve(base, `.${path.posix.normalize(`/${decoded}`)}`);
247
+ return target === base || target.startsWith(base + path.sep) ? target : null;
248
+ }
249
+
250
+ // The page may be shown inside the platform (the req-kit plugin embeds it): the platform's web UI on this
251
+ // machine, or, with REQ_KIT_REVIEW_HOST set for other computers, any page that has the token.
252
+ function appCsp(): string {
253
+ const host = process.env.REQ_KIT_REVIEW_HOST?.trim();
254
+ const local = !host || host === "127.0.0.1" || host === "localhost" || host === "::1";
255
+ const custom = process.env.REQ_KIT_REVIEW_FRAME_ANCESTORS?.trim();
256
+ // 'self' always: the page shows the prototype in a frame of its own.
257
+ const ancestors = custom ? (custom.includes("'self'") || custom === "*" ? custom : `'self' ${custom}`) : local ? "'self' http://127.0.0.1:* http://localhost:*" : "*";
258
+ return `default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors ${ancestors}`;
259
+ }
260
+ const APP_CSP = appCsp();
261
+ // Prototypes are written by an agent (from text the requester or a card supplied) and are served
262
+ // next to the page's own API, so nothing in them may run: the page reads them from outside.
263
+ // frame-ancestors is checked against every page above, so the prototype allows the same ones as
264
+ // the review page (the platform around it).
265
+ const PROTOTYPE_CSP = `default-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; media-src 'self' data:; script-src 'none'; form-action 'none'; ${APP_CSP.slice(APP_CSP.indexOf("frame-ancestors"))}`;
266
+
267
+ function send(res: http.ServerResponse, status: number, body: string | Buffer, type = "text/plain; charset=utf-8", csp = APP_CSP) {
268
+ res.writeHead(status, {
269
+ "content-type": type,
270
+ "cache-control": "no-store",
271
+ "x-content-type-options": "nosniff",
272
+ "referrer-policy": "no-referrer",
273
+ "content-security-policy": csp,
274
+ });
275
+ res.end(body);
276
+ }
277
+
278
+ const json = (res: http.ServerResponse, status: number, value: unknown) => send(res, status, JSON.stringify(value), TYPES[".json"]);
279
+
280
+ function sendFile(res: http.ServerResponse, file: string | null, csp = APP_CSP) {
281
+ if (!file) return send(res, 404, "没有这个文件");
282
+ try {
283
+ if (!fs.statSync(file).isFile()) return send(res, 404, "没有这个文件");
284
+ } catch {
285
+ return send(res, 404, "没有这个文件");
286
+ }
287
+ send(res, 200, fs.readFileSync(file), TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream", csp);
288
+ }
289
+
290
+ async function readBody(req: http.IncomingMessage): Promise<unknown> {
291
+ const chunks: Buffer[] = [];
292
+ let size = 0;
293
+ for await (const chunk of req) {
294
+ size += (chunk as Buffer).length;
295
+ if (size > MAX_BODY) throw new Error("内容太大");
296
+ chunks.push(chunk as Buffer);
297
+ }
298
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "null");
299
+ }
300
+
301
+ /** `req <approve|reply> <需求> …` in the requirement's checkout, as `req api run` does (api.ts imports this file). */
302
+ function defaultRun(command: "approve" | "reply", repo: string, featureDir: string, extra: string[]) {
303
+ const env = scrubOriginEnv();
304
+ const r = spawnSync(process.execPath, [path.join(KIT_ROOT, "bin", "req.mjs"), command, featureDir, ...extra], {
305
+ cwd: repo,
306
+ env,
307
+ encoding: "utf8",
308
+ timeout: 180_000,
309
+ windowsHide: true,
310
+ });
311
+ return { ok: r.status === 0, message: r.error ? r.error.message : `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
312
+ }
313
+
314
+ function defaultTry(repo: string, featureDir: string, stop: boolean) {
315
+ const env = scrubOriginEnv();
316
+ const r = spawnSync(process.execPath, [path.join(KIT_ROOT, "bin", "req.mjs"), "try", featureDir, "--json", ...(stop ? ["--stop"] : [])], {
317
+ cwd: repo,
318
+ env,
319
+ encoding: "utf8",
320
+ timeout: 300_000,
321
+ windowsHide: true,
322
+ });
323
+ try {
324
+ return JSON.parse((r.stdout ?? "").trim().split("\n").at(-1) ?? "") as { ok: boolean; message: string; services?: unknown[]; howTo?: string[] };
325
+ } catch {
326
+ return { ok: false, message: r.error ? r.error.message : `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() || "没有启动" };
327
+ }
328
+ }
329
+
330
+ export function createReviewServer(opts: ReviewServerOptions): http.Server {
331
+ const env = opts.env ?? process.env;
332
+ const run = opts.run ?? defaultRun;
333
+ const tryRun = opts.tryRun ?? defaultTry;
334
+ const codeFixRun = opts.codeFix ?? startReviewFix;
335
+ return http.createServer((req, res) => {
336
+ opts.onRequest?.();
337
+ handle(req, res).catch((error: Error) => json(res, 500, { ok: false, message: error.message }));
338
+ });
339
+
340
+ async function handle(req: http.IncomingMessage, res: http.ServerResponse) {
341
+ const url = new URL(req.url ?? "/", "http://localhost");
342
+ const parts = url.pathname.split("/");
343
+ // /r/<token>/health · /r/<token>/f/<key>/<rest…>
344
+ if (parts[1] !== "r" || !parts[2]) return send(res, 404, "没有这个页面");
345
+ const full = sameToken(parts[2], opts.token);
346
+ if (!full && !sameToken(parts[2], opts.readToken)) return send(res, 403, `链接无效或已过期,请从${wordsFor().requirementView ? `${wordsFor().requirementView}或 ` : " "}req review 重新打开`);
347
+ if (parts[3] === "health") return json(res, 200, { ok: true, version: kitVersion() });
348
+ if (parts[3] !== "f" || !parts[4]) return send(res, 404, "没有这个页面");
349
+ const entry = readIndex(env).find((e) => e.key === parts[4]);
350
+ if (!entry) return send(res, 404, "这台机器上没有这个需求(需求列表中找不到)");
351
+ const rest = parts.slice(5).join("/");
352
+ const featureAbs = path.join(entry.repo, entry.featureDir);
353
+ const prototypeDir = path.join(featureAbs, "prototype");
354
+ const reviewDir = path.join(featureAbs, ".pipeline", "review");
355
+
356
+ if (rest === "" && parts.length === 5) {
357
+ res.writeHead(301, { location: `${url.pathname}/` });
358
+ return res.end();
359
+ }
360
+ if (rest === "check") {
361
+ res.writeHead(301, { location: `${url.pathname}/` });
362
+ return res.end();
363
+ }
364
+ if (rest.startsWith("check/")) return handleChecklist(req, res, rest.slice("check/".length), entry, featureAbs, full);
365
+ if (rest === "code") {
366
+ res.writeHead(301, { location: `${url.pathname}/` });
367
+ return res.end();
368
+ }
369
+ if (rest.startsWith("code/")) return handleCodeReview(req, res, rest.slice("code/".length), entry, featureAbs, full);
370
+ if (rest === "") return sendFile(res, path.join(ASSETS, "app.html"));
371
+ if (rest === "app.js" || rest === "app.css" || SHARED_ASSETS.has(rest)) return sendFile(res, path.join(ASSETS, rest));
372
+ if (rest.startsWith("proto/cur/")) return sendFile(res, inside(prototypeDir, rest.slice("proto/cur/".length)), PROTOTYPE_CSP);
373
+ if (rest.startsWith("proto/v/")) {
374
+ const [hash, ...file] = rest.slice("proto/v/".length).split("/");
375
+ if (!/^[0-9a-f]{12}$/.test(hash)) return send(res, 404, "没有这个版本");
376
+ return sendFile(res, inside(path.join(reviewDir, "versions", hash), file.join("/")), PROTOTYPE_CSP);
377
+ }
378
+
379
+ if (rest === "api/info" && req.method === "GET") {
380
+ let spec = "";
381
+ try {
382
+ spec = fs.readFileSync(path.join(featureAbs, "spec.md"), "utf8");
383
+ } catch {
384
+ /* shown without criteria */
385
+ }
386
+ const state = readState(statePath(entry.repo, entry.featureDir));
387
+ const versions = fs.existsSync(prototypeDir) ? snapshotVersion(prototypeDir, reviewDir) : { current: null, previous: null };
388
+ return json(res, 200, {
389
+ key: entry.key,
390
+ project: entry.project,
391
+ featureDir: entry.featureDir,
392
+ title: specTitle(spec, path.basename(entry.featureDir)),
393
+ status: state?.status ?? null,
394
+ waitingForApproval: state?.status === "waiting_for_approval",
395
+ waitingForReply: state?.status === "waiting_for_approval" || state?.status === "waiting_for_business",
396
+ canReply: Boolean(state?.originSessionId),
397
+ readOnly: !full,
398
+ files: fs.existsSync(prototypeDir) ? prototypeFiles(prototypeDir) : [],
399
+ criteria: specCriteria(spec),
400
+ versions,
401
+ });
402
+ }
403
+ if (rest === "api/draft") {
404
+ const file = path.join(reviewDir, "draft.json");
405
+ if (req.method === "GET") {
406
+ try {
407
+ return json(res, 200, JSON.parse(fs.readFileSync(file, "utf8")));
408
+ } catch {
409
+ return json(res, 200, { comments: [], general: "" });
410
+ }
411
+ }
412
+ if (req.method === "PUT") {
413
+ if (!full) return json(res, 403, { ok: false, message: "这是只读链接" });
414
+ const body = (await readBody(req)) as { comments?: unknown; general?: unknown } | null;
415
+ if (!body || !Array.isArray(body.comments)) return json(res, 400, { ok: false, message: "格式不对" });
416
+ fs.mkdirSync(reviewDir, { recursive: true });
417
+ fs.writeFileSync(file, JSON.stringify({ comments: body.comments, general: typeof body.general === "string" ? body.general : "", savedAt: new Date().toISOString() }, null, 2));
418
+ return json(res, 200, { ok: true });
419
+ }
420
+ }
421
+ if (rest === "api/submit" && req.method === "POST") {
422
+ if (!full) return json(res, 403, { ok: false, message: "这是只读链接,不能提交" });
423
+ const body = (await readBody(req)) as { action?: string; comments?: ReviewComment[]; general?: string } | null;
424
+ const action = body?.action;
425
+ if (action !== "approve" && action !== "changes") return json(res, 400, { ok: false, message: "action 只能是 approve 或 changes" });
426
+ const comments = Array.isArray(body?.comments) ? body.comments : [];
427
+ if (action === "changes" && comments.length === 0 && !body?.general?.trim()) return json(res, 400, { ok: false, message: "还没有写任何意见" });
428
+ const result =
429
+ action === "approve" ? run("approve", entry.repo, entry.featureDir, []) : run("reply", entry.repo, entry.featureDir, [composeFeedback(comments, body?.general)]);
430
+ fs.mkdirSync(path.join(reviewDir, "submitted"), { recursive: true });
431
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
432
+ fs.writeFileSync(path.join(reviewDir, "submitted", `${stamp}-${action}.json`), JSON.stringify({ action, comments, general: body?.general ?? "", result, versions: dirHash(prototypeDir) }, null, 2));
433
+ if (result.ok) fs.rmSync(path.join(reviewDir, "draft.json"), { force: true });
434
+ return json(res, result.ok ? 200 : 409, result);
435
+ }
436
+ return send(res, 404, "没有这个页面");
437
+ }
438
+
439
+ // 1.14: the code review page, /r/<token>/f/<key>/code/…
440
+ async function handleCodeReview(req: http.IncomingMessage, res: http.ServerResponse, rest: string, entry: { repo: string; featureDir: string }, featureAbs: string, full: boolean) {
441
+ const draftFile = path.join(featureAbs, ".pipeline", "code-review", "draft.json");
442
+ if (rest === "") return sendFile(res, path.join(ASSETS, "code.html"));
443
+ if (rest === "code.js" || rest === "code.css" || SHARED_ASSETS.has(rest)) return sendFile(res, path.join(ASSETS, rest));
444
+ if (rest === "api/info" && req.method === "GET") {
445
+ let draft: unknown = null;
446
+ try {
447
+ draft = JSON.parse(fs.readFileSync(draftFile, "utf8"));
448
+ } catch {
449
+ draft = null;
450
+ }
451
+ return json(res, 200, { ...buildCodeReview(entry.repo, entry.featureDir), readOnly: !full, draft });
452
+ }
453
+ if (rest === "api/draft" && req.method === "PUT") {
454
+ if (!full) return json(res, 403, { ok: false, message: "这是只读链接" });
455
+ const body = await readBody(req);
456
+ if (!body || typeof body !== "object") return json(res, 400, { ok: false, message: "格式不对" });
457
+ fs.mkdirSync(path.dirname(draftFile), { recursive: true });
458
+ fs.writeFileSync(draftFile, JSON.stringify({ ...(body as object), savedAt: new Date().toISOString() }, null, 2));
459
+ return json(res, 200, { ok: true });
460
+ }
461
+ if (rest === "api/submit" && req.method === "POST") {
462
+ if (!full) return json(res, 403, { ok: false, message: "这是只读链接,不能提交" });
463
+ const body = (await readBody(req)) as Partial<Submission> | null;
464
+ const verdict = body?.verdict === "approve" ? "approve" : body?.verdict === "changes" ? "changes" : null;
465
+ if (!verdict) return json(res, 400, { ok: false, message: "请选择评审通过或退回修改" });
466
+ const data = buildCodeReview(entry.repo, entry.featureDir);
467
+ if (data.running) return json(res, 409, { ok: false, message: "流水线正在运行,等它结束后再提交评审。" });
468
+ const sub: Submission = {
469
+ verdict,
470
+ reviewer: typeof body?.reviewer === "string" ? body.reviewer : "",
471
+ reviewers: Array.isArray(body?.reviewers) ? body.reviewers.filter((r): r is string => typeof r === "string") : [],
472
+ comments: (Array.isArray(body?.comments) ? body.comments : []).filter((c) => c && typeof c.text === "string").map((c) => ({ file: typeof c.file === "string" ? c.file : null, line: typeof c.line === "number" ? c.line : null, text: c.text })),
473
+ fix: (Array.isArray(body?.fix) ? body.fix : []).filter((f) => f && typeof f.id === "string").map((f) => ({ id: f.id, note: typeof f.note === "string" ? f.note : undefined })),
474
+ note: typeof body?.note === "string" ? body.note : "",
475
+ };
476
+ if (verdict === "changes" && sub.comments.length === 0 && sub.fix.length === 0 && !sub.note.trim()) {
477
+ return json(res, 400, { ok: false, message: "退回修改需要至少一条意见:在代码行上写意见,或把 AI 的意见标为\"要改\"。" });
478
+ }
479
+ const { review, committed } = recordHumanReview(entry.repo, entry.featureDir, sub);
480
+ if (verdict === "approve") {
481
+ return json(res, 200, { ok: true, verdict, committed, message: `已记录:评审通过${committed ? ",已写入 code-review.md 并提交" : ""}。${review.reviewers.length ? `审核人:${review.reviewers.join("、")}。` : ""}合并请求接入后会用这些审核人。` });
482
+ }
483
+ const started = codeFixRun(entry.repo, entry.featureDir);
484
+ return json(res, 200, {
485
+ ok: true,
486
+ verdict,
487
+ committed,
488
+ message: started.ok
489
+ ? `已记录 ${review.items.length} 条修改意见,流水线开始按意见修改(需求说明不变,从方案设计开始只处理这些意见),进展会发回需求的对话。`
490
+ : `已记录 ${review.items.length} 条修改意见,但没能开始修改:${started.message.split("\n")[0]}。可以在需求的对话里说"按代码评审意见修改",或执行 req review-fix ${path.basename(entry.featureDir)}。`,
491
+ });
492
+ }
493
+ return send(res, 404, "没有这个页面");
494
+ }
495
+
496
+ // 1.14: the acceptance checklist, /r/<token>/f/<key>/check/…
497
+ async function handleChecklist(req: http.IncomingMessage, res: http.ServerResponse, rest: string, entry: { repo: string; featureDir: string; key: string; project: string }, featureAbs: string, full: boolean) {
498
+ const checkDir = path.join(featureAbs, ".pipeline", "check");
499
+ if (rest === "") return sendFile(res, path.join(ASSETS, "check.html"));
500
+ if (rest === "check.js" || rest === "check.css" || SHARED_ASSETS.has(rest)) return sendFile(res, path.join(ASSETS, rest));
501
+ if (rest === "api/info" && req.method === "GET") {
502
+ const state = readState(statePath(entry.repo, entry.featureDir));
503
+ let draft: unknown = { answers: [], reviewer: "" };
504
+ try {
505
+ draft = JSON.parse(fs.readFileSync(path.join(checkDir, "draft.json"), "utf8"));
506
+ } catch {
507
+ /* none yet */
508
+ }
509
+ const acceptance = fs.existsSync(path.join(featureAbs, "acceptance.md")) ? fs.readFileSync(path.join(featureAbs, "acceptance.md"), "utf8") : "";
510
+ return json(res, 200, {
511
+ ...buildChecklist(featureAbs),
512
+ project: entry.project,
513
+ featureDir: entry.featureDir,
514
+ readOnly: !full,
515
+ running: state?.status === "running",
516
+ accepted: /^[-*]\s*验收结论[::]\s*(.+)$/m.exec(acceptance)?.[1]?.trim() ?? null,
517
+ draft,
518
+ });
519
+ }
520
+ if (rest === "api/draft" && req.method === "PUT") {
521
+ if (!full) return json(res, 403, { ok: false, message: "这是只读链接" });
522
+ const body = (await readBody(req)) as { answers?: unknown; reviewer?: unknown } | null;
523
+ if (!body || !Array.isArray(body.answers)) return json(res, 400, { ok: false, message: "格式不对" });
524
+ fs.mkdirSync(checkDir, { recursive: true });
525
+ fs.writeFileSync(path.join(checkDir, "draft.json"), JSON.stringify({ answers: body.answers, reviewer: typeof body.reviewer === "string" ? body.reviewer : "", savedAt: new Date().toISOString() }, null, 2));
526
+ return json(res, 200, { ok: true });
527
+ }
528
+ if (rest === "api/try" && req.method === "POST") {
529
+ if (!full) return json(res, 403, { ok: false, message: "这是只读链接" });
530
+ const body = (await readBody(req)) as { stop?: boolean } | null;
531
+ return json(res, 200, tryRun(entry.repo, entry.featureDir, body?.stop === true));
532
+ }
533
+ if (rest === "api/submit" && req.method === "POST") {
534
+ if (!full) return json(res, 403, { ok: false, message: "这是只读链接,不能提交" });
535
+ const body = (await readBody(req)) as { answers?: Answer[]; reviewer?: string } | null;
536
+ const answers = (Array.isArray(body?.answers) ? body.answers : []).filter((a) => a && typeof a.id === "string" && ["pass", "fail", "skip"].includes(a.mark));
537
+ const list = buildChecklist(featureAbs);
538
+ const v = verdictOf(list, answers);
539
+ if (v.verdict === "通过" && v.missing.length > 0) {
540
+ return json(res, 400, { ok: false, message: `还有 ${v.missing.length} 条必须验的没有核对(${v.missing.map((i) => i.id).join("、")})。核对完,或者有不对的标"不对"后再提交。` });
541
+ }
542
+ const file = path.join(featureAbs, "acceptance.md");
543
+ const previous = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : undefined;
544
+ const reviewer = body?.reviewer?.trim() || "需求方(验收页)";
545
+ const text = acceptanceText(list, answers, { verdict: v.verdict, reviewer: reviewer.slice(0, 60), date: new Date().toISOString().slice(0, 10), previous });
546
+ const { committed } = recordAcceptance(entry.repo, entry.featureDir, text);
547
+ fs.rmSync(path.join(checkDir, "draft.json"), { force: true });
548
+ // 1.14: the acceptance also goes into the usage records, for req stats.
549
+ const marks = new Map(answers.map((a) => [a.id, a.mark]));
550
+ appendEvent({
551
+ kind: "acceptance",
552
+ requirement: requirementRef(entry.repo, entry.featureDir),
553
+ acceptance: {
554
+ verdict: v.verdict,
555
+ reviewer: reviewer.slice(0, 60),
556
+ total: list.items.length,
557
+ passed: list.items.filter((i) => marks.get(i.id) === "pass").length,
558
+ failed: list.items.filter((i) => marks.get(i.id) === "fail").length,
559
+ unchecked: list.items.filter((i) => !marks.get(i.id) || marks.get(i.id) === "skip").length,
560
+ },
561
+ });
562
+ if (v.verdict === "通过") {
563
+ return json(res, 200, { ok: true, verdict: v.verdict, committed, message: `已记录:验收通过${committed ? ",验收记录已提交" : ""}。下一步请开发同事审阅代码并合并。` });
564
+ }
565
+ const told = run("reply", entry.repo, entry.featureDir, ["--acceptance", acceptanceFailMessage(entry.featureDir, list, answers)]);
566
+ return json(res, 200, {
567
+ ok: true,
568
+ verdict: v.verdict,
569
+ committed,
570
+ message: told.ok ? "已记录:验收不通过。不对的地方已经转给这个需求的对话,它会和你确定怎么处理。" : `已记录:验收不通过,但没能转给需求的对话(${told.message.split("\n")[0]})。请在需求的对话里说"验收不通过"。`,
571
+ });
572
+ }
573
+ return send(res, 404, "没有这个页面");
574
+ }
575
+ }
576
+
577
+ // ---------------------------------------------------------------------------
578
+ // One server per machine
579
+
580
+ export interface ServerInfo {
581
+ pid: number;
582
+ port: number;
583
+ token: string;
584
+ readToken: string;
585
+ version: string;
586
+ publicUrl: string;
587
+ startedAt: string;
588
+ }
589
+
590
+ export const infoFile = (env: NodeJS.ProcessEnv = process.env) => path.join(kitHome(env), "review-server.json");
591
+
592
+ function readInfo(env: NodeJS.ProcessEnv): ServerInfo | null {
593
+ try {
594
+ return JSON.parse(fs.readFileSync(infoFile(env), "utf8")) as ServerInfo;
595
+ } catch {
596
+ return null;
597
+ }
598
+ }
599
+
600
+ function alive(pid: number): boolean {
601
+ try {
602
+ process.kill(pid, 0);
603
+ return true;
604
+ } catch (error) {
605
+ return (error as NodeJS.ErrnoException).code === "EPERM";
606
+ }
607
+ }
608
+
609
+ async function healthy(info: ServerInfo): Promise<boolean> {
610
+ try {
611
+ const r = await fetch(`http://127.0.0.1:${info.port}/r/${info.token}/health`, { signal: AbortSignal.timeout(2000) });
612
+ return r.ok && ((await r.json()) as { version?: string }).version === kitVersion();
613
+ } catch {
614
+ return false;
615
+ }
616
+ }
617
+
618
+ /** The running review server, started in the background when there is none (or an older one). */
619
+ export async function ensureReviewServer(env: NodeJS.ProcessEnv = process.env): Promise<ServerInfo> {
620
+ const existing = readInfo(env);
621
+ if (existing && alive(existing.pid) && (await healthy(existing))) return existing;
622
+ if (existing && alive(existing.pid)) {
623
+ try {
624
+ process.kill(existing.pid);
625
+ } catch {
626
+ /* gone */
627
+ }
628
+ }
629
+ fs.mkdirSync(kitHome(env), { recursive: true });
630
+ const log = fs.openSync(path.join(kitHome(env), "review-server.log"), "a");
631
+ const child = spawn(process.execPath, [...process.execArgv, path.join(ENGINE_DIR, "src", "review.ts"), "--serve"], {
632
+ detached: true,
633
+ stdio: ["ignore", log, log],
634
+ env,
635
+ windowsHide: true,
636
+ });
637
+ child.unref();
638
+ for (let i = 0; i < 100; i++) {
639
+ await new Promise((r) => setTimeout(r, 100));
640
+ const info = readInfo(env);
641
+ if (info && info.pid === child.pid && (await healthy(info))) return info;
642
+ }
643
+ throw new Error(`原型审查页没有启动,日志:${path.join(kitHome(env), "review-server.log")}`);
644
+ }
645
+
646
+ /** The page of one requirement (by its key in the requirement index). */
647
+ export function reviewUrl(info: ServerInfo, key: string, readOnly = false): string {
648
+ return `${info.publicUrl.replace(/\/+$/, "")}/r/${readOnly ? info.readToken : info.token}/f/${encodeURIComponent(key)}/`;
649
+ }
650
+
651
+ /** Finds the index key of a requirement from its repository and feature directory. */
652
+ export function keyOf(repo: string, featureDir: string, env: NodeJS.ProcessEnv = process.env): string | null {
653
+ const norm = (p: string) => path.resolve(p).toLowerCase();
654
+ const dir = norm(path.join(repo, featureDir));
655
+ const e = readIndex(env).find((x) => norm(path.join(x.repo, x.featureDir)) === dir || (x.sourceRepo !== null && norm(path.join(x.sourceRepo, x.featureDir)) === dir));
656
+ return e?.key ?? null;
657
+ }
658
+
659
+ async function serve(env: NodeJS.ProcessEnv): Promise<void> {
660
+ const token = crypto.randomBytes(18).toString("base64url");
661
+ const readToken = crypto.randomBytes(18).toString("base64url");
662
+ let last = Date.now();
663
+ const server = createReviewServer({ token, readToken, env, onRequest: () => (last = Date.now()) });
664
+ const host = env.REQ_KIT_REVIEW_HOST?.trim() || "127.0.0.1";
665
+ const wanted = Number(env.REQ_KIT_REVIEW_PORT ?? DEFAULT_PORT);
666
+ const listen = (port: number) =>
667
+ new Promise<number>((resolve, reject) => {
668
+ server.once("error", reject);
669
+ server.listen(port, host, () => {
670
+ server.off("error", reject);
671
+ resolve((server.address() as { port: number }).port);
672
+ });
673
+ });
674
+ let port: number;
675
+ try {
676
+ port = await listen(wanted);
677
+ } catch {
678
+ port = await listen(0);
679
+ }
680
+ const info: ServerInfo = {
681
+ pid: process.pid,
682
+ port,
683
+ token,
684
+ readToken,
685
+ version: kitVersion(),
686
+ // Listening for other computers without a public address: this computer's name is the best guess.
687
+ publicUrl: env.REQ_KIT_REVIEW_PUBLIC_URL?.trim() || `http://${/^(127\.|localhost$|::1$)/.test(host) ? "127.0.0.1" : os.hostname()}:${port}`,
688
+ startedAt: new Date().toISOString(),
689
+ };
690
+ fs.mkdirSync(kitHome(env), { recursive: true });
691
+ fs.writeFileSync(infoFile(env), JSON.stringify(info, null, 2), { mode: 0o600 });
692
+ console.log(`[${info.startedAt}] 原型审查页在 ${host}:${port} 运行(laoshi ${info.version})`);
693
+ const timer = setInterval(() => {
694
+ if (Date.now() - last < IDLE_EXIT_MS) return;
695
+ clearInterval(timer);
696
+ const current = readInfo(env);
697
+ if (current?.pid === process.pid) fs.rmSync(infoFile(env), { force: true });
698
+ server.close(() => process.exit(0));
699
+ }, 60_000);
700
+ }
701
+
702
+ // ---------------------------------------------------------------------------
703
+ // req review <需求> [--no-open] [--read-only]
704
+
705
+ export function openBrowser(url: string) {
706
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
707
+ try {
708
+ const child = spawn(cmd, args as string[], { stdio: "ignore", detached: true, windowsHide: true });
709
+ child.on("error", () => {});
710
+ child.unref();
711
+ } catch {
712
+ /* the address is printed anyway */
713
+ }
714
+ }
715
+
716
+ async function main(argv: string[]): Promise<number> {
717
+ if (argv[0] === "--serve") {
718
+ await serve(process.env);
719
+ return -1;
720
+ }
721
+ const open = !argv.includes("--no-open");
722
+ const readOnly = argv.includes("--read-only");
723
+ // 1.14: --page code opens the code review page of the same server.
724
+ const pageAt = argv.indexOf("--page");
725
+ const page = pageAt >= 0 ? argv[pageAt + 1] : null;
726
+ const feature = argv.find((a, i) => !a.startsWith("--") && !(pageAt >= 0 && i === pageAt + 1));
727
+ if (page === "code" && feature && !argv.includes("--help")) {
728
+ const { locate } = await import("./api.js");
729
+ const { repo, featureDir } = locate(process.cwd(), feature);
730
+ const key = keyOf(repo, featureDir);
731
+ if (!key) {
732
+ console.error(`${featureDir} 不在本机的需求列表中,先运行一次 req index --rebuild`);
733
+ return 1;
734
+ }
735
+ const url = `${reviewUrl(await ensureReviewServer(), key, readOnly)}code/`;
736
+ console.log(`代码审查页:${url}`);
737
+ if (open) openBrowser(url);
738
+ return 0;
739
+ }
740
+ if (!feature || argv.includes("--help") || argv.includes("-h")) {
741
+ console.log("用法:req review <需求> [--no-open] [--read-only]\n\n在浏览器中打开这个需求的原型审查页:点选要改的地方、直接改文字,然后提交修改意见或确认方案。");
742
+ return feature ? 0 : 2;
743
+ }
744
+ const { locate } = await import("./api.js");
745
+ const { repo, featureDir } = locate(process.cwd(), feature);
746
+ if (!fs.existsSync(path.join(repo, featureDir, "prototype"))) {
747
+ console.error(`${featureDir} 还没有界面原型(prototype/)。界面改动的需求在方案设计后才会有。`);
748
+ return 1;
749
+ }
750
+ const key = keyOf(repo, featureDir);
751
+ if (!key) {
752
+ console.error(`${featureDir} 不在本机的需求列表中,先运行一次 req index --rebuild`);
753
+ return 1;
754
+ }
755
+ const url = reviewUrl(await ensureReviewServer(), key, readOnly);
756
+ console.log(`原型审查页:${url}`);
757
+ if (open) openBrowser(url);
758
+ return 0;
759
+ }
760
+
761
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(import.meta.filename)) {
762
+ main(process.argv.slice(2)).then(
763
+ (code) => {
764
+ if (code >= 0) process.exit(code);
765
+ },
766
+ (error: Error) => {
767
+ console.error(error.message);
768
+ process.exit(1);
769
+ },
770
+ );
771
+ }