@aibyzero/cm-workflow 0.19.0 → 0.21.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 (127) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +38 -0
  4. package/README.md +15 -1
  5. package/VERSION +1 -1
  6. package/docs/architecture.md +3 -0
  7. package/docs/cm-acceptance-completion.md +185 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +1 -1
  10. package/docs/proposals/spec-amendment-tiers.md +100 -0
  11. package/package.json +1 -1
  12. package/runtime/js/acceptance-language.mjs +32 -0
  13. package/runtime/js/autonomy.mjs +168 -3
  14. package/runtime/js/check-coverage.mjs +130 -0
  15. package/runtime/js/cm-ai/acceptance-contract.mjs +257 -0
  16. package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
  17. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
  18. package/runtime/js/cm-ai/cm-ai-admission.mjs +49 -8
  19. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
  20. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
  21. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
  22. package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
  23. package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
  24. package/runtime/js/cm-ai/completion-summary.mjs +187 -0
  25. package/runtime/js/cm-ai/control-policy.mjs +3 -1
  26. package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
  27. package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
  28. package/runtime/js/cm-ai/drive-core.mjs +15 -4
  29. package/runtime/js/cm-ai/durable-runner-state.mjs +10 -6
  30. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  31. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
  32. package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
  33. package/runtime/js/cm-ai/execution-store.mjs +7 -4
  34. package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
  35. package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
  36. package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
  37. package/runtime/js/cm-ai/host-progress.mjs +2 -1
  38. package/runtime/js/cm-ai/log-rows.mjs +3 -2
  39. package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
  40. package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
  41. package/runtime/js/cm-ai/review-package.mjs +22 -8
  42. package/runtime/js/cm-ai/review-presentation.mjs +12 -5
  43. package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
  44. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  45. package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
  46. package/runtime/js/cm-ai/specification-material.mjs +57 -12
  47. package/runtime/js/cm-ai/task-commit.mjs +4 -2
  48. package/runtime/js/cm-ai/task-runner.mjs +64 -22
  49. package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
  50. package/runtime/js/cm-ai/verification-auto.mjs +6 -4
  51. package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
  52. package/runtime/js/cm-prd/change.mjs +52 -5
  53. package/runtime/js/cm-prd/self-check.mjs +36 -6
  54. package/runtime/js/cm-prd/session.mjs +8 -3
  55. package/runtime/js/cm-prd/summary.mjs +5 -0
  56. package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
  57. package/runtime/js/node-test-selection.mjs +38 -0
  58. package/runtime/js/run-analysis.mjs +153 -0
  59. package/runtime/js/session-boundary.mjs +17 -5
  60. package/runtime/js/session-handoff.mjs +5 -2
  61. package/runtime/js/task-scope.mjs +4 -1
  62. package/runtime/test-contract.md +1 -0
  63. package/scripts/cm-acceptance-preview.mjs +26 -0
  64. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  65. package/scripts/cm-ai-acceptance-contract.test.mjs +195 -0
  66. package/scripts/cm-ai-admission.mjs +8 -2
  67. package/scripts/cm-ai-admission.test.mjs +20 -4
  68. package/scripts/cm-ai-blockage.test.mjs +120 -0
  69. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  70. package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
  71. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
  72. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  73. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  74. package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
  75. package/scripts/cm-ai-drive.mjs +18 -11
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
  77. package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
  78. package/scripts/cm-ai-progress.test.mjs +7 -0
  79. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  80. package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
  81. package/scripts/cm-ai-run.test.mjs +23 -1
  82. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  83. package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
  84. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  85. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  86. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  87. package/scripts/cm-autonomy-review-r1.test.mjs +142 -0
  88. package/scripts/cm-autonomy.mjs +3 -1
  89. package/scripts/cm-autonomy.test.mjs +10 -9
  90. package/scripts/cm-check-runtime.sh +5 -2
  91. package/scripts/cm-delivery-evidence.mjs +59 -0
  92. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  93. package/scripts/cm-drive-liveness.test.mjs +14 -0
  94. package/scripts/cm-driver-light-import.test.mjs +32 -0
  95. package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
  96. package/scripts/cm-fix-review-storage.test.mjs +14 -4
  97. package/scripts/cm-journal-limit.test.mjs +69 -0
  98. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  99. package/scripts/cm-node-test-selection.test.mjs +108 -0
  100. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  101. package/scripts/cm-prd-completion.test.mjs +49 -0
  102. package/scripts/cm-prd-drive.mjs +1 -1
  103. package/scripts/cm-prd-host.mjs +3 -1
  104. package/scripts/cm-prd-host.test.mjs +19 -2
  105. package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
  106. package/scripts/cm-prd-self-check.test.mjs +24 -1
  107. package/scripts/cm-prd-summary.test.mjs +25 -4
  108. package/scripts/cm-review-inventory.test.mjs +25 -6
  109. package/scripts/cm-run-analysis.mjs +21 -0
  110. package/scripts/cm-run-analysis.test.mjs +120 -0
  111. package/scripts/cm-spec-amend.mjs +68 -0
  112. package/scripts/cm-spec-amend.test.mjs +510 -0
  113. package/scripts/cm-specs-status.test.mjs +6 -0
  114. package/scripts/cm-start-check.mjs +140 -53
  115. package/scripts/cm-start-check.test.mjs +139 -1
  116. package/scripts/cm-task-scope.test.mjs +3 -2
  117. package/scripts/cm-usage-report.py +8 -3
  118. package/scripts/cm019-r1-contract.test.mjs +137 -0
  119. package/scripts/cm019-review-gates.test.mjs +97 -0
  120. package/scripts/test-journal-limit-1mib.mjs +4 -0
  121. package/scripts/validate-public-repo.py +4 -0
  122. package/skills/cm-ai/references/N1-init.md +23 -1
  123. package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
  124. package/skills/cm-ai/references/js-host-recovery.md +2 -1
  125. package/skills/cm-ai/references/js-host.md +7 -2
  126. package/skills/cm-prd/references/js-change-recovery.md +2 -1
  127. package/skills/cm-prd/references/js-host.md +1 -0
