@aibyzero/cm-workflow 0.20.0 → 0.21.1

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 (78) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +36 -0
  3. package/README.md +13 -1
  4. package/VERSION +1 -1
  5. package/docs/installation.md +1 -1
  6. package/docs/js-workflow-control.md +1 -1
  7. package/docs/proposals/spec-amendment-tiers.md +100 -0
  8. package/package.json +1 -1
  9. package/runtime/js/acceptance-language.mjs +32 -0
  10. package/runtime/js/autonomy.mjs +15 -6
  11. package/runtime/js/cm-ai/acceptance-contract.mjs +8 -3
  12. package/runtime/js/cm-ai/checkpoint-package-material.mjs +13 -3
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +35 -2
  14. package/runtime/js/cm-ai/codex-review-adapter.mjs +19 -3
  15. package/runtime/js/cm-ai/drive-core.mjs +9 -2
  16. package/runtime/js/cm-ai/durable-runner-state.mjs +12 -4
  17. package/runtime/js/cm-ai/effect-contract.mjs +8 -1
  18. package/runtime/js/cm-ai/execution-snapshot.mjs +4 -3
  19. package/runtime/js/cm-ai/execution-store-limits.mjs +3 -3
  20. package/runtime/js/cm-ai/execution-store.mjs +7 -4
  21. package/runtime/js/cm-ai/fix-code-association.mjs +27 -6
  22. package/runtime/js/cm-ai/review-package.mjs +20 -6
  23. package/runtime/js/cm-ai/review-presentation.mjs +12 -5
  24. package/runtime/js/cm-ai/reviewed-deliveries.mjs +10 -7
  25. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  26. package/runtime/js/cm-ai/spec-amendment.mjs +535 -0
  27. package/runtime/js/cm-ai/task-commit-codec.mjs +4 -2
  28. package/runtime/js/cm-ai/task-commit.mjs +4 -2
  29. package/runtime/js/cm-ai/task-runner.mjs +26 -9
  30. package/runtime/js/cm-ai/user-maintained-paths.mjs +68 -0
  31. package/runtime/js/cm-prd/change.mjs +35 -4
  32. package/runtime/js/cm-prd/self-check.mjs +36 -6
  33. package/runtime/js/cm-prd/session.mjs +8 -3
  34. package/runtime/js/cm-prd/task-scope-record.mjs +13 -7
  35. package/runtime/js/task-scope.mjs +4 -1
  36. package/runtime/test-contract.md +1 -0
  37. package/scripts/cm-ai-acceptance-contract.test.mjs +10 -0
  38. package/scripts/cm-ai-admission.mjs +8 -2
  39. package/scripts/cm-ai-admission.test.mjs +15 -2
  40. package/scripts/cm-ai-batch-run-fixture.mjs +5 -1
  41. package/scripts/cm-ai-checkpoint-package-material.test.mjs +60 -6
  42. package/scripts/cm-ai-checkpoint-package-owner.test.mjs +1 -0
  43. package/scripts/cm-ai-develop-driver-gaps.test.mjs +1 -0
  44. package/scripts/cm-ai-drive.mjs +18 -11
  45. package/scripts/cm-ai-fix-later-delivery.test.mjs +2 -2
  46. package/scripts/cm-ai-later-delivery-feature.test.mjs +102 -0
  47. package/scripts/cm-ai-review-input-limit.test.mjs +91 -0
  48. package/scripts/cm-ai-user-maintained-paths.test.mjs +183 -0
  49. package/scripts/cm-autonomy-review-r1.test.mjs +49 -0
  50. package/scripts/cm-check-runtime.sh +4 -1
  51. package/scripts/cm-drive-liveness.test.mjs +8 -0
  52. package/scripts/cm-fix-observation-task-id.test.mjs +49 -0
  53. package/scripts/cm-fix-review-storage.test.mjs +14 -4
  54. package/scripts/cm-journal-limit.test.mjs +69 -0
  55. package/scripts/cm-notify.test.mjs +6 -4
  56. package/scripts/cm-prd-completion.test.mjs +37 -0
  57. package/scripts/cm-prd-drive.mjs +1 -1
  58. package/scripts/cm-prd-host.test.mjs +1 -1
  59. package/scripts/cm-prd-self-check-rules.test.mjs +23 -11
  60. package/scripts/cm-prd-self-check.test.mjs +24 -1
  61. package/scripts/cm-prd-summary.test.mjs +6 -0
  62. package/scripts/cm-review-inventory.test.mjs +5 -1
  63. package/scripts/cm-skill-hints.json +1 -1
  64. package/scripts/cm-skill-hints.mjs +66 -3
  65. package/scripts/cm-skill-hints.test.mjs +96 -0
  66. package/scripts/cm-spec-amend.mjs +68 -0
  67. package/scripts/cm-spec-amend.test.mjs +510 -0
  68. package/scripts/cm-specs-status.test.mjs +6 -0
  69. package/scripts/cm-start-check.mjs +82 -2
  70. package/scripts/cm-start-check.test.mjs +64 -1
  71. package/scripts/cm-task-scope.test.mjs +3 -2
  72. package/scripts/test-journal-limit-1mib.mjs +4 -0
  73. package/scripts/validate-public-repo.py +4 -0
  74. package/skills/cm-ai/references/N1-init.md +23 -1
  75. package/skills/cm-ai/references/js-host-qa-recovery.md +3 -2
  76. package/skills/cm-ai/references/js-host-recovery.md +2 -1
  77. package/skills/cm-ai/references/js-host.md +2 -1
  78. package/skills/cm-prd/references/js-change-recovery.md +1 -0
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {packageMaterialEligible,checkpointPackageBudget} from '../runtime/js/cm-ai/checkpoint-package-material.mjs';
2
+ import {packageMaterialEligible,checkpointPackageBudget,INLINE_PACKAGE_LIMIT} from '../runtime/js/cm-ai/checkpoint-package-material.mjs';
3
3
  // cm-ai host 的单步驾驶员。PLAN 路径相对 PLAN 文件;命令仅在 codeProject 内执行。
