@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,521 @@
1
+ import test,{after} 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 childProcess,{spawn,spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {buildManifest} from './cm-spec-manifest.mjs';
9
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
10
+ import {createConversationExecution} from './cm-ai-host.mjs';
11
+ import {createCmAiConversationEntry} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
12
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
13
+
14
+ const driver=fileURLToPath(new URL('./cm-ai-drive.mjs',import.meta.url));
15
+ const home=fs.mkdtempSync(path.join(os.tmpdir(),'cm-progress-home-'));
16
+ process.env.CM_WORKFLOW_HOME=path.join(home,'home');
17
+ process.env.CM_WORKFLOW_LOG_HOME=path.join(home,'logs');
18
+ after(()=>fs.rmSync(home,{recursive:true,force:true}));
19
+ const identity={repositoryId:'progress-fixture',runId:'progress-fixture-run',taskId:'T-001',attempt:1};
20
+ function fixture(t){
21
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-progress-')));
22
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
23
+ const specsDir=path.join(root,'specs'),codeProject=path.join(root,'code'),feature='1.sample';
24
+ fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);
25
+ for(const file of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,file),'# Fixture\n');
26
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: fixture\n');
27
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
28
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Fixture\n');
29
+ const definition={version:1,specsDir,codeProject,feature,identity,scope:['target.mjs'],requirements:['requirements.md']};
30
+ fs.writeFileSync(path.join(root,'run.json'),JSON.stringify(definition));
31
+ const statusPath=path.join(specsDir,'.cm-status.json');
32
+ const old={node:'N6',feature,task:'T-OLD',state:'qa_passed',detail:'old pass',at:'00:00:00'};
33
+ fs.writeFileSync(statusPath,JSON.stringify(old));
34
+ const answers=path.join(root,'answers');fs.mkdirSync(answers);
35
+ fs.writeFileSync(path.join(answers,'target.txt'),'export const value=42;\n');
36
+ fs.writeFileSync(path.join(answers,'develop.json'),JSON.stringify({status:'succeeded',value:{outcome:'implemented',
37
+ application:{status:'no_relevant_lesson',note:null},retrospective:{status:'no_new_lesson',candidates:[],reason:null}},edits:{'target.mjs':'target.txt'}}));
38
+ fs.writeFileSync(path.join(root,'review.json'),JSON.stringify({model:'fixture',preflight:{}}));
39
+ const plan=(checks,extra={})=>{
40
+ const file=path.join(root,'plan.json');
41
+ fs.writeFileSync(file,JSON.stringify({config:'run.json',mode:'create',hostContext:'progress-fixture-host',
42
+ permissions:['--review-config','review.json'],answers:'answers',checks,...extra}));return file;
43
+ };
44
+ const env={...process.env,CM_WORKFLOW_HOME:path.join(root,'home'),CM_WORKFLOW_LOG_HOME:path.join(root,'logs')};
45
+ const run=(checks,extra={})=>spawnSync(process.execPath,[driver,'--plan',plan(checks,extra),'advance'],{encoding:'utf8',timeout:30000,env});
46
+ return {root,specsDir,codeProject,feature,definition,statusPath,old,env,plan,run,
47
+ status:()=>JSON.parse(fs.readFileSync(statusPath,'utf8')),
48
+ events:()=>fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse)};
49
+ }
50
+ const check=(id,body)=>({id,command:[process.execPath,'-e',body]});
51
+ const control=(operation,selected=identity)=>({version:1,operation,requestId:operation,identity:selected});
52
+
53
+ for(const runtime of ['codex','claude'])test(`${runtime}: live check replaces old task status before command executes`,t=>{
54
+ const f=fixture(t);
55
+ const probe=`const s=JSON.parse(require('node:fs').readFileSync(${JSON.stringify(f.statusPath)}));if(s.task!=='T-001'||s.state!=='checking'){console.error('CM_PROGRESS_STALE '+JSON.stringify(s));process.exit(1)}`;
56
+ const run=f.run([check('probe',probe)],{runtime});
57
+ assert.equal(run.status,0,run.stderr);
58
+ const result=JSON.parse(run.stdout).result;
59
+ assert.equal(result.state,'awaiting_review','CM_PROGRESS_STALE '+run.stderr);
60
+ const status=f.status();assert.equal(status.task,'T-001');assert.equal(status.state,'awaiting_review');
61
+ assert.equal(status.run_id,identity.runId);assert.equal(status.attempt,1);assert.equal(status.node,'N4');
62
+ const events=f.events().filter(row=>row.event==='progress');
63
+ assert(events.some(row=>row.phase==='start'&&row.phase_name==='developing'));
64
+ assert(events.some(row=>row.phase==='start'&&row.phase_name==='checking'));
65
+ assert(!events.some(row=>row.phase_name==='reviewing'),'No reviewer invocation was authorized');
66
+ for(const start of events.filter(row=>row.phase==='start'))assert(events.some(row=>row.phase==='complete'&&row.operation_id===start.operation_id));
67
+ assert(fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'utf8').includes('- [ ] T-001'));
68
+ });
69
+
70
+ test('failed checks project blocked and do not start later commands or independent review',t=>{
71
+ const f=fixture(t),marker=path.join(f.root,'unexpected');
72
+ const run=f.run([check('broken',"console.error('fixture assertion failed');process.exit(2)"),
73
+ check('later',`require('node:fs').writeFileSync(${JSON.stringify(marker)},'wrong')`)]);
74
+ assert.equal(run.status,0,run.stderr);const result=JSON.parse(run.stdout).result;
75
+ assert.equal(result.code,'develop_checks_not_passed');assert.equal(result.pendingAction,'resume');
76
+ assert.equal(result.guidance.recoveryOperation,'advance');assert.equal(result.guidance.authorizationGranted,false);
77
+ assert.match(f.status().detail,/开发检查未通过/);assert.match(run.stderr,/恢复原运行并发送 advance/);
78
+ assert.equal(f.status().state,'blocked');assert.equal(f.status().code,'develop_checks_not_passed');
79
+ assert.equal(f.status().task,identity.taskId);assert.equal(fs.existsSync(marker),false);
80
+ assert.match(run.stderr,/开始检查.*broken/);assert.match(run.stderr,/检查结束.*broken.*failed/);
81
+ assert(!f.events().some(row=>row.event==='progress'&&row.phase_name==='reviewing'));
82
+ });
83
+
84
+ test('guidance survives original-run status and recovery without writing it into the journal',t=>{
85
+ const f=fixture(t),condition=path.join(f.root,'check-ready');
86
+ const checks=[check('environment',`if(!require('node:fs').existsSync(${JSON.stringify(condition)}))process.exit(2)`)];
87
+ const blocked=f.run(checks);assert.equal(blocked.status,0,blocked.stderr);
88
+ const initial=JSON.parse(blocked.stdout).result;
89
+ assert.equal(initial.state,'blocked');assert.equal(initial.guidance.recoveryOperation,'advance');
90
+ const snapshot=()=>readExecutionSnapshot({specsRoot:f.specsDir,identity:{repositoryId:identity.repositoryId,runId:identity.runId}});
91
+ const before=snapshot(),statusBytes=fs.readFileSync(f.statusPath);
92
+ const plan=f.plan(checks,{mode:'resume'});
93
+ const reported=spawnSync(process.execPath,[driver,'--plan',plan,'status'],{encoding:'utf8',timeout:30000,env:f.env});
94
+ assert.equal(reported.status,0,reported.stderr);
95
+ assert.deepEqual(JSON.parse(reported.stdout).result.guidance,initial.guidance);
96
+ assert.deepEqual(snapshot(),before);assert.deepEqual(fs.readFileSync(f.statusPath),statusBytes);
97
+ fs.writeFileSync(condition,'ready');
98
+ const resumed=f.run(checks,{mode:'resume'});assert.equal(resumed.status,0,resumed.stderr);
99
+ const result=JSON.parse(resumed.stdout).result;
100
+ assert.equal(result.state,'awaiting_review');assert.equal(result.identity.runId,identity.runId);
101
+ assert.equal(result.identity.attempt,1);assert.equal(result.guidance,undefined);
102
+ const after=snapshot();assert.deepEqual(after.records.slice(0,before.records.length),before.records);
103
+ assert.equal(JSON.stringify(after.records).includes('recoveryOperation'),false);
104
+ assert(fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'utf8').includes('- [ ] T-001'));
105
+ assert(!f.events().some(row=>row.phase_name==='reviewing'),'no independent review grant');
106
+ });
107
+
108
+ test('a quiet command announces its start before finishing and preserves the JSON result channel',async t=>{
109
+ const f=fixture(t),plan=f.plan([check('quiet',"setTimeout(()=>process.exit(0),700)")]);
110
+ const child=spawn(process.execPath,[driver,'--plan',plan,'advance'],{env:f.env,stdio:['ignore','pipe','pipe']});
111
+ let out='',err='',seen=false,code;
112
+ const timer=setTimeout(()=>child.kill('SIGKILL'),20000);t.after(()=>{clearTimeout(timer);if(child.exitCode===null)child.kill('SIGKILL');});
113
+ child.stdout.on('data',b=>{out+=b;});child.stderr.on('data',b=>{
114
+ err+=b;if(!seen&&/开始检查.*quiet/.test(err)){seen=true;assert.equal(child.exitCode,null);assert.equal(f.status().state,'checking');}
115
+ });
116
+ code=await new Promise((resolve,reject)=>{child.once('error',reject);child.once('exit',resolve);});
117
+ assert.equal(code,0,err);assert(seen,'a quiet check must be visible while it is running');
118
+ assert.match(err,/检查结束.*quiet.*passed/);assert.equal(JSON.parse(out).result.state,'awaiting_review');
119
+ });
120
+
121
+ test('read-only status and foreign/invalid operations preserve existing projection bytes',async t=>{
122
+ const f=fixture(t);let effects=0;
123
+ const current={state:'awaiting_review',code:null,identity,packageDigest:'a'.repeat(64),calls:[]};
124
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
125
+ runner:{status:()=>current,executeEffect:async()=>{effects++;return current;},cancel:()=>current,run:async()=>current}});
126
+ const before=fs.readFileSync(f.statusPath);
127
+ assert.equal((await entry.handle(control('status'))).state,'awaiting_review');
128
+ assert.equal((await entry.handle(control('advance',{...identity,runId:'foreign-run'}))).outcome,'rejected');
129
+ assert.equal((await entry.handle({...control('advance'),extra:true})).outcome,'rejected');
130
+ assert.deepEqual(fs.readFileSync(f.statusPath),before);assert.equal(effects,0);
131
+ });
132
+
133
+ test('status reads once, exposes no private calls, and never runs a second display read',async t=>{
134
+ const f=fixture(t);let reads=0;
135
+ const before=fs.readFileSync(f.statusPath),tasks=fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'));
136
+ const current={state:'unknown',code:'reconciliation_required',identity,packageDigest:'a'.repeat(64),
137
+ calls:[{secret:'private-call'}],reviewInvocation:{secret:'private-invocation'}};
138
+ const unexpected=()=>{throw Error('must not dispatch or mutate');};
139
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
140
+ runner:{status:()=>{if(++reads!==1)throw Error('unnecessary display read');return current;},
141
+ executeEffect:unexpected,cancel:unexpected,run:unexpected}});
142
+ const result=await entry.handle(control('status'));
143
+ assert.equal(result.outcome,'reported');assert.equal(result.pendingAction,'reconcile');assert.equal(reads,1);
144
+ assert(!Object.hasOwn(result,'calls'));assert(!Object.hasOwn(result,'reviewInvocation'));
145
+ assert(!JSON.stringify(result).includes('private-'));
146
+ assert.deepEqual(fs.readFileSync(f.statusPath),before);
147
+ assert.deepEqual(fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md')),tasks);
148
+ assert.equal(fs.existsSync(path.join(f.specsDir,'运行日志.jsonl')),false);
149
+ });
150
+
151
+ for(const admission of [{state:'awaiting_spec_approval',reason:'spec_approval_required'},
152
+ {state:'blocked',reason:'spec_features_invalid'}])
153
+ test(`admission ${admission.state} never reads or dispatches the original runner`,async t=>{
154
+ const f=fixture(t),before=fs.readFileSync(f.statusPath);let touches=0;
155
+ const unexpected=()=>{touches++;throw Error('admission must not touch runner');};
156
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
157
+ runner:{inspectBootstrapAdmission:()=>admission,status:unexpected,
158
+ executeEffect:unexpected,cancel:unexpected,run:unexpected}});
159
+ for(const operation of ['start','resume']){
160
+ const result=await entry.handle(control(operation));
161
+ assert.equal(result.outcome,'awaiting');assert.equal(result.code,admission.reason);
162
+ assert.deepEqual(result.identity,identity);assert.equal(result.packageDigest,null);
163
+ }
164
+ assert.equal(touches,0);
165
+ assert.deepEqual(fs.readFileSync(f.statusPath),before);
166
+ assert.equal(fs.existsSync(path.join(f.specsDir,'运行日志.jsonl')),false);
167
+ });
168
+
169
+ for(const admission of [{state:'awaiting_spec_approval',reason:'spec_approval_required'},
170
+ {state:'blocked',reason:'spec_features_invalid'}])
171
+ test(`advance preserves admission ${admission.state} without an extra display read`,async t=>{
172
+ const f=fixture(t),before=fs.readFileSync(f.statusPath);let reads=0,admissions=0,effects=0;
173
+ const current={state:'ready',code:null,identity,packageDigest:null};
174
+ const unexpected=()=>{effects++;throw Error('admission must not dispatch');};
175
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
176
+ runner:{inspectBootstrapAdmission:()=>{admissions++;return admission;},status:()=>{reads++;return current;},
177
+ executeEffect:unexpected,cancel:unexpected,run:unexpected}});
178
+ const result=await entry.handle(control('advance'));
179
+ assert.equal(result.operation,'advance');assert.equal(result.outcome,'awaiting');
180
+ assert.equal(result.state,admission.state);assert.equal(result.code,admission.reason);
181
+ assert.deepEqual(result.identity,identity);assert.equal(result.packageDigest,null);
182
+ assert.equal(reads,4,'advance keeps its state/identity reads but adds no display read');
183
+ assert.equal(admissions,1);assert.equal(effects,0);assert.deepEqual(fs.readFileSync(f.statusPath),before);
184
+ assert.equal(fs.existsSync(path.join(f.specsDir,'运行日志.jsonl')),false);
185
+ });
186
+
187
+ test('admission binds a newer real attempt once and refuses an invented attempt',async t=>{
188
+ const f=fixture(t),before=fs.readFileSync(f.statusPath),actual={...identity,attempt:2};let reads=0;
189
+ let current={state:'changes_requested',code:null,identity:actual,packageDigest:'a'.repeat(64)};
190
+ const unexpected=()=>{throw Error('must not dispatch while specs await approval');};
191
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
192
+ runner:{inspectBootstrapAdmission:()=>({state:'awaiting_spec_approval',reason:'spec_approval_required'}),
193
+ status:()=>{reads++;return current;},executeEffect:unexpected,cancel:unexpected,run:unexpected}});
194
+ for(const operation of ['start','resume']){
195
+ const result=await entry.handle(control(operation,actual));
196
+ assert.equal(result.code,'spec_approval_required');assert.deepEqual(result.identity,actual);
197
+ }
198
+ const legitimateReads=reads;
199
+ current={...current,identity};
200
+ const invented=await entry.handle(control('resume',actual));
201
+ assert.equal(invented.outcome,'rejected');assert.equal(invented.code,'identity_mismatch');
202
+ assert.equal(legitimateReads,2,'one identity read per newer-attempt admission, no display read');
203
+ assert.equal(reads,3);assert.deepEqual(fs.readFileSync(f.statusPath),before);
204
+ });
205
+
206
+ for(const waiting of ['revision_answer_required','provider_development_authorization_required'])
207
+ test(`${waiting} preserves the real waiting projection`,async t=>{
208
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
209
+ const f=fixture(t),actual={...identity,attempt:2};let reads=0;
210
+ writeStatusProjection({specsDir:f.specsDir,feature:f.feature,identity:actual,node:'N4',state:'reviewing',detail:'old review',claim:true});
211
+ const current={state:'changes_requested',code:null,identity:actual,packageDigest:'a'.repeat(64),calls:[]};
212
+ const unexpected=()=>{throw Error('waiting must not dispatch');};
213
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
214
+ ...(waiting==='revision_answer_required'?{holdRevision:true}:{developmentAttempt:1}),
215
+ runner:{status:()=>{reads++;return current;},executeEffect:unexpected,cancel:unexpected,run:unexpected}});
216
+ const result=await entry.handle(control('resume',actual));
217
+ assert.equal(result.outcome,'awaiting');assert.equal(result.code,waiting);assert.deepEqual(result.identity,actual);
218
+ assert.equal(f.status().state,'changes_requested');assert.equal(f.status().code,waiting);assert.equal(reads,3);
219
+ });
220
+
221
+ test('a completed effect projects its fresh current state once',async t=>{
222
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
223
+ const f=fixture(t);let current={state:'approved',code:null,identity,packageDigest:'a'.repeat(64)},effects=0,displayReads=0;
224
+ writeStatusProjection({specsDir:f.specsDir,feature:f.feature,identity,node:'N4',state:'reviewing',detail:'reviewed',claim:true});
225
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
226
+ runner:{status:()=>{if(effects)displayReads++;return current;},executeEffect:async()=>{
227
+ effects++;current={...current,state:'fixture_completed'};return current;},cancel:()=>current,run:async()=>current}});
228
+ const result=await entry.handle({...control('complete'),packageDigest:current.packageDigest});
229
+ assert.equal(result.outcome,'advanced');assert.equal(result.state,'fixture_completed');
230
+ assert.equal(f.status().state,'fixture_completed');assert.equal(f.status().node,'N5');
231
+ assert.equal(effects,1);assert.equal(displayReads,1);
232
+ });
233
+
234
+ test('a failed display read cannot reject a successful runner completion',async t=>{
235
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
236
+ const f=fixture(t);let completed=false,effects=0,displayReads=0;
237
+ writeStatusProjection({specsDir:f.specsDir,feature:f.feature,identity,node:'N4',state:'reviewing',detail:'reviewed',claim:true});
238
+ const before=fs.readFileSync(f.statusPath),current={state:'approved',code:null,identity,packageDigest:'a'.repeat(64)};
239
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
240
+ runner:{status:()=>{if(completed){displayReads++;throw Error('display unavailable');}return current;},
241
+ executeEffect:async()=>{effects++;completed=true;return {...current,state:'fixture_completed'};},
242
+ cancel:()=>{throw Error('unexpected cancel');},run:async()=>current}});
243
+ const result=await entry.handle({...control('complete'),packageDigest:current.packageDigest});
244
+ assert.equal(result.outcome,'advanced');assert.equal(result.state,'fixture_completed');
245
+ assert.equal(effects,1);assert.equal(displayReads,1);assert.deepEqual(fs.readFileSync(f.statusPath),before);
246
+ });
247
+
248
+ test('cancellation epoch rejects a late completion even when runner state still matches',async t=>{
249
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
250
+ const f=fixture(t);let release,enter;
251
+ const entered=new Promise(resolve=>{enter=resolve;});
252
+ let current={state:'approved',code:null,identity,packageDigest:'a'.repeat(64)};
253
+ writeStatusProjection({specsDir:f.specsDir,feature:f.feature,identity,node:'N4',state:'reviewing',detail:'original',claim:true});
254
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
255
+ runner:{status:()=>current,executeEffect:()=>{current={...current,state:'fixture_completed'};enter();
256
+ return new Promise(resolve=>{release=resolve;});},cancel:()=>current,run:async()=>current}});
257
+ const pending=entry.handle({...control('complete'),packageDigest:current.packageDigest});await entered;
258
+ const cancelled=await entry.handle(control('cancel'));
259
+ assert.equal(cancelled.outcome,'cancelled');assert.equal(cancelled.state,'fixture_completed');
260
+ const before=fs.readFileSync(f.statusPath);release(current);await pending;
261
+ assert.deepEqual(fs.readFileSync(f.statusPath),before);
262
+ });
263
+
264
+ for(const changed of ['state','runId','taskId','attempt'])
265
+ test(`a late completion cannot project over changed current ${changed}`,async t=>{
266
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
267
+ const f=fixture(t);let release,enter,displayReads=0,completed=false;
268
+ const entered=new Promise(resolve=>{enter=resolve;});
269
+ const currentBefore={state:'approved',code:null,identity,packageDigest:'a'.repeat(64)};
270
+ let current=currentBefore;
271
+ writeStatusProjection({specsDir:f.specsDir,feature:f.feature,identity,node:'N4',state:'reviewing',detail:'original',claim:true});
272
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
273
+ runner:{status:()=>{if(completed)displayReads++;return current;},
274
+ executeEffect:()=>{enter();return new Promise(resolve=>{release=resolve;});},cancel:()=>current,run:async()=>current}});
275
+ const pending=entry.handle({...control('complete'),packageDigest:current.packageDigest});await entered;
276
+ current={...current,state:'fixture_completed',identity:{...identity}};
277
+ if(changed==='state')current.state='unknown';
278
+ else current.identity[changed]=changed==='attempt'?2:changed==='taskId'?'T-002':'newer-progress-run';
279
+ const before=fs.readFileSync(f.statusPath);completed=true;
280
+ release({...currentBefore,state:'fixture_completed'});const result=await pending;
281
+ assert.equal(result.state,'fixture_completed');assert.equal(displayReads,1,'fresh state is read once after the effect');
282
+ assert.deepEqual(fs.readFileSync(f.statusPath),before);
283
+ });
284
+
285
+ test('real durable status preserves code, task, receipt, journal and checkpoint bytes',t=>{
286
+ const f=fixture(t),first=f.run([check('syntax',"process.exit(0)")]);
287
+ assert.equal(first.status,0,first.stderr);assert.equal(JSON.parse(first.stdout).result.state,'awaiting_review');
288
+ const capture=()=>{
289
+ const files=new Map();
290
+ const visit=dir=>{for(const item of fs.readdirSync(dir,{withFileTypes:true})){
291
+ const file=path.join(dir,item.name);if(item.isDirectory())visit(file);else if(item.isFile())files.set(file,fs.readFileSync(file));
292
+ }};
293
+ visit(f.codeProject);visit(path.join(f.specsDir,'.reviews'));
294
+ for(const file of [f.statusPath,path.join(f.specsDir,f.feature,'tasks.md'),path.join(f.specsDir,'运行日志.jsonl')]){
295
+ if(fs.existsSync(file))files.set(file,fs.readFileSync(file));
296
+ }
297
+ return files;
298
+ };
299
+ const before=capture(),plan=f.plan([check('syntax',"process.exit(0)")],{mode:'resume'});
300
+ const reported=spawnSync(process.execPath,[driver,'--plan',plan,'status'],{encoding:'utf8',timeout:30000,env:f.env});
301
+ assert.equal(reported.status,0,reported.stderr);const result=JSON.parse(reported.stdout).result;
302
+ assert.equal(result.outcome,'reported');assert.equal(result.state,'awaiting_review');
303
+ assert(!Object.hasOwn(result,'calls'));assert(!Object.hasOwn(result,'reviewInvocation'));
304
+ assert.deepEqual(capture(),before);
305
+ assert(!f.events().some(row=>row.phase_name==='reviewing'),'status must not start the independent reviewer');
306
+ });
307
+
308
+ test('check phase is visible to a manual current-session bridge before it replies',async t=>{
309
+ const f=fixture(t);let seen=false;
310
+ const bridge={call:async kind=>{assert.equal(kind,'check');seen=true;assert.equal(f.status().task,'T-001');assert.equal(f.status().state,'checking');return [];} };
311
+ const execution=createConversationExecution(f.definition,'progress-host',bridge,null,null,null,false,'codex');
312
+ await execution.check({identity},{signal:new AbortController().signal});assert(seen);
313
+ });
314
+
315
+ test('status projection failures do not change a successful check or follow a target symlink',async t=>{
316
+ const f=fixture(t),outside=path.join(f.root,'outside.json');fs.writeFileSync(outside,'KEEP');
317
+ fs.unlinkSync(f.statusPath);fs.symlinkSync(outside,f.statusPath);
318
+ let calls=0;const result=[{id:'check',command:['fixture'],outcome:'passed',exitCode:0,evidence:'fixture'}];
319
+ const execution=createConversationExecution(f.definition,'progress-host',{call:async()=>{calls++;return result;}},null,null,null,false,'codex');
320
+ assert.deepEqual(await execution.check({identity},{signal:new AbortController().signal}),result);
321
+ assert.equal(calls,1);assert.equal(fs.readFileSync(outside,'utf8'),'KEEP');assert(fs.lstatSync(f.statusPath).isSymbolicLink());
322
+ });
323
+
324
+ test('an already cancelled check cannot overwrite the existing projection',async t=>{
325
+ const f=fixture(t),before=fs.readFileSync(f.statusPath),controller=new AbortController();controller.abort();
326
+ const execution=createConversationExecution(f.definition,'progress-host',{call:async()=>{throw Error('must not dispatch');}},null,null,null,false,'codex');
327
+ await assert.rejects(async()=>execution.check({identity},{signal:controller.signal}),/cancelled/);
328
+ assert.deepEqual(fs.readFileSync(f.statusPath),before);
329
+ });
330
+
331
+ test('protected checks announce quiet command boundaries through the same executor',{skip:spawnSync('codex',['--version']).status!==0},async t=>{
332
+ const f=fixture(t),events=[],original=process.stderr.write;
333
+ process.stderr.write=function(chunk,...args){
334
+ if(String(chunk).includes('[check]'))events.push({text:String(chunk),status:f.status()});
335
+ return original.call(this,chunk,...args);
336
+ };
337
+ t.after(()=>{process.stderr.write=original;});
338
+ const execution=createConversationExecution(f.definition,'progress-protected-host',{
339
+ call:async()=>{throw Error('protected checks must not use the external bridge');}},null,null,null,false,'codex',{
340
+ protection:{checkCommands:[check('protected-quiet',"setTimeout(()=>process.exit(0),100)")],timeoutMs:15000}});
341
+ const result=await execution.check({identity},{signal:new AbortController().signal});
342
+ assert.equal(result[0].outcome,'passed',JSON.stringify(result));
343
+ assert.equal(events.length,2);assert.match(events[0].text,/开始检查.*protected-quiet/);
344
+ assert.equal(events[0].status.state,'checking');assert.match(events[1].text,/检查结束.*protected-quiet.*passed/);
345
+ });
346
+
347
+ test('check observers cannot change verdicts or prevent process cleanup',async t=>{
348
+ const {createHostCheck}=await import('../runtime/js/cm-ai/host-check.mjs');
349
+ const f=fixture(t),events=[];
350
+ const run=createHostCheck({cwd:f.codeProject,commands:[check('bad',"process.exit(3)"),check('not-run',"process.exit(0)")],
351
+ onProgress:event=>{events.push(event);throw Error('display unavailable');}});
352
+ const result=await run({identity},{signal:new AbortController().signal});
353
+ assert.equal(result.length,1);assert.equal(result[0].outcome,'failed');assert.equal(result[0].exitCode,3);
354
+ assert.deepEqual(events.map(row=>[row.phase,row.id]),[['start','bad'],['complete','bad']]);
355
+ });
356
+
357
+ test('late QA completion cannot overwrite a newer task, including identical task numbers in another feature',async t=>{
358
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
359
+ const {writeCmAiQaStatus}=await import('../runtime/js/cm-ai/cm-ai-run-finalizer.mjs');
360
+ const f=fixture(t);
361
+ writeCmAiQaStatus({specsDir:f.specsDir,feature:f.feature,identity,phase:'case_start',caseId:'TC-001'});
362
+ const current={...identity,runId:'newer-progress-run'};
363
+ writeStatusProjection({specsDir:f.specsDir,feature:'2.other',identity:current,node:'N3',state:'checking',detail:'new check',claim:true});
364
+ const before=fs.readFileSync(f.statusPath);
365
+ writeCmAiQaStatus({specsDir:f.specsDir,feature:f.feature,identity,phase:'complete',result:{result:'PASS',passed:1,failed:0,blocked:0}});
366
+ assert.deepEqual(fs.readFileSync(f.statusPath),before);
367
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.cm-run.json')),false,'projection must not move the run pointer');
368
+ });
369
+
370
+ test('stale phase token is refused even for the same task and run',async t=>{
371
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
372
+ const f=fixture(t),base={specsDir:f.specsDir,feature:f.feature,identity,node:'N3',state:'checking',detail:'checking'};
373
+ const old=writeStatusProjection({...base,claim:true});
374
+ const current=writeStatusProjection({...base,node:'N4',state:'reviewing',detail:'reviewing',claim:true});
375
+ assert.equal(writeStatusProjection({...base,state:'blocked',expectedToken:old.token}).written,false);
376
+ assert.equal(f.status().progress_id,current.token);assert.equal(f.status().state,'reviewing');
377
+ });
378
+
379
+ test('two processes serialize a newer claim with an older completion under the existing log lock',async t=>{
380
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
381
+ const f=fixture(t),base={feature:f.feature,identity,node:'N3',state:'checking',detail:'checking'};
382
+ const old=writeStatusProjection({specsDir:f.specsDir,...base,claim:true});
383
+ const next={...base,identity:{...identity,runId:'newer-progress-run',taskId:'T-002'},claim:true,expectedToken:null};
384
+ const logPython=fileURLToPath(new URL('./cm-log-event.py',import.meta.url));
385
+ const logNode=fileURLToPath(new URL('./cm-log-event.mjs',import.meta.url));
386
+ const holder=spawn('python3',['-u','-c',
387
+ `import importlib.util,os,sys,subprocess\nfrom pathlib import Path\nspec=importlib.util.spec_from_file_location('lock_adapter',sys.argv[1])\nm=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)\nm.acquire_file_lock(Path(sys.argv[2])/'.cm-run.lock',private=False)\nprint('locked',flush=True)\nsys.stdin.readline()\nenv=os.environ.copy();env.update(CM_LOG_LOCK_ADAPTER='1',CM_LOG_LOCK_PARENT_PID=str(os.getpid()),CM_LOG_PROJECT_LOCK=str(Path(sys.argv[2])/'.cm-run.lock'))\nr=subprocess.run([sys.argv[3],sys.argv[4],'--status-only','--specs-dir',sys.argv[2],'--status-json',sys.argv[5]],env=env,check=True)\n`,
388
+ logPython,f.specsDir,process.execPath,logNode,JSON.stringify(next)],{stdio:['pipe','pipe','pipe']});
389
+ const children=[holder];t.after(()=>{for(const c of children)if(c.exitCode===null)c.kill('SIGKILL');});
390
+ const waitLine=(child,pattern)=>new Promise((resolve,reject)=>{
391
+ let value='';const timer=setTimeout(()=>{child.kill('SIGKILL');reject(Error('fixture line timeout'));},10000);
392
+ child.stdout.on('data',b=>{value+=b;if(pattern.test(value)){clearTimeout(timer);resolve();}});
393
+ child.once('error',error=>{clearTimeout(timer);reject(error);});
394
+ });
395
+ const exit=child=>new Promise((resolve,reject)=>{child.once('error',reject);child.once('exit',resolve);});
396
+ const holderExit=exit(holder);await waitLine(holder,/locked/);
397
+ const completion={...base,state:'blocked',claim:false,expectedToken:old.token,specsDir:f.specsDir};
398
+ const moduleUrl=new URL('../runtime/js/cm-ai/status-projection.mjs',import.meta.url).href;
399
+ const late=spawn(process.execPath,['--input-type=module','-e',
400
+ `import {writeStatusProjection} from ${JSON.stringify(moduleUrl)};process.stdout.write('ready\\n');console.log(JSON.stringify(writeStatusProjection(${JSON.stringify(completion)})));`],{stdio:['ignore','pipe','pipe']});
401
+ children.push(late);let lateOut='',errors='';late.stdout.on('data',b=>{lateOut+=b;});
402
+ for(const c of children)c.stderr.on('data',b=>{errors+=b;});
403
+ const lateExit=exit(late);await waitLine(late,/ready/);
404
+ // The old completion has its previous token, but cannot validate-and-replace
405
+ // while the newer claimant owns the lock. The claimant writes before release.
406
+ holder.stdin.end('claim\n');
407
+ assert.equal(await holderExit,0,errors);assert.equal(await lateExit,0,errors);
408
+ assert.match(lateOut,/"written":false/);assert.equal(f.status().task,'T-002');
409
+ });
410
+
411
+ for(const verdict of ['approved','changes_requested'])test(`${verdict}: review projection waits for an observed provider thread`,t=>{
412
+ const f=fixture(t),bin=path.join(f.root,'bin');fs.mkdirSync(bin);
413
+ const observed=path.join(f.root,'observed-review.json');
414
+ const source=fs.readFileSync(fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url)),'utf8');
415
+ const fake=source.replace("import {randomUUID} from 'node:crypto';","import {randomUUID} from 'node:crypto';\nimport fs from 'node:fs';")
416
+ .replace(' for(const value of',` const statusPath=${JSON.stringify(f.statusPath)};
417
+ if(JSON.parse(fs.readFileSync(statusPath)).state!=='review_starting')throw Error('review started prematurely');
418
+ for(const value of`)
419
+ .replace(" process.stdout.write(JSON.stringify(value)+'\\n');",` {
420
+ process.stdout.write(JSON.stringify(value)+'\\n');
421
+ if(value.type==='thread.started'){
422
+ const deadline=Date.now()+5000;let status;
423
+ do{
424
+ await new Promise(resolve=>setTimeout(resolve,10));status=JSON.parse(fs.readFileSync(statusPath));
425
+ }while(status.state!=='reviewing'&&Date.now()<deadline);
426
+ if(status.state!=='reviewing')throw Error('observed review was not projected');
427
+ fs.writeFileSync(${JSON.stringify(observed)},JSON.stringify(status));
428
+ }
429
+ }`);
430
+ fs.writeFileSync(path.join(bin,'codex'),verdict==='approved'?fake:fake
431
+ .replace("verdict:'approved'","verdict:'changes_requested'")
432
+ .replace('findings:[]',"findings:[{id:'F1',severity:'P2',path:'target.mjs',message:'Revise value',evidence:'Synthetic fixture finding'}]"),{mode:0o700});
433
+ f.env.PATH=bin+path.delimiter+f.env.PATH;
434
+ fs.writeFileSync(path.join(f.root,'review.json'),JSON.stringify({model:'fixture',preflight:{passed:true,
435
+ cli_model:'fixture',prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd:f.codeProject,model:'fixture'})}}));
436
+ const first=f.run([check('ok','0')]);assert.equal(first.status,0,first.stderr);
437
+ assert.equal(f.status().state,'awaiting_review');assert.equal(fs.existsSync(observed),false);
438
+ const plan=f.plan(undefined,{mode:'resume',originalHostContext:'progress-fixture-host',answers:undefined,
439
+ packageDigest:JSON.parse(first.stdout).result.packageDigest,
440
+ permissions:['--review-config','review.json','--allow-review-attempt','1']});
441
+ const run=spawnSync(process.execPath,[driver,'--plan',plan,'decision'],{env:f.env,encoding:'utf8',timeout:30000});
442
+ assert.equal(run.status,0,run.stderr);assert.equal(JSON.parse(run.stdout).result.state,verdict,run.stdout+run.stderr);
443
+ assert.equal(JSON.parse(fs.readFileSync(observed)).state,'reviewing');assert.equal(f.status().state,verdict);
444
+ assert.equal(f.status().attempt,verdict==='approved'?1:2);
445
+ assert(fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'utf8').includes('- [ ] T-001'));
446
+ if(verdict==='approved'){
447
+ const completed=f.run([check('ok','0')],{mode:'resume',originalHostContext:'progress-fixture-host'});
448
+ assert.equal(completed.status,0,completed.stderr);
449
+ assert.equal(JSON.parse(completed.stdout).result.state,'fixture_completed',completed.stdout+completed.stderr);
450
+ assert.equal(f.status().state,'fixture_completed');assert.equal(f.status().node,'N5');
451
+ assert.equal(f.status().code,'qa_decision_required');
452
+ }
453
+ });
454
+
455
+ test('late N8 finalization records its own history but cannot claim another task status',async t=>{
456
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
457
+ const {recordCmAiRunDone}=await import('../runtime/js/cm-ai/cm-ai-run-finalizer.mjs');
458
+ const f=fixture(t);
459
+ writeStatusProjection({specsDir:f.specsDir,feature:f.feature,identity:{...identity,runId:'newer-run',taskId:'T-002'},
460
+ node:'N3',state:'checking',detail:'checking',claim:true});
461
+ const before=fs.readFileSync(f.statusPath);
462
+ const receipt=recordCmAiRunDone({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
463
+ packageDigest:'a'.repeat(64),contextDigest:'b'.repeat(64),documentationSyncId:'fixture-docs',logHome:path.join(f.root,'logs')});
464
+ assert.equal(receipt.runId,identity.runId);assert.deepEqual(fs.readFileSync(f.statusPath),before);
465
+ assert(f.events().some(row=>row.event==='run_done'&&row.run_id===identity.runId));
466
+ });
467
+
468
+ test('a cancelled in-flight control response cannot replace the final cancellation status',async t=>{
469
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
470
+ const f=fixture(t);let finish;
471
+ writeStatusProjection({specsDir:f.specsDir,feature:f.feature,identity,node:'N4',state:'reviewing',detail:'reviewing',claim:true});
472
+ let current={state:'approved',code:null,identity,packageDigest:'a'.repeat(64),calls:[]};
473
+ const entry=createCmAiConversationEntry({specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
474
+ runner:{status:()=>current,executeEffect:()=>new Promise(resolve=>{finish=resolve;}),
475
+ cancel:()=>{current={...current,state:'cancelled'};return current;},run:async()=>current}});
476
+ const pending=entry.handle({...control('complete'),packageDigest:current.packageDigest});
477
+ assert.equal(typeof finish,'function');
478
+ const cancelled=await entry.handle(control('cancel'));assert.equal(cancelled.state,'cancelled');
479
+ assert.equal(f.status().state,'cancelled');assert.equal(f.status().node,'N4');
480
+ const before=fs.readFileSync(f.statusPath);
481
+ finish({...current,state:'fixture_completed'});await pending;
482
+ assert.deepEqual(fs.readFileSync(f.statusPath),before);
483
+ });
484
+
485
+ test('a repeated QA completion cannot replace the same run finalization',async t=>{
486
+ const {writeStatusProjection}=await import('../runtime/js/cm-ai/status-projection.mjs');
487
+ const {writeCmAiQaStatus}=await import('../runtime/js/cm-ai/cm-ai-run-finalizer.mjs');
488
+ const f=fixture(t);
489
+ writeStatusProjection({specsDir:f.specsDir,feature:f.feature,identity,node:'N8',state:'run_done',detail:'done',claim:true});
490
+ const before=fs.readFileSync(f.statusPath);
491
+ writeCmAiQaStatus({specsDir:f.specsDir,feature:f.feature,identity,phase:'complete',result:{result:'PASS',passed:1,failed:0,blocked:0}});
492
+ assert.deepEqual(fs.readFileSync(f.statusPath),before);
493
+ });
494
+
495
+ test('N8 recovers a real status target failure without duplicating the durable completion',async t=>{
496
+ const {recordCmAiRunDone}=await import('../runtime/js/cm-ai/cm-ai-run-finalizer.mjs');
497
+ const f=fixture(t),input={specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,identity,
498
+ packageDigest:'a'.repeat(64),contextDigest:'b'.repeat(64),documentationSyncId:'fixture-docs',logHome:path.join(f.root,'logs')};
499
+ fs.unlinkSync(f.statusPath);
500
+ const original=childProcess.spawnSync;let injected=false;
501
+ try{
502
+ childProcess.spawnSync=(command,args,options)=>{
503
+ const result=original(command,args,options);
504
+ if(!injected&&args.includes('run_done')){injected=true;fs.mkdirSync(f.statusPath);}
505
+ return result;
506
+ };
507
+ assert.throws(()=>recordCmAiRunDone(input),error=>error.code==='run_finalize_unknown');
508
+ }finally{childProcess.spawnSync=original;if(injected)fs.rmdirSync(f.statusPath);}
509
+ assert(injected);const receipt=recordCmAiRunDone(input);assert.equal(receipt.deduplicated,true);
510
+ assert.equal(f.events().filter(row=>row.event==='run_done').length,1);assert.equal(f.status().state,'run_done');
511
+ });
512
+
513
+ test('status-only text in ordinary event data does not select the internal status command',t=>{
514
+ const f=fixture(t),before=fs.readFileSync(f.statusPath);
515
+ const writer=fileURLToPath(new URL('./cm-log-event.py',import.meta.url));
516
+ const run=spawnSync('python3',[writer,'--workflow','cm-ai','--event','progress','--runtime','codex',
517
+ '--specs-dir',f.specsDir,'--project-root',f.codeProject,'--run-id',identity.runId,'--detail','--status-only'],
518
+ {encoding:'utf8',env:f.env});
519
+ assert.equal(run.status,0,run.stderr);assert.equal(JSON.parse(run.stdout).pointer_written,true);
520
+ assert.equal(f.events().at(-1).detail,'--status-only');assert.deepEqual(fs.readFileSync(f.statusPath),before);
521
+ });