@aibyzero/cm-workflow 0.17.0 → 0.18.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 (372) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +27 -0
  3. package/CHANGELOG.md +230 -1
  4. package/CONTRIBUTING.md +47 -0
  5. package/README.md +21 -3
  6. package/THIRD_PARTY_NOTICES.md +13 -0
  7. package/VERSION +1 -1
  8. package/compat/claude-commands/cm-challenge.md +3 -0
  9. package/docs/architecture.md +40 -13
  10. package/docs/cm-control-policy-v2.md +127 -9
  11. package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
  12. package/docs/installation.md +310 -4
  13. package/docs/js-workflow-control.md +153 -16
  14. package/docs/live-evidence-drivers.md +28 -4
  15. package/docs/out-of-scope/README.md +25 -0
  16. package/docs/out-of-scope/background-supervisor.md +32 -0
  17. package/docs/reviewed-integration.md +48 -0
  18. package/docs/user-guide.md +50 -21
  19. package/install-codex.sh +331 -18
  20. package/install.ps1 +28 -2
  21. package/install.sh +321 -17
  22. package/package.json +2 -1
  23. package/runtime/js/cm-ai/batch-location.mjs +55 -0
  24. package/runtime/js/cm-ai/batch-plan.mjs +242 -0
  25. package/runtime/js/cm-ai/checkpoint-package-material.mjs +162 -0
  26. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +55 -1
  27. package/runtime/js/cm-ai/claude-review-stream.mjs +94 -21
  28. package/runtime/js/cm-ai/claude-tool-preview.mjs +11 -9
  29. package/runtime/js/cm-ai/cm-ai-admission.mjs +18 -12
  30. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +91 -6
  31. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +5 -1
  32. package/runtime/js/cm-ai/codex-config.mjs +6 -2
  33. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +3 -2
  34. package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
  35. package/runtime/js/cm-ai/codex-reconnect-notice.mjs +6 -0
  36. package/runtime/js/cm-ai/codex-review-adapter.mjs +27 -7
  37. package/runtime/js/cm-ai/control-policy.mjs +24 -6
  38. package/runtime/js/cm-ai/developer-adapter.mjs +19 -5
  39. package/runtime/js/cm-ai/drive-core.mjs +236 -34
  40. package/runtime/js/cm-ai/drive-rate-limit.mjs +105 -0
  41. package/runtime/js/cm-ai/durable-runner-state.mjs +234 -33
  42. package/runtime/js/cm-ai/effect-contract.mjs +11 -2
  43. package/runtime/js/cm-ai/execution-policy.mjs +3 -1
  44. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -2
  45. package/runtime/js/cm-ai/execution-store-limits.mjs +14 -7
  46. package/runtime/js/cm-ai/execution-store.mjs +60 -17
  47. package/runtime/js/cm-ai/fix-code-association.mjs +73 -2
  48. package/runtime/js/cm-ai/host-check.mjs +14 -6
  49. package/runtime/js/cm-ai/host-conversation-execution.mjs +70 -28
  50. package/runtime/js/cm-ai/host-qa-executor.mjs +38 -5
  51. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +2 -2
  52. package/runtime/js/cm-ai/host-qa-policy.mjs +19 -2
  53. package/runtime/js/cm-ai/host-replay.mjs +148 -0
  54. package/runtime/js/cm-ai/host-session.mjs +42 -9
  55. package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
  56. package/runtime/js/cm-ai/host-tool-bridge.mjs +22 -9
  57. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +19 -2
  58. package/runtime/js/cm-ai/host.mjs +1 -1
  59. package/runtime/js/cm-ai/implicit-qa-decision.mjs +5 -0
  60. package/runtime/js/cm-ai/integration-snapshots.mjs +50 -0
  61. package/runtime/js/cm-ai/live-evidence.mjs +28 -6
  62. package/runtime/js/cm-ai/operator-guidance.mjs +63 -30
  63. package/runtime/js/cm-ai/owned-process-cleanup.mjs +27 -9
  64. package/runtime/js/cm-ai/process-group-exit.mjs +46 -0
  65. package/runtime/js/cm-ai/provider-review-observation.mjs +3 -2
  66. package/runtime/js/cm-ai/qa-attachment.mjs +22 -0
  67. package/runtime/js/cm-ai/qa-config-revision.mjs +7 -2
  68. package/runtime/js/cm-ai/requirement-evidence.mjs +102 -0
  69. package/runtime/js/cm-ai/review-package.mjs +79 -7
  70. package/runtime/js/cm-ai/review-presentation-delta.mjs +166 -0
  71. package/runtime/js/cm-ai/review-presentation.mjs +177 -8
  72. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +70 -2
  73. package/runtime/js/cm-ai/reviewed-integration.mjs +260 -0
  74. package/runtime/js/cm-ai/scope-revision.mjs +38 -0
  75. package/runtime/js/cm-ai/specification-material.mjs +2 -2
  76. package/runtime/js/cm-ai/task-runner.mjs +247 -41
  77. package/runtime/js/cm-ai/verification-auto.mjs +38 -0
  78. package/runtime/js/cm-ai/worker-claude-developer.mjs +39 -15
  79. package/runtime/js/cm-ai/worker-claude.mjs +35 -13
  80. package/runtime/js/cm-ai/worker-codex-developer.mjs +43 -17
  81. package/runtime/js/cm-ai/worker-codex.mjs +41 -7
  82. package/runtime/js/cm-fix/cause-invocation.mjs +16 -2
  83. package/runtime/js/cm-fix/cause-package.mjs +46 -1
  84. package/runtime/js/cm-fix/command-correction.mjs +37 -0
  85. package/runtime/js/cm-fix/cooperative.mjs +12 -0
  86. package/runtime/js/cm-fix/dossier.mjs +8 -2
  87. package/runtime/js/cm-fix/execution.mjs +578 -100
  88. package/runtime/js/cm-fix/final-review.mjs +39 -8
  89. package/runtime/js/cm-fix/finish.mjs +15 -11
  90. package/runtime/js/cm-fix/host-review.mjs +65 -10
  91. package/runtime/js/cm-fix/host.mjs +35 -12
  92. package/runtime/js/cm-fix/jest-command-correction.mjs +69 -0
  93. package/runtime/js/cm-fix/metrics.mjs +18 -5
  94. package/runtime/js/cm-fix/regression-evidence.mjs +3 -2
  95. package/runtime/js/cm-fix/regression.mjs +16 -7
  96. package/runtime/js/cm-fix/repair.mjs +29 -8
  97. package/runtime/js/cm-fix/review-verification-command.mjs +135 -0
  98. package/runtime/js/cm-fix/review-verification-contract.mjs +54 -0
  99. package/runtime/js/cm-fix/review-verification-diagnostic.mjs +75 -0
  100. package/runtime/js/cm-fix/review-verification-recovery.mjs +44 -0
  101. package/runtime/js/cm-fix/review-verification-server.mjs +38 -0
  102. package/runtime/js/cm-fix/review-verification.mjs +214 -0
  103. package/runtime/js/cm-fix/source-correction-recovery.mjs +65 -0
  104. package/runtime/js/cm-fix/start.mjs +6 -3
  105. package/runtime/js/cm-fix/test-type-correction.mjs +86 -0
  106. package/runtime/js/cm-fix/test-type-recovery.mjs +51 -0
  107. package/runtime/js/cm-fix/type-import-correction.mjs +89 -0
  108. package/runtime/js/cm-prd/accepted-design.mjs +8 -0
  109. package/runtime/js/cm-prd/analysis.mjs +13 -9
  110. package/runtime/js/cm-prd/change.mjs +37 -16
  111. package/runtime/js/cm-prd/draft-save.mjs +13 -6
  112. package/runtime/js/cm-prd/draft.mjs +31 -3
  113. package/runtime/js/cm-prd/failed-correction.mjs +19 -3
  114. package/runtime/js/cm-prd/inputs-replaced.mjs +3 -0
  115. package/runtime/js/cm-prd/review-correction.mjs +6 -4
  116. package/runtime/js/cm-prd/review-disposition.mjs +7 -1
  117. package/runtime/js/cm-prd/self-check-revision.mjs +2 -2
  118. package/runtime/js/cm-prd/self-check.mjs +125 -6
  119. package/runtime/js/cm-prd/session.mjs +30 -1
  120. package/runtime/js/cm-prd/summary.mjs +38 -17
  121. package/runtime/js/cm-prd/task-scope-record.mjs +97 -0
  122. package/runtime/js/cm-prd/tree-digest.mjs +34 -0
  123. package/runtime/js/cm-prd/validation-reason.mjs +8 -4
  124. package/runtime/js/cm-security/scan.mjs +1 -1
  125. package/runtime/js/commander/decision.mjs +44 -0
  126. package/runtime/js/commander/dispatch-registry.mjs +110 -0
  127. package/runtime/js/commander/ledger.mjs +265 -0
  128. package/runtime/js/commander/preflight.mjs +107 -0
  129. package/runtime/js/notify-later.mjs +13 -0
  130. package/runtime/js/notify-send.mjs +6 -2
  131. package/runtime/js/notify.mjs +570 -63
  132. package/runtime/js/review-findings.mjs +38 -0
  133. package/runtime/js/session-boundary.mjs +56 -0
  134. package/runtime/js/session-handoff.mjs +68 -0
  135. package/runtime/js/spec-task-line.mjs +27 -13
  136. package/runtime/js/specs-status.mjs +1 -1
  137. package/runtime/js/task-scope.mjs +197 -0
  138. package/runtime/logging.md +6 -1
  139. package/runtime/model-efficiency.md +69 -10
  140. package/runtime/orchestration.md +3 -1
  141. package/runtime/project-learning.md +2 -0
  142. package/runtime/review.md +12 -2
  143. package/runtime/test-contract.md +1 -0
  144. package/scripts/ci-test-weights.json +3 -0
  145. package/scripts/cm-ai-admission.mjs +11 -5
  146. package/scripts/cm-ai-admission.test.mjs +23 -2
  147. package/scripts/cm-ai-batch-drive.mjs +79 -18
  148. package/scripts/cm-ai-batch-drive.test.mjs +169 -3
  149. package/scripts/cm-ai-batch-host.mjs +38 -9
  150. package/scripts/cm-ai-batch-host.test.mjs +27 -14
  151. package/scripts/cm-ai-batch-learning-merge.test.mjs +36 -0
  152. package/scripts/cm-ai-batch-location.test.mjs +57 -0
  153. package/scripts/cm-ai-batch-plan.mjs +52 -0
  154. package/scripts/cm-ai-batch-plan.test.mjs +397 -0
  155. package/scripts/cm-ai-batch-run-fixture.mjs +446 -35
  156. package/scripts/cm-ai-batch-run-member-stops.test.mjs +16 -0
  157. package/scripts/cm-ai-batch-run-parallel.test.mjs +28 -1
  158. package/scripts/cm-ai-batch-run.mjs +483 -63
  159. package/scripts/cm-ai-batch-run.test.mjs +23 -4
  160. package/scripts/cm-ai-batch-session-e2e.test.mjs +235 -0
  161. package/scripts/cm-ai-batch-session-member.test.mjs +293 -0
  162. package/scripts/cm-ai-batch-session-recovery.test.mjs +423 -0
  163. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +247 -0
  164. package/scripts/cm-ai-checklist-coverage.test.mjs +4 -2
  165. package/scripts/cm-ai-checkpoint-package-material.test.mjs +221 -0
  166. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +193 -0
  167. package/scripts/cm-ai-control-launch.test.mjs +21 -0
  168. package/scripts/cm-ai-control-policy.test.mjs +82 -0
  169. package/scripts/cm-ai-control-v2-drive.test.mjs +398 -3
  170. package/scripts/cm-ai-control-v2-supersede-race.mjs +25 -0
  171. package/scripts/cm-ai-control-v2-supersede.test.mjs +318 -0
  172. package/scripts/cm-ai-develop-driver-gaps.test.mjs +163 -0
  173. package/scripts/cm-ai-development-rework.test.mjs +423 -0
  174. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +3 -2
  175. package/scripts/cm-ai-drive.mjs +73 -17
  176. package/scripts/cm-ai-drive.test.mjs +37 -5
  177. package/scripts/cm-ai-execution-store-legacy-probe.test.mjs +84 -0
  178. package/scripts/cm-ai-host-fixture.mjs +9 -6
  179. package/scripts/cm-ai-host-protected.test.mjs +1 -1
  180. package/scripts/cm-ai-host.mjs +60 -19
  181. package/scripts/cm-ai-host.test.mjs +15 -0
  182. package/scripts/cm-ai-integration-adoption.test.mjs +223 -0
  183. package/scripts/cm-ai-integration-independence.test.mjs +23 -0
  184. package/scripts/cm-ai-integration-launch.test.mjs +240 -0
  185. package/scripts/cm-ai-integration-preview.mjs +41 -0
  186. package/scripts/cm-ai-integration-snapshots.test.mjs +197 -0
  187. package/scripts/cm-ai-nested-execution.test.mjs +29 -1
  188. package/scripts/cm-ai-operator-guidance.test.mjs +71 -0
  189. package/scripts/cm-ai-prefinal-delivery.test.mjs +278 -0
  190. package/scripts/cm-ai-project-qa-gate.test.mjs +56 -0
  191. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +28 -0
  192. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +36 -2
  193. package/scripts/cm-ai-requirement-evidence.test.mjs +65 -0
  194. package/scripts/cm-ai-review-failure.test.mjs +150 -5
  195. package/scripts/cm-ai-review-timeout.test.mjs +20 -0
  196. package/scripts/cm-ai-run.mjs +88 -21
  197. package/scripts/cm-ai-scope-revision.test.mjs +341 -0
  198. package/scripts/cm-ai-spec-rebind.test.mjs +13 -0
  199. package/scripts/cm-ai-supersede.test.mjs +28 -0
  200. package/scripts/cm-ai-verification-auto.test.mjs +99 -0
  201. package/scripts/cm-announce-hook.mjs +35 -8
  202. package/scripts/cm-announce-hook.test.mjs +25 -0
  203. package/scripts/cm-challenge.test.mjs +61 -0
  204. package/scripts/cm-check-drive-files.mjs +2 -2
  205. package/scripts/cm-check-host.test.mjs +1 -1
  206. package/scripts/cm-check-runtime.sh +58 -1
  207. package/scripts/cm-claude-developer-worker.test.mjs +56 -7
  208. package/scripts/cm-claude-install-layout.test.mjs +1 -1
  209. package/scripts/cm-claude-probe.test.mjs +26 -0
  210. package/scripts/cm-claude-review-diagnostics.test.mjs +235 -0
  211. package/scripts/cm-claude-review-stream.test.mjs +49 -0
  212. package/scripts/cm-claude-worker.test.mjs +16 -0
  213. package/scripts/cm-codex-developer-reconnect-notice.test.mjs +98 -0
  214. package/scripts/cm-codex-developer-worker.test.mjs +120 -0
  215. package/scripts/cm-codex-install-local-edit-guard.test.mjs +436 -0
  216. package/scripts/cm-codex-prompt-input.test.mjs +153 -0
  217. package/scripts/cm-codex-reconnect-notice.test.mjs +167 -0
  218. package/scripts/cm-commander-ledger.test.mjs +260 -0
  219. package/scripts/cm-commander-p2.test.mjs +295 -0
  220. package/scripts/cm-commander-preflight.mjs +84 -0
  221. package/scripts/cm-commander.mjs +116 -0
  222. package/scripts/cm-config-lock.mjs +35 -0
  223. package/scripts/cm-controlled-correction.test.mjs +10 -1
  224. package/scripts/cm-developer-failure-code.test.mjs +62 -0
  225. package/scripts/cm-display-task-id.test.mjs +41 -0
  226. package/scripts/cm-drive-liveness.test.mjs +83 -0
  227. package/scripts/cm-efficiency-presentation-delta.test.mjs +218 -0
  228. package/scripts/cm-execution-snapshot-reuse.test.mjs +115 -0
  229. package/scripts/cm-external-batch-host.test.mjs +12 -9
  230. package/scripts/cm-external-process-cleanup.test.mjs +128 -0
  231. package/scripts/cm-external-qa-fix.test.mjs +89 -7
  232. package/scripts/cm-external-review-reconciliation.test.mjs +11 -0
  233. package/scripts/cm-failover.mjs +48 -10
  234. package/scripts/cm-failover.test.mjs +46 -0
  235. package/scripts/cm-fix-cause-invocation.test.mjs +19 -4
  236. package/scripts/cm-fix-command-correction.mjs +17 -0
  237. package/scripts/cm-fix-command-correction.test.mjs +211 -0
  238. package/scripts/cm-fix-cooperative-closeout.test.mjs +87 -0
  239. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +217 -0
  240. package/scripts/cm-fix-drive.mjs +33 -5
  241. package/scripts/cm-fix-drive.test.mjs +49 -0
  242. package/scripts/cm-fix-host-review-assembly.test.mjs +197 -1
  243. package/scripts/cm-fix-host-review.test.mjs +21 -9
  244. package/scripts/cm-fix-host.mjs +26 -8
  245. package/scripts/cm-fix-monorepo-map.test.mjs +92 -0
  246. package/scripts/cm-fix-observation-task-id.test.mjs +122 -0
  247. package/scripts/cm-fix-regression-input-budget.test.mjs +111 -0
  248. package/scripts/cm-fix-repair-input-budget.test.mjs +119 -0
  249. package/scripts/cm-fix-review-file-paging.test.mjs +91 -0
  250. package/scripts/cm-fix-review-preflight.mjs +24 -0
  251. package/scripts/cm-fix-review-storage.test.mjs +233 -0
  252. package/scripts/cm-fix-review-verification-command.test.mjs +242 -0
  253. package/scripts/cm-fix-review-verification-evidence.test.mjs +218 -0
  254. package/scripts/cm-fix-review-verification-integration.test.mjs +81 -0
  255. package/scripts/cm-fix-review-verification-recovery.test.mjs +198 -0
  256. package/scripts/cm-fix-review-verification.test.mjs +146 -0
  257. package/scripts/cm-fix-revision-transport.test.mjs +81 -0
  258. package/scripts/cm-fix-source-correction.test.mjs +296 -0
  259. package/scripts/cm-fix-test-type-correction.mjs +18 -0
  260. package/scripts/cm-fix-test-type-correction.test.mjs +123 -0
  261. package/scripts/cm-fix-test-type-owner.test.mjs +208 -0
  262. package/scripts/cm-fix-test-type-verification-cost.test.mjs +66 -0
  263. package/scripts/cm-fix-type-import-correction.test.mjs +95 -0
  264. package/scripts/cm-fix-verification-diagnostic.test.mjs +200 -0
  265. package/scripts/cm-fix-verification-recovery.mjs +33 -0
  266. package/scripts/cm-host-diagnostic.test.mjs +33 -0
  267. package/scripts/cm-host-liveness.test.mjs +150 -0
  268. package/scripts/cm-host-qa-executor.test.mjs +77 -0
  269. package/scripts/cm-host-replay.test.mjs +176 -0
  270. package/scripts/cm-host-stage-observer.test.mjs +41 -0
  271. package/scripts/cm-install-local-edit-guard.test.mjs +621 -0
  272. package/scripts/cm-install-manifest.sh +351 -0
  273. package/scripts/cm-live-evidence.test.mjs +59 -1
  274. package/scripts/cm-log-event.mjs +61 -10
  275. package/scripts/cm-log-event.test.mjs +121 -1
  276. package/scripts/cm-matt-skills.mjs +576 -0
  277. package/scripts/cm-matt-skills.test.mjs +550 -0
  278. package/scripts/cm-notify-command.test.mjs +42 -10
  279. package/scripts/cm-notify.mjs +14 -10
  280. package/scripts/cm-notify.test.mjs +625 -75
  281. package/scripts/cm-patrol.mjs +4 -1
  282. package/scripts/cm-patrol.test.mjs +23 -5
  283. package/scripts/cm-prd-answer-gaps.test.mjs +2 -2
  284. package/scripts/cm-prd-completion.test.mjs +56 -13
  285. package/scripts/cm-prd-design-phase.test.mjs +78 -8
  286. package/scripts/cm-prd-draft-save.test.mjs +12 -0
  287. package/scripts/cm-prd-draft.test.mjs +1 -1
  288. package/scripts/cm-prd-drive.mjs +13 -6
  289. package/scripts/cm-prd-drive.test.mjs +46 -2
  290. package/scripts/cm-prd-gate-diagnostic.test.mjs +2 -2
  291. package/scripts/cm-prd-host.mjs +10 -5
  292. package/scripts/cm-prd-host.test.mjs +4 -2
  293. package/scripts/cm-prd-inputs-replaced.test.mjs +1 -1
  294. package/scripts/cm-prd-review-disposition.test.mjs +124 -8
  295. package/scripts/cm-prd-revision.test.mjs +1 -1
  296. package/scripts/cm-prd-self-check-revision.test.mjs +16 -1
  297. package/scripts/cm-prd-self-check-rules.test.mjs +239 -0
  298. package/scripts/cm-prd-self-check.test.mjs +105 -5
  299. package/scripts/cm-prd-session-recovery.test.mjs +5 -3
  300. package/scripts/cm-prd-summary.test.mjs +55 -3
  301. package/scripts/cm-prd-task-grouping.test.mjs +6 -6
  302. package/scripts/cm-prd-tree-digest.test.mjs +74 -0
  303. package/scripts/cm-refactor-drive.mjs +2 -1
  304. package/scripts/cm-refactor-drive.test.mjs +9 -0
  305. package/scripts/cm-release-smoke.sh +3 -15
  306. package/scripts/cm-skill-hints-autowire.test.mjs +394 -0
  307. package/scripts/cm-skill-hints-exam.mjs +149 -0
  308. package/scripts/cm-skill-hints-install.test.mjs +168 -0
  309. package/scripts/cm-skill-hints.exam.json +706 -0
  310. package/scripts/cm-skill-hints.json +119 -0
  311. package/scripts/cm-skill-hints.mjs +669 -0
  312. package/scripts/cm-skill-hints.test.mjs +831 -0
  313. package/scripts/cm-skill-judge.mjs +181 -0
  314. package/scripts/cm-skill-judge.test.mjs +255 -0
  315. package/scripts/cm-specs-status.test.mjs +4 -2
  316. package/scripts/cm-start-check.mjs +208 -0
  317. package/scripts/cm-start-check.test.mjs +321 -0
  318. package/scripts/cm-task-gate.mjs +150 -29
  319. package/scripts/cm-task-gate.test.mjs +73 -1
  320. package/scripts/cm-task-id-grammar.test.mjs +66 -0
  321. package/scripts/cm-task-scope.test.mjs +308 -0
  322. package/scripts/cm-test-suite.mjs +109 -0
  323. package/scripts/cm-test-suite.test.mjs +162 -0
  324. package/scripts/cm-upgrade-compat-batch.test.mjs +172 -0
  325. package/scripts/cm-upgrade-compat.test.mjs +239 -0
  326. package/scripts/cm-workflow-config.mjs +12 -2
  327. package/scripts/fixtures/fix-verification-claude.mjs +44 -0
  328. package/scripts/fixtures/host-diagnostic.mjs +33 -0
  329. package/scripts/fixtures/reviewed-integration.mjs +202 -0
  330. package/scripts/scan-public-safety.py +1 -0
  331. package/scripts/session-boundary.test.mjs +170 -0
  332. package/scripts/test-npm-install.py +14 -3
  333. package/scripts/test-shell-compat.sh +2 -0
  334. package/scripts/validate-public-repo.py +1 -0
  335. package/scripts/validate-test-cases.mjs +3 -2
  336. package/skills/cm-ai/SKILL.md +5 -2
  337. package/skills/cm-ai/references/N4-review.md +2 -1
  338. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  339. package/skills/cm-ai/references/N8-finish.md +22 -0
  340. package/skills/cm-ai/references/js-host-qa-recovery.md +1 -1
  341. package/skills/cm-ai/references/js-host-recovery.md +79 -3
  342. package/skills/cm-ai/references/js-host.md +89 -17
  343. package/skills/cm-challenge/SKILL.md +65 -0
  344. package/skills/cm-challenge/evals/README.md +18 -0
  345. package/skills/cm-challenge/evals/trigger-cases.json +20 -0
  346. package/skills/cm-challenge/evals/trigger-config.json +28 -0
  347. package/skills/cm-challenge/references/examples.md +15 -0
  348. package/skills/cm-check/SKILL.md +5 -0
  349. package/skills/cm-check/references/js-host.md +2 -0
  350. package/skills/cm-fix/SKILL.md +12 -3
  351. package/skills/cm-fix/references/command-correction.md +67 -0
  352. package/skills/cm-fix/references/isolated-review.md +54 -0
  353. package/skills/cm-fix/references/js-host.md +62 -2
  354. package/skills/cm-fix/references/test-type-correction.md +72 -0
  355. package/skills/cm-fix/references/verification-recovery.md +114 -0
  356. package/skills/cm-idea/SKILL.md +2 -0
  357. package/skills/cm-idea/references/js-host.md +2 -0
  358. package/skills/cm-notify/SKILL.md +2 -0
  359. package/skills/cm-prd/SKILL.md +12 -8
  360. package/skills/cm-prd/references/brownfield.md +8 -1
  361. package/skills/cm-prd/references/change-mode.md +6 -0
  362. package/skills/cm-prd/references/greenfield.md +4 -0
  363. package/skills/cm-prd/references/js-host.md +4 -2
  364. package/skills/cm-prd/references/spec-self-check.md +5 -1
  365. package/skills/cm-refactor/SKILL.md +8 -0
  366. package/skills/cm-refactor/references/js-host.md +2 -0
  367. package/skills/cm-test/SKILL.md +4 -0
  368. package/templates/dashboard/dashboard.html +2 -2
  369. package/templates/pixel/cm-pixel.html +1 -1
  370. package/templates/pixel/cm-pixel.sh +1 -1
  371. package/templates/pixel/dev/template.html +1 -1
  372. package/templates/statusline/cm-statusline.sh +1 -1
