@aibyzero/cm-workflow 0.16.4 → 0.16.6

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 (283) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +22 -0
  3. package/CHANGELOG.md +57 -0
  4. package/README.md +22 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +48 -7
  17. package/docs/js-workflow-control.md +293 -33
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/runtime-failover.md +1 -1
  21. package/docs/untested-branches.md +27 -4
  22. package/docs/user-guide.md +23 -8
  23. package/install-codex.sh +28 -11
  24. package/package.json +1 -1
  25. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  26. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  27. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  28. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  29. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  30. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  31. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  32. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +208 -34
  33. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  34. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  35. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +181 -57
  36. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +15 -58
  37. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  38. package/runtime/js/cm-ai/codex-review-adapter.mjs +56 -17
  39. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  40. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  41. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  42. package/runtime/js/cm-ai/drive-bootstrap.mjs +315 -0
  43. package/runtime/js/cm-ai/drive-core.mjs +47 -9
  44. package/runtime/js/cm-ai/durable-runner-state.mjs +413 -56
  45. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  46. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  47. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  48. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  49. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  50. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  51. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  52. package/runtime/js/cm-ai/external-models.mjs +52 -0
  53. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  54. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  55. package/runtime/js/cm-ai/host-bootstrap.mjs +126 -29
  56. package/runtime/js/cm-ai/host-check.mjs +30 -4
  57. package/runtime/js/cm-ai/host-conversation-execution.mjs +66 -20
  58. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  59. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  60. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  61. package/runtime/js/cm-ai/host-qa-executor.mjs +23 -9
  62. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +23 -6
  63. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  64. package/runtime/js/cm-ai/host-session.mjs +12 -4
  65. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  66. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +16 -5
  67. package/runtime/js/cm-ai/host.mjs +1 -1
  68. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  69. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  70. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  71. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  72. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  73. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  74. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  75. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  76. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  77. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  78. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  79. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  80. package/runtime/js/cm-ai/provider-review-observation.mjs +68 -9
  81. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  82. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  83. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  84. package/runtime/js/cm-ai/review-package.mjs +438 -31
  85. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  86. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  87. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  88. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  89. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  90. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  91. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  92. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  93. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  94. package/runtime/js/cm-ai/task-runner.mjs +658 -75
  95. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  96. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  97. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  98. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  99. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  100. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  101. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  102. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  103. package/runtime/js/cm-fix/execution.mjs +279 -52
  104. package/runtime/js/cm-fix/final-review.mjs +18 -10
  105. package/runtime/js/cm-fix/host-review.mjs +32 -9
  106. package/runtime/js/cm-fix/host.mjs +6 -1
  107. package/runtime/js/cm-fix/layout.mjs +1 -1
  108. package/runtime/js/cm-fix/progress.mjs +5 -0
  109. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  110. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  111. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  112. package/runtime/js/cm-prd/analysis.mjs +2 -1
  113. package/runtime/js/cm-prd/change.mjs +28 -10
  114. package/runtime/js/cm-prd/draft.mjs +5 -2
  115. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  116. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  117. package/runtime/js/cm-prd/review-publication.mjs +27 -15
  118. package/runtime/js/cm-prd/review-time.mjs +29 -0
  119. package/runtime/js/cm-prd/self-check.mjs +6 -3
  120. package/runtime/js/cm-prd/session.mjs +53 -6
  121. package/runtime/js/cm-prd/summary.mjs +3 -1
  122. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  123. package/runtime/js/cm-security/finalize.mjs +32 -0
  124. package/runtime/js/spec-task-line.mjs +117 -0
  125. package/runtime/js/specs-status.mjs +10 -3
  126. package/runtime/review.md +5 -0
  127. package/runtime/task-gates.md +6 -0
  128. package/runtime/workflow-config.md +10 -1
  129. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  130. package/scripts/cm-ai-admission.mjs +18 -11
  131. package/scripts/cm-ai-admission.test.mjs +65 -1
  132. package/scripts/cm-ai-batch-drive.mjs +135 -34
  133. package/scripts/cm-ai-batch-drive.test.mjs +209 -3
  134. package/scripts/cm-ai-batch-host.mjs +63 -24
  135. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  136. package/scripts/cm-ai-batch-run.mjs +101 -34
  137. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  138. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  139. package/scripts/cm-ai-bootstrap-flow.test.mjs +159 -0
  140. package/scripts/cm-ai-bootstrap-merge.test.mjs +162 -0
  141. package/scripts/cm-ai-bootstrap.test.mjs +174 -89
  142. package/scripts/cm-ai-conversation-entry-ops.test.mjs +97 -2
  143. package/scripts/cm-ai-develop-driver-gaps.test.mjs +924 -0
  144. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  145. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  146. package/scripts/cm-ai-drive.mjs +526 -60
  147. package/scripts/cm-ai-drive.test.mjs +336 -10
  148. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  149. package/scripts/cm-ai-host.mjs +142 -43
  150. package/scripts/cm-ai-host.test.mjs +232 -12
  151. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  152. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  153. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  154. package/scripts/cm-ai-progress.test.mjs +521 -0
  155. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  156. package/scripts/cm-ai-qa-config-revision.test.mjs +187 -15
  157. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  158. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  159. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  160. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  161. package/scripts/cm-ai-review-failure.test.mjs +977 -0
  162. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  163. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  164. package/scripts/cm-ai-run.mjs +206 -62
  165. package/scripts/cm-ai-run.test.mjs +6 -4
  166. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  167. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  168. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  169. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  170. package/scripts/cm-ai-supersede.test.mjs +571 -17
  171. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  172. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  173. package/scripts/cm-capability-gate.test.mjs +21 -2
  174. package/scripts/cm-check-drive.test.mjs +2 -1
  175. package/scripts/cm-check-host.test.mjs +1 -1
  176. package/scripts/cm-check-runtime.sh +12 -1
  177. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  178. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  179. package/scripts/cm-claude-probe.test.mjs +10 -2
  180. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  181. package/scripts/cm-claude-worker.test.mjs +11 -4
  182. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  183. package/scripts/cm-codex-plugin-metadata.py +83 -0
  184. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  185. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  186. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  187. package/scripts/cm-efficiency-offline.mjs +35 -0
  188. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  189. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  190. package/scripts/cm-efficiency-response.test.mjs +117 -0
  191. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  192. package/scripts/cm-external-batch-host.test.mjs +157 -0
  193. package/scripts/cm-external-fix-host.test.mjs +281 -0
  194. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  195. package/scripts/cm-external-group-models.test.mjs +60 -0
  196. package/scripts/cm-external-model-host.test.mjs +180 -0
  197. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  198. package/scripts/cm-external-models.test.mjs +89 -0
  199. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  200. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  201. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  202. package/scripts/cm-failover.mjs +8 -8
  203. package/scripts/cm-fix-abandon.test.mjs +123 -5
  204. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  205. package/scripts/cm-fix-drive.mjs +70 -23
  206. package/scripts/cm-fix-drive.test.mjs +36 -1
  207. package/scripts/cm-fix-final-review.test.mjs +11 -6
  208. package/scripts/cm-fix-host.mjs +24 -14
  209. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  210. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  211. package/scripts/cm-fix-review-budget.test.mjs +147 -0
  212. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  213. package/scripts/cm-host-check.test.mjs +6 -3
  214. package/scripts/cm-host-qa-executor.test.mjs +213 -17
  215. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  216. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  217. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  218. package/scripts/cm-live-evidence.test.mjs +64 -0
  219. package/scripts/cm-log-event.mjs +25 -2
  220. package/scripts/cm-log-event.py +15 -0
  221. package/scripts/cm-log-event.test.mjs +31 -0
  222. package/scripts/cm-model-setup.mjs +79 -0
  223. package/scripts/cm-prd-completion.test.mjs +75 -0
  224. package/scripts/cm-prd-draft.test.mjs +14 -0
  225. package/scripts/cm-prd-drive.mjs +32 -11
  226. package/scripts/cm-prd-drive.test.mjs +15 -0
  227. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  228. package/scripts/cm-prd-host.mjs +13 -4
  229. package/scripts/cm-prd-review-gate.mjs +126 -81
  230. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  231. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  232. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  233. package/scripts/cm-prd-self-check.test.mjs +6 -0
  234. package/scripts/cm-prd-summary.test.mjs +9 -0
  235. package/scripts/cm-release-smoke.sh +5 -1
  236. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  237. package/scripts/cm-review-inventory.test.mjs +253 -1
  238. package/scripts/cm-runtime-i18n.mjs +15 -4
  239. package/scripts/cm-runtime-install.mjs +8 -4
  240. package/scripts/cm-runtime.mjs +116 -23
  241. package/scripts/cm-runtime.test.mjs +121 -12
  242. package/scripts/cm-security.test.mjs +32 -0
  243. package/scripts/cm-spec-manifest.mjs +28 -10
  244. package/scripts/cm-spec-manifest.test.mjs +8 -4
  245. package/scripts/cm-spec-task-line.test.mjs +138 -0
  246. package/scripts/cm-specs-status.test.mjs +12 -1
  247. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  248. package/scripts/cm-task-gate.mjs +164 -20
  249. package/scripts/cm-task-gate.py +2 -1
  250. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  251. package/scripts/cm-test-drive.mjs +10 -4
  252. package/scripts/cm-test-drive.test.mjs +14 -1
  253. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  254. package/scripts/cm-usage-report.py +22 -3
  255. package/scripts/cm-workflow-config.mjs +10 -1
  256. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  257. package/scripts/fixtures/claude-review-process.mjs +1 -0
  258. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  259. package/scripts/fixtures/process-cleanup.mjs +101 -0
  260. package/scripts/test-cm-log-event.py +2 -0
  261. package/scripts/test-cm-native-usage.py +62 -0
  262. package/scripts/test-cm-prd-review-gate.py +2 -1
  263. package/scripts/test-external-model-setup.py +91 -0
  264. package/scripts/test-model-configuration-write.py +201 -0
  265. package/scripts/test-npm-install.py +11 -2
  266. package/scripts/test-scan-public-safety.py +1 -1
  267. package/scripts/test-spec-manifest.py +16 -8
  268. package/scripts/test-task-gate.py +2 -2
  269. package/scripts/test-workflow-config.py +1 -0
  270. package/scripts/validate-public-repo.py +1 -0
  271. package/skills/cm-ai/SKILL.md +2 -2
  272. package/skills/cm-ai/references/N1-init.md +1 -1
  273. package/skills/cm-ai/references/N8-finish.md +5 -0
  274. package/skills/cm-ai/references/js-host.md +270 -43
  275. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  276. package/skills/cm-fix/SKILL.md +1 -1
  277. package/skills/cm-fix/references/js-host.md +52 -3
  278. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  279. package/skills/cm-prd/references/js-host.md +6 -0
  280. package/skills/cm-runtime/SKILL.md +29 -6
  281. package/skills/cm-security/SKILL.md +4 -2
  282. package/skills/cm-security/references/scan-contract.md +1 -0
  283. package/templates/cm-workflow.yml +1 -1
