@aibyzero/cm-workflow 0.21.6 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +58 -0
  3. package/README.md +18 -3
  4. package/VERSION +1 -1
  5. package/docs/architecture.md +9 -0
  6. package/docs/cm-acceptance-completion.md +3 -1
  7. package/docs/cm-control-policy-v2.md +35 -3
  8. package/docs/execution-optimizations.md +1 -1
  9. package/docs/external-models.md +1 -0
  10. package/docs/human-correction.md +1 -1
  11. package/docs/installation.md +42 -16
  12. package/docs/js-workflow-control.md +65 -30
  13. package/docs/next-steps.md +10 -0
  14. package/docs/runtime-failover.md +5 -3
  15. package/docs/user-guide.md +6 -6
  16. package/package.json +1 -1
  17. package/runtime/js/cm-ai/batch-location.mjs +14 -0
  18. package/runtime/js/cm-ai/batch-plan.mjs +6 -2
  19. package/runtime/js/cm-ai/checkpoint-package-material.mjs +9 -2
  20. package/runtime/js/cm-ai/cm-ai-admission.mjs +9 -3
  21. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +51 -8
  22. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +30 -4
  23. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -4
  24. package/runtime/js/cm-ai/delivery-evidence.mjs +3 -1
  25. package/runtime/js/cm-ai/developer-adapter.mjs +15 -1
  26. package/runtime/js/cm-ai/drive-core.mjs +50 -6
  27. package/runtime/js/cm-ai/drive-next-step.mjs +61 -0
  28. package/runtime/js/cm-ai/durable-runner-state.mjs +85 -23
  29. package/runtime/js/cm-ai/execution-snapshot.mjs +5 -2
  30. package/runtime/js/cm-ai/execution-store.mjs +21 -3
  31. package/runtime/js/cm-ai/external-run-guard.mjs +9 -1
  32. package/runtime/js/cm-ai/host-check.mjs +4 -2
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +23 -2
  34. package/runtime/js/cm-ai/host-handoff.mjs +7 -0
  35. package/runtime/js/cm-ai/host-progress.mjs +18 -0
  36. package/runtime/js/cm-ai/host-qa-executor.mjs +47 -15
  37. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  38. package/runtime/js/cm-ai/host-qa-policy.mjs +24 -14
  39. package/runtime/js/cm-ai/host-session.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +1 -1
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/operator-guidance.mjs +126 -2
  43. package/runtime/js/cm-ai/project-qa-gate.mjs +13 -2
  44. package/runtime/js/cm-ai/provider-review-observation.mjs +7 -3
  45. package/runtime/js/cm-ai/qa-plan-notes.mjs +106 -0
  46. package/runtime/js/cm-ai/review-continuation.mjs +102 -0
  47. package/runtime/js/cm-ai/review-evidence-file.mjs +11 -0
  48. package/runtime/js/cm-ai/review-package.mjs +25 -4
  49. package/runtime/js/cm-ai/review-presentation.mjs +31 -14
  50. package/runtime/js/cm-ai/review-runner.mjs +5 -4
  51. package/runtime/js/cm-ai/review-verdict-rules.mjs +7 -0
  52. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +30 -1
  53. package/runtime/js/cm-ai/task-commit-codec.mjs +11 -1
  54. package/runtime/js/cm-ai/task-commit.mjs +7 -4
  55. package/runtime/js/cm-ai/task-owner.mjs +5 -2
  56. package/runtime/js/cm-ai/task-runner.mjs +343 -52
  57. package/runtime/js/cm-ai/tool-preview.mjs +6 -0
  58. package/runtime/js/cm-fix/diagnosis.mjs +16 -3
  59. package/runtime/js/cm-fix/execution.mjs +47 -9
  60. package/runtime/js/cm-fix/finish.mjs +9 -1
  61. package/runtime/js/cm-fix/step-timing.mjs +222 -0
  62. package/runtime/js/cm-idea/session.mjs +22 -3
  63. package/runtime/js/cm-init/review-evidence.mjs +20 -7
  64. package/runtime/js/cm-prd/ai-draft.mjs +260 -0
  65. package/runtime/js/cm-prd/analysis.mjs +27 -9
  66. package/runtime/js/cm-prd/change.mjs +29 -8
  67. package/runtime/js/cm-prd/failed-correction.mjs +24 -4
  68. package/runtime/js/cm-prd/narrow-review.mjs +63 -3
  69. package/runtime/js/cm-prd/review-correction.mjs +65 -5
  70. package/runtime/js/cm-prd/review-disposition.mjs +10 -1
  71. package/runtime/js/cm-prd/self-check.mjs +121 -9
  72. package/runtime/js/cm-prd/session.mjs +55 -13
  73. package/runtime/js/cm-prd/summary.mjs +34 -6
  74. package/runtime/js/cm-prd/task-scope-record.mjs +40 -15
  75. package/runtime/js/cm-refactor/records.mjs +82 -11
  76. package/runtime/js/cm-refactor/workflow.mjs +3 -1
  77. package/runtime/js/executor-version.mjs +81 -0
  78. package/runtime/js/python-log-writer.mjs +15 -0
  79. package/runtime/js/run-analysis.mjs +136 -11
  80. package/runtime/logging.md +6 -0
  81. package/runtime/review.md +3 -1
  82. package/runtime/workflow-config.md +1 -1
  83. package/scripts/ci-test-weights.json +1 -0
  84. package/scripts/cm-ai-admission.mjs +27 -1
  85. package/scripts/cm-ai-admission.test.mjs +34 -2
  86. package/scripts/cm-ai-answer-gap-recheck.test.mjs +3 -2
  87. package/scripts/cm-ai-batch-drive.mjs +54 -17
  88. package/scripts/cm-ai-batch-drive.test.mjs +123 -6
  89. package/scripts/cm-ai-batch-host.mjs +55 -9
  90. package/scripts/cm-ai-batch-host.test.mjs +22 -3
  91. package/scripts/cm-ai-batch-location.test.mjs +22 -1
  92. package/scripts/cm-ai-batch-merge.mjs +102 -0
  93. package/scripts/cm-ai-batch-plan.mjs +55 -2
  94. package/scripts/cm-ai-batch-plan.test.mjs +228 -6
  95. package/scripts/cm-ai-batch-run-fixture.mjs +239 -15
  96. package/scripts/cm-ai-batch-run-parallel.test.mjs +23 -1
  97. package/scripts/cm-ai-batch-run.mjs +435 -33
  98. package/scripts/cm-ai-batch-session-member.test.mjs +85 -0
  99. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +23 -2
  100. package/scripts/cm-ai-checkpoint-package-material.test.mjs +28 -0
  101. package/scripts/cm-ai-completion-summary.test.mjs +2 -1
  102. package/scripts/cm-ai-control-v2-drive.test.mjs +39 -9
  103. package/scripts/cm-ai-direct-review.test.mjs +1 -1
  104. package/scripts/cm-ai-disk-edits.test.mjs +229 -0
  105. package/scripts/cm-ai-drive-next-step.test.mjs +191 -0
  106. package/scripts/cm-ai-drive.mjs +66 -14
  107. package/scripts/cm-ai-drive.test.mjs +13 -3
  108. package/scripts/cm-ai-host-cli-workflow.test.mjs +4 -2
  109. package/scripts/cm-ai-host.mjs +16 -8
  110. package/scripts/cm-ai-host.test.mjs +12 -0
  111. package/scripts/cm-ai-operator-guidance.test.mjs +132 -1
  112. package/scripts/cm-ai-project-qa-gate.test.mjs +26 -0
  113. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -0
  114. package/scripts/cm-ai-review-continuation.test.mjs +335 -0
  115. package/scripts/cm-ai-review-failure.test.mjs +13 -10
  116. package/scripts/cm-ai-review-timeout.test.mjs +1 -1
  117. package/scripts/cm-ai-run.mjs +42 -11
  118. package/scripts/cm-ai-run.test.mjs +26 -0
  119. package/scripts/cm-ai-supersede.test.mjs +10 -2
  120. package/scripts/cm-capability-gate.test.mjs +1 -1
  121. package/scripts/cm-check-runtime.sh +9 -0
  122. package/scripts/cm-codex-clean-env.test.mjs +40 -0
  123. package/scripts/cm-codex-prompt-input.test.mjs +2 -1
  124. package/scripts/cm-developer-self-review.test.mjs +27 -0
  125. package/scripts/cm-efficiency-presentation-delta.test.mjs +4 -3
  126. package/scripts/cm-efficiency-response.test.mjs +2 -1
  127. package/scripts/cm-executor-version-draft.test.mjs +251 -0
  128. package/scripts/cm-executor-version-entries.test.mjs +93 -0
  129. package/scripts/cm-executor-version-prd.test.mjs +154 -0
  130. package/scripts/cm-executor-version-records.test.mjs +256 -0
  131. package/scripts/cm-executor-version.test.mjs +250 -0
  132. package/scripts/cm-external-model-host.test.mjs +6 -1
  133. package/scripts/cm-external-review-reconciliation.test.mjs +1 -1
  134. package/scripts/cm-fix-closeout-preflight.test.mjs +123 -0
  135. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +5 -1
  136. package/scripts/cm-fix-drive.mjs +7 -2
  137. package/scripts/cm-fix-drive.test.mjs +45 -0
  138. package/scripts/cm-fix-entry.mjs +5 -2
  139. package/scripts/cm-fix-frozen-baseline.test.mjs +50 -0
  140. package/scripts/cm-fix-host.mjs +9 -2
  141. package/scripts/cm-fix-test-extension.test.mjs +30 -2
  142. package/scripts/cm-host-check.test.mjs +12 -0
  143. package/scripts/cm-host-qa-executor.test.mjs +172 -1
  144. package/scripts/cm-host-qa-policy.test.mjs +55 -1
  145. package/scripts/cm-idea-drive.mjs +5 -2
  146. package/scripts/cm-idea-entry.mjs +5 -2
  147. package/scripts/cm-idea-host.mjs +3 -1
  148. package/scripts/cm-init-drive.mjs +8 -5
  149. package/scripts/cm-init-entry.mjs +5 -2
  150. package/scripts/cm-init-host.mjs +6 -2
  151. package/scripts/cm-log-event.mjs +10 -2
  152. package/scripts/cm-log-event.test.mjs +29 -0
  153. package/scripts/cm-prd-ai-draft-fixture.mjs +18 -0
  154. package/scripts/cm-prd-ai-draft.test.mjs +505 -0
  155. package/scripts/cm-prd-answer-gaps.test.mjs +110 -5
  156. package/scripts/cm-prd-completion.test.mjs +67 -4
  157. package/scripts/cm-prd-design-phase.test.mjs +48 -13
  158. package/scripts/cm-prd-drive.mjs +89 -20
  159. package/scripts/cm-prd-drive.test.mjs +109 -4
  160. package/scripts/cm-prd-entry.mjs +5 -2
  161. package/scripts/cm-prd-host.mjs +89 -20
  162. package/scripts/cm-prd-host.test.mjs +17 -8
  163. package/scripts/cm-prd-narrow-review.test.mjs +49 -1
  164. package/scripts/cm-prd-review-disposition.test.mjs +94 -1
  165. package/scripts/cm-prd-review-gate.mjs +11 -4
  166. package/scripts/cm-prd-self-check-rules.test.mjs +175 -10
  167. package/scripts/cm-prd-self-check.test.mjs +1 -1
  168. package/scripts/cm-refactor-drive.mjs +10 -4
  169. package/scripts/cm-refactor-entry.mjs +5 -2
  170. package/scripts/cm-refactor-host.mjs +3 -1
  171. package/scripts/cm-run-analysis.test.mjs +373 -1
  172. package/scripts/cm-runtime-i18n.mjs +3 -3
  173. package/scripts/cm-runtime-install.mjs +19 -10
  174. package/scripts/cm-runtime.mjs +2 -4
  175. package/scripts/cm-runtime.test.mjs +55 -13
  176. package/scripts/cm-skill-hints-autowire.test.mjs +1 -1
  177. package/scripts/cm-skill-hints-exam.mjs +3 -1
  178. package/scripts/cm-skill-hints-install.test.mjs +1 -1
  179. package/scripts/cm-skill-hints.mjs +106 -10
  180. package/scripts/cm-skill-hints.test.mjs +162 -6
  181. package/scripts/cm-skill-judge.mjs +2 -1
  182. package/scripts/cm-statusline.test.mjs +54 -0
  183. package/scripts/cm-task-gate.mjs +88 -18
  184. package/scripts/cm-task-scope.test.mjs +1 -1
  185. package/scripts/cm-test-drive.mjs +13 -8
  186. package/scripts/cm-test-entry.mjs +5 -2
  187. package/scripts/cm-test-host.mjs +3 -1
  188. package/scripts/cm-upgrade-compat-batch.test.mjs +62 -9
  189. package/scripts/fixtures/fresh-completion-checks.mjs +8 -0
  190. package/scripts/fixtures/prd-review-gate-python-oracle.py +9 -0
  191. package/scripts/policy-binding-compat.test.mjs +3 -2
  192. package/scripts/test-cm-prd-review-gate.py +25 -0
  193. package/skills/cm-ai/SKILL.md +1 -1
  194. package/skills/cm-ai/references/N1-init.md +4 -3
  195. package/skills/cm-ai/references/N4-review.md +6 -3
  196. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  197. package/skills/cm-ai/references/js-host-recovery.md +4 -1
  198. package/skills/cm-ai/references/js-host.md +25 -5
  199. package/skills/cm-fix/references/js-host.md +20 -0
  200. package/skills/cm-fix/references/test-extension.md +1 -1
  201. package/skills/cm-prd/SKILL.md +8 -6
  202. package/skills/cm-prd/references/ai-draft.md +81 -0
  203. package/skills/cm-prd/references/change-mode.md +2 -0
  204. package/skills/cm-prd/references/greenfield.md +2 -0
  205. package/skills/cm-prd/references/js-change-recovery.md +2 -2
  206. package/skills/cm-prd/references/js-host.md +9 -6
  207. package/skills/cm-prd/references/light-mode.md +19 -0
  208. package/skills/cm-prd/references/requirement-grilling.md +2 -0
  209. package/skills/cm-prd/references/spec-self-check.md +1 -0
  210. package/skills/cm-prd/references/summary-card.md +1 -0
  211. package/skills/cm-runtime/SKILL.md +6 -6
  212. package/templates/statusline/cm-statusline.sh +63 -1