@@ -107,8 +107,9 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
107
107
  checkContext:(payload,signal)=>call('prd_self_check',payload,signal),
108
108
  generate:(payload,signal)=>call('prd_generate',payload,signal),
109
109
  processMaterials:(payload,signal)=>call('prd_materials',payload,signal),
110
- analyze:(payload,signal)=>call('prd_analyze',payload,signal)}):null;
111
- const restoreChange=(restored=null,selected,reason)=>createPrdChange({admission,runtime,call,restored,...(selected?{selected,reason}:{})});
110
+ analyze:(payload,signal)=>call('prd_analyze',payload,signal),selfCheckRules:()=>session.selfCheckRules()}):null;
111
+ const restoreChange=(restored=null,selected,reason)=>createPrdChange({admission,runtime,call,restored,
112
+ selfCheckRules:()=>session.selfCheckRules(),...(selected?{selected,reason}:{})});
112
113
  let reviewState=null;const reviewController=new AbortController();
113
114
  let summaryState=null,publishedSummary=false;
114
115
  const summarize=createPrdSummaryOwner({summarize:(payload,signal)=>call('prd_summary',{
@@ -196,7 +197,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
196
197
  analysis.validateCurrent();
197
198
  need(summaryState!==null&&summaryState.summaryDigest===request.summaryDigest,'prd_summary_not_ready');
198
199
  need(!reviewController.signal.aborted,'cancelled');
199
- const result=publishPrdAwaitingReview({specs:admission.specs,summary:summaryState,writeEnabled:specWriteEnabled,recover:replaying});
200
+ const result=publishPrdAwaitingReview({specs:admission.specs,summary:summaryState,writeEnabled:specWriteEnabled,recover:replaying,
201
+ taskGrammar:session.versions().taskGrammar});
200
202
  // Even an uncertain status write must not be silently retried.
201
203
  publishedSummary=true;
202
204
  if(result.status==='awaiting_review')for(const phase of ['generated','awaiting_review'])
@@ -205,7 +207,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
205
207
  }
206
208
  if(request.operation==='save_draft')return (analysis.checkpoint().selfCheckRevision?savePrdDraft:analysis.status().designPromotion?.saved===true?savePrdPromotedDraft:savePrdDraft)({specs:admission.specs,
207
209
  writeEnabled:specWriteEnabled,getDraft:()=>analysis.currentDraftForSave({selfCheckRevisionSave:true}),getOriginal:()=>analysis.originalPromotedDraft(),
208
- getSelfCheckRevision:()=>analysis.checkpoint().selfCheckRevision??null,onSelfCheckRevisionSaved:()=>analysis.acceptSelfCheckRevisionSave()});
210
+ getSelfCheckRevision:()=>analysis.checkpoint().selfCheckRevision??null,onSelfCheckRevisionSaved:()=>analysis.acceptSelfCheckRevisionSave(),
211
+ selfCheckRules:session.selfCheckRules()});
209
212
  if(request.operation==='save_design')return savePrdDesign({specs:admission.specs,
210
213
  writeEnabled:specWriteEnabled,getDraft:()=>analysis.currentDesignForSave()});
211
214
  if(request.operation==='correct_findings'){
@@ -334,7 +337,9 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
334
337
  packageDigest:prepared.packageDigest,authorContextId:original.payload.authorContextId,response})};