@@ -0,0 +1,138 @@
1
+ // #27 one tasks.md grammar for admission, cm-prd checks, N5 mark-done and the
2
+ // approval manifest; #28 one dependency rule for nextTask and --task.
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 {createHash} from 'node:crypto';
9
+ import {spawnSync} from 'node:child_process';
10
+ import {fileURLToPath} from 'node:url';
11
+ import {inspectCmAiAdmission,approveCmAiSpecs,parseFeatureTaskText} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
12
+ import {captureSpecificationMaterial} from '../runtime/js/cm-ai/specification-material.mjs';
13
+ import {checkPrdDraftMechanics} from '../runtime/js/cm-prd/self-check.mjs';
14
+ import {buildManifest} from './cm-spec-manifest.mjs';
15
+ import {parseTasks} from './cm-failover.mjs';
16
+
17
+ // N5 mark-done and admission may write run logs: keep them out of the invoking user's home.
18
+ const isolatedWorkflowHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-task-line-home-'));
19
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedWorkflowHome,'user');
20
+ process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedWorkflowHome,'logs');
21
+ after(()=>fs.rmSync(isolatedWorkflowHome,{recursive:true,force:true}));
22
+ const scripts=fileURLToPath(new URL('.',import.meta.url));
23
+ const gate=path.join(scripts,'cm-task-gate.py'),admissionCli=path.join(scripts,'cm-ai-admission.mjs');
24
+ const oracle=path.join(scripts,'fixtures','spec-manifest-python-oracle.py');
25
+ const python=process.env.CM_PYTHON_BIN||'python3';
26
+
27
+ function fixture(tasks,run){
28
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-task-line-')));
29
+ const specs=path.join(root,'specs'),code=path.join(root,'code'),feature=path.join(specs,'1.login');
30
+ fs.mkdirSync(feature,{recursive:true});fs.mkdirSync(code);fs.writeFileSync(path.join(code,'README.md'),'existing\n');
31
+ fs.writeFileSync(path.join(feature,'requirements.md'),'# Requirements\n- [ ] [AC-001] login works\n');
32
+ fs.writeFileSync(path.join(feature,'design.md'),'# Design\n');
33
+ fs.writeFileSync(path.join(feature,'tasks.md'),tasks);
34
+ try{return run({root,specs,code,feature,tasksPath:path.join(feature,'tasks.md')});}
35
+ finally{fs.rmSync(root,{recursive:true,force:true});}
36
+ }
37
+ // The real N5 path: an approved legacy-unbound handoff/review pair, then the
38
+ // Python lock adapter's mark-done, which delegates the line edit to cm-task-gate.mjs.
39
+ function markDone({specs,tasksPath},task){
40
+ const reviews=path.join(specs,'.reviews');fs.mkdirSync(reviews,{recursive:true});
41
+ const handoff=path.join(reviews,`login-${task}-a1-handoff.json`);
42
+ fs.writeFileSync(handoff,JSON.stringify({schema_version:1,task_id:task,attempt:1,status:'ready_for_review',
43
+ changed_files:['src/login.ts'],verification:[{command:'npm test',status:'passed',evidence:'passed'}],
44
+ evidence:['src/login.ts'],blockers:[],scope_deviation:[]},null,2)+'\n');
45
+ const sha=createHash('sha256').update(fs.readFileSync(handoff)).digest('hex');
46
+ fs.writeFileSync(path.join(reviews,`login-${task}-r1.md`),`---\nat: 2026-09-28T07:00:00-07:00\nreviewer: codex-subagent\n`
47
+ +`independent: true\ntask: ${task}\nattempt: 1\nround: 1\nverdict: approved\nblocking_findings: 0\n`
48
+ +`handoff: ${path.basename(handoff)}\nhandoff_sha256: ${sha}\nscope:\n - src/login.ts\n---\n\nZero findings.\n`);
49
+ return spawnSync(python,[gate,'mark-done','--handoff',handoff,'--reviews-dir',reviews,'--feature','login',
50
+ '--task',task,'--tasks',tasksPath,'--allow-legacy-unbound'],{encoding:'utf8'});
51
+ }
52
+
53
+ for(const [label,line,description='实现登录'] of [
54
+ ['no colon','- [ ] T-001 实现登录'],
55
+ ['dash separator','- [ ] T-001 - 实现登录','- 实现登录'],
56
+ ['nested four-space item','- 阶段一\n - [ ] T-001: 实现登录'],
57
+ ['full-width colon','- [ ] T-001:实现登录'],
58
+ ])test(`${label}: a task admission selects stays approved after the real N5 mark-done`,()=>
59
+ fixture(`# tasks\n${line}\n- [ ] T-002: 退出登录\n\n- T-002 依赖 T-001\n`,f=>{
60
+ const approved=approveCmAiSpecs({specsDir:f.specs,codeProject:f.code,approvalResponse:'开始'});
61
+ assert.equal(approved.approveRefused,undefined);
62
+ const before=inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code});
63
+ assert.equal(before.state,'ready');assert.equal(before.nextTask.id,'T-001');
64
+ assert.equal(before.nextTask.description,description);
65
+ const marked=markDone(f,'T-001');
66
+ assert.equal(marked.status,0,marked.stderr);
67
+ assert.match(fs.readFileSync(f.tasksPath,'utf8'),/\[x\] T-001/);
68
+ const after=inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code});
69
+ assert.equal(after.reason,'task_selected',`admission after N5: ${after.state}/${after.reason}`);
70
+ assert.equal(after.nextTask.id,'T-002');
71
+ // The next task's material still binds the unchanged approval.
72
+ assert.equal(captureSpecificationMaterial({specsRoot:f.specs,feature:'1.login',taskId:'T-002'}).task.id,'T-002');
73
+ }));
74
+
75
+ test('a manifest approved by the pre-grammar rule keeps matching the same bytes',()=>
76
+ fixture('- [x] T-001 已完成且无冒号\n- [ ] T-002 待做\n',f=>{
77
+ // Legacy-shaped approval: the frozen pre-migration implementation wrote these rows.
78
+ const legacy=spawnSync(python,[oracle,f.specs],{encoding:'utf8'});
79
+ assert.equal(legacy.status,0,legacy.stderr);
80
+ const specFiles=JSON.parse(legacy.stdout).specFiles;
81
+ const tasksRow=row=>row.path==='1.login/tasks.md';
82
+ assert.notEqual(specFiles.find(tasksRow).sha256,buildManifest(f.specs).find(tasksRow).sha256,
83
+ 'fixture must exercise a digest the new grammar computes differently');
84
+ fs.writeFileSync(path.join(f.specs,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.login'],specFiles}));
85
+ const admission=inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code});
86
+ assert.equal(admission.state,'ready');assert.equal(admission.nextTask.id,'T-002');
87
+ const material=captureSpecificationMaterial({specsRoot:f.specs,feature:'1.login',taskId:'T-002'});
88
+ assert.deepEqual(material.sources,specFiles,'material keeps the approved digests');
89
+ const cli=spawnSync(process.execPath,[path.join(scripts,'cm-spec-manifest.mjs'),f.specs,'--status-file',
90
+ path.join(f.specs,'.cm-specs-status')],{encoding:'utf8'});
91
+ assert.equal(cli.status,0,cli.stderr);
92
+ // Real drift still fails closed.
93
+ fs.appendFileSync(f.tasksPath,'- [ ] T-003 新增\n');
94
+ assert.equal(inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code}).reason,'spec_drift');
95
+ }));
96
+
97
+ test('fenced examples are never declarations for admission, cm-prd, failover or N5',()=>
98
+ fixture('- [ ] T-001: real\n```md\n- [ ] T-001: example copy\n- [x] T-009: example\n```\n',f=>{
99
+ const parsed=parseFeatureTaskText(fs.readFileSync(f.tasksPath,'utf8'));
100
+ assert.deepEqual(parsed.tasks.map(task=>task.id),['T-001']);
101
+ assert.deepEqual(parseTasks(fs.readFileSync(f.tasksPath,'utf8')).map(task=>task.id),['T-001']);
102
+ approveCmAiSpecs({specsDir:f.specs,codeProject:f.code,approvalResponse:'开始'});
103
+ const marked=markDone(f,'T-001');assert.equal(marked.status,0,marked.stderr);
104
+ assert.equal(fs.readFileSync(f.tasksPath,'utf8'),'- [x] T-001: real\n```md\n- [ ] T-001: example copy\n- [x] T-009: example\n```\n');
105
+ assert.equal(inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code}).state,'complete');
106
+ }));
107
+
108
+ test('cm-prd self-check reads the same declarations as admission',()=>{
109
+ const contract={schemaVersion:'1.0',feature:'sample',cases:[{id:'TC-001',origin:'user',kind:'logic',blocking:true,
110
+ acIds:['AC-001'],taskIds:['T-001'],title:'Check',preconditions:[],steps:['Do'],expected:['Works'],cleanup:[]}]};
111
+ for(const tasks of ['- [ ] T-001:全角冒号','- [ ] T-001 无冒号','- 父项\n - [ ] T-001: 嵌套']){
112
+ const report=checkPrdDraftMechanics({draftDigest:'a'.repeat(64),features:[{directory:'1.sample',name:'sample',documents:[
113
+ {path:'requirements.md',content:'- [ ] [AC-001] Works.'},{path:'tasks.md',content:tasks},
114
+ {path:'test-cases.json',content:JSON.stringify(contract)}]}]});
115
+ assert.equal(report.status,'mechanical_subset_passed',`${tasks}: ${JSON.stringify(report.findings)}`);
116
+ assert.deepEqual(parseFeatureTaskText(tasks).tasks.map(task=>task.id),['T-001']);
117
+ }
118
+ });
119
+
120
+ test('#28 --task on a task whose prerequisite was DROPPED matches nextTask semantics',()=>
121
+ fixture('- [x] T-001: a\n- [ ] ~~T-002: b~~ `[DROPPED v2]`\n- [ ] T-003: c\n- [ ] T-004: d\n\n- T-003 依赖 T-002\n- T-004 依赖 T-003\n',f=>{
122
+ approveCmAiSpecs({specsDir:f.specs,codeProject:f.code,approvalResponse:'开始'});
123
+ const admission=inspectCmAiAdmission({specsDir:f.specs,codeProject:f.code});
124
+ assert.equal(admission.nextTask.id,'T-003');
125
+ assert.deepEqual(admission.eligibleTasks.map(task=>task.id),['T-003']);
126
+ const print=task=>spawnSync(process.execPath,[admissionCli,'--specs-dir',f.specs,'--code-project',f.code,
127
+ '--print-run-definition','--scope','src/a.js','--task',task],{encoding:'utf8'});
128
+ const selected=print('T-003');
129
+ assert.equal(selected.status,0,selected.stderr);
130
+ assert.deepEqual(JSON.parse(selected.stdout).taskSelection,{version:1,taskId:'T-003'});
131
+ // A real mismatch names why instead of a bare code.
132
+ for(const [task,reason] of [['T-004',/T-004 依赖的 T-003 尚未完成/],['T-001',/T-001 已勾选完成/],
133
+ ['T-002',/T-002 已标记 DROPPED/],['T-404',/没有任务 T-404/]]){
134
+ const refused=print(task);assert.equal(refused.status,1);
135
+ const error=JSON.parse(refused.stderr).error;
136
+ assert.equal(error.code,'task_selection_mismatch');assert.match(error.reason,reason);
137
+ }
138
+ }));
@@ -82,12 +82,23 @@ test('revision digest is optional, validated, and retained by shared status stor
82
82
  assert.equal(Object.hasOwn(f.value(),'revisionDigest'),false);
83
83
  });
