@aibyzero/cm-workflow 0.16.5 → 0.16.7

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 (202) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +14 -0
  3. package/CHANGELOG.md +19 -1
  4. package/README.md +17 -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 +28 -7
  17. package/docs/js-workflow-control.md +96 -6
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/untested-branches.md +27 -4
  21. package/docs/user-guide.md +23 -8
  22. package/install-codex.sh +28 -11
  23. package/package.json +1 -1
  24. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  25. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  26. package/runtime/js/cm-ai/cm-ai-admission.mjs +34 -10
  27. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
  28. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -34
  29. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +93 -31
  30. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
  31. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  32. package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
  33. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  34. package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
  35. package/runtime/js/cm-ai/drive-bootstrap.mjs +22 -12
  36. package/runtime/js/cm-ai/drive-core.mjs +9 -3
  37. package/runtime/js/cm-ai/durable-runner-state.mjs +146 -14
  38. package/runtime/js/cm-ai/effect-contract.mjs +1 -1
  39. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  40. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  41. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  42. package/runtime/js/cm-ai/external-models.mjs +52 -0
  43. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  44. package/runtime/js/cm-ai/host-bootstrap.mjs +70 -20
  45. package/runtime/js/cm-ai/host-check.mjs +30 -4
  46. package/runtime/js/cm-ai/host-conversation-execution.mjs +59 -17
  47. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  48. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  49. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  50. package/runtime/js/cm-ai/host-qa-executor.mjs +54 -8
  51. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
  52. package/runtime/js/cm-ai/host-session.mjs +1 -1
  53. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
  54. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  55. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  56. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  57. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  58. package/runtime/js/cm-ai/log-rows.mjs +36 -0
  59. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  60. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  61. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  62. package/runtime/js/cm-ai/operator-guidance.mjs +89 -0
  63. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  64. package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
  65. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  66. package/runtime/js/cm-ai/review-package.mjs +11 -0
  67. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  68. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  69. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  70. package/runtime/js/cm-ai/task-runner.mjs +176 -25
  71. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  72. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  73. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  74. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  75. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  76. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  77. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  78. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  79. package/runtime/js/cm-fix/execution.mjs +183 -40
  80. package/runtime/js/cm-fix/final-review.mjs +18 -10
  81. package/runtime/js/cm-fix/finish.mjs +2 -19
  82. package/runtime/js/cm-fix/host-review.mjs +25 -6
  83. package/runtime/js/cm-fix/host.mjs +4 -1
  84. package/runtime/js/cm-fix/layout.mjs +1 -1
  85. package/runtime/js/cm-fix/log-events.mjs +29 -0
  86. package/runtime/js/cm-fix/metrics.mjs +3 -2
  87. package/runtime/js/cm-fix/progress.mjs +4 -0
  88. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  89. package/runtime/js/cm-prd/analysis.mjs +5 -2
  90. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  91. package/runtime/js/cm-prd/review-host.mjs +2 -1
  92. package/runtime/js/cm-prd/review-publication.mjs +23 -13
  93. package/runtime/js/cm-prd/review-time.mjs +29 -0
  94. package/runtime/js/cm-prd/session.mjs +53 -6
  95. package/runtime/js/cm-security/finalize.mjs +32 -0
  96. package/runtime/js/cm-test/recovery.mjs +4 -4
  97. package/runtime/review.md +5 -0
  98. package/runtime/task-gates.md +6 -0
  99. package/runtime/workflow-config.md +10 -1
  100. package/scripts/cm-ai-admission.mjs +14 -3
  101. package/scripts/cm-ai-batch-drive.mjs +52 -23
  102. package/scripts/cm-ai-batch-drive.test.mjs +47 -2
  103. package/scripts/cm-ai-batch-host.mjs +44 -16
  104. package/scripts/cm-ai-batch-run.mjs +77 -29
  105. package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
  106. package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
  107. package/scripts/cm-ai-bootstrap.test.mjs +80 -87
  108. package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
  109. package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
  110. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
  111. package/scripts/cm-ai-drive.mjs +73 -28
  112. package/scripts/cm-ai-drive.test.mjs +119 -1
  113. package/scripts/cm-ai-feature-selection.test.mjs +178 -0
  114. package/scripts/cm-ai-host.mjs +79 -27
  115. package/scripts/cm-ai-host.test.mjs +88 -0
  116. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  117. package/scripts/cm-ai-progress.test.mjs +521 -0
  118. package/scripts/cm-ai-protected-scope.test.mjs +194 -0
  119. package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
  120. package/scripts/cm-ai-review-failure.test.mjs +71 -11
  121. package/scripts/cm-ai-run.mjs +94 -19
  122. package/scripts/cm-ai-run.test.mjs +2 -1
  123. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  124. package/scripts/cm-check-drive.test.mjs +1 -0
  125. package/scripts/cm-check-runtime.sh +11 -0
  126. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  127. package/scripts/cm-claude-probe.test.mjs +1 -1
  128. package/scripts/cm-codex-plugin-metadata.py +83 -0
  129. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  130. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  131. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  132. package/scripts/cm-efficiency-offline.mjs +35 -0
  133. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  134. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  135. package/scripts/cm-efficiency-response.test.mjs +117 -0
  136. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  137. package/scripts/cm-external-batch-host.test.mjs +157 -0
  138. package/scripts/cm-external-fix-host.test.mjs +281 -0
  139. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  140. package/scripts/cm-external-group-models.test.mjs +60 -0
  141. package/scripts/cm-external-model-host.test.mjs +180 -0
  142. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  143. package/scripts/cm-external-models.test.mjs +89 -0
  144. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  145. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  146. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  147. package/scripts/cm-fix-drive.mjs +28 -13
  148. package/scripts/cm-fix-final-review.test.mjs +11 -6
  149. package/scripts/cm-fix-host.mjs +17 -10
  150. package/scripts/cm-fix-large-log.test.mjs +113 -0
  151. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  152. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  153. package/scripts/cm-fix-review-budget.test.mjs +7 -1
  154. package/scripts/cm-host-qa-executor.test.mjs +329 -3
  155. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  156. package/scripts/cm-live-evidence.test.mjs +64 -0
  157. package/scripts/cm-log-event.mjs +34 -7
  158. package/scripts/cm-log-event.py +15 -0
  159. package/scripts/cm-model-setup.mjs +79 -0
  160. package/scripts/cm-prd-drive.mjs +32 -11
  161. package/scripts/cm-prd-drive.test.mjs +15 -0
  162. package/scripts/cm-prd-host.mjs +26 -6
  163. package/scripts/cm-prd-host.test.mjs +4 -0
  164. package/scripts/cm-prd-review-host.test.mjs +17 -0
  165. package/scripts/cm-prd-session-recovery.test.mjs +44 -2
  166. package/scripts/cm-prd-task-grouping.test.mjs +206 -0
  167. package/scripts/cm-release-smoke.sh +5 -1
  168. package/scripts/cm-review-scope-recovery.test.mjs +5 -3
  169. package/scripts/cm-runtime-i18n.mjs +15 -4
  170. package/scripts/cm-runtime-install.mjs +8 -4
  171. package/scripts/cm-runtime.mjs +116 -23
  172. package/scripts/cm-runtime.test.mjs +121 -12
  173. package/scripts/cm-security.test.mjs +32 -0
  174. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  175. package/scripts/cm-task-gate.mjs +146 -10
  176. package/scripts/cm-task-gate.py +1 -0
  177. package/scripts/cm-test-branch-impact.test.mjs +11 -0
  178. package/scripts/cm-test-drive.mjs +10 -4
  179. package/scripts/cm-test-drive.test.mjs +14 -1
  180. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  181. package/scripts/cm-usage-report.py +22 -3
  182. package/scripts/cm-workflow-config.mjs +10 -1
  183. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  184. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  185. package/scripts/fixtures/process-cleanup.mjs +3 -1
  186. package/scripts/test-cm-native-usage.py +62 -0
  187. package/scripts/test-external-model-setup.py +91 -0
  188. package/scripts/test-model-configuration-write.py +201 -0
  189. package/scripts/test-npm-install.py +10 -1
  190. package/skills/cm-ai/SKILL.md +2 -2
  191. package/skills/cm-ai/references/N1-init.md +1 -1
  192. package/skills/cm-ai/references/N8-finish.md +5 -0
  193. package/skills/cm-ai/references/js-host.md +16 -7
  194. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  195. package/skills/cm-fix/SKILL.md +1 -1
  196. package/skills/cm-fix/references/js-host.md +30 -2
  197. package/skills/cm-prd/SKILL.md +5 -4
  198. package/skills/cm-prd/references/spec-self-check.md +3 -1
  199. package/skills/cm-runtime/SKILL.md +29 -6
  200. package/skills/cm-security/SKILL.md +4 -2
  201. package/skills/cm-security/references/scan-contract.md +1 -0
  202. package/templates/cm-workflow.yml +1 -1