335
338
  session.commit(checkpoint());return status();
336
339
  }
337
- }else{replaying=false;session.begin(request,checkpoint());}
340
+ }else{
341
+ // A new operation runs under the rule its session bound at creation, never the current one.
342
+ replaying=false;session.begin(request,checkpoint(),{selfCheckRules:session.versions().selfCheckRules});}
338
343
  if(!contextLogged){
339
344
  const segment=session.segment('context_load');
340
345
  record({event:'progress',phase:'start',at:contextStartedAt,data:{operation_id:'prd-context',phase_name:'context_load',segment}});
@@ -73,7 +73,7 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
73
73
  send({type:'host_result',sessionId,callId:message.callId,requestDigest:message.requestDigest,
74
74
  result:{status:'draft',summary:'Synthetic documentation draft',features:[{name:'guide',testCasesReason:'no_observable_behavior',
75
75
  documents:['requirements.md','design.md','tasks.md'].map(file=>({path:file,
76
- content:file==='requirements.md'?'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Document setup.':file==='tasks.md'?'- [ ] T-001: Update guide':'## 方案摘要\nUnreviewed synthetic design'}))}]}});continue;
76
+ content:file==='requirements.md'?'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Document setup.':file==='tasks.md'?'- [ ] T-001: Update guide\n - 范围: `README.md`':'## 方案摘要\nUnreviewed synthetic design'}))}]}});continue;
77
77
  }