84
84
 
85
+ test('task grammar is only version 2 and is carried through awaiting review',t=>{
86
+ const f=fixture(t),expected=f.initial(),approved={...expected,status:'approved',approval:{response:'开始',at:expected.at}};
87
+ assert.deepEqual(writeSpecsStatus(f.specs,{...approved,taskGrammar:2}),{...approved,taskGrammar:2});
88
+ assert.equal(readSpecsStatus(f.specs).value.taskGrammar,2);
89
+ assert.deepEqual(writeSpecsStatus(f.specs,{...expected,taskGrammar:2}),{...expected,taskGrammar:2});
90
+ for(const invalid of [{...approved,taskGrammar:1},{...approved,taskGrammar:'2'},{...expected,taskGrammar:3}])
91
+ assert.throws(()=>writeSpecsStatus(f.specs,invalid),/spec_status_invalid/);
92
+ });
93
+
85
94
  test('--approve writes only the three permitted reasons with explicit human input and reruns admission',t=>{
86
95
  const f=fixture(t),approve=['--approve','--approval-response','开始'];
87
96
  f.raw(f.initial());
88
97
  assert.equal(f.run('--approval-response','开始').result.reason,'approval_write_required');
89
98
  let result=f.run(...approve);assert.equal(result.exit,0);assert.equal(result.result.state,'ready');
90
- assert.deepEqual(Object.keys(f.value()),keys);assert.equal(f.value().approval.response,'开始');
99
+ // A new approval binds the shared tasks.md grammar (spec-task-line.mjs).
100
+ assert.deepEqual(Object.keys(f.value()),[...keys,'taskGrammar']);assert.equal(f.value().taskGrammar,2);
101
+ assert.equal(f.value().approval.response,'开始');
91
102
  assert.equal(f.value().approval.at,f.value().at);
92
103
  feature(f.specs,'2.appendix');
93
104
  assert.equal(f.run('--approval-response','开始').result.reason,'spec_features_changed');
@@ -0,0 +1,117 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {createHash} from 'node:crypto';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {spawnSync} from 'node:child_process';
9
+ import {checkN4,checkN5,implementationSha256,prepareHumanCorrection,publishHumanCorrectionReview,
10
+ prepareMarkDone,verifyMarkDonePlan} from './cm-task-gate.mjs';
11
+
12
+ const sha=file=>createHash('sha256').update(fs.readFileSync(file)).digest('hex');
13
+ function fixture(t){
14
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-human-correction-')));
15
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
16
+ const reviewsDir=path.join(root,'.reviews');fs.mkdirSync(reviewsDir);
17
+ fs.mkdirSync(path.join(root,'src'));const code=path.join(root,'src/example.ts');fs.writeFileSync(code,'old');
18
+ const tasks=path.join(root,'tasks.md');fs.writeFileSync(tasks,'- [ ] T-001: fixture\n');
19
+ const payload=attempt=>({schema_version:1,task_id:'T-001',attempt,status:'ready_for_review',changed_files:['src/example.ts'],
20
+ implementation_sha256:implementationSha256(root,['src/example.ts']),
21
+ verification:[{command:'fixture',status:'passed',evidence:'synthetic fixture'}],
22
+ evidence:['learning: no_relevant_lesson','learning: retrospective no_new_lesson'],blockers:[],scope_deviation:[]});
23
+ const review=(file,handoff,attempt,verdict,correctionDigest=null)=>fs.writeFileSync(file,`---\nat: 2026-09-30T12:00:00Z\nreviewer: codex-subagent\nindependent: true\ntask: T-001\nattempt: ${attempt}\nround: ${attempt}\nverdict: ${verdict}\nblocking_findings: ${verdict==='approved'?0:1}\nhandoff: ${path.basename(handoff)}\nhandoff_sha256: ${sha(handoff)}\n${correctionDigest?`correction_sha256: ${correctionDigest}\n`:''}scope:\n - src/example.ts\n---\n${verdict==='approved'?'Zero findings.':'Blocking fixture finding.'}\n`);
24
+ const history=[];
25
+ for(const [attempt,verdict] of [[1,'changes_requested'],[2,'blocked']]){
26
+ const handoff=path.join(reviewsDir,`login-T-001-a${attempt}-handoff.json`),file=path.join(reviewsDir,`login-T-001-r${attempt}.md`);
27
+ fs.writeFileSync(handoff,JSON.stringify(payload(attempt)));review(file,handoff,attempt,verdict);history.push(handoff,file);
28
+ }
29
+ const original=history.map(sha);fs.writeFileSync(code,'fixed');
30
+ const draft=path.join(root,'draft.json');fs.writeFileSync(draft,JSON.stringify(payload(2)));
31
+ const selectors={handoff:draft,reviewsDir,feature:'login',task:'T-001',projectRoot:root,
32
+ humanAuthorized:true,reason:'Human approved exact selector correction after original blocked round 2.'};
33
+ const prepare=()=>prepareHumanCorrection(selectors);
34
+ const finish=(record,verdict='approved')=>{
35
+ const selected={...selectors,...record,tasksPath:tasks};
36
+ review(record.review,record.handoff,2,verdict,record.correction_sha256);
37
+ publishHumanCorrectionReview(selected);return selected;
38
+ };
39
+ return {root,reviewsDir,code,tasks,draft,history,original,selectors,review,prepare,finish};
40
+ }
41
+
42
+ test('one-shot human correction retains blocked history and completes through the existing locked adapter',t=>{
43
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
44
+ assert.equal(checkN4(selected).outcome,'ready_for_review');
45
+ assert.throws(()=>checkN5(selected));
46
+ const done=f.finish(record);assert.equal(checkN5(done).outcome,'approved');
47
+ assert.throws(()=>checkN4(done),/already exists/);assert.throws(()=>f.prepare(),/already exists/);
48
+ const plan=prepareMarkDone(done);assert.equal(plan.evidence.length,8);
49
+ const args=['mark-done','--handoff',done.handoff,'--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001',
50
+ '--project-root',f.root,'--tasks',f.tasks,'--correction',done.correction];
51
+ const result=spawnSync(process.env.CM_PYTHON_BIN||'python3',[fileURLToPath(new URL('./cm-task-gate.py',import.meta.url)),...args],{encoding:'utf8'});
52
+ assert.equal(result.status,0,result.stderr);assert.match(fs.readFileSync(f.tasks,'utf8'),/\[x\]/);
53
+ assert.deepEqual(f.history.map(sha),f.original);
54
+ assert.throws(()=>checkN5({...done,handoff:f.history[2],correction:null}),/implementation content changed/);
55
+ });
56
+
57
+ test('correction authorization, original verdict, full scope, and mandatory Learning cannot be omitted',t=>{
58
+ const f=fixture(t);
59
+ assert.throws(()=>prepareHumanCorrection({...f.selectors,humanAuthorized:false}),/authorization/);
60
+ assert.throws(()=>prepareHumanCorrection({...f.selectors,reason:''}),/reason/);
61
+ const draft=JSON.parse(fs.readFileSync(f.draft));draft.evidence=['unbound application'];fs.writeFileSync(f.draft,JSON.stringify(draft));
62
+ assert.throws(()=>prepareHumanCorrection({...f.selectors,allowLegacyUnbound:true}),/Learning/);
63
+ assert.equal(fs.readdirSync(f.reviewsDir).length,4);
64
+ draft.evidence=['learning: no_relevant_lesson','learning: retrospective no_new_lesson'];draft.changed_files=['src/new.ts'];
65
+ fs.writeFileSync(path.join(f.root,'src/new.ts'),'new');draft.implementation_sha256=implementationSha256(f.root,draft.changed_files);
66
+ fs.writeFileSync(f.draft,JSON.stringify(draft));assert.throws(()=>f.prepare(),/full original/);
67
+ f.review(f.history[3],f.history[2],2,'approved');assert.throws(()=>f.prepare(),/blocked round 2/);
68
+ });
69
+
70
+ test('original evidence, correction handoff, implementation and authorization record drift invalidate approval',t=>{
71
+ const f=fixture(t),record=f.prepare(),done=f.finish(record),plan=prepareMarkDone(done);
72
+ for(const file of [...f.history,record.correction,record.handoff,record.review,done.receipt??path.join(f.reviewsDir,'login-T-001-human-correction-receipt.json'),f.code]){
73
+ const bytes=fs.readFileSync(file);fs.appendFileSync(file,'\nchanged');
74
+ assert.throws(()=>checkN5(done),undefined,file);assert.throws(()=>verifyMarkDonePlan(done,plan.planDigest),undefined,file);
75
+ fs.writeFileSync(file,bytes);
76
+ }
77
+ assert.equal(checkN5(done).outcome,'approved');assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
78
+ });
79
+
80
+ test('blocked correction review is sealed once and cannot be replaced by a new approval',t=>{
81
+ const f=fixture(t),record=f.prepare(),done=f.finish(record,'blocked');
82
+ assert.throws(()=>checkN5(done),/remains blocked/);
83
+ assert.throws(()=>publishHumanCorrectionReview(done),/already exists/);
84
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
85
+ assert.throws(()=>checkN5(done),/review or receipt changed/);
86
+ assert.throws(()=>publishHumanCorrectionReview(done),/already exists/);
87
+ assert.throws(()=>f.prepare(),/already exists/);
88
+ });
89
+
90
+ test('old review or self-degraded review cannot authorize a correction',t=>{
91
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
92
+ f.review(record.review,record.handoff,2,'approved');
93
+ assert.throws(()=>publishHumanCorrectionReview(selected),/fresh independent/);
94
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
95
+ fs.writeFileSync(record.review,fs.readFileSync(record.review,'utf8').replace('codex-subagent','self-degraded').replace('independent: true','independent: false').replace('scope:','degraded_reason: fixture\nscope:'));
96
+ assert.throws(()=>publishHumanCorrectionReview(selected),/fresh independent/);
97
+ });
98
+
99
+ test('correction file identities reject symlinks, hardlinks, sibling selection and duplicate record fields',t=>{
100
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
101
+ assert.throws(()=>checkN4({...selected,correction:path.join(f.root,'other.json')}),/fixed evidence/);
102
+ const bytes=fs.readFileSync(record.correction);
103
+ fs.writeFileSync(record.correction,bytes.toString().replace('"version": 1','"version": 1, "version": 1'));
104
+ assert.throws(()=>checkN4(selected),/duplicate key/);fs.writeFileSync(record.correction,bytes);
105
+ const link=path.join(f.root,'alias');fs.linkSync(record.correction,link);
106
+ assert.throws(()=>checkN4(selected),/hardlinked/);fs.unlinkSync(link);
107
+ fs.renameSync(record.correction,link);fs.symlinkSync(link,record.correction);
108
+ assert.throws(()=>checkN4(selected),/non-symlink/);
109
+ });
110
+
111
+ test('CLI human correction refuses missing human authorization and exposes the fixed review record',t=>{
112
+ const f=fixture(t),script=fileURLToPath(new URL('./cm-task-gate.mjs',import.meta.url));
113
+ const args=['prepare-human-correction','--handoff',f.draft,'--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001','--project-root',f.root,'--reason','Explicit human correction'];
114
+ const denied=spawnSync(process.execPath,[script,...args],{encoding:'utf8'});assert.equal(denied.status,1);assert.match(denied.stderr,/authorization/);
115
+ const result=spawnSync(process.execPath,[script,...args,'--human-authorized'],{encoding:'utf8'});
116
+ assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).attempt,2);
117
+ });
@@ -8,6 +8,7 @@ import childProcess from 'node:child_process';
8
8
  import {fileURLToPath} from 'node:url';