@@ -0,0 +1,94 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {operatorGuidance,guidanceText} from '../runtime/js/cm-ai/operator-guidance.mjs';
4
+ import {batchMemberResult} from './cm-ai-batch-run.mjs';
5
+
6
+ const identity={repositoryId:'fixture',runId:'guidance-run',taskId:'T-001',attempt:1};
7
+ const result=(state,code,pendingAction,extra={})=>({workflow:'cm-ai',identity,state,code,pendingAction,outcome:'reported',...extra});
8
+ const explain=(...args)=>operatorGuidance(result(...args));
9
+
10
+ test('only native resume paths advertise same-run development and never grant permission',()=>{
11
+ for(const code of ['develop_checks_not_passed','develop_package_too_large','developer_result_invalid',
12
+ 'verification_precheck_failed','check_output_out_of_scope','develop_empty_changes','develop_unchanged_after_review',
13
+ 'develop_requirement_missing','bootstrap_verification_failed']){
14
+ const input=result('blocked',code,'resume',{reason:'technical detail'}),before=JSON.stringify(input);
15
+ const guidance=operatorGuidance(input);
16
+ assert.equal(guidance.recoveryOperation,'advance',code);assert.equal(guidance.authorizationGranted,false);
17
+ assert.match(guidance.nextStep,/本轮交付和检查/);assert.match(guidance.prerequisites.join(' '),/原配置、runId/);
18
+ assert.equal(JSON.stringify(input),before,'guidance cannot mutate authority');
19
+ assert.equal(explain('blocked',code,'none').recoveryOperation,null,'no action when native recovery unavailable');
20
+ assert.equal(explain('unknown',code,'reconcile').recoveryOperation,null,'same code is not retry permission');
21
+ }
22
+ assert.match(explain('blocked','develop_package_too_large','resume').nextStep,/先走规格变更/);
23
+ assert.match(explain('blocked','develop_checks_not_passed','resume').summary,/尚未进入独立审查/);
24
+ });
25
+ test('bootstrap recovery restores the package without redispatching developer',()=>{
26
+ const g=explain('blocked','bootstrap_review_mismatch','bootstrap_review_recover');
27
+ assert.equal(g.recoveryOperation,'bootstrap_review_recover');assert.match(g.nextStep,/不重新派发开发/);
28
+ assert.match(g.prerequisites.join(' '),/--allow-bootstrap-review-recovery/);
29
+ assert.equal(explain('blocked','bootstrap_review_mismatch','none').recoveryOperation,null);
30
+ });
31
+ test('spec drift and rejection precede otherwise retryable package or development actions',()=>{
32
+ assert.equal(explain('blocked','spec_drift','bootstrap_review_recover').recoveryOperation,null);
33
+ assert.equal(explain('blocked','spec_drift','spec_rebind').recoveryOperation,null);
34
+ for(const outcome of ['rejected','denied']){
35
+ const g=explain('blocked','develop_checks_not_passed','resume',{outcome});
36
+ assert.equal(g.recoveryOperation,null);assert.match(g.summary,/拒绝/);
37
+ }
38
+ });
39
+ test('unknown must be audited; abandonment is conditional and never an advance instruction',()=>{
40
+ for(const action of ['abandon_effect','abandon_review']){
41
+ const g=explain('unknown','execution_error',action);
42
+ assert.equal(g.recoveryOperation,action);assert.match(g.nextStep,/子进程已退出/);
43
+ assert.match(g.nextStep,/不代表成功/);assert.equal(g.authorizationGranted,false);
44
+ }
45
+ assert.equal(explain('unknown','limit_exceeded','reconcile').recoveryOperation,null);
46
+ assert.match(explain('unknown','execution_error','reconcile').nextStep,/只读核对/);
47
+ });
48
+ test('active operation suppresses recovery and completion is kept separate from development',()=>{
49
+ const g=operatorGuidance(result('unknown','execution_error','abandon_effect'),{executionActive:true});
50
+ assert.equal(g.recoveryOperation,null);assert.match(g.nextStep,/不重复派发/);
51
+ assert.equal(explain('blocked','completion_package_changed','complete').recoveryOperation,'complete');
52
+ assert.match(explain('blocked','completion_checks_changed','complete').nextStep,/不重新开发/);
53
+ assert.equal(explain('blocked','checks_not_passed','none').recoveryOperation,null);
54
+ assert.match(explain('blocked','checks_not_passed','none').summary,/旧完成阶段/);
55
+ assert.equal(explain('fixture_completed','correction_review_required','none').recoveryOperation,null);
56
+ });
57
+ test('unrecognized and successful states do not invent a recovery contract',()=>{
58
+ assert.equal(explain('blocked','unrecognized_code','none').recoveryOperation,null);
59
+ for(const code of ['constructor','__proto__','toString'])assert.equal(explain('blocked',code,'resume').recoveryOperation,null);
60
+ assert.equal(explain('blocked','bootstrap_instruction_conflict','none').recoveryOperation,null);
61
+ for(const state of ['ready','awaiting_review','approved','fixture_completed','run_done'])assert.equal(explain(state,null,'none'),null);
62
+ assert.equal(operatorGuidance(null),null);assert.equal(operatorGuidance({workflow:'cm-fix',state:'blocked',identity}),null);
63
+ });
64
+ test('review redispatch keeps package and fresh authorization prerequisites',()=>{
65
+ const g=explain('pending_review','review_transport_timeout','resume');
66
+ assert.equal(g.recoveryOperation,'advance');assert.match(g.prerequisites.join(' '),/审查包绑定不变/);
67
+ assert.match(g.nextStep,/本轮绑定/);
68
+ });
69
+ test('rendering never uses raw reason and malformed foreign guidance is ignored',()=>{
70
+ const value=result('unknown','execution_error','reconcile',{reason:'private raw provider message'});
71
+ value.guidance=operatorGuidance(value);const rendered=guidanceText(value);
72
+ assert(!rendered.includes(value.reason));assert.match(rendered,/只读核对/);
73
+ assert.equal(guidanceText({...value,workflow:'cm-fix'}),null);
74
+ for(const change of [{authorizationGranted:true},{summary:'control\nline'},{prerequisites:null},{nextStep:'x'.repeat(2001)}])
75
+ assert.equal(guidanceText({...value,guidance:{...value.guidance,...change}}),null);
76
+ });
77
+
78
+ test('batch guidance matches its narrower control surface and never advertises single-host flags',()=>{
79
+ const member=(...args)=>{const value=result(...args);return {...value,guidance:operatorGuidance(value)};};
80
+ const blocked=member('blocked','develop_checks_not_passed','resume');
81
+ const wrapped=batchMemberResult(blocked);
82
+ assert.equal(wrapped.pendingAction,blocked.pendingAction);assert.equal(wrapped.guidance.recoveryOperation,'advance');
83
+ assert.match(guidanceText(wrapped),/原批次入口/);assert.doesNotMatch(guidanceText(wrapped),/--mode/);
84
+ assert.match(guidanceText(batchMemberResult(member('blocked','completion_checks_changed','complete'))),/成员宿主继续完成复核/);
85
+ for(const [state,code,action] of [['unknown','execution_error','abandon_effect'],
86
+ ['unknown','execution_error','abandon_review'],['blocked','bootstrap_review_mismatch','bootstrap_review_recover']]){
87
+ const output=batchMemberResult(member(state,code,action));
88
+ assert.equal(output.guidance.recoveryOperation,null);assert.doesNotMatch(guidanceText(output),/--allow-/);
89
+ assert.match(guidanceText(output),/批次入口不支持/);
90
+ }
91
+ const rebound=batchMemberResult(member('blocked','spec_drift','spec_rebind'));
92
+ assert.equal(rebound.pendingAction,'none');assert.match(rebound.guidance.nextStep,/不能换绑/);
93
+ assert.equal(rebound.guidance.recoveryOperation,null);
94
+ });
@@ -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
+ });