78
78
  if(message.kind==='prd_materials'){
79
79
  assert.equal(mode,'materials');const source=message.payload.sources[0];
@@ -105,6 +105,8 @@ for(const mode of ['codex','claude','cancel','cases','materials','draft','self-c
105
105
  else{assert.equal(message.result.stage,'self_check_reported_passed');send({requestId:'save',operation:'save_draft'});}
106
106
  }else if(message.requestId==='save'){
107
107
  assert.equal(message.result.status,'draft_saved');assert.equal(message.result.artifacts.length,3);
108
+ // The save keeps its operation's rule, so later re-checks of these files use it.
109
+ assert.equal(JSON.parse(fs.readFileSync(path.join(dir,'.reviews/prd-guide-task-scope.json'),'utf8')).selfCheckRules,4);
108
110
  assert.equal(fs.existsSync(path.join(dir,'.cm-specs-status')),false);
109
111
  send({requestId:'package',operation:'final_review_package',stage:'split',feature:'1.guide'});
110
112
  }else if(message.requestId==='package'){
@@ -189,7 +191,7 @@ for(const known of [true,false])test(`summary without draft uses only current du
189
191
  for(const name of ['docs','mirror','1.history','2.current'])fs.mkdirSync(path.join(dir,name));
190
192
  fs.writeFileSync(path.join(dir,'docs/input.md'),'Synthetic request');
191
193
  for(const feature of ['1.history','2.current'])for(const [file,content] of Object.entries({
192
- 'requirements.md':'- [ ] [AC-001] Read guide','tasks.md':'- [ ] T-001: Guide','design.md':'# Design'}))
194
+ 'requirements.md':'- [ ] [AC-001] Read guide','tasks.md':'- [ ] T-001: Guide\n - 范围: `README.md`','design.md':'# Design'}))
193
195
  fs.writeFileSync(path.join(dir,feature,file),feature==='1.history'?content.replace('[ ]','[x]'):content,{mode:0o600});
194
196
  const entry={skillDir:path.join(root,'skills/cm-prd'),project:dir,specs:dir};
195
197
  const analysis=createCmPrdAnalysis({input:entry,runtime:'codex',record:()=>{},analyze:async()=>({
@@ -31,7 +31,7 @@ async function fixture(t){
31
31
  analyze:async()=>({status:'analyzed',summary:'Synthetic batch',sourcePaths:['docs/input.md'],openQuestions:[]}),
32
32
  generate:async()=>({status:'draft',summary:'Synthetic batch',features:['alpha','beta'].map(name=>({name,
33
33
  testCasesReason:'no_observable_behavior',documents:[{path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Explain setup.'},
34
- {path:'design.md',content:'## 方案摘要\nDocumentation'},{path:'tasks.md',content:'- [ ] T-001: Explain setup'}]}))}),checkContext:async p=>checked(p)};
34
+ {path:'design.md',content:'## 方案摘要\nDocumentation'},{path:'tasks.md',content:'- [ ] T-001: Explain setup\n - 范围: `README.md`'}]}))}),checkContext:async p=>checked(p)};
35
35
  const analysis=createCmPrdAnalysis(options);await analysis.advance('Analyze');await analysis.plan('Draft');await analysis.verify();
36
36
  savePrdDraft({specs:entry.specs,writeEnabled:true,getDraft:()=>analysis.currentDraftForSave()});
37
37
  const prepare=()=>analysis.prepareReview('split','1.alpha');
@@ -11,12 +11,14 @@ import {recordPrdHostDisposition,createPrdDispositionOwner} from '../runtime/js/
11
11
  import {createPrdCorrectionOwner,inspectPrdCorrectionRecovery,resumePrdCorrection} from '../runtime/js/cm-prd/review-correction.mjs';
12
12
  import {createPrdSummaryOwner,publishPrdAwaitingReview} from '../runtime/js/cm-prd/summary.mjs';
13
13
  import {claimPrdReview} from './cm-prd-review-gate.mjs';
14
+ import {recordPrdTaskScopes} from '../runtime/js/cm-prd/task-scope-record.mjs';
14
15
  const sha=content=>createHash('sha256').update(content).digest('hex');
15
- function fixture(t,{stage='design',finding=false,blocked=false,twoFindings=false,testCases=false}={}){
16
+ const SCOPED_TASKS='- [ ] T-001: Guide\n - 范围: `README.md`';
17
+ function fixture(t,{stage='design',finding=false,blocked=false,twoFindings=false,testCases=false,scoped=false,tasks=null,rules=null}={}){
16
18
  const specs=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-disposition-')));
17
19
  t.after(()=>fs.rmSync(specs,{recursive:true,force:true}));fs.mkdirSync(path.join(specs,'.reviews'));
18
20
  const feature='1.guide',documents=[{path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Document setup.'},
19
- {path:'design.md',content:'## 方案摘要\nDocumentation'}, {path:'tasks.md',content:'- [ ] T-001: Guide'}];
21
+ {path:'design.md',content:'## 方案摘要\nDocumentation'}, {path:'tasks.md',content:tasks??(scoped?SCOPED_TASKS:'- [ ] T-001: Guide')}];
20
22
  if(testCases)documents.push({path:'test-cases.json',content:JSON.stringify({schemaVersion:'1.0',feature:'guide',cases:[{id:'TC-001',origin:'user',kind:'logic',blocking:true,acIds:['AC-001'],taskIds:['T-001'],title:'Check guide',preconditions:[],steps:['Read'],expected:['Explained'],cleanup:[]}]})});
21
23
  const prepared=preparePrdReview({specs,stage,feature,draft:{draftDigest:'a'.repeat(64),features:[{name:'guide',directory:feature,documents}]}});
22
24
  claimPrdReview({...prepared.paths,package_sha256:prepared.packageDigest});
@@ -28,7 +30,9 @@ function fixture(t,{stage='design',finding=false,blocked=false,twoFindings=false
28
30
  examinedPaths:(stage==='design'?documents.slice(0,2):documents.slice(0,3)).map(item=>`${feature}/${item.path}`).sort(),findings,summary:'Synthetic review'}}});
29
31
  const args={specs,stage,feature,packageDigest:prepared.packageDigest,decisions:[],
30
32
  artifacts:documents.map(item=>({path:`${feature}/${item.path}`,sha256:sha(item.content)})),writeEnabled:true};
31
- const save=()=>{fs.mkdirSync(path.join(specs,feature));for(const item of documents)fs.writeFileSync(path.join(specs,feature,item.path),item.content,{mode:0o600});};
33
+ const save=()=>{fs.mkdirSync(path.join(specs,feature));for(const item of documents)fs.writeFileSync(path.join(specs,feature,item.path),item.content,{mode:0o600});
34
+ // The draft save records that these tasks carry scopes (and the saving operation's rule).
35
+ if(scoped||rules!==null)recordPrdTaskScopes(specs,[{directory:feature,name:'guide',documents}],{},rules===null?{}:{selfCheckRules:rules});};
32
36
  return {args,save,receipt:prepared.paths.receipt};
33
37
  }
34
38
  test('no-findings requires saved original artifacts and records only original receipt',t=>{
@@ -202,9 +206,23 @@ for(const mode of ['ready','design-required','missing-review','drift'])test(`hum
202
206
  }
203
207
  });
204
208
 
209
+ // A draft saved with scopes keeps them through the split correction; one saved
210
+ // before the rule (no record) is checked exactly as before.
211
+ for(const recorded of [true,false])test(`correction cannot drop a recorded task scope (record ${recorded})`,async t=>{
212
+ const {args,save}=fixture(t,{stage:'split',finding:true,scoped:true});
213
+ save();if(!recorded)fs.unlinkSync(path.join(args.specs,'.reviews/prd-guide-task-scope.json'));
214
+ const owner=createPrdCorrectionOwner({correct:async({documents})=>({
215
+ documents:documents.map(doc=>({path:doc.path,content:doc.path.endsWith('/tasks.md')?'- [ ] T-001: Guide':doc.content+(doc.path.endsWith('/design.md')?'\nClarified':'')})),
216
+ decisions:[{id:'R1',status:'applied',evidence:['Clarified'],changedPaths:['1.guide/design.md','1.guide/tasks.md']}]})});
217
+ const run=owner({specs:args.specs,stage:'split',feature:'1.guide',writeEnabled:true},new AbortController().signal);
218
+ if(recorded){await assert.rejects(run,/prd_correction_mechanics_failed/);
219
+ assert.equal(fs.readFileSync(path.join(args.specs,'1.guide/tasks.md'),'utf8'),SCOPED_TASKS);}
220
+ else assert.equal((await run).status,'correction_saved');
221
+ });
222
+
205
223
  // F2: a saved correction whose single check fails must still reach the human.
206
- async function failedCorrectionFixture(t,{mechanical=false}={}){
207
- const f=fixture(t,{stage:'split',finding:true});f.save();let calls=0;
224
+ async function failedCorrectionFixture(t,{mechanical=false,scopeDropped=false}={}){
225
+ const f=fixture(t,{stage:'split',finding:true,scoped:scopeDropped});f.save();let calls=0;
208
226
  const correction=await createPrdCorrectionOwner({correct:async({documents})=>({
209
227
  documents:documents.map(doc=>({path:doc.path,content:doc.content+(doc.path.endsWith('/design.md')?'\nCorrection':'')})),
210
228
  decisions:[{id:'R1',status:'applied',evidence:['Saved original correction'],changedPaths:['1.guide/design.md']}]
@@ -216,6 +234,12 @@ async function failedCorrectionFixture(t,{mechanical=false}={}){
216
234
  f.args.artifacts.find(a=>a.path===file).sha256=sha(fs.readFileSync(path.join(f.args.specs,file)));
217
235
  f.args.decisions[0].changedPaths.push(file);
218
236
  }
237
+ if(scopeDropped){const file='1.guide/tasks.md';
238
+ // A saved manual correction that drops the task's scope.
239
+ fs.writeFileSync(path.join(f.args.specs,file),'- [ ] T-001: Guide');
240
+ f.args.artifacts.find(a=>a.path===file).sha256=sha(fs.readFileSync(path.join(f.args.specs,file)));
241
+ f.args.decisions[0].changedPaths.push(file);
242
+ }
219
243
  const owner=createPrdDispositionOwner({checkContext:async({draft})=>{calls++;return {draftDigest:draft.draftDigest,
220
244
  features:[{directory:'1.guide',checks:draft.mechanicalSelfCheck.pending.map((id,i)=>({id,status:i===0?'failed':'passed',evidence:['Cannot prove original correction']}))}]};}});
221
245
  return {...f,owner,calls:()=>calls};
@@ -225,8 +249,96 @@ const humanSummary=()=>createPrdSummaryOwner({summarize:async({evidenceDigest})=
225
249
  contextScope:'Fixture',platformReadiness:'N/A',uiBaseline:'None',designRisk:[{feature:'1.guide',
226
250
  signals:{greenfieldAdr:false,architectureOrDataFlow:false,newRuntimeDependencyOrToolchain:false,publicContractDataOrSecurity:false,fiveOrMoreFunctions:false},evidence:['Fixture']} ]})});
227
251
 
228
- for(const mechanical of [false,true])test(`F2 failed correction reaches human and revision (mechanical ${mechanical})`,async t=>{
229
- const f=await failedCorrectionFixture(t,{mechanical}),signal=new AbortController().signal;
252
+ // The summary re-checks the saved files with the same record: a scope missing from
253
+ // a feature whose save recorded scopes blocks the human summary.
254
+ for(const recorded of [true,false])test(`summary holds a recorded feature to its task scopes (record ${recorded})`,async t=>{
255
+ const clean=fixture(t,{stage:'split'});clean.save();
256
+ if(recorded)fs.writeFileSync(path.join(clean.args.specs,'.reviews/prd-guide-task-scope.json'),
257
+ JSON.stringify({version:1,enforced:true,exempt:[]})+'\n',{mode:0o600});
258
+ assert.equal(recordPrdHostDisposition(clean.args).gate.disposition,'no_findings');
259
+ const summary=await humanSummary()(clean.args.specs);
260
+ assert.deepEqual(summary.blockers,recorded?['mechanical_self_check_failed']:[]);
261
+ if(recorded)assert.deepEqual(summary.mechanicalSelfCheck.findings.map(item=>item.code),['task_scope_missing']);
262
+ });
263
+
264
+ // R1-03: a draft saved under rule 4 keeps its session-task checks through the
265
+ // split correction, the disposition's check and the summary; a draft saved under
266
+ // rule 3 (or before any record) keeps reading `开发: 会话` as prose.
267
+ const SESSION_TASKS=['- [ ] T-001: Guide',' - 范围: `README.md`','- [ ] T-002: Walk',' - 范围: `docs/qa.md`',' - 开发: 会话'].join('\n');
268
+ const SESSION_MARKS={kept:SESSION_TASKS,
269
+ 'not-final':SESSION_TASKS.replace('\n - 开发: 会话','').replace('`README.md`','`README.md`\n - 开发: 会话'),
270
+ multiple:SESSION_TASKS.replace('`README.md`','`README.md`\n - 开发: 会话')};
271
+ for(const rules of [4,3,null])for(const [mode,tasks] of Object.entries(SESSION_MARKS))
272
+ test(`correction keeps the session-task rule its save recorded (rules ${rules}, ${mode})`,async t=>{
273
+ const {args,save}=fixture(t,{stage:'split',finding:true,tasks:SESSION_TASKS,rules});save();
274
+ const owner=createPrdCorrectionOwner({correct:async({documents})=>({
275
+ documents:documents.map(doc=>({path:doc.path,content:doc.path.endsWith('/tasks.md')?tasks:doc.content+(doc.path.endsWith('/design.md')?'\nClarified':'')})),
276
+ decisions:[{id:'R1',status:'applied',evidence:['Clarified'],changedPaths:['1.guide/design.md',...(mode==='kept'?[]:['1.guide/tasks.md'])]}]})});
277
+ const run=owner({specs:args.specs,stage:'split',feature:'1.guide',writeEnabled:true},new AbortController().signal);
278
+ if(rules===4&&mode!=='kept'){await assert.rejects(run,/prd_correction_mechanics_failed/);
279
+ assert.equal(fs.readFileSync(path.join(args.specs,'1.guide/tasks.md'),'utf8'),SESSION_TASKS);}
280
+ else{assert.equal((await run).status,'correction_saved');
281
+ assert.equal(fs.readFileSync(path.join(args.specs,'1.guide/tasks.md'),'utf8'),tasks);}
282
+ });
283
+ for(const rules of [4,3])test(`disposition and summary re-check under the rule the save recorded (rules ${rules})`,async t=>{
284
+ const f=fixture(t,{stage:'split',finding:true,tasks:SESSION_TASKS,rules});f.save();
285
+ const correction=await createPrdCorrectionOwner({correct:async({documents})=>({
286
+ documents:documents.map(doc=>({path:doc.path,content:doc.content+(doc.path.endsWith('/design.md')?'\nCorrection':'')})),
287
+ decisions:[{id:'R1',status:'applied',evidence:['Saved original correction'],changedPaths:['1.guide/design.md']}]
288
+ })})({...f.args},new AbortController().signal);
289
+ Object.assign(f.args,structuredClone({decisions:correction.decisions,artifacts:correction.artifacts}));
290
+ // A saved manual correction that moves the session mark off the final task.
291
+ const file='1.guide/tasks.md';fs.writeFileSync(path.join(f.args.specs,file),SESSION_MARKS['not-final']);
292
+ f.args.artifacts.find(a=>a.path===file).sha256=sha(fs.readFileSync(path.join(f.args.specs,file)));
293
+ f.args.decisions[0].changedPaths.push(file);
294
+ let calls=0;
295
+ const owner=createPrdDispositionOwner({checkContext:async({draft})=>{calls++;return {draftDigest:draft.draftDigest,
296
+ features:[{directory:'1.guide',checks:draft.mechanicalSelfCheck.pending.map(id=>({id,status:'passed',evidence:['Fixture']}))}]};}});
297
+ const result=await owner(f.args,new AbortController().signal);
298
+ // The check input keeps the policy it ran under, as it keeps taskScopes.
299
+ assert.deepEqual(JSON.parse(fs.readFileSync(f.receipt)).correction_check?.input.draft.sessionTasks,rules===4?['1.guide']:undefined);
300
+ const summary=await humanSummary()(f.args.specs);
301
+ if(rules===4){
302
+ assert.equal(result.gate.disposition,'self_check_failed');assert.equal(calls,0);
303
+ assert.deepEqual(result.mechanicalSelfCheck.findings.map(item=>item.code),['session_task_not_final']);
304
+ // The failed check reaches the human as such, verified under the rule it ran under.
305
+ assert.equal(summary.riskCard[0].status,'awaiting_human_ruling');
306
+ assert.match(summary.details.risks,/session_task_not_final/);
307
+ }else{
308
+ assert.equal(result.gate.disposition,'applied');assert.equal(calls,1);
309
+ assert.deepEqual(summary.blockers,[]);assert.doesNotMatch(JSON.stringify(summary),/session_task/);
310
+ }
311
+ });
312
+ for(const rules of [4,3])test(`summary holds a rule-4 save to its session-task checks (rules ${rules})`,async t=>{
313
+ const clean=fixture(t,{stage:'split',tasks:SESSION_MARKS.multiple,rules});clean.save();
314
+ assert.equal(recordPrdHostDisposition(clean.args).gate.disposition,'no_findings');
315
+ const summary=await humanSummary()(clean.args.specs);
316
+ assert.deepEqual(summary.blockers,rules===4?['mechanical_self_check_failed']:[]);
317
+ assert.deepEqual(summary.mechanicalSelfCheck.findings.map(item=>item.code),rules===4?['session_task_multiple']:[]);
318
+ });
319
+
320
+ // Evidence recorded before the scope policy joined the check input (no taskScopes)
321
+ // still verifies, without options or under the record on disk.
322
+ test('F2 legacy failed-check evidence without taskScopes still verifies',async t=>{
323
+ const {digest}=await import('../runtime/js/cm-ai/effect-contract.mjs');
324
+ const {inspectPrdFailedCorrection}=await import('../runtime/js/cm-prd/failed-correction.mjs');
325
+ const f=await failedCorrectionFixture(t,{scopeDropped:true});await f.owner(f.args,new AbortController().signal);
326
+ const reviews=path.join(f.args.specs,'.reviews'),rewrite=(name,value)=>fs.writeFileSync(path.join(reviews,name),JSON.stringify(value)+'\n',{mode:0o600});
327
+ const receipt=JSON.parse(fs.readFileSync(f.receipt)),input=receipt.correction_check.input;
328
+ assert.ok(input.draft.taskScopes);delete input.draft.taskScopes;
329
+ const start={...JSON.parse(fs.readFileSync(path.join(reviews,'prd-guide-split-correction-check-start.json'))),inputDigest:digest(input)};
330
+ const result={...JSON.parse(fs.readFileSync(path.join(reviews,'prd-guide-split-correction-check-result.json'))),startDigest:digest(start)};
331
+ rewrite('prd-guide-split-correction-check-start.json',start);rewrite('prd-guide-split-correction-check-result.json',result);
332
+ receipt.correction_check.resultDigest=digest(result);
333
+ assert.equal(inspectPrdFailedCorrection({specs:f.args.specs,receipt}).status,'failed');
334
+ // The legacy path still binds the exact report: a changed finding is refused.
335
+ const forged=structuredClone(receipt);forged.correction_check.input.draft.mechanicalSelfCheck.findings[0].reason.tasks=['T-009'];
336
+ assert.throws(()=>inspectPrdFailedCorrection({specs:f.args.specs,receipt:forged}),/prd_failed_check_binding|prd_check_inputs_changed/);
337
+ });
338
+
339
+ for(const mode of [false,true,'scope'])test(`F2 failed correction reaches human and revision (mechanical ${mode})`,async t=>{
340
+ const mechanical=mode!==false;
341
+ const f=await failedCorrectionFixture(t,{mechanical:mode===true,scopeDropped:mode==='scope'}),signal=new AbortController().signal;
230
342
  const result=await f.owner(f.args,signal);
231
343
  assert.equal(result.status,'disposition_recorded');assert.equal(result.gate.disposition,'self_check_failed');
232
344
  assert.equal(result.next,'prepare_human_summary_with_failed_checks');assert.equal(result.completionAuthorized,false);
@@ -234,6 +346,9 @@ for(const mechanical of [false,true])test(`F2 failed correction reaches human an
234
346
  const before=files.map(n=>fs.readFileSync(path.join(f.args.specs,'.reviews',n)));
235
347
  const receipt=fs.readFileSync(f.receipt),value=JSON.parse(receipt);
236
348
  assert.deepEqual(value.correction_check.input.decisions,f.args.decisions);
349
+ // A later save may rewrite the scope record; the failed check keeps the policy it ran under.
350
+ const record=path.join(f.args.specs,'.reviews/prd-guide-task-scope.json'),recordBytes=mode==='scope'?fs.readFileSync(record):null;
351
+ if(mode==='scope')fs.writeFileSync(record,JSON.stringify({version:1,enforced:true,exempt:['T-001']})+'\n',{mode:0o600});
237
352
  const summary=await humanSummary()(f.args.specs);
238
353
  assert.equal(summary.readyForAwaitingReview,true);assert.deepEqual(summary.blockers,[]);
239
354
  assert.equal(summary.features[0].reviews.split.correctionSelfCheck.status,'failed');
@@ -241,8 +356,9 @@ for(const mechanical of [false,true])test(`F2 failed correction reaches human an
241
356
  assert.equal(summary.riskCard[0].status,'awaiting_human_ruling');
242
357
  assert.ok(summary.riskCard[0].failedChecks.length>0);
243
358
  assert.match(summary.details.risks,/自检失败.*待人工裁决/);
244
- assert.match(summary.details.risks,mechanical?/new_task_not_pending/:/Cannot prove original correction/);
359
+ assert.match(summary.details.risks,mode==='scope'?/task_scope_missing/:mechanical?/new_task_not_pending/:/Cannot prove original correction/);
245
360
  assert.equal(publishPrdAwaitingReview({specs:f.args.specs,summary,writeEnabled:true}).status,'awaiting_review');
361
+ if(mode==='scope')fs.writeFileSync(record,recordBytes,{mode:0o600});
246
362
  const {assertPrdReviewsSettled}=await import('../runtime/js/cm-prd/change.mjs');
247
363
  assert.doesNotThrow(()=>assertPrdReviewsSettled(f.args.specs,['1.guide'],{requireSplit:true}));
248
364
  assert.equal((await f.owner(f.args,signal)).gate.disposition,'self_check_failed');
@@ -16,7 +16,7 @@ for(const mode of ['repair','limit','scope'])test(`bounded self-check revision:
16
16
  drafts++;assert.equal(payload.revision===null,drafts===1);
17
17
  return {status:'draft',summary:'Guide',features:[{name:mode==='scope'&&drafts===2?'outside':'guide',testCasesReason:'no_observable_behavior',
18
18
  documents:[{path:'requirements.md',content:'- [ ] [AC-001] Document setup.'},
19
- {path:'tasks.md',content:'- [ ] T-001: Update guide'},{path:'design.md',content:`# Design v${drafts}`}]}]};
19
+ {path:'tasks.md',content:'- [ ] T-001: Update guide\n - 范围: `README.md`'},{path:'design.md',content:`# Design v${drafts}`}]}]};
20
20
  },checkContext:async({draft})=>{
21
21
  checks++;return {draftDigest:draft.draftDigest,features:draft.features.map(feature=>({directory:feature.directory,
22
22
  checks:draft.mechanicalSelfCheck.pending.map((id,index)=>({id,status:index===0&&(checks===1||mode==='limit')?'failed':'passed',
@@ -41,7 +41,7 @@ async function fixture(t,{fail=true,lowRisk=false,mechanical=false,allLowRisk=fa
41
41
  {path:'design.md',content:'## 方案摘要\nGuide architecture'}]}))};
42
42
  return transform({status:'draft',summary:'Tasks',features:payload.acceptedDesign.features.map(f=>({name:f.name,
43
43
  testCasesReason:'no_observable_behavior',documents:[...structuredClone(f.documents),{path:'tasks.md',content:mechanical&&payload.revision===null?
44
- '- [x] T-001: Invalid completed task':'- [ ] T-001: Update guide'}]}))},payload);
44
+ '- [x] T-001: Invalid completed task':'- [ ] T-001: Update guide\n - 范围: `README.md`'}]}))},payload);
45
45
  }};
46
46
  const review=async(stage,feature='1.guide',finding=false)=>{
47
47
  const prepare=()=>host.prepareReview(stage,feature);
@@ -300,3 +300,18 @@ test('saving after an unchanged feature split preserves pending revised features
300
300
  const f=await regenerate(await fixture(t));f.save();f.dispose(await f.review('split','2.second'));
301
301
  assert.equal(f.save().status,'draft_saved');await finish(f);assert.doesNotThrow(()=>f.host.validateCurrent());
302
302
  });
303
+
304
+ // 2026-10-12 交叉审查 P2:历史 feature 带自检修订记录时,摘要还会经 inspectPrdSplitDesign 再查同一旧拆分回执。
305
+ test('historical feature with a self-check revision is registered after a later approved change; current stays strict',async t=>{
306
+ const f=await regenerate(await fixture(t));await finish(f);
307
+ assert.doesNotThrow(()=>inspectPrdSummaryEvidence(f.specs,{currentFeatures:['1.guide','2.second']}));
308
+ fs.appendFileSync(path.join(f.specs,'1.guide/requirements.md'),'\nLater approved change');
309
+ const evidence=inspectPrdSummaryEvidence(f.specs,{currentFeatures:['2.second']});
310
+ const guide=evidence.features.find(item=>item.directory==='1.guide');
311
+ assert.equal(guide.historical,true);assert.equal(guide.reviews.split.archive,'unavailable');
312
+ assert.match(guide.reviews.split.reason,/^prd_review_artifact_changed; self_check_revision:\S+$/);
313
+ assert.ok(evidence.evidenceFiles.some(item=>item.path==='.reviews/prd-guide-self-check-revision.json'));
314
+ assert.equal(evidence.features.find(item=>item.directory==='2.second').reviews.split.gate.outcome,'completed');
315
+ assert.throws(()=>inspectPrdSummaryEvidence(f.specs,{currentFeatures:['1.guide','2.second']}),{code:'prd_review_artifact_changed'});
316
+ assert.throws(()=>inspectPrdSummaryEvidence(f.specs),{code:'prd_review_artifact_changed'});
317
+ });
@@ -0,0 +1,239 @@
1
+ // Which self-check rule a draft is judged under. A reply registered by an
2
+ // operation that began before rules were recorded is replayed under rule 1.
3
+ import test,{after} from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {createCmPrdAnalysis} from '../runtime/js/cm-prd/analysis.mjs';
10
+ import {openPrdSession,prdSessionVersions} from '../runtime/js/cm-prd/session.mjs';
11
+ import {PRD_SELF_CHECK_RULES,PRD_SELF_CHECK_RULE_VERSIONS,checkPrdDraftMechanics,matchesPrdDraftMechanics} from '../runtime/js/cm-prd/self-check.mjs';
12
+ import {recordPrdTaskScopes,prdTaskScopeOptions} from '../runtime/js/cm-prd/task-scope-record.mjs';
13
+ import {TASK_GRAMMAR} from '../runtime/js/spec-task-line.mjs';
14
+ const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
15
+ const isolatedHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-rules-home-'));
16
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedHome,'user');
17
+ after(()=>fs.rmSync(isolatedHome,{recursive:true,force:true}));
18
+ function specs(t){
19
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-prd-rules-')));
20
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
21
+ fs.mkdirSync(path.join(dir,'docs'));fs.writeFileSync(path.join(dir,'docs/input.md'),'Synthetic requirement');
22
+ return {dir,entry:{skillDir:path.join(root,'skills/cm-prd'),project:dir,specs:dir}};
23
+ }
24
+ // A legal T-001 plus a line rule 1 skips and rule 2 rejects.
25
+ const reply={status:'draft',summary:'Synthetic',features:[{name:'guide',testCasesReason:'no_observable_behavior',documents:[
26
+ {path:'requirements.md',content:'## 功能需求\n1. [F-001] Guide\n- [ ] [AC-001] Explain setup.'},
27
+ {path:'design.md',content:'## 方案摘要\nDocumentation'},
28
+ {path:'tasks.md',content:'- [ ] T-001: Explain setup\n- [ ] T-002/a: Hidden task'}]}]};
29
+ async function planned(t,options={}){
30
+ const {entry}=specs(t);
31
+ const analysis=createCmPrdAnalysis({input:entry,runtime:'codex',record:()=>{},
32
+ analyze:async()=>({status:'analyzed',summary:'Synthetic',sourcePaths:['docs/input.md'],openQuestions:[]}),
33
+ generate:async()=>structuredClone(reply),...options});
34
+ await analysis.advance('Analyze');return analysis.plan('Draft');
35
+ }
36
+ test('a fresh draft round is judged under rule 2 by default',async t=>{
37
+ const status=await planned(t);
38
+ assert.equal(status.stage,'draft_self_check_failed');
39
+ assert.ok(status.draft.mechanicalSelfCheck.findings.some(item=>item.code==='tasks_invalid'));
40
+ });
41
+ test('a draft replayed for an operation begun under rule 1 is judged as then',async t=>{
42
+ const status=await planned(t,{selfCheckRules:()=>1});
43
+ assert.equal(status.stage,'draft_ready');
44
+ });
45
+ test('an operation records its rule; one recorded before rules existed reports rule 1',t=>{
46
+ const {dir,entry}=specs(t);const sessionId='prd-rules-fixture',identity={entry,runtime:'codex'};
47
+ const open=()=>openPrdSession({specs:dir,sessionId,identity});
48
+ let session=open();
49
+ try{assert.equal(session.selfCheckRules(),1);
50
+ session.begin({requestId:'r1',operation:'plan'},null,{selfCheckRules:PRD_SELF_CHECK_RULES});
51
+ assert.equal(session.selfCheckRules(),PRD_SELF_CHECK_RULES);}finally{session.close();}
52
+ session=open();try{assert.equal(session.selfCheckRules(),PRD_SELF_CHECK_RULES);
53
+ assert.equal(session.replay().selfCheckRules,PRD_SELF_CHECK_RULES);}finally{session.close();}
54
+ // The state an older host left: the same operation without the field.
55
+ const file=path.join(dir,'.reviews/prd-sessions',sessionId,'state.json');
56
+ const state=JSON.parse(fs.readFileSync(file,'utf8'));delete state.active.selfCheckRules;
57
+ fs.writeFileSync(file,JSON.stringify(state));
58
+ session=open();try{assert.equal(session.selfCheckRules(),1);assert.equal(session.replay().request.requestId,'r1');}
59
+ finally{session.close();}
60
+ });
61
+ test('the host binds both draft entries to the operation rule',()=>{
62
+ const host=fs.readFileSync(path.join(root,'scripts/cm-prd-host.mjs'),'utf8');
63
+ assert.match(host,/session\.begin\(request,checkpoint\(\),\{selfCheckRules:session\.versions\(\)\.selfCheckRules\}\)/);
64
+ assert.doesNotMatch(host,/PRD_SELF_CHECK_RULES/,'a new operation never re-reads the current rule');
65
+ assert.match(host,/publishPrdAwaitingReview\(\{[^}]*taskGrammar:session\.versions\(\)\.taskGrammar\}\)/);
66
+ const drive=fs.readFileSync(path.join(root,'scripts/cm-prd-drive.mjs'),'utf8');
67
+ assert.match(drive,/ctx\.state\.active\?\.selfCheckRules\?\?1:prdSessionVersions\(ctx\.state,ctx\.specs\)\.selfCheckRules/);
68
+ assert.equal([...host.matchAll(/selfCheckRules:\(\)=>session\.selfCheckRules\(\)/g)].length,2);
69
+ const change=fs.readFileSync(path.join(root,'runtime/js/cm-prd/change.mjs'),'utf8');
70
+ assert.match(change,/inspectPrdChangeProposal\(state\.before,response,state\.selected,config,\{rules:selfCheckRules\(\)\}\)/);
71
+ });
72
+
73
+ // Design 3.7: a session binds the task grammar and self-check rule when it is created;
74
+ // they govern only operations it starts later.
75
+ const stateFile=(dir,sessionId)=>path.join(dir,'.reviews/prd-sessions',sessionId,'state.json');
76
+ const created=open=>{const session=open();try{session.segment('context_load');}finally{session.close();}};
77
+ const edit=(file,change)=>{const state=JSON.parse(fs.readFileSync(file,'utf8'));change(state);fs.writeFileSync(file,JSON.stringify(state),{mode:0o600});};
78
+ test('a new session records the current task grammar and self-check rule',t=>{
79
+ const {dir,entry}=specs(t),sessionId='prd-bound-fixture',session=openPrdSession({specs:dir,sessionId,identity:{entry,runtime:'codex'}});
80
+ // Written with the first saved state (nothing is persisted before that).
81
+ try{assert.deepEqual(session.versions(),{taskGrammar:TASK_GRAMMAR,selfCheckRules:PRD_SELF_CHECK_RULES});session.segment('context_load');}
82
+ finally{session.close();}
83
+ const state=JSON.parse(fs.readFileSync(stateFile(dir,sessionId),'utf8'));
84
+ assert.equal(state.taskGrammar,TASK_GRAMMAR);assert.equal(state.selfCheckRules,PRD_SELF_CHECK_RULES);
85
+ assert.deepEqual(prdSessionVersions(null),{taskGrammar:TASK_GRAMMAR,selfCheckRules:PRD_SELF_CHECK_RULES});
86
+ });
87
+ test('a session created before the fields existed keeps the literal grammar 2 and rule 3, unrewritten',t=>{
88
+ const {dir,entry}=specs(t),sessionId='prd-legacy-fixture',open=()=>openPrdSession({specs:dir,sessionId,identity:{entry,runtime:'codex'}});
89
+ created(open);edit(stateFile(dir,sessionId),state=>{delete state.taskGrammar;delete state.selfCheckRules;});
90
+ const session=open();
91
+ try{assert.deepEqual(session.versions(),{taskGrammar:2,selfCheckRules:3});
92
+ session.begin({requestId:'r1',operation:'plan'},null,{selfCheckRules:session.versions().selfCheckRules});
93
+ assert.equal(session.selfCheckRules(),3);}finally{session.close();}
94
+ const state=JSON.parse(fs.readFileSync(stateFile(dir,sessionId),'utf8'));
95
+ assert.equal(Object.hasOwn(state,'taskGrammar')||Object.hasOwn(state,'selfCheckRules'),false,'an old session is not upgraded');
96
+ assert.deepEqual(prdSessionVersions(state),{taskGrammar:2,selfCheckRules:3});
97
+ });
98
+ test('an active operation keeps its own rule over the session binding; one without a rule replays rule 1',t=>{
99
+ const {dir,entry}=specs(t),sessionId='prd-active-fixture',open=()=>openPrdSession({specs:dir,sessionId,identity:{entry,runtime:'codex'}});
100
+ let session=open();
101
+ try{session.begin({requestId:'r1',operation:'plan'},null,{selfCheckRules:2});}finally{session.close();}
102
+ session=open();try{assert.equal(session.selfCheckRules(),2);assert.equal(session.versions().selfCheckRules,PRD_SELF_CHECK_RULES);}
103
+ finally{session.close();}
104
+ edit(stateFile(dir,sessionId),state=>{delete state.active.selfCheckRules;});
105
+ session=open();try{assert.equal(session.selfCheckRules(),1);}finally{session.close();}
106
+ });
107
+ test('a session binding outside the known versions is refused',t=>{
108
+ const {dir,entry}=specs(t),sessionId='prd-invalid-fixture',open=()=>openPrdSession({specs:dir,sessionId,identity:{entry,runtime:'codex'}});
109
+ created(open);
110
+ for(const change of [state=>{delete state.taskGrammar;},state=>{state.taskGrammar=1;},state=>{state.taskGrammar=TASK_GRAMMAR+1;},
111
+ state=>{state.selfCheckRules=PRD_SELF_CHECK_RULES+1;},state=>{state.selfCheckRules='3';}]){
112
+ const file=stateFile(dir,sessionId),bytes=fs.readFileSync(file);edit(file,change);
113
+ assert.throws(open,/prd_session_versions_invalid/);fs.writeFileSync(file,bytes,{mode:0o600});
114
+ }
115
+ open().close();
116
+ });
117
+ test('the historical rule set lists rule 3 explicitly, so raising the current rule keeps it',()=>{
118
+ for(const rules of [3,2,1,PRD_SELF_CHECK_RULES])assert.ok(PRD_SELF_CHECK_RULE_VERSIONS.includes(rules));
119
+ assert.equal(new Set(PRD_SELF_CHECK_RULE_VERSIONS).size,PRD_SELF_CHECK_RULE_VERSIONS.length);
120
+ const source=fs.readFileSync(path.join(root,'runtime/js/cm-prd/self-check.mjs'),'utf8');
121
+ assert.match(source,/new Set\(\[PRD_SELF_CHECK_RULES,3,2,1\]\)/);
122
+ assert.doesNotMatch(source,/\[PRD_SELF_CHECK_RULES,2,1\]|\[1,2,PRD_SELF_CHECK_RULES\]/);
123
+ });
124
+
125
+ test('a new session binds grammar 3 only where the specs directory has none or grammar 3; earlier grammars keep 2/3',t=>{
126
+ const write=(dir,status)=>fs.writeFileSync(path.join(dir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[],specFiles:[],approval:{response:'开始',at:'2026-10-27T00:00:00.000Z'},...status})+'\n');
127
+ const fresh=specs(t).dir;
128
+ assert.deepEqual(prdSessionVersions(null,fresh),{taskGrammar:TASK_GRAMMAR,selfCheckRules:PRD_SELF_CHECK_RULES});
129
+ const g3=specs(t).dir;write(g3,{taskGrammar:3});
130
+ assert.deepEqual(prdSessionVersions(null,g3),{taskGrammar:3,selfCheckRules:PRD_SELF_CHECK_RULES});
131
+ const g2=specs(t).dir;write(g2,{taskGrammar:2});
132
+ assert.deepEqual(prdSessionVersions(null,g2),{taskGrammar:2,selfCheckRules:3});
133
+ const g1=specs(t).dir;write(g1,{});
134
+ assert.deepEqual(prdSessionVersions(null,g1),{taskGrammar:2,selfCheckRules:3});
135
+ const {dir,entry}=specs(t);write(dir,{taskGrammar:2});
136
+ const session=openPrdSession({specs:dir,sessionId:'prd-g2-fixture',identity:{entry,runtime:'codex'}});
137
+ session.checkpoint(null);
138
+ const state=JSON.parse(fs.readFileSync(path.join(dir,'.reviews/prd-sessions/prd-g2-fixture/state.json'),'utf8'));
139
+ assert.deepEqual([state.taskGrammar,state.selfCheckRules],[2,3]);
140
+ });
141
+ test('rule 4 refuses a task that waits for the session task, directly or transitively',()=>{
142
+ const draft=deps=>({draftDigest:'d'.repeat(64),features:[{directory:'1.walk',name:'walk',documents:[
143
+ {path:'requirements.md',content:'## 功能需求\n1. [F-001] Walk\n- [ ] [AC-001] Walk it.'},
144
+ {path:'design.md',content:'## 方案摘要\nx'},
145
+ {path:'tasks.md',content:['- [ ] T-001: Build',' - 范围: `src/a.js`','- [ ] T-002: Wire',' - 范围: `src/b.js`',
146
+ '- [ ] T-003: Walk',' - 范围: `docs/qa.md`',' - 开发: 会话','','## 依赖关系',...deps,''].join('\n')}]}]});
147
+ const session=(deps,rules=4)=>checkPrdDraftMechanics(draft(deps),{rules}).findings.filter(item=>item.code.startsWith('session_task'));
148
+ // The reviewed counterexample: dependencies are legal and T-003 is declared last, yet it would run first.
149
+ const direct=session(['- T-001 依赖 T-003']);
150
+ assert.deepEqual(direct.map(item=>[item.code,item.reason.dependents]),[['session_task_depended_on',['T-001']]]);
151
+ const transitive=session(['- T-001 依赖 T-002','- T-002 依赖 T-003']);
152
+ assert.deepEqual(transitive.map(item=>[item.code,item.reason.dependents]),[['session_task_depended_on',['T-001','T-002']]]);
153
+ // The session task waiting for the others, last of all, is the intended shape.
154
+ assert.deepEqual(session(['- T-002 依赖 T-001','- T-003 依赖 T-002']),[]);
155
+ assert.deepEqual(session(['- T-001 依赖 T-003'],3),[],'rule 3 keeps 开发: as prose');
156
+ });
157
+ test('rule 4 reads the developer mark and checks session tasks; rules 1-3 keep it as prose',()=>{
158
+ const tasks=['- [ ] T-001: Build',' - 范围: `src/a.js`',' - 开发: 会话','- [ ] T-002: Walk',' - 范围: `docs/qa.md`','','## 依赖关系','- T-002 依赖 T-001',''].join('\n');
159
+ const draft={draftDigest:'d'.repeat(64),features:[{directory:'1.walk',name:'walk',documents:[
160
+ {path:'requirements.md',content:'## 功能需求\n1. [F-001] Walk\n- [ ] [AC-001] Walk it.'},
161
+ {path:'design.md',content:'## 方案摘要\nx'},{path:'tasks.md',content:tasks}]}]};
162
+ const codes=rules=>checkPrdDraftMechanics(draft,{rules}).findings.map(item=>item.code);
163
+ assert.ok(codes(4).includes('session_task_not_final'),'grammar 3 sees a session task that is not last');
164
+ for(const rules of [3,2])assert.ok(!codes(rules).some(code=>code.startsWith('session_task')),`rule ${rules} keeps 开发: as prose`);
165
+ assert.ok(!codes(3).includes('task_scope_invalid'),'rule 3 does not reject the line it predates');
166
+ const bad=structuredClone(draft);bad.features[0].documents[2].content=tasks.replace('开发: 会话','开发: 外包');
167
+ const badCodes=rules=>checkPrdDraftMechanics(bad,{rules}).findings.map(item=>item.code);
168
+ assert.ok(badCodes(4).includes('task_scope_invalid'),'grammar 3 rejects an unknown developer value');
169
+ assert.ok(!badCodes(3).includes('task_scope_invalid'),'rule 3 reads tasks.md as grammar 2, where the line is prose');
170
+ });
171
+
172
+ // R2-03: a re-check that carries only `sessionTasks` (no scope record) still rejects the
173
+ // 开发 line's own grammar errors, without the rest of rule 3's scope check.
174
+ test('a sessionTasks-only re-check reports a bad, repeated or stray developer line',()=>{
175
+ const draft=lines=>({draftDigest:'d'.repeat(64),features:[{directory:'1.walk',name:'walk',documents:[
176
+ {path:'requirements.md',content:'## 功能需求\n1. [F-001] Walk\n- [ ] [AC-001] Walk it.'},
177
+ {path:'design.md',content:'## 方案摘要\nx'},{path:'tasks.md',content:[...lines,''].join('\n')}]}]});
178
+ const invalid=(lines,options)=>checkPrdDraftMechanics(draft(lines),options).findings.filter(item=>item.code==='task_scope_invalid');
179
+ const only={rules:1,sessionTasks:['1.walk']};
180
+ // T-001 has no scope at all: the scope check stays off, so only the 开发 line can fail.
181
+ const valid=['- [ ] T-001: Build','- [ ] T-002: Walk',' - 开发: 会话'];
182
+ assert.deepEqual(invalid(valid,only),[]);
183
+ for(const [lines,message] of [
184
+ [['- [ ] T-001: Build','- [ ] T-002: Walk',' - 开发: 外包'],'开发只能写'],
185
+ [['- [ ] T-001: Build','- [ ] T-002: Walk',' - 开发: 会话',' - 开发: 会话'],'重复'],
186
+ [['- 开发: 会话','- [ ] T-001: Build'],'不在任何任务行下面']]){
187
+ for(const options of [only,{...only,rules:2}]){
188
+ const found=invalid(lines,options);
189
+ assert.equal(found.length,1,`${lines.join(' / ')} rules ${options.rules}`);
190
+ assert.match(found[0].reason.problems.join('\n'),new RegExp(message));
191
+ }
192
+ assert.deepEqual(invalid(lines,{rules:1}),[],'without the rule-4 record the line stays prose');
193
+ }
194
+ // With the scope record too, the scope check reports it once, not twice.
195
+ const both=invalid(['- [ ] T-001: Build',' - 范围: `src/a.js`','- [ ] T-002: Walk',' - 范围: `docs/qa.md`',' - 开发: 外包'],
196
+ {...only,scopes:{'1.walk':{exempt:[]}}});
197
+ assert.equal(both.length,1);
198
+ assert.equal(both[0].reason.problems.length,1);
199
+ });
200
+
201
+ // R1-03: re-checks of saved files (correction, disposition, summary, driver) run
202
+ // outside the saving operation; the task-scope record carries a rule-4 save's rule.
203
+ test('a save records rule 4 for the re-checks; an earlier rule or an operation without a rule keeps the old record',t=>{
204
+ const {dir,entry}=specs(t),sessionId='prd-record-fixture',open=()=>openPrdSession({specs:dir,sessionId,identity:{entry,runtime:'codex'}});
205
+ const tasks=['- [ ] T-001: Build',' - 范围: `src/a.js`','- [ ] T-002: Walk',' - 范围: `docs/qa.md`',' - 开发: 会话',''].join('\n');
206
+ const feature=content=>({directory:'1.walk',name:'walk',documents:[
207
+ {path:'requirements.md',content:'## 功能需求\n1. [F-001] Walk\n- [ ] [AC-001] Walk it.'},
208
+ {path:'design.md',content:'## 方案摘要\nx'},{path:'tasks.md',content}]});
209
+ const moved=tasks.replace('\n - 开发: 会话','').replace('`src/a.js`','`src/a.js`\n - 开发: 会话');
210
+ const second=tasks.replace('`src/a.js`','`src/a.js`\n - 开发: 会话');
211
+ const record=path.join(dir,'.reviews/prd-walk-task-scope.json');
212
+ const recheck=content=>checkPrdDraftMechanics({draftDigest:'d'.repeat(64),features:[feature(content)]},prdTaskScopeOptions(dir,'1.walk'))
213
+ .findings.map(item=>item.code);
214
+ const save=()=>{const session=open();try{recordPrdTaskScopes(dir,[feature(tasks)],{},{selfCheckRules:session.selfCheckRules()});}finally{session.close();}};
215
+ let session=open();
216
+ try{session.begin({requestId:'r1',operation:'save_draft'},null,{selfCheckRules:session.versions().selfCheckRules});}finally{session.close();}
217
+ save();
218
+ assert.deepEqual(JSON.parse(fs.readFileSync(record,'utf8')),{version:1,enforced:true,exempt:[],selfCheckRules:4});
219
+ assert.deepEqual(prdTaskScopeOptions(dir,'1.walk'),{scopes:{'1.walk':{exempt:[]}},sessionTasks:['1.walk']});
220
+ assert.deepEqual(recheck(tasks),[]);
221
+ assert.deepEqual(recheck(moved),['session_task_not_final']);
222
+ assert.deepEqual(recheck(second),['session_task_multiple']);
223
+ // The bound options add nothing to a rule-4 report, so recorded reports still match.
224
+ const draft={draftDigest:'d'.repeat(64),features:[feature(moved)]};
225
+ assert.ok(matchesPrdDraftMechanics(draft,checkPrdDraftMechanics(draft,{rules:4}),prdTaskScopeOptions(dir,'1.walk')));
226
+ // The state an older host left: the active operation without a rule saves as rule 1, the old record.
227
+ edit(stateFile(dir,sessionId),state=>{delete state.active.selfCheckRules;});
228
+ save();
229
+ assert.equal(fs.readFileSync(record,'utf8'),JSON.stringify({version:1,enforced:true,exempt:[]})+'\n');
230
+ assert.deepEqual(prdTaskScopeOptions(dir,'1.walk'),{scopes:{'1.walk':{exempt:[]}}});
231
+ for(const content of [moved,second])assert.deepEqual(recheck(content),[]);
232
+ // Rule 3 adds nothing beyond the scope record, so its save keeps the old bytes too.
233
+ recordPrdTaskScopes(dir,[feature(tasks)],{},{selfCheckRules:3});
234
+ assert.equal(fs.readFileSync(record,'utf8'),JSON.stringify({version:1,enforced:true,exempt:[]})+'\n');
235
+ for(const value of [3,5,'4']){
236
+ fs.writeFileSync(record,JSON.stringify({version:1,enforced:true,exempt:[],selfCheckRules:value})+'\n',{mode:0o600});
237
+ assert.throws(()=>prdTaskScopeOptions(dir,'1.walk'),/prd_task_scope_record_invalid/);
238
+ }
239
+ });