4
4
  // 请求表来自 host-session.mjs operationNames(传输允许集)、host-conversation-execution.mjs
5
5
  // developer/check/verificationGate、host-workflow-capabilities.mjs QA/文档接线、
@@ -257,9 +257,10 @@ function diskScopeEntry(codeProject,target){
257
257
  sha256:stat.size<=REVIEW_MATERIAL_LIMITS.file?sha256(fs.readFileSync(file)):null};
258
258
  }
259
259
  const kib=bytes=>`${bytes} 字节`;
260
- // Everything the runner would refuse only after the answer is written and the
260
+ // Most of what the runner would refuse only after the answer is written and the
261
261
  // checks have run is refused here instead, with the path and the limit. The
262
- // runner stays the authority; this is the same rule applied earlier.
262
+ // runner stays the authority: the reviewer's input limit, for one, is checked
263
+ // only by the runner, on the exact review prompt.
263
264
  // What the next develop starts from, read the way the runner will read it: the
264
265
  // baseline (the one the host is about to capture for a new run, or the run's own
265
266
  // journaled one), the material the review package snapshot selects from the
@@ -441,14 +442,15 @@ export function preflightDevelopDeliveries({deliveries,answersRoot,codeProject,s
441
442
  +FRAME_ALLOWANCE+CHECK_EVIDENCE_ALLOWANCE*checks.length;
442
443
  const reserve=developCheckpointReserve({examinedPathsBytes:size(reviewPaths(pkg)),receiptsBytes:preview.receiptsBytes,
443
444
  callsBytes:preview.callsBytes+1024,writebackBytes:1024});
444
- const budget=JOURNAL_PAYLOAD_LIMIT-reserve;
445
445
  const enabled=preview.packageMaterialEnabled===true;
446
- const capacity=enabled?checkpointPackageBudget({inlineBytes:bytes,packageBytes,reserve,enabled,
447
- referenced:preview.archivedPackageDigests.includes(pkg.packageDigest)}):{fits:bytes<=budget};
446
+ // Same budget as the runner (checkpointPackageBudget), archive or not.
447
+ const capacity=checkpointPackageBudget({inlineBytes:bytes,packageBytes,reserve,enabled,
448
+ referenced:enabled&&preview.archivedPackageDigests.includes(pkg.packageDigest)});
449
+ const budget=capacity.budget;
448
450
  if(!capacity.fits){
449
451
  const largest=pkg.changes.filter(change=>change.after).map(change=>change.after).sort((a,b)=>b.size-a.size).slice(0,3)
450
452
  .map(file=>`${file.path} ${kib(file.size)}`).join(',');
451
- stop(2,`${label}: 交付后的开发检查点约 ${kib(bytes)}(其中审查包 ${kib(packageBytes)},含 handoff),超过运行存档单条记录上限 ${JOURNAL_PAYLOAD_LIMIT} `
453
+ stop(2,`${label}: 交付后的开发检查点约 ${kib(bytes)}(其中审查包 ${kib(packageBytes)},含 handoff),超过${enabled?`运行存档单条记录上限 ${JOURNAL_PAYLOAD_LIMIT}`:`未归档审查包的内联上限 ${Math.min(JOURNAL_PAYLOAD_LIMIT,INLINE_PACKAGE_LIMIT)}`} `
452
454
  +`减去为有界审查与完成记录预留的 ${reserve}(即 ${budget});最大的改动文件是 ${largest};请缩小这些文件或移出 scope`);
453
455
  }
454
456
  }
@@ -817,11 +819,16 @@ function load(){
817
819
  preview:developPreview({definition,journal:plan.mode==='create'?null:journal,controlPolicy:control?.policy??null,
818
820
  exact:!permissions.includes('--bootstrap-config')})});
819
821
  const unique=[...new Set(asks.filter(kind=>FILES[kind]&&kind!=='develop'))];
822
+ // A rediagnosis is a new conclusion; never reuse the first diagnosis file (same as cm-fix-drive).
823
+ const answerFile=kind=>answerPath(answers??'',operation==='fix_action'&&plan.fixOperation==='rediagnose'&&kind==='fix_diagnose'
824
+ ?'diagnosis-rediagnosis.json':FILES[kind]);
825
+ // Report every missing answer at once: stopping at the first one made each
826
+ // advance reveal a single file (Wue specs8 T-001: qa-assess, then
827
+ // documentation-inspect, one stopped advance each).
828
+ const missingAnswers=unique.filter(kind=>!answers||!fs.existsSync(answerFile(kind)));
829
+ if(missingAnswers.length)stop(2,missingAnswers.map(kind=>`步骤 ${operation} 会反问 ${kind},但答案文件不存在: ${answerFile(kind)}`).join(';'));
820
830
  const answer=preflightAnswers(unique,kind=>{
821
- // A rediagnosis is a new conclusion; never reuse the first diagnosis file (same as cm-fix-drive).
822
- const file=answerPath(answers??'',operation==='fix_action'&&plan.fixOperation==='rediagnose'&&kind==='fix_diagnose'
823
- ?'diagnosis-rediagnosis.json':FILES[kind]);
824
- if(!answers||!fs.existsSync(file))stop(2,`步骤 ${operation} 会反问 ${kind},但答案文件不存在: ${file}`);
831
+ const file=answerFile(kind);
825
832
  const value=readJson(file,kind);validateCmAiAnswer(kind,value,answers);return value;
826
833
  });
827
834
  if(answer.documentation_sync)for(const target of Object.keys(answer.documentation_sync.edits))
@@ -14,7 +14,7 @@ import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
14
14
  import {qaFixIdentity} from '../runtime/js/cm-fix/qa-source.mjs';
15
15
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
16
16
  import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
17
- import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
17
+ import {digest,JOURNAL_PAYLOAD_LIMIT} from '../runtime/js/cm-ai/effect-contract.mjs';
18
18
  import {readProjectInstructionContext} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
19
19
  import {attemptBaseline,readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
20
20
  import {validateAcceptedFix} from '../runtime/js/cm-ai/accepted-fix.mjs';
@@ -371,7 +371,7 @@ test('#18 the accepted-fix size check mirrors the store exactly: a record one by
371
371
  let store=openExecutionStore({...options,create:true});
372
372
  try{
373
373
  const input=(id,n)=>({id,kind:'result',payload:{s:'x'.repeat(n)},expectedRevision:store.snapshot().revision});
374
- const limit=1024*1024-Buffer.byteLength(JSON.stringify({s:''}));
374
+ const limit=JOURNAL_PAYLOAD_LIMIT-Buffer.byteLength(JSON.stringify({s:''}));
375
375
  assert.equal(appendFits(store.snapshot(),input('fits',limit)),true);
376
376
  store.append(input('fits',limit));
377
377
  assert.equal(appendFits(store.snapshot(),input('over',limit+1)),false);
@@ -0,0 +1,102 @@
1
+ // AI潮 specs7 (2026-11-03): every feature numbers its tasks from T-001, so a
2
+ // later reviewed delivery of another feature's T-005 was mistaken for a rerun of
3
+ // this run's own T-005 and dropped. The completed run then reported its shared
4
+ // files as unreviewed (correction_review_required) once QA was attached.
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 {completedReviewedDeliveries,sameDeliveryTask} from '../runtime/js/cm-ai/reviewed-deliveries.mjs';
16
+
17
+ const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-later-delivery-feature-'));
18
+ const saved={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
19
+ process.env.CM_WORKFLOW_HOME=path.join(isolated,'home');process.env.CM_WORKFLOW_LOG_HOME=path.join(isolated,'logs');
20
+ after(()=>{
21
+ for(const [key,value] of Object.entries(saved)){if(value===undefined)delete process.env[key];else process.env[key]=value;}
22
+ fs.rmSync(isolated,{recursive:true,force:true});
23
+ });
24
+ const events=(onEvent,thread)=>{
25
+ for(const event of [{event:'thread.started',provider_thread:thread},{event:'turn.started',item_type:null},
26
+ {event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},
27
+ {event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
28
+ };
29
+
30
+ test('a later reviewed delivery of another feature\'s same-numbered task is adopted; a same-feature rerun is not',async()=>{
31
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(isolated,'project-')));
32
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs');fs.mkdirSync(codeProject);
33
+ for(const feature of ['1.value','2.more']){
34
+ fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
35
+ for(const name of ['requirements','design'])fs.writeFileSync(path.join(specsDir,feature,`${name}.md`),'# Synthetic fixture');
36
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: implement\n');
37
+ }
38
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.value','2.more'],specFiles:buildManifest(specsDir)}));
39
+ fs.writeFileSync(path.join(codeProject,'shared.md'),'# Shared\n');
40
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'Synthetic requirements.');
41
+ fs.writeFileSync(path.join(codeProject,'existing.mjs'),'process.exit(0)');
42
+ fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
43
+ const execution=({write,qa})=>({configuration:{kind:'synthetic-feature-delivery'},timeoutMs:2000,excludedContexts:['parent-host'],
44
+ developer:{provider:'codex',requestedModel:'synthetic',contextId:'author',run:createCodexDeveloperRun({requestedModel:'synthetic',worker:async()=>{
45
+ write();return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
46
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};}})},
47
+ reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic',allowed:true,available:true,
48
+ contexts:['review-1','review-2'],run:async(request,{onEvent})=>{
49
+ events(onEvent,`synthetic-review-${request.identity.runId}`);
50
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,
51
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic review'}};}}],
52
+ reviewInvocation:{developerThreadId:'author',excludedThreadIds:['parent-host']},
53
+ check:createHostCheck({cwd:codeProject,commands:[{id:'existing',command:[process.execPath,'existing.mjs']}]}),
54
+ qaLogHome:path.join(root,'logs'),qaDecisionProvider:{timeoutMs:1000,decide:async binding=>({decisionId:`qa-${binding.identity.runId}`,
55
+ identity:binding.identity,packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-11-03T01:00:00Z'})},
56
+ qaExecutor:{mode:'commands',caseCount:1,timeoutMs:1000,run:async binding=>{
57
+ const result=qa(),report=path.join(specsDir,'.reviews',`${binding.testRunId}.md`);
58
+ fs.writeFileSync(report,`Synthetic QA ${result}`);
59
+ return {result,passed:result==='PASS'?1:0,failed:result==='FAIL'?1:0,blocked:0,report};}},
60
+ applicableAgentFiles:[],documentationProvider:{timeoutMs:1000,inspect:async binding=>({
61
+ syncId:binding.syncId,identity:binding.identity,packageDigest:binding.packageDigest,contextDigest:binding.contextDigest,
62
+ status:'completed',reason:'Synthetic documentation unchanged',at:'2026-11-03T02:00:00Z'})}});
63
+ const identity={repositoryId:'fixture',runId:'feature1-T001',taskId:'T-001',attempt:1};
64
+ const definition={version:1,specsDir,codeProject,feature:'1.value',identity,scope:['shared.md'],requirements:['requirements.md']};
65
+ const parentExecution=execution({write:()=>fs.writeFileSync(path.join(codeProject,'shared.md'),'# Shared\nfeature 1\n'),qa:()=>'FAIL'});
66
+ let run=await openControlRun(definition,'create',parentExecution);
67
+ let before;
68
+ try{
69
+ assert.equal((await run.host.handle({version:1,requestId:'p',operation:'advance',identity})).code,'qa_failed');
70
+ before=await run.host.handle({version:1,requestId:'b',operation:'status',identity});
71
+ }finally{run.close();}
72
+ // Feature 2's own T-001 is reviewed later and appends to the same shared file.
73
+ const laterIdentity={repositoryId:'fixture',runId:'feature2-T001',taskId:'T-001',attempt:1};
74
+ const later=await openControlRun({version:1,specsDir,codeProject,feature:'2.more',identity:laterIdentity,
75
+ scope:['shared.md'],requirements:['requirements.md']},'create',
76
+ execution({write:()=>fs.appendFileSync(path.join(codeProject,'shared.md'),'feature 2\n'),qa:()=>'PASS'}));
77
+ try{
78
+ const done=await later.host.handle({version:1,requestId:'l',operation:'advance',identity:laterIdentity});
79
+ assert.equal(done.code,'project_qa_not_passed',JSON.stringify(done));
80
+ }finally{later.close();}
81
+
82
+ // Discovery keys a task by its feature tasks.md and task id. Unknown stays conservative.
83
+ const found=tasksPath=>completedReviewedDeliveries({specsRoot:specsDir,root:codeProject,identity,tasksPath}).map(item=>item.runId);
84
+ assert.deepEqual(found(path.join(specsDir,'1.value','tasks.md')),['feature2-T001']);
85
+ assert.deepEqual(found(path.join(specsDir,'2.more','tasks.md')),[],'a rerun of the same feature and task is never adopted');
86
+ assert.deepEqual(found(null),[],'without a feature the historical task-id exclusion holds');
87
+
88
+ run=await openControlRun(definition,'resume',parentExecution);
89
+ try{
90
+ const status=await run.host.handle({version:1,requestId:'s',operation:'status',identity});
91
+ assert.notEqual(status.code,'correction_review_required',JSON.stringify(status));
92
+ assert.deepEqual([status.state,status.code,status.pendingAction],[before.state,before.code,before.pendingAction]);
93
+ }finally{run.close();}
94
+ });
95
+
96
+ test('sameDeliveryTask compares tasks.md only when both sides record one',()=>{
97
+ const a='/specs/1.a/tasks.md',b='/specs/2.b/tasks.md';
98
+ assert.equal(sameDeliveryTask({taskId:'T-005',tasksPath:a},{taskId:'T-005',tasksPath:b}),false);
99
+ assert.equal(sameDeliveryTask({taskId:'T-005',tasksPath:a},{taskId:'T-005',tasksPath:a}),true);
100
+ assert.equal(sameDeliveryTask({taskId:'T-005',tasksPath:null},{taskId:'T-005',tasksPath:b}),true);
101
+ assert.equal(sameDeliveryTask({taskId:'T-005',tasksPath:a},{taskId:'T-006',tasksPath:a}),false);
102
+ });
@@ -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
+ }));
@@ -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
+ });
@@ -42,6 +42,55 @@ test('M7 version metadata cannot override the acceptance contract of an older ta
42
42
  assert.deepEqual(contract(proposal.files),contract(before.files));
43
43
  });
44
44
 
45
+ // Codex review (spec amendment tiers): a full-width task id cannot hide a version note
46
+ // from the standing authorization; tiered amendment reads it the same way.
47
+ for(const id of ['T-002','T-002'])test(`M7 version metadata with a full-width id ${id} still needs explicit confirmation`,()=>{
48
+ const {before,proposal}=fixture();
49
+ proposal.files[taskFile]=tasks.replace('| 2026-10-01 | v1 | 初始任务 |',`| 2026-10-01 | v1 | 初始任务 |\n| 2026-11-01 | v2 | ${id} 验收改为只测成功路径 |`);
50
+ assert.match(standingProposalProblem(before,proposal),/T-002.*需明确确认/);
51
+ });
52
+
53
+ // Codex review r3: without a named task, a version note about tests or acceptance still
54
+ // stops the standing authorization unless it only states that nothing changed.
55
+ for(const [note,stops] of [['验收改为只测成功路径',true],['T-002 跳过错误密码测试',true],['Omit negative scenarios; HTTP 200 is sufficient',true],
56
+ ['范围与验收不变,但失败场景免跑',true],['范围与验收不变',false],['expanded scope',false]])
57
+ test(`M7 standing authorization on version note: ${note}`,()=>{
58
+ const {before,proposal}=fixture();
59
+ proposal.files[taskFile]=tasks.replace('| 2026-10-01 | v1 | 初始任务 |',`| 2026-10-01 | v1 | 初始任务 |\n| 2026-11-01 | v2 | ${note} |`);
60
+ const problem=standingProposalProblem(before,proposal);
61
+ if(stops)assert.match(problem??'',/需明确确认/);else assert.equal(problem,null);
62
+ });
63
+
64
+ // Codex review r4: a design without protected wording cannot skip the version-note check.
65
+ for(const [note,stops] of [['跳过错误密码测试',true],['范围与验收不变',false]])
66
+ test(`M7 standing authorization on a design version note: ${note}`,()=>{
67
+ const {before,proposal}=fixture();
68
+ proposal.files[designFile]+=`\n## 设计版本\n| 日期 | 版本 | 说明 |\n| --- | --- | --- |\n| 2026-11-01 | v2 | ${note} |\n`;
69
+ const problem=standingProposalProblem(before,proposal);
70
+ if(stops)assert.match(problem??'',/需明确确认/);else assert.equal(problem,null);
71
+ });
72
+
73
+ // Codex review r5: an approved design note about tests does not turn a plain design edit into a stop.
74
+ test('M7 approved design version notes do not block an ordinary design edit',()=>{
75
+ const {before,proposal}=fixture();
76
+ const versions='\n## 设计版本\n| 日期 | 版本 | 说明 |\n| --- | --- | --- |\n| 2026-10-01 | v1 | 跳过错误密码测试 |\n';
77
+ before.files[designFile]+=versions;
78
+ proposal.files[designFile]=before.files[designFile].replace('登录表单调用 API。','登录表单调用 API,失败时显示提示。');
79
+ assert.equal(standingProposalProblem(before,proposal),null);
80
+ });
81
+
82
+ // Codex review r6: a duplicated approved note, or one copied over another, counts as new.
83
+ for(const [label,edit] of [['duplicated',versions=>versions+'| 2026-10-01 | v1 | 跳过错误密码测试 |\n'],
84
+ ['copied over another',versions=>versions.replace('| 2026-10-02 | v1.1 | 补记沟通 |','| 2026-10-01 | v1 | 跳过错误密码测试 |')]])
85
+ test(`M7 an approved design note that is ${label} still stops`,()=>{
86
+ const {before,proposal}=fixture();
87
+ const versions='\n## 设计版本\n| 日期 | 版本 | 说明 |\n| --- | --- | --- |\n| 2026-10-01 | v1 | 跳过错误密码测试 |\n| 2026-10-02 | v1.1 | 补记沟通 |\n';
88
+ before.files[designFile]+=versions;
89
+ proposal.files[designFile]=before.files[designFile].replace(versions,edit(versions));
90
+ assert.notEqual(proposal.files[designFile],before.files[designFile]);
91
+ assert.match(standingProposalProblem(before,proposal)??'',/需明确确认/);
92
+ });
93
+
45
94
  test('M8 additive design detail preserves standing approval without changing earlier acceptance',()=>{
46
95
  const {before,proposal}=fixture();proposal.files[designFile]+='\n记住我状态写入 storage.js。\n';
47
96
  assert.equal(standingProposalProblem(before,proposal),null);
@@ -283,7 +283,7 @@ for module in \
283
283
  cm-ai-run-finalizer.mjs codex-config.mjs codex-review-adapter.mjs contracts.mjs \
284
284
  durable-runner-state.mjs effect-contract.mjs execution-store.mjs gate-bridge.mjs \
285
285
  host.mjs host-session.mjs diagnostic-reason.mjs index.mjs provider-review-observation.mjs review-package.mjs \
286
- review-result.schema.json review-runner.mjs task-commit-codec.mjs task-commit.mjs \
286
+ review-result.schema.json review-runner.mjs spec-amendment.mjs task-commit-codec.mjs task-commit.mjs \
287
287
  task-owner.mjs task-runner.mjs worker-codex.mjs operator-guidance.mjs completion-summary.mjs delivery-evidence.mjs; do
288
288
  require_file "runtime/js/cm-ai/$module"
289
289
  done
@@ -324,6 +324,7 @@ require_file "runtime/js/cm-security/scan.mjs"
324
324
  require_file "scripts/cm-notify.mjs"
325
325
  require_file "scripts/cm-autonomy.mjs"
326
326
  require_file "runtime/js/autonomy.mjs"
327
+ require_file "runtime/js/acceptance-language.mjs"
327
328
  require_file "runtime/js/notify-send.mjs"
328
329
  require_file "scripts/cm-check-update.mjs"
329
330
  require_file "scripts/cm-check-update.test.mjs"
@@ -332,6 +333,8 @@ require_file "scripts/cm-ai-admission.mjs"
332
333
  require_file "scripts/cm-ai-run.mjs"
333
334
  require_file "scripts/cm-ai-run.test.mjs"
334
335
  require_file "scripts/cm-ai-admission.test.mjs"
336
+ require_file "scripts/cm-spec-amend.mjs"
337
+ require_file "scripts/cm-spec-amend.test.mjs"
335
338
  require_file "scripts/cm-log-event.mjs"
336
339
  require_file "scripts/cm-log-event.test.mjs"
337
340
  require_file "scripts/cm-log-event.py"
@@ -87,3 +87,11 @@ test('R1 G11 malformed optional completion display does not change the returned
87
87
  assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.state,'fixture_completed');
88
88
  assert.match(out.stderr,/完成摘要显示失败/);
89
89
  });
90
+
91
+ // Codex review: a create captures its baseline before host_ready, and the Git ignore
92
+ // query alone may take GIT_IGNORE_TIMEOUT_MS; the startup budget must not kill it first.
93
+ test('default startup budget outlasts the Git ignore query of the baseline capture',async()=>{
94
+ const {DRIVE_LIVENESS_DEFAULTS}=await import('../runtime/js/cm-ai/drive-core.mjs');
95
+ const {GIT_IGNORE_TIMEOUT_MS}=await import('../runtime/js/cm-ai/review-package.mjs');
96
+ assert(DRIVE_LIVENESS_DEFAULTS.startupMs>GIT_IGNORE_TIMEOUT_MS);
97
+ });
@@ -53,6 +53,55 @@ test(`existing observation identity closes without reproduction replay or comple
53
53
  }finally{owner.close();fs.rmSync(root,{recursive:true,force:true});}
54
54
  });
55
55
 
56
+ // A recorded T-OBS observation keeps its identity and archive across new evidence:
57
+ // resume reads the obs.<slug> archive, the continued dossier appends to it, and a
58
+ // second observation exit is recorded without completion (review follow-up).
59
+ test('existing observation identity resumes on new evidence and exits again without completion',async()=>{
60
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-obs-resume-')));
61
+ const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
62
+ const identity={repositoryId:'fixture',runId:'same-run',taskId:'T-OBS-original-identity',attempt:1};
63
+ const configuration={hostContextId:'fixture-host',defect:'Busy; root unknown',reproduction:{cwd,
64
+ command:[process.execPath,'-e',"require('node:fs').appendFileSync('visits','1');process.exit(0)"],
65
+ expectedFailure:{exitCode:1,outputIncludes:'BUSY'},timeoutMs:2000}};
66
+ const options={specsRoot,identity,configuration,create:true};
67
+ let owner=openFixExecution(options,{prepare:async()=>learning});
68
+ try{
69
+ startFixRun({specsRoot,identity,configuration});
70
+ assert.equal((await owner.advance({authorized:true})).stage,'observation');
71
+ const first=owner.finish({authorized:true});
72
+ assert.equal(first.observationRunEnded,true);assert.equal(first.completionEligible,false);
73
+ assert.match(path.basename(first.dossier.path),/^\d{8}-obs\.original-identity\.md$/);
74
+ const archived=fs.readFileSync(first.dossier.path);
75
+ assert.equal(fs.readFileSync(path.join(cwd,'visits'),'utf8'),'1');
76
+ const exitEvent=fs.readFileSync(path.join(specsRoot,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse).find(row=>row.event==='run_done');
77
+ fs.writeFileSync(path.join(specsRoot,'failure.txt'),'BUSY: new observed failure, synthetic fixture');
78
+ owner=openFixExecution({...options,create:false});
79
+ const prepared=owner.resume({authorized:true,evidenceFiles:['failure.txt']});
80
+ assert.equal(prepared.stage,'observation_resume_prepared');assert.deepEqual(prepared.identity,identity);
81
+ assert.equal(prepared.observationResume.eventId,exitEvent.event_id);
82
+ assert.equal(prepared.observationResume.dossier.sha256,exitEvent.dossier_sha256);
83
+ assert.equal(path.posix.basename(prepared.observationResume.dossier.path),path.basename(first.dossier.path));
84
+ assert.equal(fs.readFileSync(path.join(cwd,'visits'),'utf8'),'1');
85
+ owner.close();owner=openFixExecution({...options,create:false},{prepare:async()=>learning});
86
+ assert.equal((await owner.advance({authorized:true})).stage,'observation_not_reproduced');
87
+ const draft=owner.publishDossier(),continued=fs.readFileSync(draft.dossier.path);
88
+ assert.equal(draft.dossier.path,first.dossier.path);
89
+ assert.deepEqual(continued.subarray(0,archived.length),archived);
90
+ assert.match(continued.toString(),/恢复观测(仍未完成)/);
91
+ const again=owner.finish({authorized:true});
92
+ assert.equal(again.observationRunEnded,true);assert.equal(again.completionEligible,false);assert.deepEqual(again.identity,identity);
93
+ const rows=fs.readFileSync(path.join(specsRoot,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
94
+ const exits=rows.filter(row=>row.event==='run_done');
95
+ assert.equal(exits.length,2);assert.equal(exits[1].observation_exit_event_id,exitEvent.event_id);
96
+ assert.equal(exits[1].dossier_sha256,draft.dossier.sha256);
97
+ assert.equal(exits[1].phase,'observation');assert.equal(exits[1].result,'observing');
98
+ // Resume re-runs the reproduction exactly once; neither exit replays it.
99
+ assert.equal(fs.readFileSync(path.join(cwd,'visits'),'utf8'),'11');
100
+ assert(!rows.some(row=>row.event==='task_done'));assert(!fs.existsSync(path.join(specsRoot,'METRICS.md')));
101
+ assert.deepEqual(fs.readdirSync(path.dirname(first.dossier.path)).filter(name=>name.endsWith('.md')),[path.basename(first.dossier.path)]);
102
+ }finally{owner.close();fs.rmSync(root,{recursive:true,force:true});}
103
+ });
104
+
56
105
  for(const taskId of ['T-OBS-../escape','T-OBS-UPPER','T-OTHER-safe','T-OBS-safe/escape','T-OBS-a--b','T-OBS-','T-OBS-foo.md','T-OBS-café','T-OBS-foo\\escape'])
57
106
  test(`observation archive rejects malformed or unsupported id ${taskId}`,()=>{
58
107
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-obs-invalid-')));