@@ -0,0 +1,91 @@
1
+ // 默认 4 MiB 存档上限下的真实驾驶员与宿主(实跑 aihot 副本发现):存档放得下、审查输入却超过
2
+ // Codex 的 1 MiB 时,开发交付当场拦为 develop_package_too_large,不再留下无法重派的审查;
3
+ // 超过 1 MiB 原内联预算但审查放得下的包走材料归档,两轮审查后完成。审查方是进程替身,不是模型证据。
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} from 'node:url';
11
+ const R=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
12
+ const {buildManifest}=await import(R+'/scripts/cm-spec-manifest.mjs');
13
+ const {configFingerprint}=await import(R+'/runtime/js/cm-ai/codex-config.mjs');
14
+ const {JOURNAL_PAYLOAD_LIMIT}=await import(R+'/runtime/js/cm-ai/effect-contract.mjs');
15
+ const {STATE_LIMIT}=await import(R+'/runtime/js/cm-ai/execution-store-limits.mjs');
16
+ const {readRunnerHistory}=await import(R+'/runtime/js/cm-ai/durable-runner-state.mjs');
17
+ const DRIVER=R+'/scripts/cm-ai-drive.mjs',REVIEWER=R+'/scripts/fixtures/codex-review-process.mjs';
18
+ const developValue={outcome:'implemented',application:{status:'no_relevant_lesson',note:null},retrospective:{status:'no_new_lesson',candidates:[],reason:null}};
19
+ const policy={version:2,development:'conversation',bootstrap:'disabled',qa:'disabled',qaFix:'disabled'};
20
+ const big=(seed,bytes)=>'export const seed = "'+seed+'";\n'+('// '+seed+' '+'y'.repeat(80)+'\n').repeat(Math.ceil(bytes/90));
21
+ function scenario(fileBytes,check){
22
+ assert.equal(JOURNAL_PAYLOAD_LIMIT,4*1024*1024);
23
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-review-input-')));
24
+ const specsDir=path.join(root,'specs'),codeProject=path.join(root,'app'),feature='1.work',scope=['target.mjs','data.mjs'];
25
+ const identity={repositoryId:'review-input',runId:'review-input-'+fileBytes,taskId:'T-001',attempt:1};
26
+ fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);
27
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# B1\n');
28
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: b1\n');
29
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
30
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'# B1\n');fs.writeFileSync(path.join(codeProject,'target.mjs'),'export const v = 1;\n');fs.writeFileSync(path.join(codeProject,'data.mjs'),'export const d = 1;\n');
31
+ const config=path.join(root,'run.json');
32
+ fs.writeFileSync(config,JSON.stringify({version:1,specsDir,codeProject,feature,identity,scope,requirements:['requirements.md']}));
33
+ const answers=path.join(root,'answers');fs.mkdirSync(answers);const bin=path.join(root,'bin');fs.mkdirSync(bin);
34
+ fs.writeFileSync(path.join(root,'control.json'),JSON.stringify(policy));
35
+ const env={...process.env,PATH:bin+path.delimiter+process.env.PATH,CM_WORKFLOW_HOME:path.join(root,'home'),CM_WORKFLOW_LOG_HOME:path.join(root,'logs')};
36
+ delete env.CM_JOURNAL_PAYLOAD_LIMIT_TEST;
37
+ const reviewer=verdict=>{let fake=fs.readFileSync(REVIEWER,'utf8');
38
+ if(verdict==='changes_requested')fake=fake.replace("verdict:'approved'","verdict:data.reviewPackage.identity.attempt===1?'changes_requested':'approved'")
39
+ .replace('findings:[]',"findings:data.reviewPackage.identity.attempt===1?[{id:'F1',severity:'P2',path:'target.mjs',message:'Revise',evidence:'B1 finding'}]:[]");
40
+ fs.writeFileSync(path.join(bin,'codex'),fake,{mode:0o700});
41
+ fs.writeFileSync(path.join(root,'review.json'),JSON.stringify({model:'fixture',preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture'})}}));};
42
+ reviewer('changes_requested');
43
+ const develop=(seed,name,bytes=fileBytes)=>{fs.writeFileSync(path.join(answers,seed+'-t.mjs'),big(seed+'t',bytes));fs.writeFileSync(path.join(answers,seed+'-d.mjs'),big(seed+'d',bytes));fs.writeFileSync(path.join(answers,name),JSON.stringify({status:'succeeded',value:developValue,edits:{'target.mjs':seed+'-t.mjs','data.mjs':seed+'-d.mjs'}}));};
44
+ const checks=[{id:'syntax',command:[process.execPath,'--check',path.join(codeProject,'target.mjs')]},{id:'syntax-data',command:[process.execPath,'--check',path.join(codeProject,'data.mjs')]}];
45
+ const plan=extra=>{const file=path.join(root,'plan-'+Math.random().toString(36).slice(2)+'.json');
46
+ fs.writeFileSync(file,JSON.stringify({config:'run.json',mode:'create',hostContext:'review-input-host',controlConfig:'control.json',
47
+ permissions:['--review-config','review.json'],answers:'answers',checks,...extra}));return file;};
48
+ const drive=(file,op)=>spawnSync(process.execPath,[DRIVER,'--plan',file,op],{encoding:'utf8',timeout:600000,env});
49
+ const out=run=>{assert.equal(run.status,0,run.stderr.slice(-4000)+" | STDOUT "+run.stdout.slice(-1500));return JSON.parse(run.stdout).result;};
50
+ const store=path.join(specsDir,'.reviews','.execution',identity.runId,'state.json');
51
+ const rows=()=>JSON.parse(fs.readFileSync(store,'utf8')).records;
52
+ try{
53
+ develop('a1','develop.json');develop('a2','develop-a2.json');
54
+ check({drive,plan,out,rows,specsDir,feature,develop,reviewer,answers});
55
+ }finally{fs.rmSync(root,{recursive:true,force:true});}
56
+ }
57
+
58
+ test('a delivery whose review input exceeds the Codex limit is refused at develop, then redone smaller in the same run',()=>scenario(900000,({drive,plan,out,rows,develop,reviewer})=>{
59
+ const run=drive(plan({}),'advance');assert.equal(run.status,0,run.stderr.slice(-2000));
60
+ const result=JSON.parse(run.stdout).result;
61
+ assert.equal(result.state,'blocked');assert.equal(result.code,'develop_package_too_large');
62
+ assert.match(result.reason,/review input for codex would exceed its limit of 1048576 bytes/);
63
+ assert(rows().every(row=>!String(row.payload.type).startsWith('review-invocation')),'no review was dispatched');
64
+ // Shrink the delivery and resume the same run: develop is redone at the same attempt
65
+ // with a new effect, the blocked record stays in history, and the task completes.
66
+ const blockedRows=rows();
67
+ reviewer('approved');develop('small','develop.json',2000);
68
+ let state=out(drive(plan({mode:'resume'}),'advance'));
69
+ for(let i=0;i<3&&!['approved','fixture_completed'].includes(state.state);i++)
70
+ state=out(drive(plan({mode:'resume',...(state.packageDigest?{packageDigest:state.packageDigest}:{})}),state.state==='awaiting_review'?'decision':'advance'));
71
+ assert.equal(state.identity.attempt,1);
72
+ if(state.state!=='fixture_completed')state=out(drive(plan({mode:'resume',packageDigest:state.packageDigest}),'complete'));
73
+ assert.equal(state.state,'fixture_completed');
74
+ const finalRows=rows();
75
+ assert.deepEqual(finalRows.slice(0,blockedRows.length),blockedRows,'the refused delivery stays in history');
76
+ assert(finalRows.some(row=>row.payload.checkpoint?.code==='develop_package_too_large'));
77
+ }));
78
+
79
+ test('a package above the original 1 MiB inline budget that the review can take is archived and completes after two rounds',()=>scenario(400000,({drive,plan,out,rows,specsDir,feature})=>{
80
+ let state=out(drive(plan({}),'advance'));
81
+ for(let i=0;i<3&&!['approved','fixture_completed'].includes(state.state);i++)
82
+ state=out(drive(plan({mode:'resume',...(state.packageDigest?{packageDigest:state.packageDigest}:{})}),state.state==='awaiting_review'?'decision':'advance'));
83
+ assert.equal(state.identity.attempt,2);
84
+ if(state.state!=='fixture_completed')state=out(drive(plan({mode:'resume',packageDigest:state.packageDigest}),'complete'));
85
+ assert.equal(state.state,'fixture_completed');
86
+ const list=rows();
87
+ assert.equal(list.filter(row=>row.payload.packageMaterial).length,2);assert(list.filter(row=>row.payload.packageRef).length>=2);
88
+ assert(Buffer.byteLength(JSON.stringify(list))<STATE_LIMIT);
89
+ assert.equal(readRunnerHistory(list,list[0].payload.config,3).state.state,'fixture_completed');
90
+ assert.match(fs.readFileSync(path.join(specsDir,feature,'tasks.md'),'utf8'),/\[x\] T-001/);
91
+ }));
@@ -77,7 +77,20 @@ test(`trusted host execution uses the same entry and sole gate: ${mode} nested=$
77
77
  // include/follow its external metadata in the provider review package.
78
78
  fs.writeFileSync(path.join(f.codeProject,'.git'),'gitdir: /nonexistent/cm-synthetic-worktree-metadata\n');
79
79
  let stdout='',stderr='',calls=0,reviews=0;output.on('data',x=>stdout+=x);error.on('data',x=>stderr+=x);
80
+ fs.writeFileSync(path.join(f.specsDir,'1.login','tasks.md'),'- [ ] T-001: implement\n - 必验: preserve implementation\n');
81
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.login'],specFiles:buildManifest(f.specsDir)}));
80
82
  const execution={configuration:{kind:'synthetic-host-v1'},timeoutMs:2000,excludedContexts:['main'],
83
+ verificationGate:async request=>{
84
+ // These fixtures deliberately vary Review, not the implemented task's
85
+ // acceptance. Bind the evidence to the fixed fixture and real check.
86
+ assert.equal(request.description,'implement');
87
+ assert.deepEqual(request.acceptanceContract.obligations.map(item=>item.requirement),['- [ ] T-001: implement','- 必验: preserve implementation']);
88
+ assert.equal(request.checks.length,1);assert.equal(request.checks[0].id,'content');
89
+ assert.equal(request.checks[0].outcome,'passed');
90
+ assert.match(fs.readFileSync(path.join(f.codeProject,'a.js'),'utf8'),/^new( 2)?\n$/);
91
+ return {satisfied:true,items:request.acceptanceContract.obligations.map(item=>({...item,satisfied:true,
92
+ evidence:'Synthetic fixture a.js matches the implemented value; the real content subprocess passed'}))};
93
+ },
81
94
  developer:{provider:'codex',requestedModel:'fixture',contextId:'dev',run:createCodexDeveloperRun({requestedModel:'fixture',worker:async({prompt})=>{
82
95
  // Attempt 2 must change the rejected bytes (develop_unchanged_after_review).
83
96
  calls++;fs.writeFileSync(path.join(f.codeProject,'a.js'),JSON.parse(prompt.split('<cm-developer-data-json>\n')[1]).identity.attempt===1?'new\n':'new 2\n');
@@ -367,13 +380,22 @@ test('trusted parallel selection binds admission, Learning, start and resume fin
367
380
  const {inspectCmAiTaskLearningInput}=await import('../runtime/js/cm-ai/cm-ai-context-refresh.mjs');
368
381
  const {createCodexDeveloperRun}=await import('../runtime/js/cm-ai/codex-developer-adapter.mjs');
369
382
  const {createCmAiHost}=await import('../runtime/js/cm-ai/host.mjs');
370
- fs.writeFileSync(path.join(f.specsDir,'1.login','tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n- [ ] T-003: final\n\n- T-003 依赖 T-001, T-002\n');
383
+ fs.writeFileSync(path.join(f.specsDir,'1.login','tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n - 必验: preserve second\n- [ ] T-003: final\n\n- T-003 依赖 T-001, T-002\n');
371
384
  fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.login'],specFiles:buildManifest(f.specsDir)}));
372
385
  const definition={...f.definition,identity:{...identity,taskId:'T-002'}},parallelSelection={version:1,group:['T-001','T-002']};
373
386
  const learning={specsDir:f.specsDir,codeProject:f.codeProject,feature:'1.login',identity:definition.identity,applicableAgentFiles:[]};
374
387
  assert.throws(()=>inspectCmAiTaskLearningInput(learning),{code:'learning_context_invalid'});
375
388
  assert.equal(inspectCmAiTaskLearningInput(learning,{parallelSelection}).identity.taskId,'T-002');
376
389
  const execution={configuration:{kind:'selection-fixture'},timeoutMs:2000,excludedContexts:['host'],
390
+ verificationGate:async request=>{
391
+ assert.equal(request.description,'second');
392
+ assert.deepEqual(request.acceptanceContract.obligations.map(item=>item.requirement),
393
+ ['- [ ] T-002: second','- 必验: preserve second']);
394
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'a.js'),'utf8'),'selected implementation\n');
395
+ assert.equal(request.checks[0].outcome,'passed');
396
+ return {satisfied:true,items:request.acceptanceContract.obligations.map(item=>({...item,satisfied:true,
397
+ evidence:'Synthetic selected implementation bytes and T-002 dependency references match this fixed fixture'}))};
398
+ },
377
399
  developer:{provider:'codex',requestedModel:'fixture',contextId:'author',run:createCodexDeveloperRun({requestedModel:'fixture',worker:async()=>{fs.writeFileSync(path.join(f.codeProject,'a.js'),'selected implementation\n');return {status:'succeeded',value:{outcome:'implemented',
378
400
  application:{status:'no_relevant_lesson',note:null},retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};}})},
379
401
  check:async()=>[{id:'check',command:['fixture'],outcome:'passed',exitCode:0,evidence:'fixture'}],reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',
@@ -34,7 +34,7 @@ function fixture(t){
34
34
  const file=name=>path.join(specsDir,feature,name);
35
35
  fs.writeFileSync(file('requirements.md'),'# Requirements\n- [ ] [AC-001] a exports new\n');
36
36
  fs.writeFileSync(file('design.md'),'# Design\nsimple\n');
37
- fs.writeFileSync(file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b\n\n- T-002 依赖 T-001\n');
37
+ fs.writeFileSync(file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b\n\n- T-002 依赖 T-001\n');
38
38
  fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
39
39
  const identity=(runId='rebind-run-0001')=>({repositoryId:'rebind-fixture',runId,taskId:'T-001',attempt:1});
40
40
  const definition=(runId)=>({version:1,specsDir,codeProject,feature,identity:identity(runId),scope:['a.mjs'],requirements:['requirements.md']});
@@ -60,6 +60,8 @@ function executionFor(f,{decision=null,onReview=()=>{},onDevelop=()=>{}}={}){
60
60
  examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic review'}};
61
61
  }};
62
62
  return {configuration:{kind:'synthetic-host-v1'},timeoutMs:2000,excludedContexts:['control'],
63
+ verificationGate:async request=>({satisfied:true,...(request.acceptanceContract?{items:request.acceptanceContract.obligations.map(item=>
64
+ ({...item,satisfied:true,evidence:'Synthetic fixture checks and independent review cover this approved obligation'}))}:{})}),
63
65
  developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:createCodexDeveloperRun({
64
66
  requestedModel:'fixture',worker:async()=>{fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'export const a=2;\n');onDevelop();
65
67
  return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
@@ -83,7 +85,7 @@ const stateFile=(f,runId='rebind-run-0001')=>path.join(f.specsDir,'.reviews','.e
83
85
 
84
86
  test('another task changed and re-approved: status names spec_drift and the rebind; the rebind keeps the delivery',async t=>{
85
87
  const f=fixture(t),packageDigest=await awaitingReview(f);
86
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b(导出 3)\n\n- T-002 依赖 T-001\n');
88
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b(导出 3)\n\n- T-002 依赖 T-001\n');
87
89
  reapprove(f);
88
90
  await withRun(f,'resume',{decision:{status:'approved'}},async(host,identity)=>{
89
91
  const status=await ask(host,identity,'status');
@@ -146,7 +148,7 @@ test('a change to what the run saw fails closed, names it, and both recovery exi
146
148
 
147
149
  test('a rebind cannot carry changed content: a later content change still drifts',async t=>{
148
150
  const f=fixture(t);await awaitingReview(f);
149
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
151
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
150
152
  await withRun(f,'resume',{specRebindReason:'只改了 T-002'},async()=>{});
151
153
  fs.appendFileSync(f.file('requirements.md'),'- [ ] [AC-002] b exports 3\n');reapprove(f);
152
154
  await withRun(f,'resume',{},async(host,identity)=>{
@@ -162,7 +164,7 @@ test('a spec change during review never leaves status advertising a refused acti
162
164
  const f=fixture(t);
163
165
  await withRun(f,'create',{},async(host,identity)=>assert.equal((await ask(host,identity,'start')).state,'awaiting_review'));
164
166
  const changeDuringReview=()=>{
165
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 审查期间改了\n\n- T-002 依赖 T-001\n');reapprove(f);};
167
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 审查期间改了\n\n- T-002 依赖 T-001\n');reapprove(f);};
166
168
  await withRun(f,'resume',{decision:{status:'approved'},onReview:changeDuringReview},async(host,identity)=>{
167
169
  await ask(host,identity,'advance');
168
170
  const status=await ask(host,identity,'status');
@@ -199,7 +201,7 @@ test('host CLI accepts the rebind only on resume with a single-line reason',t=>{
199
201
  test('a run rebound before its first delivery develops against the re-approved spec',async t=>{
200
202
  const f=fixture(t);
201
203
  await withRun(f,'create',{},async(host,identity)=>assert.equal((await ask(host,identity,'status')).state,'ready'));
202
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
204
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
203
205
  await withRun(f,'resume',{},async(host,identity)=>{
204
206
  const status=await ask(host,identity,'status');
205
207
  assert.equal(status.state,'ready');assert.equal(status.code,'spec_drift');assert.equal(status.pendingAction,'spec_rebind');
@@ -213,7 +215,7 @@ test('a run rebound before its first delivery develops against the re-approved s
213
215
 
214
216
  test('journal replay accepts a rebind only bound to this run material and before completion',async t=>{
215
217
  const f=fixture(t);await awaitingReview(f);
216
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
218
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
217
219
  await withRun(f,'resume',{specRebindReason:'只改了 T-002'},async()=>{});
218
220
  const records=JSON.parse(fs.readFileSync(stateFile(f),'utf8')).records,config=records[0].payload.config;
219
221
  const index=records.findIndex(row=>row.payload.type==='specification-rebound');
@@ -249,7 +251,7 @@ test('a spec change while the developer works stops the run with its real exits'
249
251
  // decide from the material alone.
250
252
  async function multiLineRun(f){
251
253
  fs.writeFileSync(f.file('requirements.md'),'# Requirements\n- [ ] [AC-001] Store user data\n 必须静态加密\n- [ ] [AC-002] b exports 3\n');
252
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n - 约束:保留旧接口\n- [ ] T-002: 新增 b\n - 约束:导出 3\n\n## 验证要求\n- T-002: node --test b\n\n## 依赖关系\n- T-002 依赖 T-001\n');
254
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n - 约束:保留旧接口\n- [ ] T-002: 新增 b\n - 约束:导出 3\n\n## 验证要求\n- T-002: node --test b\n\n## 依赖关系\n- T-002 依赖 T-001\n');
253
255
  reapprove(f);
254
256
  return awaitingReview(f);
255
257
  }
@@ -293,12 +295,12 @@ test('multi-line spec: other tasks items, sub-bullets, verification and new task
293
295
  test('a run bound before taskScopeDigest keeps verifying but is never rebindable',async t=>{
294
296
  const f=fixture(t);
295
297
  await withRun(f,'create',{},async(host,identity)=>assert.equal((await ask(host,identity,'status')).state,'ready'));
296
- // Legacy-shaped journal: the init baseline material without taskScopeDigest.
298
+ // Legacy-shaped journal: before either taskScopeDigest or acceptanceContract existed.
297
299
  const file=stateFile(f),state=JSON.parse(fs.readFileSync(file,'utf8'));
298
300
  assert.equal(state.records.length,1);
299
301
  const init=state.records[0],{baselineDigest,...baseline}=init.payload.baseline;
300
302
  assert.match(baseline.specification.taskScopeDigest,/^[a-f0-9]{64}$/);
301
- const {taskScopeDigest,...material}=baseline.specification;
303
+ const {taskScopeDigest,acceptanceContract,...material}=baseline.specification;
302
304
  const legacyBaseline={...baseline,specification:material};
303
305
  const {digest:oldDigest,...body}=init;
304
306
  const record={...body,payload:{...init.payload,baseline:{...legacyBaseline,baselineDigest:digest(legacyBaseline)}}};
@@ -307,12 +309,46 @@ test('a run bound before taskScopeDigest keeps verifying but is never rebindable
307
309
  await withRun(f,'resume',{},async(host,identity)=>{
308
310
  const status=await ask(host,identity,'status');assert.equal(status.state,'ready');assert.equal(status.code,null);
309
311
  });
310
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
312
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
311
313
  const status=await statusOf(f);
312
314
  assert.equal(status.code,'spec_drift');assert.equal(status.pendingAction,'none');assert.match(status.reason,/旧版本创建/);
313
315
  await assert.rejects(withRun(f,'resume',{specRebindReason:'旧运行'},async()=>{}),error=>error.code==='spec_rebind_refused');
314
316
  });
315
317
 
318
+ test('a 0.19 journal without acceptanceContract resumes through review and completion without rewriting its baseline',async t=>{
319
+ const f=fixture(t);
320
+ // The old material allowed a task description beyond the new evidence-item
321
+ // bound. Resume must not construct a new contract just to discard it later.
322
+ fs.writeFileSync(f.file('tasks.md'),fs.readFileSync(f.file('tasks.md'),'utf8')
323
+ .replace('修改 a [AC-001]','必验: 修改 a [AC-001] '+ 'x'.repeat(2100)));
324
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[f.feature],
325
+ specFiles:buildManifest(f.specsDir)}));
326
+ await withRun(f,'create',{},async(host,identity)=>assert.equal((await ask(host,identity,'status')).state,'ready'));
327
+ // A 0.19 run already recorded taskScopeDigest, but had no acceptance contract.
328
+ // Reseal only this synthetic init to model that original, supported shape.
329
+ const file=stateFile(f),state=JSON.parse(fs.readFileSync(file,'utf8'));
330
+ assert.equal(state.records.length,1);
331
+ const init=state.records[0],{baselineDigest,...baseline}=init.payload.baseline;
332
+ const {acceptanceContract,...material}=baseline.specification;
333
+ assert.equal(acceptanceContract.version,1);assert.match(material.taskScopeDigest,/^[a-f0-9]{64}$/);
334
+ assert.ok(material.task.description.length>2100,'legacy task text is beyond the new evidence item bound');
335
+ const legacyBaseline={...baseline,specification:material},{digest:oldDigest,...body}=init;
336
+ const record={...body,payload:{...init.payload,baseline:{...legacyBaseline,baselineDigest:digest(legacyBaseline)}}};
337
+ const legacyInit={...record,digest:digest(record)},{revision,...rest}=state,next={...rest,records:[legacyInit]};
338
+ fs.writeFileSync(file,JSON.stringify({...next,revision:digest(next)})+'\n');
339
+ let developments=0,reviews=0;
340
+ const execution=()=>({...executionFor(f,{onDevelop:()=>developments++,onReview:()=>reviews++}),verificationGate:null});
341
+ let opened=await openControlRun(f.definition(),'resume',execution());
342
+ try{assert.equal((await ask(opened.host,f.identity(),'start')).state,'awaiting_review');}finally{opened.close();}
343
+ opened=await openControlRun(f.definition(),'resume',execution(),{decision:{status:'approved'}});
344
+ try{assert.equal((await ask(opened.host,f.identity(),'advance')).state,'fixture_completed');}finally{opened.close();}
345
+ assert.equal(developments,1);assert.equal(reviews,1);
346
+ const records=JSON.parse(fs.readFileSync(file,'utf8')).records;
347
+ assert.deepEqual(records[0],legacyInit,'the old baseline and its digest remain original');
348
+ assert.equal(readRunnerHistory(records,records[0].payload.config,3).state.state,'fixture_completed');
349
+ assert.match(fs.readFileSync(f.file('tasks.md'),'utf8'),/\[x\] T-001/);
350
+ });
351
+
316
352
  test('test cases: another task case may change, this task case may not',async t=>{
317
353
  const f=fixture(t);
318
354
  const testCase=(id,taskId,title)=>({id,origin:'user',kind:'logic',blocking:true,acIds:['AC-001'],taskIds:[taskId],
@@ -340,7 +376,7 @@ test('task scope keeps shared fenced text after another task item',async()=>{
340
376
 
341
377
  test('a line naming this task under another task item changes: refused',async t=>{
342
378
  const f=fixture(t);
343
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b\n - T-001 must encrypt backups\n\n## 依赖关系\n- T-002 依赖 T-001\n');
379
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b\n - T-001 must encrypt backups\n\n## 依赖关系\n- T-002 依赖 T-001\n');
344
380
  reapprove(f);await awaitingReview(f);
345
381
  fs.writeFileSync(f.file('tasks.md'),fs.readFileSync(f.file('tasks.md'),'utf8').replace('T-001 must encrypt backups','T-001 may store plaintext backups'));
346
382
  reapprove(f);
@@ -364,7 +400,7 @@ test('another task test case that names this task changes: refused',async t=>{
364
400
  // original parse. Under the old parser `T-001:` is prose, not a duplicate task.
365
401
  test('an approval recorded before the shared grammar keeps parsing with the old grammar end to end',async t=>{
366
402
  const f=fixture(t);
367
- const tasks='# tasks\n- [ ] T-001: 修改 a\n- [ ] T-001:示例写法(旧解析器视为说明)\n- [ ] T-002: 新增 b\n\n- T-002 依赖 T-001\n';
403
+ const tasks='# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-001:示例写法(旧解析器视为说明)\n- [ ] T-002: 新增 b\n\n- T-002 依赖 T-001\n';
368
404
  fs.writeFileSync(f.file('tasks.md'),tasks);
369
405
  // Legacy-shaped approval: no taskGrammar field.
370
406
  fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[f.feature],specFiles:buildManifest(f.specsDir)}));
@@ -372,7 +408,7 @@ test('an approval recorded before the shared grammar keeps parsing with the old
372
408
  const done=await withRun(f,'create',{decision:{status:'approved'}},(host,identity)=>ask(host,identity,'advance'));
373
409
  assert.equal(done.state,'fixture_completed',JSON.stringify(done));
374
410
  const after=fs.readFileSync(f.file('tasks.md'),'utf8');
375
- assert.equal(after,tasks.replace('- [ ] T-001: 修改 a','- [x] T-001: 修改 a'),'the old mark-done flips only the real task');
411
+ assert.equal(after,tasks.replace('- [ ] T-001: 修改 a [AC-001]','- [x] T-001: 修改 a [AC-001]'),'the old mark-done flips only the real task');
376
412
  assert.equal(inspectCmAiAdmission({specsDir:f.specsDir,codeProject:f.codeProject}).nextTask.id,'T-002');
377
413
  // supersede reads the tick with the same old grammar: one task, already ticked.
378
414
  await assert.rejects(withRun(f,'create',{supersedeReason:'重跑'},async()=>{},'rebind-run-legacy-2'),
@@ -398,7 +434,7 @@ function reapproveRaw(f){
398
434
 
399
435
  test('re-approving another feature is refused while an untouched feature would change meaning',async t=>{
400
436
  const f=fixture(t);
401
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-001:旧示例\n');
437
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-001:旧示例\n');
402
438
  const other=path.join(f.specsDir,'2.other');fs.mkdirSync(other);
403
439
  for(const [name,body] of [['requirements.md','# R\n- [ ] [AC-001] other\n'],['design.md','# D\n'],['tasks.md','- [ ] T-001: other\n']])
404
440
  fs.writeFileSync(path.join(other,name),body);
@@ -482,7 +518,7 @@ test('a batch member never advertises spec_rebind and names the real exits',asyn
482
518
  executionFor:async()=>({...executionFor(f),check:createHostCheck({cwd:f.codeProject,commands:[{id:'hold',command:[process.execPath,'-e','process.exit(1)']}]})}),logHome:path.join(f.root,'batch-logs')});
483
519
  const first=await batch().handle({operation:'advance',requestId:'batch-advance'});
484
520
  assert.equal(first.state,'blocked',JSON.stringify(first));assert.equal(first.code,'develop_checks_not_passed');
485
- fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
521
+ fs.writeFileSync(f.file('tasks.md'),'# tasks\n- [ ] T-001: 修改 a [AC-001]\n- [ ] T-002: 新增 b 改\n\n- T-002 依赖 T-001\n');reapprove(f);
486
522
  const status=await batch().handle({operation:'status',requestId:'batch-status'});
487
523
  assert.equal(status.code,'spec_drift');assert.equal(status.pendingAction,'none');
488
524
  assert.match(status.reason,/1\.work\/tasks\.md/);assert.match(status.reason,/批次成员不能换绑/);
@@ -0,0 +1,183 @@
1
+ // AI潮 specs7 (2026-11-03): the user hand-maintains Baseline/glass-verdicts.json
2
+ // (project rule: only the user edits it). Their direct commit could never be
3
+ // explained by a reviewed delivery, so completed runs stayed at
4
+ // correction_review_required. A code project may now declare such files.
5
+ import test,{after} from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
11
+ import {openControlRun} from './cm-ai-run.mjs';
12
+ import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
13
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
14
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
15
+ import {USER_MAINTAINED_FILE,readUserMaintainedPaths} from '../runtime/js/cm-ai/user-maintained-paths.mjs';
16
+ import {captureReviewBaseline,compareReviewInventoryToBaseline} from '../runtime/js/cm-ai/review-package.mjs';
17
+
18
+ const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-user-maintained-'));
19
+ const saved={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
20
+ process.env.CM_WORKFLOW_HOME=path.join(isolated,'home');process.env.CM_WORKFLOW_LOG_HOME=path.join(isolated,'logs');
21
+ after(()=>{
22
+ for(const [key,value] of Object.entries(saved)){if(value===undefined)delete process.env[key];else process.env[key]=value;}
23
+ fs.rmSync(isolated,{recursive:true,force:true});
24
+ });
25
+ const events=(onEvent,thread)=>{
26
+ for(const event of [{event:'thread.started',provider_thread:thread},{event:'turn.started',item_type:null},
27
+ {event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},
28
+ {event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
29
+ };
30
+ const declare=(root,value)=>fs.writeFileSync(path.join(root,USER_MAINTAINED_FILE),
31
+ typeof value==='string'?value:JSON.stringify(value));
32
+
33
+ // A completed run of one feature whose QA failed; status() reopens it read-only.
34
+ async function completedRun(initialDeclaration=null){
35
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(isolated,'project-')));
36
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs');fs.mkdirSync(codeProject);
37
+ fs.mkdirSync(path.join(specsDir,'1.value'),{recursive:true});
38
+ for(const name of ['requirements','design'])fs.writeFileSync(path.join(specsDir,'1.value',`${name}.md`),'# Synthetic fixture');
39
+ fs.writeFileSync(path.join(specsDir,'1.value','tasks.md'),'- [ ] T-001: implement\n');
40
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.value'],specFiles:buildManifest(specsDir)}));
41
+ fs.mkdirSync(path.join(codeProject,'Baseline'));
42
+ fs.writeFileSync(path.join(codeProject,'Baseline','verdicts.json'),'{"approved":[]}');
43
+ fs.writeFileSync(path.join(codeProject,'other.md'),'# Other\n');
44
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=0;');
45
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'Synthetic requirements.');
46
+ fs.writeFileSync(path.join(codeProject,'existing.mjs'),'process.exit(0)');
47
+ fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
48
+ if(initialDeclaration)declare(codeProject,initialDeclaration);
49
+ const execution={configuration:{kind:'synthetic-user-maintained'},timeoutMs:2000,excludedContexts:['parent-host'],
50
+ developer:{provider:'codex',requestedModel:'synthetic',contextId:'author',run:createCodexDeveloperRun({requestedModel:'synthetic',worker:async()=>{
51
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=1;');
52
+ return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
53
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};}})},
54
+ reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic',allowed:true,available:true,
55
+ contexts:['review-1','review-2'],run:async(request,{onEvent})=>{
56
+ events(onEvent,`synthetic-review-${request.identity.runId}`);
57
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,
58
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic review'}};}}],
59
+ reviewInvocation:{developerThreadId:'author',excludedThreadIds:['parent-host']},
60
+ check:createHostCheck({cwd:codeProject,commands:[{id:'existing',command:[process.execPath,'existing.mjs']}]}),
61
+ qaLogHome:path.join(root,'logs'),qaDecisionProvider:{timeoutMs:1000,decide:async binding=>({decisionId:`qa-${binding.identity.runId}`,
62
+ identity:binding.identity,packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-11-03T01:00:00Z'})},
63
+ qaExecutor:{mode:'commands',caseCount:1,timeoutMs:1000,run:async binding=>{
64
+ const report=path.join(specsDir,'.reviews',`${binding.testRunId}.md`);fs.writeFileSync(report,'Synthetic QA FAIL');
65
+ return {result:'FAIL',passed:0,failed:1,blocked:0,report};}},
66
+ applicableAgentFiles:[],documentationProvider:{timeoutMs:1000,inspect:async binding=>({
67
+ syncId:binding.syncId,identity:binding.identity,packageDigest:binding.packageDigest,contextDigest:binding.contextDigest,
68
+ status:'completed',reason:'Synthetic documentation unchanged',at:'2026-11-03T02:00:00Z'})}};
69
+ const identity={repositoryId:'fixture',runId:'feature1-T001',taskId:'T-001',attempt:1};
70
+ const definition={version:1,specsDir,codeProject,feature:'1.value',identity,scope:['value.mjs'],requirements:['requirements.md']};
71
+ let run=await openControlRun(definition,'create',execution),before;
72
+ try{
73
+ assert.equal((await run.host.handle({version:1,requestId:'p',operation:'advance',identity})).code,'qa_failed');
74
+ before=await run.host.handle({version:1,requestId:'b',operation:'status',identity});
75
+ }finally{run.close();}
76
+ const status=async()=>{
77
+ const opened=await openControlRun(definition,'resume',execution);
78
+ try{return await opened.host.handle({version:1,requestId:'s',operation:'status',identity});}finally{opened.close();}
79
+ };
80
+ const same=result=>assert.deepEqual([result.state,result.code,result.pendingAction],[before.state,before.code,before.pendingAction],JSON.stringify(result));
81
+ return {codeProject,status,same};
82
+ }
83
+ // Replace the declaration right after the reader closed it, before the tree scan.
84
+ async function swappedDuring(codeProject,status,replacement){
85
+ const declaration=path.join(codeProject,USER_MAINTAINED_FILE),open=fs.openSync,close=fs.closeSync;
86
+ let watched=null;
87
+ fs.openSync=(file,...rest)=>{const fd=open(file,...rest);
88
+ if(file===declaration&&watched===null&&new Error().stack.includes('user-maintained-paths.mjs'))watched=fd;return fd;};
89
+ fs.closeSync=fd=>{close(fd);if(fd===watched){watched=-1;declare(codeProject,replacement);}};
90
+ try{return await status();}finally{fs.openSync=open;fs.closeSync=close;assert.equal(watched,-1);}
91
+ }
92
+
93
+ test('a declared user-maintained file is tolerated on a completed run; nothing else is',async()=>{
94
+ const {codeProject,status,same}=await completedRun();
95
+
96
+ // The user records a verdict by hand: unexplained until it is declared.
97
+ fs.writeFileSync(path.join(codeProject,'Baseline','verdicts.json'),'{"approved":["glass"]}');
98
+ let result=await status();
99
+ assert.equal(result.code,'correction_review_required');assert.equal(result.reason,'未经审查的改动:Baseline/verdicts.json');
100
+ declare(codeProject,{version:1,paths:['Baseline/verdicts.json']});
101
+ same(await status());
102
+
103
+ // Only the declared file: another unreviewed edit is still reported alone.
104
+ fs.appendFileSync(path.join(codeProject,'other.md'),'hand edit\n');
105
+ result=await status();
106
+ assert.equal(result.code,'correction_review_required');assert.equal(result.reason,'未经审查的改动:other.md');
107
+ fs.writeFileSync(path.join(codeProject,'other.md'),'# Other\n');same(await status());
108
+
109
+ // The run's own delivered file can never be declared away.
110
+ declare(codeProject,{version:1,paths:['Baseline/verdicts.json','value.mjs']});
111
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=2;');
112
+ result=await status();
113
+ assert.equal(result.code,'correction_review_required');assert.equal(result.reason,'未经审查的改动:value.mjs');
114
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=1;');
115
+
116
+ // A case variant of the run's own file is never declared away either.
117
+ declare(codeProject,{version:1,paths:['Baseline/verdicts.json','VALUE.mjs']});same(await status());
118
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=3;');
119
+ result=await status();
120
+ assert.equal(result.code,'correction_review_required');assert.equal(result.reason,'未经审查的改动:value.mjs');
121
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=1;');
122
+
123
+ // A declaration replaced after the reader read it and before the tree is compared is refused.
124
+ declare(codeProject,{version:1,paths:['Baseline/verdicts.json']});same(await status());
125
+ result=await swappedDuring(codeProject,status,{version:1,paths:['other.md']});
126
+ assert.equal(result.code,'correction_review_required');assert.match(result.reason,/核对期间声明已变化/);
127
+ declare(codeProject,{version:1,paths:['Baseline/verdicts.json']});same(await status());
128
+
129
+ // A malformed declaration tolerates nothing and says why.
130
+ declare(codeProject,{version:1,paths:['../escape']});
131
+ result=await status();
132
+ assert.equal(result.code,'correction_review_required');assert.match(result.reason,/\.cm-user-maintained\.json/);
133
+ fs.rmSync(path.join(codeProject,USER_MAINTAINED_FILE));
134
+ result=await status();
135
+ assert.equal(result.code,'correction_review_required');assert.equal(result.reason,'未经审查的改动:Baseline/verdicts.json');
136
+ });
137
+
138
+ test('a declaration already in the baseline binds to the same scan, unchanged or replaced',async()=>{
139
+ const {codeProject,status,same}=await completedRun({version:1,paths:['Baseline/verdicts.json']});
140
+ fs.writeFileSync(path.join(codeProject,'Baseline','verdicts.json'),'{"approved":["glass"]}');
141
+ same(await status());
142
+ const result=await swappedDuring(codeProject,status,{version:1,paths:['other.md']});
143
+ assert.equal(result.code,'correction_review_required');assert.match(result.reason,/核对期间声明已变化/);
144
+ });
145
+
146
+ test('an inventory probe reports one path from the same scan, present or not',()=>{
147
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(isolated,'probe-')));
148
+ fs.writeFileSync(path.join(root,'kept.md'),'kept');fs.writeFileSync(path.join(root,'req.md'),'req');
149
+ const baseline=captureReviewBaseline({root,identity:{repositoryId:'unit',runId:'probe-run',taskId:'T-001',attempt:1},
150
+ scope:['kept.md'],requirements:['req.md']});
151
+ assert.deepEqual(compareReviewInventoryToBaseline(root,baseline),[]);
152
+ const [kept]=compareReviewInventoryToBaseline(root,baseline,{probe:'kept.md'});
153
+ assert.equal(kept.probe,true);assert.equal(kept.path,'kept.md');assert.match(kept.sha256,/^[0-9a-f]{64}$/);
154
+ assert.deepEqual(compareReviewInventoryToBaseline(root,baseline,{probe:'missing.md'}),[{path:'missing.md',sha256:null,probe:true}]);
155
+ });
156
+
157
+ test('the declaration is strict: exact relative files, no instructions, config or itself',()=>{
158
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(isolated,'reader-')));
159
+ assert.deepEqual(readUserMaintainedPaths(root),{paths:[],sha256:null});
160
+ declare(root,{version:1,paths:['Baseline/glass-verdicts.json','notes.md']});
161
+ const read=readUserMaintainedPaths(root);
162
+ assert.deepEqual(read.paths,['Baseline/glass-verdicts.json','notes.md']);assert.match(read.sha256,/^[0-9a-f]{64}$/);
163
+ fs.mkdirSync(path.join(root,'folder'));
164
+ for(const value of [
165
+ {version:2,paths:['a.md']},{version:1,paths:[]},{version:1,paths:['a.md'],extra:true},{version:1},
166
+ {version:1,paths:['/abs.md']},{version:1,paths:['a/../b.md']},{version:1,paths:['./a.md']},{version:1,paths:['a//b.md']},
167
+ {version:1,paths:['dir/']},{version:1,paths:['a\\b.md']},{version:1,paths:['a.md','a.md']},{version:1,paths:[7]},
168
+ {version:1,paths:['AGENTS.md']},{version:1,paths:['sub/CLAUDE.md']},{version:1,paths:['.cm-workflow.yml']},
169
+ {version:1,paths:[USER_MAINTAINED_FILE]},{version:1,paths:['.git/config']},
170
+ {version:1,paths:['agents.md']},{version:1,paths:['Sub/Claude.MD']},{version:1,paths:['.CM-Workflow.YML']},
171
+ {version:1,paths:['.CM-USER-MAINTAINED.JSON']},{version:1,paths:['.GIT/config']},{version:1,paths:['.env']},
172
+ {version:1,paths:['a*.md']},{version:1,paths:['a:b.md']},{version:1,paths:['a\nb.md']},
173
+ {version:1,paths:['cafe\u0301.md']},{version:1,paths:['a.md','A.md']},{version:1,paths:['folder']},
174
+ '{"version":1,"version":1,"paths":["a.md"]}','not json',
175
+ ]){
176
+ declare(root,value);
177
+ assert.throws(()=>readUserMaintainedPaths(root),{code:'user_maintained_invalid'},JSON.stringify(value));
178
+ }
179
+ fs.rmSync(path.join(root,USER_MAINTAINED_FILE));
180
+ fs.writeFileSync(path.join(root,'real.json'),JSON.stringify({version:1,paths:['a.md']}));
181
+ fs.symlinkSync('real.json',path.join(root,USER_MAINTAINED_FILE));
182
+ assert.throws(()=>readUserMaintainedPaths(root),{code:'user_maintained_invalid'});
183
+ });
@@ -29,7 +29,7 @@ async function fixture(fn){
29
29
  fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,runtimes:{available:'codex'}}));
30
30
  fs.writeFileSync(path.join(specsDir,feature,'requirements.md'),'# Requirements\n');
31
31
  fs.writeFileSync(path.join(specsDir,feature,'design.md'),'# Design\n');
32
- fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: 实现 a.js\n - 范围: `a.js`, `a.test.js`\n - 测试文件: `a.test.js`\n\n'
32
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: 必验: 实现 a.js\n - 范围: `a.js`, `a.test.js`\n - 测试文件: `a.test.js`\n\n'
33
33
  +'## 验证要求\n\n- T-001: RED 必须先失败;全部放入后检查通过。\n');
34
34
  fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
35
35
  const definition={version:1,codeProject,specsDir,feature,identity,scope:['a.js','a.test.js'],requirements:['requirements.md'],
@@ -40,11 +40,12 @@ async function fixture(fn){
40
40
  const develop=(requirements,test=TEST)=>({async call(kind,payload){
41
41
  assert.equal(kind,'develop');
42
42
  return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
43
- retrospective:{status:'no_new_lesson',candidates:[],reason:null},...(requirements===undefined?{}:{requirements})},
43
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null},...(requirements===undefined?{}:{requirements:typeof requirements==='function'?requirements(payload.request.payload.specification.acceptanceContract):requirements})},
44
44
  edits:[{path:'a.js',beforeSha256:payload.expected['a.js'],content:'new\n'},{path:'a.test.js',beforeSha256:null,content:test}]};
45
45
  }});
46
- const run=async(definition,bridge,protection)=>{
47
- const execution=createConversationExecution(definition,'host',bridge,null,null,null,false,'codex',{protection,controlPolicy:policy});
46
+ const completeReport=contract=>contract.obligations.map(item=>({...item,satisfied:true,evidence:'isolated fixture: a.js export and a.test.js assertions'}));
47
+ const run=async(definition,bridge,protection,selectedPolicy=policy)=>{
48
+ const execution=createConversationExecution(definition,'host',bridge,null,null,null,false,'codex',{protection,controlPolicy:selectedPolicy});
48
49
  const control=await openControlRun(definition,'create',execution);
49
50
  try{return await control.host.handle(request('start'));}finally{control.close();}
50
51
  };
@@ -52,8 +53,7 @@ const handoff=definition=>JSON.parse(fs.readFileSync(path.join(definition.specsD
52
53
 
53
54
  test('auto gate: a failing-first claim the host replay confirms passes, and the handoff carries the host record',
54
55
  {skip:!supported},()=>fixture(async({definition,protection})=>{
55
- const result=await run(definition,develop([{requirement:'T-001: RED 必须先失败',satisfied:true,evidence:'a.test.js 在旧 a.js 下失败',run:'red'},
56
- {requirement:'全部放入后检查通过',satisfied:true,evidence:'unit 检查'}]),protection);
56
+ const result=await run(definition,develop(completeReport),protection);
57
57
  assert.equal(result.state,'awaiting_review',JSON.stringify(result));
58
58
  const entries=handoff(definition).evidence;
59
59
  assert.match(entries.find(entry=>entry.startsWith('cm-requirement-evidence-v1: ')),/RED 必须先失败/);
@@ -69,6 +69,7 @@ test('auto gate: no report from the developer stops before review, with nothing
69
69
  {skip:!supported},()=>fixture(async({definition,protection})=>{
70
70
  const result=await run(definition,develop(undefined),protection);
71
71
  assert.equal(result.state,'blocked');assert.equal(result.code,'verification_precheck_failed');
72
+ assert.match(result.reason,/mandatory acceptance report missing/);
72
73
  assert.equal(fs.existsSync(path.join(definition.specsDir,'.reviews',`${definition.feature.replace(/^\d+\./,'')}-T-001-a1-handoff.json`)),false);
73
74
  }));
74
75
 
@@ -88,8 +89,7 @@ test('auto gate after a stopped attempt: the replay uses the task baseline, not
88
89
  const first=await run(definition,develop(undefined),protection);
89
90
  assert.equal(first.code,'verification_precheck_failed');
90
91
  assert.equal(fs.readFileSync(path.join(definition.codeProject,'a.js'),'utf8'),'new\n','the stopped delivery stays on disk');
91
- const execution=createConversationExecution(definition,'host',develop([{requirement:'T-001: RED 必须先失败',satisfied:true,
92
- evidence:'a.test.js 在旧 a.js 下失败',run:'red'}]),null,null,null,false,'codex',{protection,controlPolicy:policy});
92
+ const execution=createConversationExecution(definition,'host',develop(completeReport),null,null,null,false,'codex',{protection,controlPolicy:policy});
93
93
  const control=await openControlRun(definition,'resume',execution);
94
94
  let result;try{result=await control.host.handle(request('advance'));}finally{control.close();}
95
95
  // The gate passed and the handoff was published; this fixture has no reviewer, so the run stops at review.
@@ -97,3 +97,28 @@ test('auto gate after a stopped attempt: the replay uses the task baseline, not
97
97
  const record=JSON.parse(handoff(definition).evidence.find(entry=>entry.startsWith('cm-host-replay-v1: ')).slice('cm-host-replay-v1: '.length));
98
98
  assert.deepEqual([record.facts.baseline.outcome,record.facts.red.outcome],['failed','failed']);
99
99
  }));
100
+
101
+ for(const verification of ['auto','precheck','disabled'])test(`new contract cannot omit mandatory items through ${verification}`,
102
+ {skip:!supported},()=>fixture(async({definition,protection})=>{
103
+ const developer=develop(completeReport);
104
+ const bridge={async call(kind,payload){
105
+ if(kind==='verification_precheck')return {items:completeReport(payload.acceptanceContract).slice(0,1)};
106
+ const result=await developer.call(kind,payload);
107
+ result.value.requirements=result.value.requirements.slice(0,1);return result;
108
+ }};
109
+ const result=await run(definition,bridge,protection,{...policy,verification});
110
+ assert.equal(result.code,'verification_precheck_failed',JSON.stringify(result));
111
+ assert.match(result.reason,/missing acceptance obligation/);
112
+ assert.doesNotMatch(result.reason,/mandatory acceptance report missing/,'a partial report must identify missing items, not claim the whole report is absent');
113
+ }));
114
+
115
+ test('manual precheck cannot accept a RED claim contradicted by host replay',
116
+ {skip:!supported},()=>fixture(async({definition,protection})=>{
117
+ const developer=develop(completeReport,"process.exit(0);\n");
118
+ const bridge={async call(kind,payload){
119
+ if(kind==='verification_precheck')return {items:completeReport(payload.acceptanceContract)};
120
+ return developer.call(kind,payload);
121
+ }};
122
+ const result=await run(definition,bridge,protection,{...policy,verification:'precheck'});
123
+ assert.equal(result.code,'verification_precheck_failed',JSON.stringify(result));
124
+ }));
@@ -113,5 +113,5 @@ test('the gate receives both the task description and the verification section',
113
113
  assert.match(body[1],/written\(description\)\?\{description\}/);
114
114
  assert.match(body[1],/written\(verification\)\?\{verification\}/);
115
115
  // The gate steps aside only when neither exists.
116
- assert.match(body[1],/if\(!written\(verification\)&&!written\(description\)\)return true;/);
116
+ assert.match(body[1],/if\(!contract&&!written\(verification\)&&!written\(description\)\)return true;/);
117
117
  });