@@ -0,0 +1,256 @@
1
+ // Executor release recorded by cm-test and cm-refactor journals (format 2). Older
2
+ // and newer executors are real copies of this tree that differ only in VERSION;
3
+ // the 0.21.7 case runs the real released code taken from git history.
4
+ import test from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import {spawnSync} from 'node:child_process';
10
+ import {fileURLToPath,pathToFileURL} from 'node:url';
11
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
12
+ import {executorRelease} from '../runtime/js/executor-version.mjs';
13
+ import {openRefactorRecords,JOURNAL_FORMAT_SEED} from '../runtime/js/cm-refactor/records.mjs';
14
+ import {createCmRefactorHost} from '../runtime/js/cm-refactor/host.mjs';
15
+ import {fixture} from './fixtures/cm-refactor.mjs';
16
+
17
+ const repo=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
18
+ const temp=(t,prefix)=>{const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),prefix)));
19
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));return dir;};
20
+ // A workflow root holding this tree's runtime/ with the given VERSION (null: none).
21
+ function executor(t,version){
22
+ const root=temp(t,'cm-executor-records-');
23
+ fs.cpSync(path.join(repo,'runtime'),path.join(root,'runtime'),{recursive:true,filter:source=>!source.endsWith('.test.mjs')});
24
+ if(version!==null)fs.writeFileSync(path.join(root,'VERSION'),version+'\n');
25
+ return {root,records:()=>import(pathToFileURL(path.join(root,'runtime/js/cm-refactor/records.mjs')).href)};
26
+ }
27
+ const lines=dir=>fs.readFileSync(path.join(dir,'execution.jsonl'),'utf8').trimEnd().split('\n').map(line=>JSON.parse(line));
28
+ const snapshot=dir=>Object.fromEntries(fs.readdirSync(dir).map(name=>[name,fs.readFileSync(path.join(dir,name))]));
29
+ // Start a journal with the given records module, as that executor's host would.
30
+ function start(open,dir,context={workflow:'fixture'}){
31
+ const records=open(dir);records.acquire();try{records.initialize(context);records.progressWrite({stage:'started'});}finally{records.release();}
32
+ }
33
+ // Rewrite the format row and re-chain the rows after it, so only the field under test differs.
34
+ function rewriteFormat(dir,change){
35
+ const rows=lines(dir),{hash:_,...body}=rows[0],next=change({...body});
36
+ rows[0]={...next,hash:digest(next)};
37
+ for(let i=1;i<rows.length;i++){const {hash:__,...rest}=rows[i],row={...rest,previous:rows[i-1].hash};rows[i]={...row,hash:digest(row)};}
38
+ fs.writeFileSync(path.join(dir,'execution.jsonl'),rows.map(row=>JSON.stringify(row)+'\n').join(''));
39
+ }
40
+ const newer=error=>error.code==='run_created_by_newer_executor'&&/99\.0\.0/.test(error.reason)&&/升级/.test(error.reason);
41
+
42
+ test('a new journal opens with a format row naming its creator; a format-1 journal resumes unchanged',t=>{
43
+ const dir=path.join(temp(t,'cm-records-'),'run');start(openRefactorRecords,dir);
44
+ const rows=lines(dir);
45
+ assert.deepEqual(Object.keys(rows[0]),['type','version','createdBy','previous','hash']);
46
+ assert.equal(rows[0].previous,JOURNAL_FORMAT_SEED,'not null: older executors fail their own chain check');
47
+ assert.deepEqual(rows[0].createdBy,{version:1,release:executorRelease()});
48
+ assert.equal(rows[1].type,'context');assert.equal(rows[1].previous,rows[0].hash);
49
+ const reopened=openRefactorRecords(dir);assert.deepEqual(reopened.createdBy,rows[0].createdBy);
50
+ assert.deepEqual(reopened.context,{workflow:'fixture'});
51
+ reopened.acquire();reopened.progressWrite({stage:'resumed'});reopened.release();
52
+ assert.equal(lines(dir).filter(row=>row.type==='format').length,1,'a resume never adds a second format row');
53
+ // Format 1: written by 0.21.7 and earlier, first row previous null.
54
+ const legacy=path.join(temp(t,'cm-records-'),'run');fs.mkdirSync(legacy,{mode:0o700});
55
+ const body={type:'context',value:{workflow:'fixture'},previous:null};
56
+ fs.writeFileSync(path.join(legacy,'execution.jsonl'),JSON.stringify({...body,hash:digest(body)})+'\n',{mode:0o600});
57
+ const old=openRefactorRecords(legacy);assert.equal(old.createdBy,null);
58
+ old.acquire();old.progressWrite({stage:'resumed'});old.release();
59
+ assert.deepEqual(lines(legacy).map(row=>row.type),['context','progress']);
60
+ });
61
+
62
+ test('an older executor reads a newer journal but refuses to write before touching the disk',async t=>{
63
+ const future=await executor(t,'99.0.0').records(),dir=path.join(temp(t,'cm-records-'),'run');start(future.openRefactorRecords,dir);
64
+ const before=snapshot(dir),records=openRefactorRecords(dir);
65
+ assert.deepEqual(records.createdBy,{version:1,release:'99.0.0'},'read-only views still see the run');
66
+ assert.throws(()=>records.acquire(),newer);
67
+ assert.deepEqual(snapshot(dir),before,'no writer lock, no row');
68
+ // The same or an older creator resumes.
69
+ for(const release of [executorRelease(),'0.21.9']){
70
+ const own=path.join(temp(t,'cm-records-'),'run');start(openRefactorRecords,own);
71
+ rewriteFormat(own,body=>({...body,createdBy:{version:1,release}}));
72
+ const opened=openRefactorRecords(own);opened.acquire();opened.progressWrite({stage:'resumed'});opened.release();
73
+ }
74
+ });
75
+
76
+ test('a damaged format row is an invalid creator, never a legacy journal',t=>{
77
+ const damage=[body=>{delete body.createdBy;return body;},body=>({...body,createdBy:{version:1,release:'next'}}),
78
+ body=>({...body,createdBy:{version:2,release:'0.22.0'}}),body=>({...body,extra:true}),body=>({...body,type:'context'}),
79
+ body=>({...body,version:3})];
80
+ for(const change of damage){
81
+ const dir=path.join(temp(t,'cm-records-'),'run');start(openRefactorRecords,dir);rewriteFormat(dir,change);
82
+ assert.throws(()=>openRefactorRecords(dir),error=>error.code==='run_created_by_invalid'&&/创建版本/.test(error.reason));
83
+ }
84
+ // Not re-hashed, or a second format row later: the chain itself is broken.
85
+ const dir=path.join(temp(t,'cm-records-'),'run');start(openRefactorRecords,dir);
86
+ const rows=lines(dir),file=path.join(dir,'execution.jsonl');
87
+ fs.writeFileSync(file,[{...rows[0],createdBy:{version:1,release:'0.1.0'}},...rows.slice(1)].map(row=>JSON.stringify(row)+'\n').join(''));
88
+ assert.throws(()=>openRefactorRecords(dir),{code:'refactor_journal_invalid'});
89
+ const late={type:'format',version:2,createdBy:rows[0].createdBy,previous:rows.at(-1).hash};
90
+ fs.writeFileSync(file,[...rows,{...late,hash:digest(late)}].map(row=>JSON.stringify(row)+'\n').join(''));
91
+ assert.throws(()=>openRefactorRecords(dir),{code:'refactor_journal_invalid'});
92
+ });
93
+
94
+ test('a new journal needs a readable release before creating its directory or lock',async t=>{
95
+ const broken=await executor(t,null).records(),dir=path.join(temp(t,'cm-records-'),'run');
96
+ const records=broken.openRefactorRecords(dir);
97
+ assert.throws(()=>records.acquire(),error=>error.code==='executor_version_unavailable'&&/重新安装 CM/.test(error.reason));
98
+ assert.equal(fs.existsSync(dir),false);
99
+ // A format-1 journal does not need the release: it never had one.
100
+ const legacy=path.join(temp(t,'cm-records-'),'run');fs.mkdirSync(legacy,{mode:0o700});
101
+ const body={type:'context',value:{workflow:'fixture'},previous:null};
102
+ fs.writeFileSync(path.join(legacy,'execution.jsonl'),JSON.stringify({...body,hash:digest(body)})+'\n',{mode:0o600});
103
+ const old=broken.openRefactorRecords(legacy);old.acquire();old.progressWrite({stage:'resumed'});old.release();
104
+ });
105
+
106
+ // A pid that has exited: its writer lock is stale, so acquire would remove and replace it.
107
+ const deadPid=()=>spawnSync(process.execPath,['-e','0']).pid;
108
+ const staleLock=dir=>fs.writeFileSync(path.join(dir,'.writer.json'),JSON.stringify({pid:deadPid()}),{mode:0o600});
109
+ test('a journal another executor wrote after construction is judged before the lock is touched',async t=>{
110
+ // Newer creator: refused with the upgrade reason. The stale lock left in place proves
111
+ // acquire neither removed it nor wrote its own.
112
+ const future=await executor(t,'99.0.0').records(),dir=path.join(temp(t,'cm-records-'),'run');
113
+ const records=openRefactorRecords(dir);
114
+ start(future.openRefactorRecords,dir);staleLock(dir);const before=snapshot(dir);
115
+ assert.throws(()=>records.acquire(),newer);
116
+ assert.deepEqual(snapshot(dir),before,'no lock handling and no row before the refusal');
117
+ assert.throws(()=>openRefactorRecords(dir).acquire(),newer,'reopening applies the same creator check');
118
+ // Format 1 or this release: a reopen is asked for, again before any lock write.
119
+ for(const kind of ['legacy','same']){
120
+ const other=path.join(temp(t,'cm-records-'),'run'),late=openRefactorRecords(other);
121
+ if(kind==='legacy'){fs.mkdirSync(other,{mode:0o700});const body={type:'context',value:{workflow:'fixture'},previous:null};
122
+ fs.writeFileSync(path.join(other,'execution.jsonl'),JSON.stringify({...body,hash:digest(body)})+'\n',{mode:0o600});}
123
+ else start(openRefactorRecords,other);
124
+ staleLock(other);const was=snapshot(other);
125
+ assert.throws(()=>late.acquire(),{code:'refactor_reopen_required'},kind);
126
+ assert.deepEqual(snapshot(other),was,`${kind}: the stale lock is left alone`);
127
+ }
128
+ });
129
+
130
+ test('a newer journal created in the gap before the lock still gets the upgrade reason, and the lock is given back',async t=>{
131
+ const future=await executor(t,'99.0.0').records(),dir=path.join(temp(t,'cm-records-'),'run');
132
+ const records=openRefactorRecords(dir),original=fs.mkdirSync;let raced=false;
133
+ // The journal lands right after the pre-check, while acquire creates the directory.
134
+ fs.mkdirSync=(...args)=>{const result=original.apply(fs,args);
135
+ if(!raced&&args[0]===dir){raced=true;fs.mkdirSync=original;start(future.openRefactorRecords,dir);}return result;};
136
+ try{assert.throws(()=>records.acquire(),newer);}finally{fs.mkdirSync=original;}
137
+ assert.ok(raced,'the race was staged');
138
+ assert.ok(!fs.existsSync(path.join(dir,'.writer.json')),'the lock written in the gap is removed');
139
+ });
140
+
141
+ test('a journal path that is not a plain file is refused without reading it',{skip:process.platform==='win32'},t=>{
142
+ for(const kind of ['fifo','symlink']){
143
+ const dir=path.join(temp(t,'cm-records-'),'run'),records=openRefactorRecords(dir);fs.mkdirSync(dir,{mode:0o700});
144
+ const target=path.join(dir,'execution.jsonl');
145
+ if(kind==='fifo')assert.equal(spawnSync('mkfifo',[target]).status,0,'mkfifo');
146
+ else{const real=path.join(dir,'real.jsonl');fs.writeFileSync(real,'');fs.symlinkSync(real,target);}
147
+ // A FIFO with no writer would block a plain read forever; the refusal must come back at once.
148
+ assert.throws(()=>records.acquire(),{code:'refactor_journal_invalid'},`${kind} after construction`);
149
+ assert.ok(!fs.existsSync(path.join(dir,'.writer.json')),`${kind}: no lock written`);
150
+ assert.throws(()=>openRefactorRecords(dir),{code:'refactor_journal_invalid'},`${kind} at construction`);
151
+ }
152
+ });
153
+
154
+ test('a journal is read only as the file that was checked, and to its end',t=>{
155
+ // A row appended after the size check (by a writer ignoring the lock) is still seen by
156
+ // the recheck after the lock: a reopen is asked for and the lock is given back.
157
+ const grown=path.join(temp(t,'cm-records-'),'run');start(openRefactorRecords,grown);
158
+ const target=path.join(grown,'execution.jsonl'),records=openRefactorRecords(grown),fstat=fs.fstatSync;let appended=false;
159
+ fs.fstatSync=(...args)=>{const stat=fstat.apply(fs,args);
160
+ if(!appended){appended=true;fs.fstatSync=fstat;const last=lines(grown).at(-1).hash,body={type:'progress',value:{stage:'late'},previous:last};
161
+ fs.appendFileSync(target,JSON.stringify({...body,hash:digest(body)})+'\n');}return stat;};
162
+ try{assert.throws(()=>records.acquire(),{code:'refactor_reopen_required'});}finally{fs.fstatSync=fstat;}
163
+ assert.ok(appended,'the growth was staged');
164
+ assert.ok(!fs.existsSync(path.join(grown,'.writer.json')),'the lock is given back');
165
+ // A different, valid journal swapped in before the open, or after the read, is refused.
166
+ // A row appended after the read reached the end, before the last path check, is caught too.
167
+ const late=path.join(temp(t,'cm-records-'),'run');start(openRefactorRecords,late);
168
+ const lateJournal=path.join(late,'execution.jsonl'),lateRecords=openRefactorRecords(late),lstatLate=fs.lstatSync;let lateCalls=0,lateAppended=false;
169
+ fs.lstatSync=(file,...rest)=>{if(file===lateJournal&&++lateCalls===2&&!lateAppended){lateAppended=true;
170
+ const last=lines(late).at(-1).hash,body={type:'progress',value:{stage:'late'},previous:last};
171
+ fs.appendFileSync(lateJournal,JSON.stringify({...body,hash:digest(body)})+'\n');}return lstatLate.call(fs,file,...rest);};
172
+ try{assert.throws(()=>lateRecords.acquire(),{code:'refactor_reopen_required'});}finally{fs.lstatSync=lstatLate;}
173
+ assert.ok(lateAppended,'the late growth was staged');
174
+ assert.ok(!fs.existsSync(path.join(late,'.writer.json')),'the lock is given back after a late growth');
175
+ // Windows refuses to rename over a file that is open for reading, so the after-read swap is POSIX only.
176
+ for(const moment of process.platform==='win32'?['before open']:['before open','after read']){
177
+ const swapped=path.join(temp(t,'cm-records-'),'run'),other=path.join(temp(t,'cm-records-'),'run');
178
+ start(openRefactorRecords,swapped);start(openRefactorRecords,other,{workflow:'other'});
179
+ const journal=path.join(swapped,'execution.jsonl'),swap=()=>fs.renameSync(path.join(other,'execution.jsonl'),journal);
180
+ const open=fs.openSync,lstat=fs.lstatSync;let calls=0,replaced=false;
181
+ if(moment==='before open')fs.openSync=(file,...rest)=>{if(!replaced&&file===journal){replaced=true;swap();}return open.call(fs,file,...rest);};
182
+ else fs.lstatSync=(file,...rest)=>{if(file===journal&&++calls===2&&!replaced){replaced=true;swap();}return lstat.call(fs,file,...rest);};
183
+ try{assert.throws(()=>openRefactorRecords(swapped),{code:'refactor_journal_invalid'},moment);}finally{fs.openSync=open;fs.lstatSync=lstat;}
184
+ assert.ok(replaced,`${moment}: the swap was staged`);
185
+ }
186
+ });
187
+
188
+ const RELEASE_0_21_7='034d460';
189
+ const release0217Available=spawnSync('git',['-C',repo,'cat-file','-e',`${RELEASE_0_21_7}^{commit}`]).status===0;
190
+ test('the real 0.21.7 cm-test and cm-refactor code refuses a format-2 journal while reading',
191
+ {skip:release0217Available?false:`${RELEASE_0_21_7} 不在本地历史(浅克隆),跳过真实旧代码运行`},async t=>{
192
+ const old=temp(t,'cm-release-0217-');
193
+ const archive=spawnSync('sh',['-c',`git -C "$1" archive ${RELEASE_0_21_7} runtime | tar -x -C "$2"`,'archive',repo,old],{encoding:'utf8'});
194
+ assert.equal(archive.status,0,archive.stderr);
195
+ const load=file=>import(pathToFileURL(path.join(old,file)).href);
196
+ const {openRefactorRecords:openOld}=await load('runtime/js/cm-refactor/records.mjs');
197
+ const {openTestSession}=await load('runtime/js/cm-test/session.mjs');
198
+ const base=temp(t,'cm-records-'),dir=path.join(base,'session'),project=path.join(base,'project');fs.mkdirSync(project);
199
+ start(openRefactorRecords,dir,{workflow:'cm-test'});const before=snapshot(dir);
200
+ assert.throws(()=>openOld(dir),{code:'refactor_journal_invalid'},'cm-refactor host and driver read it this way');
201
+ assert.throws(()=>openTestSession(dir,{project,arguments:{}}),{code:'refactor_journal_invalid'});
202
+ assert.deepEqual(snapshot(dir),before,'0.21.7 wrote nothing, not even its writer lock');
203
+ });
204
+
205
+ // Entry points: the one-line reason reaches the user unchanged.
206
+ async function futureJournal(t,dir,context){const future=await executor(t,'99.0.0').records();start(future.openRefactorRecords,dir,context);}
207
+
208
+ test('cm-test host and driver show the upgrade reason for a newer session',async t=>{
209
+ const base=temp(t,'cm-test-entry-'),project=path.join(base,'project'),session=path.join(base,'session');fs.mkdirSync(project);
210
+ fs.writeFileSync(path.join(project,'input.mjs'),'export const valid = value => value !== null;\n');
211
+ const cases=path.join(base,'cases.json');
212
+ fs.writeFileSync(cases,JSON.stringify({schemaVersion:'1.0',feature:'guide',cases:[{id:'TC-001',origin:'user',kind:'logic',blocking:true,
213
+ acIds:[],taskIds:[],title:'Invalid input',preconditions:[],steps:['Call invalid input'],expected:['Returns error'],cleanup:[]}]}));
214
+ const config={skillDir:path.join(repo,'skills/cm-test'),project,runtime:'codex',arguments:{cases,logic:true},sources:['input.mjs'],
215
+ commands:[],environment:{scope:'local',kind:'web',carrier:'browser',target:'fixture-local-ui'},logHome:path.join(base,'logs')};
216
+ const configPath=path.join(base,'config.json');fs.writeFileSync(configPath,JSON.stringify(config));
217
+ await futureJournal(t,session,{workflow:'cm-test',configDigest:digest(config)});const before=snapshot(session);
218
+ const host=spawnSync(process.execPath,[path.join(repo,'scripts/cm-test-host.mjs'),'serve','--config',configPath,'--session-dir',session],
219
+ {encoding:'utf8',input:'',timeout:60000});
220
+ assert.equal(host.status,1,host.stderr);
221
+ const {error}=JSON.parse(host.stderr.trim().split('\n').at(-1));
222
+ assert.equal(error.code,'run_created_by_newer_executor');assert.match(error.reason,/99\.0\.0/);
223
+ fs.writeFileSync(path.join(base,'plan.json'),JSON.stringify({config:'config.json',answers:'answers',sessionDir:'session',resolution:null}));
224
+ const drive=spawnSync(process.execPath,[path.join(repo,'scripts/cm-test-drive.mjs'),'--plan',path.join(base,'plan.json'),'resume'],
225
+ {encoding:'utf8',timeout:60000});
226
+ assert.equal(drive.status,2,drive.stderr);
227
+ assert.match(drive.stderr,/run_created_by_newer_executor: 此运行由 CM 99\.0\.0 创建/);
228
+ assert.deepEqual(snapshot(session),before);
229
+ });
230
+
231
+ test('cm-refactor host and driver show the reason for a newer or damaged run',async t=>{
232
+ const f=fixture(t),dir=path.join(f.project,'docs/refactors/extract');
233
+ await futureJournal(t,dir,{configDigest:digest(f.config)});const before=snapshot(dir);
234
+ const host=createCmRefactorHost(f.config,{call:()=>{throw new Error('no host call expected');}});
235
+ const status=await host.handle({operation:'resume'});
236
+ assert.equal(status.stage,'blocked');assert.equal(status.reason,'run_created_by_newer_executor');
237
+ assert.match(status.reasonDetail,/此运行由 CM 99\.0\.0 创建/);
238
+ const configPath=path.join(f.temp,'config.json');fs.writeFileSync(configPath,JSON.stringify(f.config));
239
+ fs.writeFileSync(path.join(f.temp,'plan.json'),JSON.stringify({config:'config.json',answers:'answers'}));
240
+ const drive=spawnSync(process.execPath,[path.join(repo,'scripts/cm-refactor-drive.mjs'),'--plan',path.join(f.temp,'plan.json'),'resume'],
241
+ {encoding:'utf8',timeout:60000});
242
+ assert.equal(drive.status,2,drive.stderr);assert.match(drive.stderr,/run_created_by_newer_executor: 此运行由 CM 99\.0\.0 创建/);
243
+ assert.deepEqual(snapshot(dir),before);
244
+ // A damaged creator stops the host at construction; the entry prints its reason.
245
+ rewriteFormat(dir,body=>({...body,createdBy:{version:1,release:'next'}}));
246
+ const entry=spawnSync(process.execPath,[path.join(repo,'scripts/cm-refactor-host.mjs'),'serve','--config',configPath],
247
+ {encoding:'utf8',input:'',timeout:60000});
248
+ assert.equal(entry.status,1,entry.stderr);
249
+ const {error}=JSON.parse(entry.stderr.trim().split('\n').at(-1));
250
+ assert.equal(error.code,'run_created_by_invalid');assert.match(error.reason,/创建版本/);
251
+ // The driver reads the journal itself and shows the same reason, not the bare code.
252
+ const damaged=spawnSync(process.execPath,[path.join(repo,'scripts/cm-refactor-drive.mjs'),'--plan',path.join(f.temp,'plan.json'),'resume'],
253
+ {encoding:'utf8',timeout:60000});
254
+ assert.equal(damaged.status,2,damaged.stderr);
255
+ assert.match(damaged.stderr,/run_created_by_invalid: 运行记录里的创建版本(createdBy)格式不对/);
256
+ });
@@ -0,0 +1,250 @@
1
+ // Executor release recorded at run creation (0.22.0). Two executors are real copies
2
+ // of this tree that differ only in their VERSION file, so the older one runs its
3
+ // own code against a run the newer one created; no version string is injected.
4
+ import test from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import {fileURLToPath,pathToFileURL} from 'node:url';
10
+ import {digest} from '../runtime/js/cm-ai/contracts.mjs';
11
+ import {executorRelease,compareReleases} from '../runtime/js/executor-version.mjs';
12
+
13
+ const repo=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
14
+ const identity={repositoryId:'executor-version',runId:'run-1'};
15
+ const fingerprints={workflow:digest('workflow'),config:digest('config'),inputs:digest('inputs')};
16
+ const temp=(t,prefix)=>{const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),prefix)));
17
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));return dir;};
18
+ // A workflow root holding this tree's runtime/ and scripts/ and the given markers.
19
+ function executor(t,{version='0.30.0',claude=null}={}){
20
+ const root=temp(t,'cm-executor-');
21
+ for(const part of ['runtime','scripts'])fs.cpSync(path.join(repo,part),path.join(root,part),{recursive:true,
22
+ filter:source=>!source.endsWith('.test.mjs')&&!source.includes(`${path.sep}fixtures${path.sep}`)});
23
+ if(version!==null)fs.writeFileSync(path.join(root,'VERSION'),version+'\n');
24
+ if(claude!==null){fs.mkdirSync(path.join(root,'templates'));fs.writeFileSync(path.join(root,'templates','cm-VERSION'),claude+'\n');}
25
+ const load=file=>import(pathToFileURL(path.join(root,file)).href);
26
+ return {root,store:()=>load('runtime/js/cm-ai/execution-store.mjs'),snapshot:()=>load('runtime/js/cm-ai/execution-snapshot.mjs'),
27
+ run:()=>load('scripts/cm-ai-run.mjs'),version:()=>load('runtime/js/executor-version.mjs')};
28
+ }
29
+ const specs=t=>temp(t,'cm-specs-');
30
+ const stateFile=root=>path.join(root,'.reviews','.execution',identity.runId,'state.json');
31
+ const options=(specsRoot,create)=>({specsRoot,identity,fingerprints,create});
32
+ // Rewrite the stored state as another executor would have left it, resealed so
33
+ // only the field under test differs.
34
+ function rewrite(specsRoot,change){
35
+ const file=stateFile(specsRoot),{revision,...data}=JSON.parse(fs.readFileSync(file,'utf8'));
36
+ const next=change(data);fs.writeFileSync(file,JSON.stringify({...next,revision:digest(next)})+'\n');
37
+ }
38
+ const entry=(store,id)=>({id,kind:'intent',payload:{value:id},expectedRevision:store.snapshot().revision});
39
+
40
+ test('the release comes from VERSION, from a Claude install marker, or stops the caller',async t=>{
41
+ assert.equal(executorRelease(),fs.readFileSync(path.join(repo,'VERSION'),'utf8').trim());
42
+ const cases=[[{version:'0.30.0'},'0.30.0'],[{version:null,claude:'0.29.1'},'0.29.1'],[{version:'0.30.0',claude:'0.30.0'},'0.30.0'],
43
+ [{version:'0.30.0+codex.20261128'},'0.30.0']];
44
+ for(const [markers,expected] of cases){
45
+ const root=temp(t,'cm-marker-');
46
+ if(markers.version!==null)fs.writeFileSync(path.join(root,'VERSION'),markers.version+'\n');
47
+ if(markers.claude){fs.mkdirSync(path.join(root,'templates'));fs.writeFileSync(path.join(root,'templates','cm-VERSION'),markers.claude);}
48
+ assert.equal(executorRelease(root),expected);
49
+ }
50
+ for(const write of [()=>{},root=>fs.writeFileSync(path.join(root,'VERSION'),'next\n'),
51
+ root=>{fs.writeFileSync(path.join(root,'VERSION'),'0.30.0');fs.mkdirSync(path.join(root,'templates'));
52
+ fs.writeFileSync(path.join(root,'templates','cm-VERSION'),'0.29.0');}]){
53
+ const root=temp(t,'cm-marker-');write(root);
54
+ assert.throws(()=>executorRelease(root),error=>error.code==='executor_version_unavailable'&&/重新安装 CM/.test(error.reason));
55
+ }
56
+ assert.equal(compareReleases('0.10.0','0.9.9'),1);assert.equal(compareReleases('0.22.0','0.22.0'),0);
57
+ });
58
+
59
+ test('a new run records its creator once; appends keep it and a read-only snapshot shows it',async t=>{
60
+ const newer=executor(t,{version:'0.30.0'}),{openExecutionStore}=await newer.store(),root=specs(t);
61
+ const store=openExecutionStore(options(root,true));
62
+ try{store.append(entry(store,'first'));store.append(entry(store,'second'));}finally{store.close();}
63
+ const state=JSON.parse(fs.readFileSync(stateFile(root),'utf8'));
64
+ assert.equal(state.version,2);assert.deepEqual(state.createdBy,{version:1,release:'0.30.0'});assert.equal(state.records.length,2);
65
+ const {readExecutionSnapshot}=await newer.snapshot();
66
+ assert.deepEqual(readExecutionSnapshot({specsRoot:root,identity}).createdBy,{version:1,release:'0.30.0'});
67
+ const {inspectRunHistory}=await newer.run();
68
+ assert.deepEqual(inspectRunHistory({specsDir:root,identity}).createdBy,{version:1,release:'0.30.0'});
69
+ });
70
+
71
+ test('an install without a release marker creates nothing',async t=>{
72
+ const broken=executor(t,{version:null}),{openExecutionStore}=await broken.store(),root=specs(t);
73
+ assert.throws(()=>openExecutionStore(options(root,true)),error=>error.code==='executor_version_unavailable');
74
+ assert.equal(fs.existsSync(path.join(root,'.reviews')),false);
75
+ });
76
+
77
+ test('an older executor refuses a run a newer one created before anything is written; same or newer resumes',async t=>{
78
+ const newer=executor(t,{version:'0.30.0'}),older=executor(t,{version:'0.29.9'}),root=specs(t);
79
+ const created=(await newer.store()).openExecutionStore(options(root,true));created.close();
80
+ const before=fs.readFileSync(stateFile(root));
81
+ const {openExecutionStore:openOld}=await older.store();
82
+ assert.throws(()=>openOld(options(root,false)),error=>error.code==='run_created_by_newer_executor'
83
+ &&/此运行由 CM 0\.30\.0 创建,当前是 0\.29\.9/.test(error.reason));
84
+ const {assertSupportedResumeHistory}=await older.run();
85
+ assert.throws(()=>assertSupportedResumeHistory({specsDir:root,identity}),error=>error.code==='run_created_by_newer_executor');
86
+ assert.deepEqual(fs.readFileSync(stateFile(root)),before);
87
+ for(const opener of [newer,executor(t,{version:'0.31.0'})]){
88
+ const store=(await opener.store()).openExecutionStore(options(root,false));
89
+ try{assert.deepEqual(store.snapshot().createdBy,{version:1,release:'0.30.0'});}finally{store.close();}
90
+ }
91
+ });
92
+
93
+ test('a run created before releases were recorded resumes as before and stays unversioned',async t=>{
94
+ const current=executor(t,{version:'0.30.0'}),{openExecutionStore}=await current.store(),root=specs(t);
95
+ openExecutionStore(options(root,true)).close();
96
+ rewrite(root,({createdBy,...data})=>({...data,version:1}));
97
+ const store=openExecutionStore(options(root,false));
98
+ try{store.append(entry(store,'after-upgrade'));assert.equal(store.snapshot().version,1);}finally{store.close();}
99
+ const state=JSON.parse(fs.readFileSync(stateFile(root),'utf8'));
100
+ assert.equal(state.version,1);assert.equal(Object.hasOwn(state,'createdBy'),false);
101
+ const {inspectRunHistory}=await current.run();
102
+ assert.equal(inspectRunHistory({specsDir:root,identity}).createdBy,null);
103
+ });
104
+
105
+ test('a damaged creator record is refused, never treated as an unversioned run',async t=>{
106
+ const current=executor(t,{version:'0.30.0'}),root=specs(t);
107
+ const {openExecutionStore}=await current.store(),{readExecutionSnapshot}=await current.snapshot();
108
+ openExecutionStore(options(root,true)).close();
109
+ for(const createdBy of [{version:1,release:'latest'},{version:2,release:'0.30.0'},{version:1,release:'0.30.0',extra:true},null]){
110
+ rewrite(root,data=>({...data,createdBy}));
111
+ assert.throws(()=>openExecutionStore(options(root,false)),error=>error.code==='run_created_by_invalid');
112
+ assert.throws(()=>readExecutionSnapshot({specsRoot:root,identity}),error=>error.code==='run_created_by_invalid');
113
+ }
114
+ // A v2 state without the field is damage too, not a legacy run.
115
+ rewrite(root,({createdBy,...data})=>data);
116
+ assert.throws(()=>openExecutionStore(options(root,false)),error=>error.code==='run_created_by_invalid');
117
+ assert.throws(()=>readExecutionSnapshot({specsRoot:root,identity}),error=>error.code==='run_created_by_invalid');
118
+ });
119
+
120
+ test('an unreadable release marker is the same unavailable refusal',{skip:process.getuid?.()===0?'root 可读任何文件':false},t=>{
121
+ const root=temp(t,'cm-marker-'),file=path.join(root,'VERSION');
122
+ fs.writeFileSync(file,'0.30.0\n');fs.chmodSync(file,0o000);
123
+ try{assert.throws(()=>executorRelease(root),error=>error.code==='executor_version_unavailable');}finally{fs.chmodSync(file,0o600);}
124
+ });
125
+
126
+ // The owners check the release before writing their own files: the cm-ai task
127
+ // owner binding, and cm-fix's bare archive directory, evidence and run guard.
128
+ function taskOptions(specsRoot,create){
129
+ const tasksPath=path.join(specsRoot,'1.work','tasks.md');fs.mkdirSync(path.dirname(tasksPath),{recursive:true});
130
+ if(!fs.existsSync(tasksPath))fs.writeFileSync(tasksPath,'- [ ] T-001: fixture\n');
131
+ return {tasksPath,feature:'work',specsRoot,identity,fingerprints,create};
132
+ }
133
+ const binding=specsRoot=>path.join(specsRoot,'1.work','.reviews','.cm-task-owner.json');
134
+ test('the cm-ai task owner writes no binding when the release is unknown or newer',async t=>{
135
+ const broken=executor(t,{version:null}),root=specs(t);
136
+ const {openTaskExecutionStore:openBroken}=await import(pathToFileURL(path.join(broken.root,'runtime/js/cm-ai/task-owner.mjs')).href);
137
+ assert.throws(()=>openBroken(taskOptions(root,true)),error=>error.code==='executor_version_unavailable');
138
+ assert.equal(fs.existsSync(binding(root)),false);
139
+ const newer=executor(t,{version:'0.30.0'}),older=executor(t,{version:'0.29.9'}),other=specs(t);
140
+ const owner=path=>import(pathToFileURL(path).href);
141
+ (await owner(path.join(newer.root,'runtime/js/cm-ai/task-owner.mjs'))).openTaskExecutionStore(taskOptions(other,true)).close();
142
+ const before={binding:fs.readFileSync(binding(other)),state:fs.readFileSync(stateFile(other))};
143
+ fs.rmSync(binding(other));
144
+ const {openTaskExecutionStore:openOld}=await owner(path.join(older.root,'runtime/js/cm-ai/task-owner.mjs'));
145
+ assert.throws(()=>openOld(taskOptions(other,false)),error=>error.code==='run_created_by_newer_executor');
146
+ assert.equal(fs.existsSync(binding(other)),false,'the binding is not rewritten before the refusal');
147
+ assert.deepEqual(fs.readFileSync(stateFile(other)),before.state);
148
+ });
149
+
150
+ function fixOptions(root,{bare=false,create=true,executionPolicy=null}={}){
151
+ const cwd=path.join(root,'code');fs.mkdirSync(cwd,{recursive:true});
152
+ const specsRoot=path.join(root,'specs');if(!bare)fs.mkdirSync(specsRoot,{recursive:true});
153
+ return {...(bare?{}:{specsRoot}),identity:{repositoryId:'fix-fixture',runId:'fix-demo',taskId:'T-FIX-demo',attempt:1},create,
154
+ configuration:{hostContextId:'actual-fixture-host',defect:'Synthetic failure',reproduction:{cwd,
155
+ command:[process.execPath,'-e',"process.stderr.write('BUG');process.exit(3)"],expectedFailure:{exitCode:3,outputIncludes:'BUG'},timeoutMs:1000},
156
+ ...(executionPolicy?{executionPolicy}:{})}};
157
+ }
158
+ test('cm-fix creates no archive directory without a release and never opens a run a newer release created',async t=>{
159
+ const fixModule=tree=>import(pathToFileURL(path.join(tree.root,'runtime/js/cm-fix/execution.mjs')).href);
160
+ const broken=executor(t,{version:null}),bare=temp(t,'cm-fix-bare-');
161
+ const {openFixExecution:openBroken}=await fixModule(broken);
162
+ assert.throws(()=>openBroken(fixOptions(bare,{bare:true})),error=>error.code==='executor_version_unavailable');
163
+ assert.equal(fs.existsSync(path.join(bare,'code','docs')),false,'no docs/fixes before the refusal');
164
+ const newer=executor(t,{version:'0.30.0'}),older=executor(t,{version:'0.29.9'}),root=temp(t,'cm-fix-');
165
+ // With execution optimization the owner takes a run guard and a code-root binding
166
+ // before its store; a resume in a copy lacking the binding must not recreate it.
167
+ const {EXECUTION_POLICY_V1}=await import(pathToFileURL(path.join(newer.root,'runtime/js/cm-ai/execution-policy.mjs')).href);
168
+ (await fixModule(newer)).openFixExecution(fixOptions(root,{executionPolicy:EXECUTION_POLICY_V1})).close();
169
+ const file=path.join(root,'specs','.reviews','.execution','fix-demo','state.json'),before=fs.readFileSync(file);
170
+ for(const name of fs.readdirSync(path.join(root,'code')))if(name.startsWith('.cm-external'))fs.rmSync(path.join(root,'code',name),{recursive:true,force:true});
171
+ const tree=dir=>fs.readdirSync(dir,{recursive:true}).sort();
172
+ const entries={specs:tree(path.join(root,'specs')),code:tree(path.join(root,'code'))};
173
+ const {openFixExecution:openOld}=await fixModule(older);
174
+ assert.throws(()=>openOld(fixOptions(root,{create:false,executionPolicy:EXECUTION_POLICY_V1})),error=>error.code==='run_created_by_newer_executor'
175
+ &&/此运行由 CM 0\.30\.0 创建/.test(error.reason));
176
+ assert.deepEqual(fs.readFileSync(file),before);
177
+ assert.deepEqual({specs:tree(path.join(root,'specs')),code:tree(path.join(root,'code'))},entries,'no guard, binding or other store was written');
178
+ });
179
+
180
+
181
+ // A serial batch opens its first member before writing batch_start. Interrupted
182
+ // there, the batch takes that member's release, never the resuming executor's.
183
+ test('a batch takes its release from batch_start, else from a member an interrupted start left, else this executor',async t=>{
184
+ const {batchCreatedBy}=await import('./cm-ai-batch-run.mjs'),{openExecutionStore}=await import('../runtime/js/cm-ai/execution-store.mjs');
185
+ const root=specs(t),log=path.join(root,'运行日志.jsonl'),config={batchId:'batch-a',specsDir:root};
186
+ const plans=new Map([['1.work/T-001',{identity:{repositoryId:identity.repositoryId,runId:identity.runId}}]]);
187
+ assert.deepEqual(batchCreatedBy(config,plans,log),{version:1,release:executorRelease()},'new batch: this executor');
188
+ openExecutionStore(options(root,true)).close();
189
+ rewrite(root,data=>({...data,createdBy:{version:1,release:'0.0.1'}}));
190
+ assert.deepEqual(batchCreatedBy(config,plans,log),{version:1,release:'0.0.1'},'interrupted start: the member store');
191
+ rewrite(root,({createdBy,...data})=>({...data,version:1}));
192
+ assert.equal(batchCreatedBy(config,plans,log),null,'a pre-0.22.0 member: unversioned batch');
193
+ const row=release=>JSON.stringify({workflow:'cm-ai',event:'decision',phase:'batch_start',run_id:'batch-a',
194
+ ...(release?{created_by:{version:1,release}}:{})})+'\n';
195
+ fs.writeFileSync(log,row('0.0.2'));
196
+ assert.deepEqual(batchCreatedBy(config,plans,log),{version:1,release:'0.0.2'},'batch_start wins');
197
+ fs.writeFileSync(log,row(null));assert.equal(batchCreatedBy(config,plans,log),null);
198
+ fs.writeFileSync(log,row('99.0.0'));
199
+ assert.throws(()=>batchCreatedBy(config,plans,log),error=>error.code==='run_created_by_newer_executor');
200
+ });
201
+
202
+ // A batch host settles its release when built and again under batch.lock: a row or
203
+ // member another executor wrote in between (long-lived host, race) stops it there.
204
+ function batchProject(t){
205
+ const root=temp(t,'cm-batch-release-'),specsDir=path.join(root,'specs'),codeProject=path.join(root,'code');
206
+ fs.mkdirSync(path.join(specsDir,'1.work'),{recursive:true});fs.mkdirSync(codeProject);
207
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,'1.work',name),'# Fixture\n');
208
+ fs.writeFileSync(path.join(specsDir,'1.work','tasks.md'),'- [ ] T-001: first\n - 范围: `a.mjs`\n');
209
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Fixture\n');
210
+ return {root,specsDir,codeProject,batch:{version:1,repositoryId:'r',batchId:'release-batch',specsDir,codeProject,
211
+ tasks:[{feature:'1.work',taskId:'T-001',scope:['a.mjs'],requirements:['requirements.md']}]}};
212
+ }
213
+ const approve=async f=>{const {buildManifest}=await import('./cm-spec-manifest.mjs');
214
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));};
215
+ const startRow=release=>JSON.stringify({schema_version:1,workflow:'cm-ai',event:'decision',phase:'batch_start',run_id:'release-batch',
216
+ created_by:{version:1,release}})+'\n';
217
+ test('a built batch host re-checks its release under the lock and writes nothing when it changed',async t=>{
218
+ const {createCmAiBatch}=await import('./cm-ai-batch-run.mjs');
219
+ const f=batchProject(t);await approve(f);
220
+ const lock=path.join(f.specsDir,'.reviews','.execution','batch.lock'),log=path.join(f.specsDir,'运行日志.jsonl');
221
+ for(const change of [()=>fs.writeFileSync(log,startRow('99.0.0')),()=>{
222
+ // An older executor's first member (v1, no createdBy) written after this host was built.
223
+ const {openExecutionStore}=awaited.store;const runId=`task-${digest({batchId:'release-batch',task:'1.work/T-001'}).slice(0,48)}`;
224
+ const ident={repositoryId:'r',runId};openExecutionStore({specsRoot:f.specsDir,identity:ident,fingerprints,create:true}).close();
225
+ const file=path.join(f.specsDir,'.reviews','.execution',runId,'state.json'),{revision,createdBy,...data}=JSON.parse(fs.readFileSync(file,'utf8'));
226
+ const v1={...data,version:1};fs.writeFileSync(file,JSON.stringify({...v1,revision:digest(v1)})+'\n');}]){
227
+ for(const name of ['.reviews'])fs.rmSync(path.join(f.specsDir,name),{recursive:true,force:true});fs.rmSync(log,{force:true});
228
+ const batch=createCmAiBatch({configuration:f.batch,executionFor:async()=>{throw Error('no member may open');},logHome:path.join(f.root,'logs')});
229
+ change();const before=fs.existsSync(log)?fs.readFileSync(log):null;
230
+ await assert.rejects(batch.handle({requestId:'r1',operation:'advance'}),
231
+ error=>['run_created_by_newer_executor','batch_history_changed'].includes(error.code));
232
+ assert.equal(fs.existsSync(lock),false,'the lock is released');
233
+ assert.deepEqual(fs.existsSync(log)?fs.readFileSync(log):null,before,'no row written');
234
+ }
235
+ });
236
+ const awaited={store:await import('../runtime/js/cm-ai/execution-store.mjs')};
237
+
238
+ test('the batch host entry shows the upgrade exit of a release refusal',async t=>{
239
+ const f=batchProject(t);await approve(f);
240
+ fs.writeFileSync(path.join(f.specsDir,'运行日志.jsonl'),startRow('99.0.0'));
241
+ const config=path.join(f.root,'batch.json');fs.writeFileSync(config,JSON.stringify({batch:f.batch,workflows:{'1.work/T-001':null}}));
242
+ const {spawnSync}=await import('node:child_process'),{configFingerprint}=await import('../runtime/js/cm-ai/codex-config.mjs');
243
+ const review=path.join(f.root,'review.json');fs.writeFileSync(review,JSON.stringify({model:'fixture',preflight:{passed:true,cli_model:'fixture',
244
+ prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd:f.codeProject,model:'fixture'})}}));
245
+ const result=spawnSync(process.execPath,[path.join(repo,'scripts','cm-ai-batch-host.mjs'),'serve','--config',config,'--host-context','h',
246
+ '--allow-development','--review-config',review],{encoding:'utf8',input:'',timeout:60000});
247
+ assert.equal(result.status,1,result.stderr);
248
+ const error=JSON.parse(result.stderr.trim().split('\n').at(-1)).error;
249
+ assert.equal(error.code,'run_created_by_newer_executor',result.stderr);assert.match(error.reason,/此运行由 CM 99\.0\.0 创建/);
250
+ });
@@ -95,7 +95,12 @@ test('new mode owns a serial lease and a different run ID cannot bypass unfinish
95
95
  const run=await f.open();
96
96
  assert.throws(()=>acquireExternalRunGuard(f.definition),{code:'store_busy'});
97
97
  const otherSpecs=path.join(f.tmp,'other-specs');fs.mkdirSync(otherSpecs);
98
- assert.throws(()=>acquireExternalRunGuard({...f.definition,specsDir:otherSpecs}),{code:'external_code_specs_conflict'});
98
+ // dogfood: a code root bound to old specs8 refused specs10 with only a bare code.
99
+ const writes=[],write=process.stderr.write;process.stderr.write=chunk=>{writes.push(String(chunk));return true;};
100
+ try{assert.throws(()=>acquireExternalRunGuard({...f.definition,specsDir:otherSpecs}),{code:'external_code_specs_conflict'});}
101
+ finally{process.stderr.write=write;}
102
+ const notice=writes.join('');
103
+ assert(notice.includes(JSON.stringify(path.basename(f.definition.specsDir)))&&!notice.includes(f.tmp)&&notice.includes('git worktree add')&&notice.includes('不要删除'),notice);
99
104
  let status=await run.host.handle(f.operation('start'));assert.equal(status.state,'awaiting_review');
100
105
  const fake=path.join(f.tmp,'fake.mjs');fs.writeFileSync(fake,fs.readFileSync(fake,'utf8').replace("verdict:'approved'","verdict:'invalid'"));
101
106
  status=await run.host.handle(f.operation('decision',{packageDigest:status.packageDigest}));assert.equal(status.state,'unknown');f.close();
@@ -67,7 +67,7 @@ async function fixture(fn,{reviewRun,times,timeoutMs=1000,provider='codex'}={})
67
67
  const current=store.snapshot(),at=last?current.records.findLastIndex(record=>record.payload.type===type)
68
68
  :current.records.findIndex(record=>record.payload.type===type);assert(at>=0);store.close();
69
69
  const statePath=path.join(specsRoot,'.reviews','.execution',identity.runId,'state.json');
70
- const body={version:current.version,identity:current.identity,fingerprints:current.fingerprints,records:current.records.slice(0,at+1)};
70
+ const body={version:current.version,identity:current.identity,fingerprints:current.fingerprints,...(Object.hasOwn(current,"createdBy")?{createdBy:current.createdBy}:{}),records:current.records.slice(0,at+1)};
71
71
  fs.writeFileSync(statePath,JSON.stringify({...body,revision:digest(body)})+'\n',{mode:0o600});
72
72
  store=openTaskExecutionStore({...owner,create:false});return make('resume');
73
73
  };