9
9
  import {inspectFixWalkthrough,readFixWalkthrough,fixWalkthroughBinding} from '../runtime/js/cm-fix/walkthrough.mjs';
10
10
  import {inspectFixRegressionFailure} from '../runtime/js/cm-fix/regression-evidence.mjs';
11
+ import {taskDeclarations,approvedTaskGrammar,TASK_GRAMMAR} from '../runtime/js/spec-task-line.mjs';
11
12
 
12
13
  const TASK_RE=/^T-[A-Za-z0-9][A-Za-z0-9._-]*$/;
13
14
  const REVIEWERS=new Set(['codex-subagent','codex-cli','claude-cli','self-degraded']);
@@ -471,7 +472,135 @@ function verifyLearningRecord(payload,projectRoot){
471
472
  throw new GateError('Learning requires a content-bound handoff');
472
473
  }
473
474
 
474
- export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false}){
475
+ // A single explicitly authorized human continuation after a blocked second
476
+ // round. The ordinary two-attempt chain and original evidence stay intact.
477
+ function correctionPaths(reviewsDir,feature,task){
478
+ requireFeature(feature);requireTaskId(task,'task');
479
+ const info=fs.lstatSync(reviewsDir);
480
+ if(!info.isDirectory()||info.isSymbolicLink())throw new GateError('correction reviews directory must be real');
481
+ const root=fs.realpathSync(reviewsDir),prefix=path.join(root,`${feature}-${task}-human-correction`);
482
+ return {record:prefix+'.json',handoff:prefix+'-handoff.json',review:prefix+'.md',receipt:prefix+'-receipt.json'};
483
+ }
484
+ function absent(file){
485
+ try{fs.lstatSync(file);throw new GateError(`human correction evidence already exists: ${file}`);}
486
+ catch(error){if(error.code!=='ENOENT')throw error;}
487
+ }
488
+ function exactFields(value,fields,label){
489
+ if(value===null||typeof value!=='object'||Array.isArray(value)
490
+ ||!sameSet(new Set(Object.keys(value)),new Set(fields)))throw new GateError(`invalid ${label} fields`);
491
+ }
492
+ function correctionHistory({reviewsDir,feature,task,projectRoot}){
493
+ const handoff=expectedHandoff(reviewsDir,feature,task,2);
494
+ requireExpectedHandoff(handoff,{reviewsDir,feature,task,attempt:2});
495
+ const payload=loadHandoff(handoff,{task,attempt:2});
496
+ if(payload.status!=='ready_for_review'||!payload.implementation_sha256)
497
+ throw new GateError('human correction requires a bound ready attempt 2 handoff');
498
+ validateAttemptChain(reviewsDir,feature,task,2,payload,projectRoot);
499
+ const review=reviewPath(reviewsDir,feature,task,2);
500
+ const header=validateReview(review,{task,attempt:2,handoff,changedFiles:payload.changed_files});
501
+ if(header.verdict!=='blocked'||header.independent!=='true')
502
+ throw new GateError('human correction requires an independent blocked round 2');
503
+ const files=[expectedHandoff(reviewsDir,feature,task,1),reviewPath(reviewsDir,feature,task,1),handoff,review];
504
+ const revisions=files.map(file=>fileRevision(file,PREPARATION_FILE_LIMIT));
505
+ requireRevisions(revisions);
506
+ return {payload,revisions,history:revisions.map(item=>({file:path.basename(item.path),
507
+ sha256:createHash('sha256').update(item.bytes).digest('hex')}))};
508
+ }
509
+ function boundCorrectionHandoff(handoff,task,projectRoot){
510
+ const payload=loadHandoff(handoff,{task,attempt:2});
511
+ if(payload.status!=='ready_for_review')throw new GateError('human correction requires ready_for_review');
512
+ verifyLearningRecord(payload,projectRoot);verifyImplementationBinding(payload,{projectRoot});
513
+ return payload;
514
+ }
515
+ export function prepareHumanCorrection(selectors){
516
+ const {reviewsDir,feature,task,handoff,projectRoot,humanAuthorized,reason}=selectors;
517
+ if(humanAuthorized!==true)throw new GateError('human correction requires explicit human authorization');
518
+ if(typeof reason!=='string'||!reason.trim()||reason.length>2000)
519
+ throw new GateError('human correction requires a concrete bounded reason');
520
+ const paths=correctionPaths(reviewsDir,feature,task);
521
+ absent(paths.record);absent(paths.review);absent(paths.receipt);
522
+ const original=correctionHistory(selectors),draft=fileRevision(handoff,PREPARATION_FILE_LIMIT);
523
+ const payload=boundCorrectionHandoff(handoff,task,projectRoot);
524
+ if(!sameSet(new Set(original.payload.changed_files),new Set(payload.changed_files)))
525
+ throw new GateError('human correction must retain the full original reviewed file scope');
526
+ requireRevisions([...original.revisions,draft]);
527
+ // Permit only an identical orphan handoff after interruption before record
528
+ // creation. Published authorization/review/receipt are never overwritten.
529
+ try{absent(paths.handoff);fs.writeFileSync(paths.handoff,draft.bytes,{flag:'wx',mode:0o600});}
530
+ catch(error){
531
+ if(error instanceof GateError&&!fs.existsSync(paths.record)&&fileRevision(paths.handoff,PREPARATION_FILE_LIMIT).bytes.equals(draft.bytes)){}
532
+ else throw error;
533
+ }
534
+ const record={version:1,protocol:'cm-human-correction',feature,task,attempt:2,
535
+ authorization:'explicit-human-confirmation',at:new Date().toISOString(),reason:reason.trim(),
536
+ history:original.history,handoff_sha256:sha256(paths.handoff)};
537
+ requireRevisions(original.revisions);
538
+ boundCorrectionHandoff(paths.handoff,task,projectRoot);
539
+ fs.writeFileSync(paths.record,JSON.stringify(record,null,2)+'\n',{flag:'wx',mode:0o600});
540
+ return {outcome:'ready_for_correction_review',correction:paths.record,handoff:paths.handoff,
541
+ review:paths.review,correction_sha256:sha256(paths.record),attempt:2};
542
+ }
543
+ function inspectHumanCorrection(selectors){
544
+ const {reviewsDir,feature,task,correction,handoff,projectRoot}=selectors;
545
+ const paths=correctionPaths(reviewsDir,feature,task);
546
+ if(typeof correction!=='string'||typeof handoff!=='string'||path.resolve(correction)!==paths.record||path.resolve(handoff)!==paths.handoff)
547
+ throw new GateError('human correction must use its fixed evidence paths');
548
+ const pinned=fileRevision(paths.record,PREPARATION_FILE_LIMIT);
549
+ const record=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(pinned.bytes));
550
+ exactFields(record,['version','protocol','feature','task','attempt','authorization','at','reason','history','handoff_sha256'],'human correction');
551
+ if(record.version!==1n||record.protocol!=='cm-human-correction'||record.feature!==feature||record.task!==task
552
+ ||record.attempt!==2n||record.authorization!=='explicit-human-confirmation'
553
+ ||typeof record.reason!=='string'||!record.reason.trim()||record.reason.length>2000
554
+ ||typeof record.at!=='string'||!/(?:Z|[+-]\d{2}:\d{2})$/.test(record.at)||Number.isNaN(Date.parse(record.at)))
555
+ throw new GateError('invalid human correction authorization record');
556
+ const original=correctionHistory(selectors);
557
+ if(canonical(record.history)!==canonical(original.history))throw new GateError('human correction history changed');
558
+ const payload=boundCorrectionHandoff(paths.handoff,task,projectRoot);
559
+ fileRevision(paths.handoff,PREPARATION_FILE_LIMIT);
560
+ if(record.handoff_sha256!==sha256(paths.handoff)
561
+ ||!sameSet(new Set(original.payload.changed_files),new Set(payload.changed_files)))
562
+ throw new GateError('human correction handoff changed or omitted original scope');
563
+ requireRevisions([pinned,...original.revisions]);
564
+ return {paths,payload,correctionDigest:sha256(paths.record)};
565
+ }
566
+ export function publishHumanCorrectionReview(selectors){
567
+ const {paths,payload,correctionDigest}=inspectHumanCorrection(selectors);
568
+ absent(paths.receipt);
569
+ const pinned=fileRevision(paths.review,PREPARATION_FILE_LIMIT);
570
+ const header=validateReview(paths.review,{task:selectors.task,attempt:2,handoff:paths.handoff,changedFiles:payload.changed_files});
571
+ if(header.independent!=='true'||header.correction_sha256!==correctionDigest)
572
+ throw new GateError('human correction requires fresh independent review bound to the correction record');
573
+ requireRevisions([pinned]);
574
+ inspectHumanCorrection(selectors);
575
+ const receipt={version:1,protocol:'cm-human-correction-review',correction_sha256:correctionDigest,
576
+ review_sha256:createHash('sha256').update(pinned.bytes).digest('hex'),verdict:header.verdict};
577
+ fs.writeFileSync(paths.receipt,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
578
+ return {outcome:header.verdict,receipt:paths.receipt};
579
+ }
580
+ function checkHumanCorrection(selectors,stage){
581
+ const {paths,payload,correctionDigest}=inspectHumanCorrection(selectors);
582
+ if(stage==='n4'){
583
+ absent(paths.receipt);
584
+ return {gate:'n4',task:selectors.task,attempt:2,outcome:'ready_for_review',content_bound:true,
585
+ handoff_sha256:sha256(paths.handoff),correction_sha256:correctionDigest};
586
+ }
587
+ const pinned=fileRevision(paths.review,PREPARATION_FILE_LIMIT);
588
+ const result=validateReview(paths.review,{task:selectors.task,attempt:2,handoff:paths.handoff,changedFiles:payload.changed_files});
589
+ const receiptRevision=fileRevision(paths.receipt,PREPARATION_FILE_LIMIT);
590
+ const receipt=parseJsonStrict(new TextDecoder('utf8',{fatal:true}).decode(receiptRevision.bytes));
591
+ exactFields(receipt,['version','protocol','correction_sha256','review_sha256','verdict'],'human correction receipt');
592
+ if(receipt.version!==1n||receipt.protocol!=='cm-human-correction-review'
593
+ ||receipt.correction_sha256!==correctionDigest||result.correction_sha256!==correctionDigest
594
+ ||receipt.review_sha256!==sha256(paths.review)||receipt.verdict!==result.verdict)
595
+ throw new GateError('human correction review or receipt changed');
596
+ if(result.verdict!=='approved'||result.independent!=='true')throw new GateError('human correction remains blocked');
597
+ requireRevisions([pinned,receiptRevision]);
598
+ return {gate:'n5',task:selectors.task,attempt:2,outcome:'approved',review:paths.review,
599
+ content_bound:true,correction_sha256:correctionDigest};
600
+ }
601
+
602
+ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null}){
603
+ if(correction!==null)return checkHumanCorrection({handoff,reviewsDir,feature,task,projectRoot,correction},'n4');
475
604
  requireTaskId(task,'task');
476
605
  const payload=loadHandoff(handoff,{task});
477
606
  if(payload.status!=='ready_for_review')throw new GateError('N4 requires a ready_for_review handoff');
@@ -483,7 +612,8 @@ export function checkN4({handoff,reviewsDir,feature,task,projectRoot=null,allowL
483
612
  return {gate:'n4',task,attempt,outcome:'ready_for_review',handoff_sha256:sha256(handoff),content_bound:contentBound};
484
613
  }
485
614
 
486
- export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false}){
615
+ export function checkN5({handoff,reviewsDir,feature,task,projectRoot=null,allowLegacyUnbound=false,requireLearning=false,correction=null}){
616
+ if(correction!==null)return checkHumanCorrection({handoff,reviewsDir,feature,task,projectRoot,correction},'n5');
487
617
  requireTaskId(task,'task');
488
618
  const payload=loadHandoff(handoff,{task});
489
619
  if(payload.status!=='ready_for_review')throw new GateError('N5 requires a ready_for_review handoff');
@@ -553,6 +683,10 @@ function pinApproval(selectors){
553
683
  if(!revisions.some(revision=>revision.path===pinned.path))revisions.push(pinned);
554
684
  }
555
685
  }
686
+ if(selectors.correction){
687
+ const paths=correctionPaths(reviewsDir,feature,task);
688
+ for(const file of [paths.record,paths.review,paths.receipt])revisions.push(fileRevision(file,preparationReadLimit));
689
+ }
556
690
  const approval={...checkN5(selectors)};
557
691
  requireRevisions(revisions);
558
692
  return {approval,revisions};
@@ -601,27 +735,34 @@ function splitLinesKeepEnds(text){
601
735
  if(start<text.length)lines.push({start,text:text.slice(start)});
602
736
  return lines;
603
737
  }
604
-
605
738
  function withoutLineEnding(line){return line.replace(/(?:\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029])$/,'');}
606
739
  function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');}
607
740
 
741
+ // An approval recorded with taskGrammar 2 uses the shared declaration grammar
742
+ // (spec-task-line.mjs): fenced examples are never flipped. Approvals recorded
743
+ // earlier keep the exact original mark-done match on the bytes they approved.
608
744
  function parseTaskTarget(task,tasksPath,revision){
609
745
  let text;
610
- try{text=new TextDecoder('utf-8',{fatal:true}).decode(revision.bytes);}
746
+ try{text=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(revision.bytes);}
611
747
  catch(error){throw new GateError(`cannot read tasks file ${tasksPath}: ${error.message}`);}
612
- const pattern=new RegExp(`^(\\s*-\\s*)\\[([ xX])\\](\\s+${escapeRegExp(task)}(?=[:\\s]|$).*)$`);
613
- const matches=[];
614
- for(const line of splitLinesKeepEnds(text)){
615
- const match=pattern.exec(withoutLineEnding(line.text));
616
- if(match)matches.push({line,match});
748
+ let matches;
749
+ if(approvedTaskGrammar(path.dirname(path.dirname(tasksPath)))===TASK_GRAMMAR)
750
+ matches=taskDeclarations(text).filter(item=>item.id===task).map(item=>({start:item.start,markOffset:item.markOffset,completed:item.completed}));
751
+ else{
752
+ const pattern=new RegExp(`^(\\s*-\\s*)\\[([ xX])\\](\\s+${escapeRegExp(task)}(?=[:\\s]|$).*)$`);
753
+ matches=[];
754
+ for(const line of splitLinesKeepEnds(text)){
755
+ const match=pattern.exec(withoutLineEnding(line.text));
756
+ if(match)matches.push({start:line.start,markOffset:match[1].length+1,completed:match[2].toLowerCase()==='x'});
757
+ }
617
758
  }
618
759
  if(matches.length!==1)throw new GateError(`tasks file must contain exactly one checkbox for ${task}`);
619
- return {text,...matches[0]};
760
+ return {text,declaration:matches[0]};
620
761
  }
621
762
 
622
763
  function taskAfterBytes(target,original){
623
- if(target.match[2].toLowerCase()==='x')return original;
624
- const characterOffset=target.line.start+target.match[1].length+1;
764
+ if(target.declaration.completed)return original;
765
+ const characterOffset=target.declaration.start+target.declaration.markOffset;
625
766
  const byteOffset=Buffer.byteLength(target.text.slice(0,characterOffset));
626
767
  if(original[byteOffset]!==32)throw new GateError('task checkbox byte offset mismatch');
627
768
  return Buffer.concat([original.subarray(0,byteOffset),Buffer.from('x'),original.subarray(byteOffset+1)]);
@@ -651,7 +792,7 @@ export function prepareMarkDone(selectors){
651
792
  if(existing&&!sameRevision(existing,pinned))throw new GateError('conflicting revisions for physical preparation evidence');
652
793
  physical.set(pinned.path,pinned);
653
794
  }
654
- if(physical.size>4)throw new GateError('preparation evidence count exceeds bound');
795
+ if(physical.size>(selectors.correction?8:4))throw new GateError('preparation evidence count exceeds bound');
655
796
  const plan={
656
797
  version:1,protocol:'cm-mark-done-plan',feature:selectors.feature,taskId:selectors.task,
657
798
  attempt:approval.attempt,tasksPath:revision.path,mode:Number(BigInt(revision.stat[2])&0o7777n),
@@ -793,17 +934,18 @@ export function checkParallelWrite({repo,assignment}){
793
934
  return {gate:'parallel-write',outcome:'isolated',assignments:result};
794
935
  }
795
936
 
796
- function usage(){return 'usage: cm-task-gate.mjs {validate-handoff|hash-implementation|check-n4|check-n5|prepare-mark-done|verify-mark-done-plan|check-parallel-write} [options]';}
937
+ function usage(){return 'usage: cm-task-gate.mjs {validate-handoff|hash-implementation|check-n4|check-n5|prepare-mark-done|verify-mark-done-plan|prepare-human-correction|publish-human-correction-review|check-parallel-write} [options]';}
797
938
 
798
939
  function parseCli(argv){
799
940
  if(argv.length===0||argv.includes('--help')||argv.includes('-h'))return {help:true};
800
941
  const command=argv[0];
801
- if(!['validate-handoff','hash-implementation','check-n4','check-n5','prepare-mark-done','verify-mark-done-plan','mark-done-locked','check-parallel-write'].includes(command))
942
+ if(!['validate-handoff','hash-implementation','check-n4','check-n5','prepare-mark-done','verify-mark-done-plan','mark-done-locked','prepare-human-correction','publish-human-correction-review','check-parallel-write'].includes(command))
802
943
  throw new GateError('unsupported command');
803
944
  const allowed=command==='validate-handoff'?new Set(['--handoff','--task','--attempt'])
804
945
  :command==='hash-implementation'?new Set(['--project-root','--file'])
805
946
  :command==='check-parallel-write'?new Set(['--repo','--assignment'])
806
- :new Set(['--handoff','--reviews-dir','--feature','--task','--project-root','--allow-legacy-unbound','--require-learning',
947
+ :new Set(['--handoff','--reviews-dir','--feature','--task','--project-root','--allow-legacy-unbound','--require-learning','--correction',
948
+ ...(command==='prepare-human-correction'?['--human-authorized','--reason']:[]),
807
949
  ...(['prepare-mark-done','verify-mark-done-plan','mark-done-locked'].includes(command)?['--tasks']:[]),
808
950
  ...(['verify-mark-done-plan','mark-done-locked'].includes(command)?['--expected-plan-digest']:[])]);
809
951
  const required=command==='validate-handoff'?new Set(['--handoff','--task','--attempt'])
@@ -816,15 +958,15 @@ function parseCli(argv){
816
958
  for(let index=1;index<argv.length;){
817
959
  const flag=argv[index];
818
960
  if(!allowed.has(flag))throw new GateError('invalid arguments');
819
- if(flag==='--allow-legacy-unbound'||flag==='--require-learning'){
820
- const key=flag==='--require-learning'?'requireLearning':'allowLegacyUnbound';
961
+ if(flag==='--allow-legacy-unbound'||flag==='--require-learning'||flag==='--human-authorized'){
962
+ const key=flag==='--human-authorized'?'humanAuthorized':flag==='--require-learning'?'requireLearning':'allowLegacyUnbound';
821
963
  if(Object.hasOwn(values,key))throw new GateError(`duplicate argument: ${flag}`);
822
964
  values[key]=true;index++;continue;
823
965
  }
824
966
  const value=argv[index+1];if(value===undefined)throw new GateError('invalid arguments');
825
967
  const key={'--handoff':'handoff','--reviews-dir':'reviewsDir','--feature':'feature','--task':'task','--attempt':'attempt',
826
968
  '--tasks':'tasksPath','--expected-plan-digest':'expectedPlanDigest','--repo':'repo','--assignment':'assignment',
827
- '--project-root':'projectRoot','--file':'file'}[flag];
969
+ '--project-root':'projectRoot','--file':'file','--correction':'correction','--reason':'reason'}[flag];
828
970
  if(['assignment','file'].includes(key)){
829
971
  if(!Object.hasOwn(values,key))values[key]=[];
830
972
  values[key].push(value);
@@ -837,7 +979,7 @@ function parseCli(argv){
837
979
  for(const flag of required){
838
980
  const key={'--handoff':'handoff','--reviews-dir':'reviewsDir','--feature':'feature','--task':'task','--attempt':'attempt',
839
981
  '--tasks':'tasksPath','--expected-plan-digest':'expectedPlanDigest','--repo':'repo','--assignment':'assignment',
840
- '--project-root':'projectRoot','--file':'file'}[flag];
982
+ '--project-root':'projectRoot','--file':'file','--correction':'correction','--reason':'reason'}[flag];
841
983
  if(!Object.hasOwn(values,key))throw new GateError(`missing argument: ${flag}`);
842
984
  }
843
985
  if(Object.hasOwn(values,'attempt')){
@@ -858,6 +1000,8 @@ export function main(argv=process.argv.slice(2),environment=process.env){
858
1000
  result={gate:'handoff',task:payload.task_id,attempt:payload.attempt,outcome:payload.status};
859
1001
  }else if(args.command==='hash-implementation')result={gate:'implementation-hash',
860
1002
  implementation_sha256:implementationSha256(args.projectRoot,args.file),changed_files:[...args.file].sort((left,right)=>Buffer.compare(Buffer.from(left),Buffer.from(right)))};
1003
+ else if(args.command==='prepare-human-correction')result=prepareHumanCorrection(args);
1004
+ else if(args.command==='publish-human-correction-review')result=publishHumanCorrectionReview(args);
861
1005
  else if(args.command==='check-n4')result=checkN4(args);
862
1006
  else if(args.command==='check-n5')result=checkN5(args);
863
1007
  else if(args.command==='prepare-mark-done')result=prepareMarkDone(args);
@@ -245,7 +245,7 @@ def task_writer(reviews: Path, tasks: Path, feature: str) -> Iterator[Path]:
245
245
 
246
246
  def run_js(arguments: Sequence[str], *, environment: Mapping[str, str] | None = None, capture: bool = False):
247
247
  entry = Path(__file__).resolve().with_name("cm-task-gate.mjs")
248
- return subprocess.run(["node", str(entry), *arguments], check=False, text=True, capture_output=capture, env=dict(environment) if environment is not None else None)
248
+ return subprocess.run(["node", str(entry), *arguments], check=False, text=True, encoding="utf-8", capture_output=capture, env=dict(environment) if environment is not None else None)
249
249
 
250
250
 
251
251
  def read_js_object(arguments: Sequence[str], *, environment: Mapping[str, str] | None = None) -> dict[str, object]:
@@ -271,6 +271,7 @@ def mark_parser() -> argparse.ArgumentParser:
271
271
  parser.add_argument("--task", required=True)
272
272
  parser.add_argument("--tasks", required=True)
273
273
  parser.add_argument("--project-root")
274
+ parser.add_argument("--correction")
274
275
  parser.add_argument("--allow-legacy-unbound", action="store_true")
275
276
  parser.add_argument("--require-learning", action="store_true")
276
277
  return parser
@@ -60,9 +60,12 @@ test('remote default selects main unpushed commits; detached HEAD works; ambiguo
60
60
  f.git('branch','-D','main','master');assert.throws(()=>inspectBranchComparison(f.project),/cm_test_main_missing/);
61
61
  });
62
62
  test('non-Git and unborn repositories do not fall back to whole-worktree analysis',t=>{
63
- const f=fixture(t);fs.rmSync(path.join(f.project,'.git'),{recursive:true});
64
- assert.throws(()=>inspectBranchComparison(f.project),/cm_test_git_required/);
65
- f.git('init','-q','-b','main');assert.throws(()=>inspectBranchComparison(f.project),/cm_test_head_required/);
63
+ const project=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-impact-non-git-')));
64
+ t.after(()=>fs.rmSync(project,{recursive:true,force:true}));
65
+ assert.throws(()=>inspectBranchComparison(project),/cm_test_git_required/);
66
+ const initialized=spawnSync('git',['-C',project,'init','-q','-b','main'],{encoding:'utf8'});
67
+ assert.equal(initialized.status,0,initialized.stderr);
68
+ assert.throws(()=>inspectBranchComparison(project),/cm_test_head_required/);
66
69
  });
67
70
  test('two-tip diff includes main-only additions and tracks rename/deletion plus both committed sides',t=>{
68
71
  const f=fixture(t);f.write('old name.txt','old content\n');f.write('gone.txt','removed content\n');f.commit();