@aibyzero/cm-workflow 0.18.0 → 0.20.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 (90) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +26 -0
  4. package/README.md +14 -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/package.json +1 -1
  10. package/runtime/js/autonomy.mjs +308 -0
  11. package/runtime/js/check-coverage.mjs +130 -0
  12. package/runtime/js/cm-ai/acceptance-contract.mjs +252 -0
  13. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +53 -12
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
  16. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
  17. package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
  18. package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
  19. package/runtime/js/cm-ai/completion-summary.mjs +187 -0
  20. package/runtime/js/cm-ai/control-policy.mjs +3 -1
  21. package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
  22. package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
  23. package/runtime/js/cm-ai/drive-core.mjs +8 -3
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +2 -2
  25. package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
  26. package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
  27. package/runtime/js/cm-ai/host-progress.mjs +2 -1
  28. package/runtime/js/cm-ai/log-rows.mjs +3 -2
  29. package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
  30. package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
  31. package/runtime/js/cm-ai/review-package.mjs +2 -2
  32. package/runtime/js/cm-ai/specification-material.mjs +57 -12
  33. package/runtime/js/cm-ai/task-runner.mjs +38 -13
  34. package/runtime/js/cm-ai/verification-auto.mjs +6 -4
  35. package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
  36. package/runtime/js/cm-prd/change.mjs +17 -1
  37. package/runtime/js/cm-prd/summary.mjs +5 -0
  38. package/runtime/js/node-test-selection.mjs +38 -0
  39. package/runtime/js/notify.mjs +17 -8
  40. package/runtime/js/run-analysis.mjs +153 -0
  41. package/runtime/js/session-boundary.mjs +17 -5
  42. package/runtime/js/session-handoff.mjs +5 -2
  43. package/runtime/js/specs-status.mjs +4 -3
  44. package/scripts/cm-acceptance-preview.mjs +26 -0
  45. package/scripts/cm-acceptance-preview.test.mjs +156 -0
  46. package/scripts/cm-ai-acceptance-contract.test.mjs +185 -0
  47. package/scripts/cm-ai-admission.mjs +10 -2
  48. package/scripts/cm-ai-admission.test.mjs +151 -1
  49. package/scripts/cm-ai-blockage.test.mjs +120 -0
  50. package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
  51. package/scripts/cm-ai-completion-summary.test.mjs +154 -0
  52. package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
  53. package/scripts/cm-ai-progress.test.mjs +7 -0
  54. package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
  55. package/scripts/cm-ai-run.test.mjs +23 -1
  56. package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
  57. package/scripts/cm-ai-verification-auto.test.mjs +33 -8
  58. package/scripts/cm-ai-verification-gate.test.mjs +1 -1
  59. package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
  60. package/scripts/cm-autonomy-review-r1.test.mjs +93 -0
  61. package/scripts/cm-autonomy.mjs +96 -0
  62. package/scripts/cm-autonomy.test.mjs +163 -0
  63. package/scripts/cm-check-runtime.sh +3 -1
  64. package/scripts/cm-delivery-evidence.mjs +59 -0
  65. package/scripts/cm-delivery-evidence.test.mjs +177 -0
  66. package/scripts/cm-drive-liveness.test.mjs +6 -0
  67. package/scripts/cm-driver-light-import.test.mjs +32 -0
  68. package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
  69. package/scripts/cm-node-test-selection.test.mjs +108 -0
  70. package/scripts/cm-notify-read-drift.test.mjs +6 -3
  71. package/scripts/cm-notify.test.mjs +6 -0
  72. package/scripts/cm-prd-completion.test.mjs +12 -0
  73. package/scripts/cm-prd-host.mjs +3 -1
  74. package/scripts/cm-prd-host.test.mjs +18 -1
  75. package/scripts/cm-prd-summary.test.mjs +19 -4
  76. package/scripts/cm-review-inventory.test.mjs +21 -6
  77. package/scripts/cm-run-analysis.mjs +21 -0
  78. package/scripts/cm-run-analysis.test.mjs +120 -0
  79. package/scripts/cm-start-check.mjs +128 -6
  80. package/scripts/cm-start-check.test.mjs +163 -3
  81. package/scripts/cm-usage-report.py +8 -3
  82. package/scripts/cm019-r1-contract.test.mjs +137 -0
  83. package/scripts/cm019-review-gates.test.mjs +97 -0
  84. package/scripts/validate-public-repo.py +3 -0
  85. package/skills/cm-ai/references/N3-execute-task.md +1 -1
  86. package/skills/cm-ai/references/js-host.md +31 -1
  87. package/skills/cm-prd/SKILL.md +3 -2
  88. package/skills/cm-prd/references/change-mode.md +3 -2
  89. package/skills/cm-prd/references/js-change-recovery.md +14 -0
  90. package/skills/cm-prd/references/js-host.md +1 -0
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env node
2
+ // Standing "run to the end" authorization (runtime/js/autonomy.mjs).
3
+ // show (default) read-only
4
+ // on --response TEXT record the person's own words; nothing else grants it
5
+ // off keep the record as autonomy.off.json
6
+ // notify --kind fatal|finished --project PATH --reason TEXT [--session NAME]
7
+ // page at once (never rate limited): a fatal stop, or everything finished
8
+ // check-proposal --specs-dir PATH --proposal FILE
9
+ // before any decision: may the standing authorization approve it? (exit 1: no)
10
+ // reopen --project PATH --task N.feature/T-xxx
11
+ // take one automatic reopen of the task (exit 1 at the limit: a fatal stop)
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import {readAutonomy,writeAutonomy,clearAutonomy,autonomyHome,takeReopen,readReopens,standingProposalProblem,AUTO_REOPEN_LIMIT} from '../runtime/js/autonomy.mjs';
15
+ import {notify} from '../runtime/js/notify.mjs';
16
+ import {createHash} from 'node:crypto';
17
+
18
+ const usage='usage: cm-autonomy.mjs [show] | on --response TEXT | off | notify --kind fatal|finished --project PATH --reason TEXT [--session NAME]'
19
+ +' | check-proposal --specs-dir PATH --proposal FILE | reopen --project PATH --task N.feature/T-xxx';
20
+
21
+ function parse(argv){
22
+ const [command='show',...rest]=argv,options={};
23
+ for(let index=0;index<rest.length;index++){
24
+ const key={'--response':'response','--kind':'kind','--project':'project','--reason':'reason','--session':'session',
25
+ '--specs-dir':'specsDir','--proposal':'proposal','--task':'task'}[rest[index]];
26
+ if(!key||index+1>=rest.length||Object.hasOwn(options,key))throw new Error('invalid arguments');
27
+ options[key]=rest[++index];
28
+ }
29
+ const allowed={show:[],off:[],on:['response'],notify:['kind','project','reason','session'],
30
+ 'check-proposal':['specsDir','proposal'],reopen:['project','task']}[command];
31
+ if(!allowed||Object.keys(options).some(key=>!allowed.includes(key)))throw new Error('invalid arguments');
32
+ if(command==='on'&&!options.response?.trim())throw new Error('on needs --response with the person\'s own words');
33
+ if(command==='notify'&&(!['fatal','finished'].includes(options.kind)||!options.project||!options.reason?.trim()))
34
+ throw new Error('notify needs --kind fatal|finished, --project and --reason');
35
+ if(command==='check-proposal'&&(!options.specsDir||!options.proposal))throw new Error('check-proposal needs --specs-dir and --proposal');
36
+ if(command==='reopen'&&(!options.project||!options.task))throw new Error('reopen needs --project and --task');
37
+ return {command,...options};
38
+ }
39
+
40
+ const readReopensSafe=env=>{try{return readReopens(env);}catch{return {};}};
41
+
42
+ export function main(argv=process.argv.slice(2),{env=process.env,stdout=process.stdout,stderr=process.stderr}={}){
43
+ let input;
44
+ try{input=parse(argv);}catch(error){stderr.write(`${usage}\nERROR: ${error.message}\n`);return 2;}
45
+ if(input.command==='on'){
46
+ const value=writeAutonomy(input.response,{env});
47
+ stdout.write(`常设授权已开启:一路执行到底,只在致命问题时停下并立即提醒。\n用户原话:${value.response}\n时间:${value.at}\n`);
48
+ return 0;
49
+ }
50
+ if(input.command==='off'){
51
+ stdout.write(clearAutonomy({env})?'常设授权已关闭(记录改名为 autonomy.off.json 保留)。\n':'常设授权本来就没开。\n');
52
+ return 0;
53
+ }
54
+ if(input.command==='notify'){
55
+ const fatal=input.kind==='fatal',project=path.resolve(input.project),reason=input.reason.trim();
56
+ const key=`autonomy|${input.kind}|${project}|${createHash('sha256').update(reason).digest('hex').slice(0,16)}`;
57
+ const result=notify({key,event:fatal?'stuck':'done',workflow:'cm-ai',project,session:input.session,
58
+ code:fatal?'autonomy_fatal_stop':'autonomy_finished',nextAction:reason,
59
+ action:fatal?`致命问题,已停下:${reason}`:`已全部完成:${reason}`},{env,urgent:true});
60
+ // Handed to the channel is not delivered: the channel's own failures go to notify.log.
61
+ if(result.sent){stdout.write('已交给提醒渠道发送(是否送达看手机;发送失败记在 notify.log)。\n');return 0;}
62
+ if(result.reason==='duplicate'){stdout.write('6 小时内已发过同一条提醒,这次不重复发。\n');return 0;}
63
+ stdout.write(`没有发出提醒(${result.reason}):请直接在会话里告诉用户。\n`);return 1;
64
+ }
65
+ if(input.command==='check-proposal'){
66
+ let problem;
67
+ try{
68
+ const raw=JSON.parse(fs.readFileSync(input.proposal,'utf8')),proposal=raw?.result?.proposal??raw?.proposal??raw;
69
+ const specs=path.resolve(input.specsDir),directories=fs.readdirSync(specs).filter(dir=>/^\d+\./.test(dir)).sort(),files={};
70
+ for(const dir of directories)for(const name of ['requirements.md','design.md','tasks.md','test-cases.json']){
71
+ const file=path.join(specs,dir,name);if(fs.existsSync(file))files[`${dir}/${name}`]=fs.readFileSync(file,'utf8');
72
+ }
73
+ const statusFile=path.join(specs,'.cm-specs-status');
74
+ problem=standingProposalProblem({directories,files,
75
+ ...(fs.existsSync(statusFile)?{status:fs.readFileSync(statusFile,'utf8')}:{})},proposal);
76
+ }catch{problem='读不到提案或规格目录';}
77
+ stdout.write(problem?`不能自行批准:${problem}。这是致命停车:不要发送 decision,先提醒用户。\n`:'可以按常设授权自行批准。\n');
78
+ return problem?1:0;
79
+ }
80
+ if(input.command==='reopen'){
81
+ if(!readAutonomy(env).on){stdout.write('常设授权没开:重开要用户本人同意。\n');return 1;}
82
+ let taken;
83
+ try{taken=takeReopen(input.project,input.task,{env});}catch(error){stderr.write(`ERROR: ${error.message}\n`);return 2;}
84
+ stdout.write(taken.refused?`${input.task} 已自动重开 ${taken.count} 次(上限 ${AUTO_REOPEN_LIMIT}):这是致命停车,先提醒用户。\n`
85
+ :`可以自动重开:这是 ${input.task} 第 ${taken.count} 次自动重开(上限 ${AUTO_REOPEN_LIMIT})。--supersede-reason 以「常设授权自动重开第 ${taken.count} 次:」开头。\n`);
86
+ return taken.refused?1:0;
87
+ }
88
+ const state=readAutonomy(env);
89
+ stdout.write(state.on
90
+ ?`常设授权:开启(${autonomyHome(env)}/autonomy.json)\n用户原话:${state.value.response}\n时间:${state.value.at}\n同一任务自动重开上限:${AUTO_REOPEN_LIMIT} 次\n`
91
+ +Object.entries(readReopensSafe(env)).map(([key,count])=>`已自动重开:${key.split('|').pop()} ${count} 次(${key.split('|')[0]})\n`).join('')
92
+ :`常设授权:关闭(${state.reason==='missing'?'未开启':'文件无效,按关闭处理'})\n`);
93
+ return 0;
94
+ }
95
+
96
+ if(import.meta.main)process.exitCode=main();
@@ -0,0 +1,163 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {main} from './cm-autonomy.mjs';
7
+ import {spawn} from 'node:child_process';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {readAutonomy,standingProposalProblem,takeReopen,readReopens} from '../runtime/js/autonomy.mjs';
10
+ import {driveNotice,notifyLater,sendPendingNotice} from '../runtime/js/notify.mjs';
11
+
12
+ function home(t){
13
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-autonomy-')));
14
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
15
+ const env={...process.env,CM_WORKFLOW_HOME:dir};delete env.CM_NOTIFY_OFF;delete env.CLAUDE_CODE_SESSION_ID;
16
+ const out=[],err=[];
17
+ const run=(...argv)=>({code:main(argv,{env,stdout:{write:s=>out.push(s)},stderr:{write:s=>err.push(s)}}),out:out.splice(0).join(''),err:err.splice(0).join('')});
18
+ return {dir,env,run};
19
+ }
20
+
21
+ test('autonomy is on only from recorded words, and off keeps the record',t=>{
22
+ const h=home(t);
23
+ assert.match(h.run().out,/关闭(未开启)/);
24
+ assert.equal(h.run('on').code,2);
25
+ assert.equal(h.run('on','--response',' ').code,2);
26
+ assert.equal(h.run('on','--response','就按这份','--kind','fatal').code,2);
27
+ assert.equal(h.run('on','--response','就按这份').code,0);
28
+ assert.deepEqual({on:readAutonomy(h.env).on,response:readAutonomy(h.env).value.response},{on:true,response:'就按这份'});
29
+ assert.equal(fs.statSync(path.join(h.dir,'autonomy.json')).mode&0o777,0o600);
30
+ assert.match(h.run('show').out,/开启[\s\S]*就按这份[\s\S]*上限:2 次/);
31
+ assert.equal(h.run('off').code,0);
32
+ assert.equal(readAutonomy(h.env).on,false);
33
+ assert.ok(fs.existsSync(path.join(h.dir,'autonomy.off.json')));
34
+ // A file that is not exactly the recorded shape is off, never on.
35
+ for(const value of [{version:1,mode:'until_fatal',response:'',at:'2026-11-01T00:00:00.000Z'},{version:2,mode:'until_fatal',response:'x',at:'2026-11-01T00:00:00.000Z'},'not json']){
36
+ fs.writeFileSync(path.join(h.dir,'autonomy.json'),typeof value==='string'?value:JSON.stringify(value));
37
+ assert.deepEqual(readAutonomy(h.env),{on:false,reason:'invalid'});
38
+ }
39
+ });
40
+
41
+ test('a fatal stop pages at once with the reason as the action',async t=>{
42
+ const h=home(t),sent=path.join(h.dir,'sent.jsonl'),script=path.join(h.dir,'fake.mjs');
43
+ fs.writeFileSync(script,`import fs from 'node:fs';let i='';process.stdin.on('data',c=>i+=c);process.stdin.on('end',()=>{fs.appendFileSync(${JSON.stringify(sent)},i);});`);
44
+ fs.writeFileSync(path.join(h.dir,'notify.json'),JSON.stringify({version:1,command:[process.execPath,script]}));
45
+ assert.equal(h.run('notify','--kind','fatal','--project','/w/app').code,2);
46
+ const result=h.run('notify','--kind','fatal','--project','/w/app','--reason','T-004 自动重开 2 次仍未通过');
47
+ assert.equal(result.code,0);assert.match(result.out,/已交给提醒渠道发送/);
48
+ for(let i=0;i<100&&!fs.existsSync(sent);i++)await new Promise(resolve=>setTimeout(resolve,50));
49
+ const payload=JSON.parse(fs.readFileSync(sent,'utf8'));
50
+ assert.equal(payload.event,'stuck');assert.equal(payload.code,'autonomy_fatal_stop');
51
+ assert.match(payload.action,/致命问题,已停下:T-004 自动重开 2 次仍未通过/);
52
+ // The window limit never swallows a fatal stop.
53
+ const state=path.join(h.dir,'notify-state.json'),now=Date.now();
54
+ fs.writeFileSync(state,JSON.stringify({version:2,keys:{},attention:{},sends:[now-3000,now-2000,now-1000],suppressed:0}));
55
+ assert.equal(h.run('notify','--kind','fatal','--project','/w/app','--reason','额度用完').code,0);
56
+ assert.equal(h.run('notify','--kind','fatal','--project','/w/app','--reason','额度用完').code,0,'same reason within 6 h is not resent');
57
+ fs.rmSync(path.join(h.dir,'notify.json'));
58
+ const off=h.run('notify','--kind','fatal','--project','/w/app','--reason','设备要本人解锁');
59
+ assert.equal(off.code,1);assert.match(off.out,/没有发出提醒/);
60
+ });
61
+
62
+ test('under autonomy a driver stop waits and a finished unit is not paged',t=>{
63
+ const h=home(t);
64
+ const notice=row=>driveNotice({host:'/x/scripts/cm-ai-host.mjs',cwd:'/w/app',args:['serve'],operation:'advance',row,env:h.env});
65
+ const result=over=>({requestId:'drive',result:{version:1,workflow:'cm-ai',operation:'advance',
66
+ identity:{runId:'r1',taskId:'T-001',attempt:1},packageDigest:'d',...over}});
67
+ const limit=result({outcome:'advanced',state:'blocked',code:'review_limit',pendingAction:'none'});
68
+ const done=result({outcome:'finalized',state:'run_done',code:'run_done',pendingAction:'none'});
69
+ assert.equal(notice(limit).delivery,'now');assert.equal(notice(done)?.event,'done');
70
+ h.run('on','--response','就按这份');
71
+ assert.equal(notice(limit).delivery,'later');assert.equal(notice(done),null);
72
+ });
73
+
74
+ test('standing approval preserves existing obligations while allowing scope expansion and optional generated cases',()=>{
75
+ const cases=list=>JSON.stringify({schemaVersion:'1.0',feature:'login',cases:list});
76
+ const user={id:'TC-001',origin:'user',kind:'logic',blocking:true,title:'login works',acIds:['AC-001'],taskIds:['T-001'],
77
+ preconditions:[],steps:['sign in'],expected:['signed in'],cleanup:[]},generated={...user,id:'TC-002',origin:'generated',blocking:false,title:'g'};
78
+ const before={directories:['1.login'],files:{'1.login/requirements.md':'R','1.login/design.md':'D','1.login/tasks.md':'- [ ] T-001: implement login\n - 范围: `login.js`\n',
79
+ '1.login/test-cases.json':cases([user,generated])}};
80
+ const proposal=(files={},over={})=>({changedUserCases:[],removed:[],...over,files:{...before.files,'1.login/tasks.md':'- [ ] T-001: implement login\n - 范围: `login.js`, `helper.js`\n',...files}});
81
+ assert.equal(standingProposalProblem(before,proposal()),null);
82
+ assert.equal(standingProposalProblem(before,proposal({'1.login/test-cases.json':cases([user])})),null);
83
+ const refused=[
84
+ [proposal({'1.login/requirements.md':'R2'}),'提案改了需求'],
85
+ [proposal({},{changedUserCases:[{id:'TC-001'}]}),'提案删除或减弱了用户用例'],
86
+ [proposal({'1.login/test-cases.json':cases([generated])}),'提案删除或减弱了用户用例'],
87
+ [proposal({'1.login/test-cases.json':cases([{...user,title:'weaker'}])}),'提案删除或减弱了用户用例'],
88
+ [(()=>{const value=proposal();delete value.files['1.login/test-cases.json'];return value;})(),'提案删除或减弱了用户用例'],
89
+ [proposal({'1.login/test-cases.json':'not json'}),'提案的测试用例无法解析'],
90
+ [proposal({},{removed:['1.login']}),'提案删除了功能'],
91
+ [proposal({'2.new/requirements.md':'R','2.new/design.md':'D','2.new/tasks.md':'T'}),'提案新增了功能'],
92
+ [proposal({'1.login/assets/x.png':'b'}),'提案改了规格以外的文件(1.login/assets/x.png)'],
93
+ [(()=>{const value=proposal();delete value.files['1.login/design.md'];return value;})(),'提案内容不完整,无法判断'],
94
+ [{changedUserCases:[],removed:[],files:[]},'提案内容不完整,无法判断'],
95
+ [{changedUserCases:[],removed:[],files:{}},'提案内容不完整,无法判断'],
96
+ [{changedUserCases:[],removed:[],files:null},'提案内容不完整,无法判断'],
97
+ [proposal({'1.login/tasks.md':5}),'提案内容不完整,无法判断']];
98
+ for(const [value,reason] of refused)assert.equal(standingProposalProblem(before,value),reason,JSON.stringify(value).slice(0,120));
99
+ });
100
+
101
+ test('check-proposal judges against the specs on disk and reopen counts to the limit',t=>{
102
+ const h=home(t),specs=path.join(h.dir,'specs'),feature=path.join(specs,'1.login');
103
+ fs.mkdirSync(feature,{recursive:true});
104
+ for(const [name,content] of [['requirements.md','R'],['design.md','D'],['tasks.md','- [ ] T-001: login\n - 范围: `login.js`\n']])fs.writeFileSync(path.join(feature,name),content);
105
+ const file=path.join(h.dir,'proposal.json'),check=files=>{
106
+ fs.writeFileSync(file,JSON.stringify({result:{proposal:{changedUserCases:[],removed:[],files}}}));
107
+ return h.run('check-proposal','--specs-dir',specs,'--proposal',file);
108
+ };
109
+ const ok=check({'1.login/requirements.md':'R','1.login/design.md':'D','1.login/tasks.md':'- [ ] T-001: login\n - 范围: `login.js`, `helper.js`\n'});
110
+ assert.equal(ok.code,0);assert.match(ok.out,/可以按常设授权自行批准/);
111
+ const no=check({'1.login/requirements.md':'R2','1.login/design.md':'D','1.login/tasks.md':'- [ ] T-001: login\n - 范围: `login.js`, `helper.js`\n'});
112
+ assert.equal(no.code,1);assert.match(no.out,/提案改了需求.*不要发送 decision/);
113
+ assert.equal(h.run('check-proposal','--specs-dir',specs,'--proposal',path.join(h.dir,'missing.json')).code,1);
114
+ const reopen=()=>h.run('reopen','--project',h.dir,'--task','1.login/T-004');
115
+ assert.equal(reopen().code,1,'off: the person decides');
116
+ h.run('on','--response','就按这份');
117
+ assert.equal(h.run('reopen','--project',h.dir,'--task','T-004').code,2);
118
+ assert.match(reopen().out,/第 1 次/);assert.match(reopen().out,/第 2 次/);
119
+ const third=reopen();assert.equal(third.code,1);assert.match(third.out,/上限 2.*致命停车/);
120
+ assert.match(h.run('reopen','--project',h.dir,'--task','1.login/T-005').out,/第 1 次/);
121
+ assert.match(h.run('show').out,/1\.login\/T-004 2 次/);
122
+ });
123
+
124
+ test('a deferred stop that comes due is not lost to the window limit',async t=>{
125
+ const h=home(t),sent=path.join(h.dir,'sent.jsonl'),script=path.join(h.dir,'fake.mjs');
126
+ fs.writeFileSync(script,`import fs from 'node:fs';let i='';process.stdin.on('data',c=>i+=c);process.stdin.on('end',()=>{fs.appendFileSync(${JSON.stringify(sent)},i);});`);
127
+ fs.writeFileSync(path.join(h.dir,'notify.json'),JSON.stringify({version:1,command:[process.execPath,script]}));
128
+ const fields={key:'cm-ai|r1|T-001|1|blocked|review_limit',attentionKey:'attn|w/app|cm-ai|r1',event:'stuck',workflow:'cm-ai',project:'/w/app',code:'review_limit'};
129
+ assert.equal((await notifyLater(fields,{env:h.env,delayMs:5*60000})).scheduled,true);
130
+ const pending=path.join(h.dir,'notify-pending'),[name]=fs.readdirSync(pending);
131
+ const token=JSON.parse(fs.readFileSync(path.join(pending,name),'utf8')).token,now=Date.now();
132
+ // Both the window and the daily limit are already used up.
133
+ fs.writeFileSync(path.join(h.dir,'notify-state.json'),JSON.stringify({version:2,keys:{},attention:{},
134
+ sends:Array.from({length:150},(_,i)=>now-1000-i*1000),suppressed:0}));
135
+ assert.deepEqual(await sendPendingNotice(fields,token,{env:h.env}),{sent:true,reason:'launched'});
136
+ });
137
+
138
+ test('concurrent reopen takers never pass the limit',async t=>{
139
+ const h=home(t),cli=fileURLToPath(new URL('./cm-autonomy.mjs',import.meta.url));
140
+ h.run('on','--response','就按这份');
141
+ const take=()=>new Promise(resolve=>{
142
+ const child=spawn(process.execPath,[cli,'reopen','--project',h.dir,'--task','1.login/T-004'],{env:h.env,stdio:'ignore'});
143
+ child.on('exit',code=>resolve(code));
144
+ });
145
+ const codes=await Promise.all(Array.from({length:8},take));
146
+ assert.deepEqual(codes.sort(),[0,0,1,1,1,1,1,1]);
147
+ assert.equal(readReopens(h.env)[`${h.dir}|1.login/T-004`],2);
148
+ });
149
+
150
+ test('a reopen slot left half-written by a crash still counts',t=>{
151
+ const h=home(t);
152
+ assert.deepEqual(takeReopen(h.dir,'1.login/T-004',{env:h.env}),{count:1});
153
+ const dir=path.join(h.dir,'autonomy-reopens'),[first]=fs.readdirSync(dir);
154
+ // The second slot exists but its content never got written.
155
+ fs.writeFileSync(path.join(dir,first.replace(/-1$/,'-2')),'');
156
+ assert.deepEqual(takeReopen(h.dir,'1.login/T-004',{env:h.env}),{refused:true,count:2});
157
+ assert.equal(readReopens(h.env)[`${h.dir}|1.login/T-004`],2,'show counts the half-written slot too');
158
+ fs.writeFileSync(path.join(dir,first),'');
159
+ assert.deepEqual(Object.values(readReopens(h.env)),[2],'a group with no readable slot is still shown');
160
+ // A count kept in any other file stops the take instead of starting over.
161
+ fs.writeFileSync(path.join(h.dir,'autonomy-reopens.json'),'{}');
162
+ assert.throws(()=>takeReopen(h.dir,'1.login/T-009',{env:h.env}),/autonomy_reopens_legacy/);
163
+ });
@@ -284,7 +284,7 @@ for module in \
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
286
  review-result.schema.json review-runner.mjs task-commit-codec.mjs task-commit.mjs \
287
- task-owner.mjs task-runner.mjs worker-codex.mjs operator-guidance.mjs; do
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
290
290
  # completion_rework is a paired producer/consumer contract, including transport.
@@ -322,6 +322,8 @@ require_file "scripts/cm-security.mjs"
322
322
  require_file "scripts/cm-security.test.mjs"
323
323
  require_file "runtime/js/cm-security/scan.mjs"
324
324
  require_file "scripts/cm-notify.mjs"
325
+ require_file "scripts/cm-autonomy.mjs"
326
+ require_file "runtime/js/autonomy.mjs"
325
327
  require_file "runtime/js/notify-send.mjs"
326
328
  require_file "scripts/cm-check-update.mjs"
327
329
  require_file "scripts/cm-check-update.test.mjs"
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ import path from 'node:path';
3
+ import {pathToFileURL} from 'node:url';
4
+ import {createInterface} from 'node:readline/promises';
5
+ import {need} from '../runtime/js/cm-ai/effect-contract.mjs';
6
+ import {previewDelivery,recordDelivery,deliveryCandidate,deliveryProjection,deliveryLines,readDeliveryRecords} from '../runtime/js/cm-ai/delivery-evidence.mjs';
7
+
8
+ const usage=`Usage: cm-delivery-evidence.mjs preview|record|status|history --specs DIR
9
+ preview/record/status: --repository ID --run ID --feature NAME --artifact FILE
10
+ preview/record: --kind acceptance|deployment --actor NAME --environment NAME --note TEXT --report FILE
11
+ acceptance: --outcome accepted|rejected|revoked
12
+ deployment: --execution succeeded|failed --verification passed|failed|unknown [--verification-report FILE]
13
+ --json is allowed for read-only commands. record always requires an interactive terminal.
14
+ Records are local human declarations, not authenticated identity or remote verification.`;
15
+ export async function deliveryMain(argv,{input=process.stdin,output=process.stdout,error=process.stderr}={}){
16
+ try{
17
+ if(argv.length===1&&argv[0]==='--help'){output.write(usage+'\n');return 0;}
18
+ const operation=argv[0];need(['preview','record','status','history'].includes(operation),'delivery_invalid_arguments');
19
+ const values={},flags=new Set(['specs','repository','run','feature','artifact','kind','actor','environment','note','report','outcome','execution','verification','verification-report']);
20
+ let asJson=false;
21
+ for(let i=1;i<argv.length;i++){
22
+ if(argv[i]==='--json'){need(!asJson,'delivery_invalid_arguments');asJson=true;continue;}
23
+ const name=argv[i]?.slice(2);need(argv[i]?.startsWith('--')&&flags.has(name)&&!Object.hasOwn(values,name)
24
+ &&typeof argv[i+1]==='string'&&!argv[i+1].startsWith('--'),'delivery_invalid_arguments');values[name]=argv[++i];
25
+ }
26
+ need(typeof values.specs==='string','delivery_invalid_arguments');
27
+ const specsDir=path.resolve(values.specs);
28
+ const needed=operation==='history'?['specs']:['specs','repository','run','feature','artifact'];
29
+ if(['preview','record'].includes(operation))needed.push('kind','actor','environment','note','report',
30
+ ...(values.kind==='acceptance'?['outcome']:['execution','verification']));
31
+ const allowed=new Set([...needed,...(values.kind==='deployment'&&['preview','record'].includes(operation)?['verification-report']:[])]);
32
+ need(needed.every(key=>Object.hasOwn(values,key))&&Object.keys(values).every(key=>allowed.has(key)),'delivery_invalid_arguments');
33
+ if(operation==='record')need(!asJson&&input.isTTY===true&&output.isTTY===true,'delivery_interactive_terminal_required');
34
+ let value;
35
+ if(operation==='history')value=readDeliveryRecords(specsDir);
36
+ else {
37
+ const options={specsDir,repositoryId:values.repository,runId:values.run,feature:values.feature,artifact:path.resolve(values.artifact)};
38
+ if(operation==='status'){
39
+ const candidate=deliveryCandidate(options);
40
+ value=deliveryProjection({...options,identity:candidate.identity,packageDigest:candidate.packageDigest,specificationDigest:candidate.specificationDigest,artifactSha256:candidate.artifact.sha256});
41
+ }else{
42
+ Object.assign(options,{kind:values.kind,statement:{actor:values.actor,environment:values.environment,note:values.note,
43
+ ...(values.kind==='acceptance'?{outcome:values.outcome}:{execution:values.execution,verification:values.verification})},
44
+ report:path.resolve(values.report),verificationReport:values['verification-report']?path.resolve(values['verification-report']):null});
45
+ if(operation==='preview')value=previewDelivery(options);
46
+ else value=await recordDelivery(options,{confirm:async(preview,phrase)=>{
47
+ output.write(JSON.stringify(preview,null,2)+'\n此操作仅记录上述声明,不执行部署,也不证明声明者身份。\n');
48
+ const rl=createInterface({input,output});
49
+ try{return await rl.question(`请由验收/部署负责人核对后输入完整确认串:\n${phrase}\n> `);}finally{rl.close();}
50
+ }});
51
+ }
52
+ }
53
+ if(operation==='status'&&!asJson)output.write(deliveryLines(value).join('\n')+'\n');
54
+ else output.write(JSON.stringify(value,null,asJson?0:2)+'\n');
55
+ return 0;
56
+ }catch(e){const code=typeof e?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(e.code)?e.code:'delivery_evidence_unavailable';
57
+ error.write(JSON.stringify({error:{code}})+'\n');return 2;}
58
+ }
59
+ if(process.argv[1]&&import.meta.url===pathToFileURL(path.resolve(process.argv[1])).href)process.exitCode=await deliveryMain(process.argv.slice(2));
@@ -0,0 +1,177 @@
1
+ import test,{after} from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {buildManifest} from './cm-spec-manifest.mjs';
9
+ import {openControlRun} from './cm-ai-run.mjs';
10
+ import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
11
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
12
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
13
+ import {previewDelivery,recordDelivery,deliveryCandidate,deliveryProjection,deliveryLines,readDeliveryRecords,deliveryFile} from '../runtime/js/cm-ai/delivery-evidence.mjs';
14
+ import {completionSummary,completionLines} from '../runtime/js/cm-ai/completion-summary.mjs';
15
+ import {deliveryMain} from './cm-delivery-evidence.mjs';
16
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
17
+ import {PassThrough,Writable} from 'node:stream';
18
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-delivery-fixture-')));
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(root,'home');process.env.CM_WORKFLOW_LOG_HOME=path.join(root,'logs');
21
+ after(()=>{for(const [k,v] of Object.entries(saved))if(v===undefined)delete process.env[k];else process.env[k]=v;fs.rmSync(root,{recursive:true,force:true});});
22
+ const identity={repositoryId:'delivery-fixture',runId:'delivery-run',taskId:'T-001',attempt:1},feature='1.demo';
23
+ const cli=fileURLToPath(new URL('./cm-delivery-evidence.mjs',import.meta.url));
24
+ async function fixture(){
25
+ const local=fs.mkdtempSync(path.join(root,'project-')),specsDir=path.join(local,'specs'),codeProject=path.join(local,'code');
26
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
27
+ fs.writeFileSync(path.join(codeProject,'a.mjs'),'export const a=1;\n');fs.writeFileSync(path.join(codeProject,'requirements.md'),'fixture\n');
28
+ for(const [name,body] of [['requirements.md','# R\n'],['design.md','# D\n'],['tasks.md','- [ ] T-001: fixture\n- [ ] T-002: remaining\n']])fs.writeFileSync(path.join(specsDir,feature,name),body);
29
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
30
+ const definition={version:1,codeProject,specsDir,feature,identity,scope:['a.mjs'],requirements:['requirements.md']};
31
+ const execution={configuration:{kind:'synthetic-host-v1'},timeoutMs:4000,excludedContexts:['control'],
32
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:createCodexDeveloperRun({requestedModel:'fixture',worker:async()=>{
33
+ fs.writeFileSync(path.join(codeProject,'a.mjs'),'export const a=2;\n');
34
+ return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};}})},
35
+ check:createHostCheck({cwd:codeProject,commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]}),
36
+ verificationGate:async request=>request.acceptanceContract?{satisfied:true,items:request.acceptanceContract.obligations.map(item=>({...item,satisfied:true,evidence:'Synthetic fixture verified'}))}:{satisfied:true},
37
+ reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,contexts:['review1','review2'],run:(request,{onEvent})=>{
38
+ onEvent({event:'thread.started',provider_thread:'independent-fixture'});onEvent({event:'turn.started',item_type:null});
39
+ onEvent({event:'item.completed',item_type:'agent_message'});onEvent({event:'turn.completed',item_type:null});onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
40
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic independent review'}};
41
+ }}],reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control']}};
42
+ let opened=await openControlRun(definition,'create',execution);
43
+ const ask=()=>opened.host.handle({version:1,operation:'advance',requestId:'advance',identity});
44
+ try{assert.equal((await opened.host.handle({version:1,operation:'start',requestId:'start',identity})).state,'awaiting_review');}finally{opened.close();}
45
+ opened=await openControlRun(definition,'resume',execution,{decision:{status:'approved'}});let result;
46
+ try{result=await ask();assert.equal(result.state,'fixture_completed',JSON.stringify(result));}finally{opened.close();}
47
+ const artifact=path.join(local,'build.txt'),report=path.join(local,'owner-report.txt'),verificationReport=path.join(local,'deployed-check.txt');
48
+ fs.writeFileSync(artifact,'build bytes');fs.writeFileSync(report,'human observed flow');fs.writeFileSync(verificationReport,'post deploy check');
49
+ const options={specsDir,repositoryId:identity.repositoryId,runId:identity.runId,feature,artifact,kind:'acceptance',
50
+ statement:{actor:'fixture-owner',environment:'staging',outcome:'accepted',note:'fixture manual declaration'},report};
51
+ const projection=()=>{const candidate=deliveryCandidate(options);return deliveryProjection({...options,identity,packageDigest:candidate.packageDigest,specificationDigest:candidate.specificationDigest});};
52
+ return {local,specsDir,codeProject,options,verificationReport,result,projection};
53
+ }
54
+ const accept={confirm:async(_preview,phrase)=>phrase};
55
+
56
+ test('real completed owner: preview is read-only, explicit declaration is bound and cannot finish a feature',async()=>{
57
+ const f=await fixture(),journal=path.join(f.specsDir,'.reviews','.execution',identity.runId,'state.json'),bytes=fs.readFileSync(journal),mtime=fs.statSync(journal).mtimeMs;
58
+ const preview=previewDelivery(f.options);assert.equal(preview.candidate.packageDigest,f.result.packageDigest);
59
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.delivery')),false);
60
+ assert.equal(f.projection().productAcceptance.status,'unknown');
61
+ await assert.rejects(recordDelivery(f.options),{code:'delivery_confirmation_required'});
62
+ await assert.rejects(recordDelivery(f.options,{confirm:async()=> 'yes'}),{code:'delivery_confirmation_refused'});
63
+ const record=await recordDelivery(f.options,accept);assert.equal(record.sequence,1);assert.equal(record.provenance,'interactive-terminal-declaration');
64
+ assert.equal(readDeliveryRecords(f.specsDir).length,1);assert.equal(f.projection().productAcceptance.status,'recorded');
65
+ const summary=completionSummary({specsDir:f.specsDir,feature,result:f.result});
66
+ assert.equal(summary.productAcceptance.status,'recorded');assert.notEqual(summary.feature.status,'passed');assert.notEqual(summary.project.status,'completed');
67
+ assert.match(completionLines(summary).at(-1),/staging \[.*\] 声明已记录(accepted)/);
68
+ assert.deepEqual(fs.readFileSync(journal),bytes);assert.equal(fs.statSync(journal).mtimeMs,mtime);
69
+ const rejected=await recordDelivery({...f.options,statement:{...f.options.statement,outcome:'rejected'}},accept);
70
+ assert.equal(rejected.previousDigest,record.recordDigest);assert.equal(readDeliveryRecords(f.specsDir).length,2);
71
+ assert.equal(f.projection().productAcceptance.environments[0].statement.outcome,'rejected');
72
+ });
73
+
74
+ test('confirmation rechecks artifact, report, code candidate and record head; no stale approval is applied',async()=>{
75
+ const f=await fixture();
76
+ for(const file of [f.options.artifact,f.options.report,path.join(f.codeProject,'a.mjs')]){
77
+ const original=fs.readFileSync(file);
78
+ await assert.rejects(recordDelivery(f.options,{confirm:async(_p,phrase)=>{fs.appendFileSync(file,'drift');return phrase;}}));
79
+ fs.writeFileSync(file,original);assert.equal(readDeliveryRecords(f.specsDir).length,0);
80
+ }
81
+ await assert.rejects(recordDelivery(f.options,{confirm:async(_p,phrase)=>{await recordDelivery(f.options,accept);return phrase;}}),{code:'delivery_preview_changed'});
82
+ assert.equal(readDeliveryRecords(f.specsDir).length,1);
83
+ });
84
+
85
+ test('latest declaration, environment and candidate are never replaced by an older success',async()=>{
86
+ const f=await fixture();await recordDelivery(f.options,accept);
87
+ const candidate=deliveryCandidate(f.options),base={specsDir:f.specsDir,feature,identity,packageDigest:candidate.packageDigest,specificationDigest:candidate.specificationDigest};
88
+ assert.equal(deliveryProjection({...base,packageDigest:'f'.repeat(64)}).productAcceptance.status,'stale');
89
+ assert.equal(deliveryProjection({...base,current:false}).productAcceptance.status,'stale');
90
+ const code=path.join(f.codeProject,'a.mjs'),before=fs.readFileSync(code);fs.appendFileSync(code,'// changed');
91
+ assert.equal(completionSummary({specsDir:f.specsDir,feature,result:f.result}).productAcceptance.status,'stale');
92
+ fs.writeFileSync(code,before);
93
+ assert.equal(deliveryProjection({...base,artifactSha256:'b'.repeat(64)}).productAcceptance.status,'stale');
94
+ fs.appendFileSync(f.options.report,'changed');assert.equal(deliveryProjection(base).productAcceptance.status,'stale');
95
+ fs.writeFileSync(f.options.report,'human observed flow');
96
+ await recordDelivery({...f.options,statement:{...f.options.statement,environment:'production',outcome:'revoked'}},accept);
97
+ const value=deliveryProjection(base);assert.equal(value.productAcceptance.environments.length,2);
98
+ assert.match(deliveryLines(value)[0],/production \[.*\] 声明已记录(revoked)/);
99
+ });
100
+
101
+ test('deployment execution and post-deployment verification remain distinct, with separate evidence',async()=>{
102
+ const f=await fixture(),options={...f.options,kind:'deployment',statement:{actor:'fixture-operator',environment:'staging',execution:'succeeded',verification:'unknown',note:'deployment declaration'}};
103
+ await recordDelivery(options,accept);assert.equal(f.projection().deployment.environments[0].statement.verification,'unknown');
104
+ await assert.rejects(recordDelivery({...options,statement:{...options.statement,verification:'passed'}},accept),{code:'delivery_verification_report_required'});
105
+ await recordDelivery({...options,statement:{...options.statement,verification:'passed'},verificationReport:f.verificationReport},accept);
106
+ fs.appendFileSync(f.verificationReport,'changed');assert.equal(f.projection().deployment.status,'stale');
107
+ await recordDelivery({...options,statement:{...options.statement,execution:'failed'}},accept);
108
+ assert.equal(f.projection().deployment.environments[0].statement.execution,'failed');assert.equal(readDeliveryRecords(f.specsDir).length,3);
109
+ });
110
+
111
+ test('malformed records and unsafe source links fail closed; read-only CLI cannot bypass terminal confirmation',async()=>{
112
+ const f=await fixture();await recordDelivery(f.options,accept);
113
+ const file=path.join(f.specsDir,'.reviews','.delivery','000001','record.json'),original=fs.readFileSync(file);
114
+ const raw=JSON.parse(original);raw.statement.outcome='accepted-by-ai';fs.writeFileSync(file,JSON.stringify(raw));
115
+ assert.throws(()=>readDeliveryRecords(f.specsDir));assert.equal(f.projection().productAcceptance.status,'unknown');fs.writeFileSync(file,original);
116
+ const linked=path.join(f.local,'linked.txt');fs.symlinkSync(f.options.artifact,linked);assert.throws(()=>deliveryFile(linked));
117
+ const args=['--specs',f.specsDir,'--repository',identity.repositoryId,'--run',identity.runId,'--feature',feature,'--artifact',f.options.artifact];
118
+ const status=spawnSync(process.execPath,[cli,'status',...args,'--json'],{encoding:'utf8'});assert.equal(status.status,0,status.stderr);assert.equal(JSON.parse(status.stdout).productAcceptance.status,'recorded');
119
+ const recordArgs=[...args,'--kind','acceptance','--actor','owner','--environment','staging','--note','tested','--report',f.options.report,'--outcome','accepted'];
120
+ const refused=spawnSync(process.execPath,[cli,'record',...recordArgs],{encoding:'utf8',input:'yes\n'});
121
+ assert.equal(refused.status,2);assert.match(refused.stderr,/delivery_interactive_terminal_required/);assert.equal(readDeliveryRecords(f.specsDir).length,1);
122
+ const bypass=spawnSync(process.execPath,[cli,'record',...recordArgs,'--yes'],{encoding:'utf8'});assert.equal(bypass.status,2);
123
+ assert.deepEqual(fs.readFileSync(file),original);
124
+ });
125
+
126
+ test('interactive CLI records only the displayed digest; competing publication cannot overwrite history',async()=>{
127
+ const f=await fixture(),input=new PassThrough();input.isTTY=true;
128
+ let shown='',errors='';const output=new Writable({write(chunk,_encoding,done){const value=chunk.toString();shown+=value;
129
+ const phrase=value.match(/RECORD acceptance [a-f0-9]{64}/)?.[0];if(phrase)queueMicrotask(()=>input.write(phrase+'\n'));done();}});output.isTTY=true;
130
+ const args=['record','--specs',f.specsDir,'--repository',identity.repositoryId,'--run',identity.runId,'--feature',feature,'--artifact',f.options.artifact,
131
+ '--kind','acceptance','--actor','fixture-owner','--environment','staging','--note','manual fixture','--report',f.options.report,'--outcome','accepted'];
132
+ assert.equal(await deliveryMain(args,{input,output,error:{write(value){errors+=value;}}}),0,errors);input.destroy();
133
+ assert.match(shown,/interactive-terminal-declaration/);assert.equal(readDeliveryRecords(f.specsDir).length,1);
134
+ const originalRename=fs.renameSync;let collided=false;
135
+ fs.renameSync=function(from,to){if(!collided&&to.endsWith('000002')){collided=true;fs.mkdirSync(to);
136
+ fs.writeFileSync(path.join(to,'record.json'),fs.readFileSync(path.join(from,'record.json')));}
137
+ return originalRename(from,to);};
138
+ try{await assert.rejects(recordDelivery(f.options,accept),{code:'delivery_concurrent_write'});}finally{fs.renameSync=originalRename;}
139
+ assert.equal(readDeliveryRecords(f.specsDir).length,2,'one atomic publication survives collision');
140
+ await recordDelivery(f.options,accept);assert.equal(readDeliveryRecords(f.specsDir).length,3,'losing stage does not block later append');
141
+ fs.renameSync=()=>{throw Object.assign(new Error('fixture interrupted publication'),{code:'EIO'});};
142
+ try{await assert.rejects(recordDelivery(f.options,accept),{code:'EIO'});}finally{fs.renameSync=originalRename;}
143
+ assert.equal(readDeliveryRecords(f.specsDir).length,3);
144
+ await recordDelivery(f.options,accept);assert.equal(readDeliveryRecords(f.specsDir).length,4,'interrupted unpublished stage is preserved without corrupting committed rows');
145
+ });
146
+
147
+ test('record capacity is rejected before confirmation, preserving a fully readable ledger',async()=>{
148
+ const f=await fixture(),first=await recordDelivery(f.options,accept);let previous=first.recordDigest;
149
+ const {recordDigest,...template}=first;
150
+ for(let sequence=2;sequence<=1000;sequence++){
151
+ const body={...template,sequence,previousDigest:previous},record={...body,recordDigest:digest(body)};
152
+ const dir=path.join(f.specsDir,'.reviews','.delivery',String(sequence).padStart(6,'0'));fs.mkdirSync(dir);
153
+ fs.writeFileSync(path.join(dir,'record.json'),JSON.stringify(record)+'\n');previous=record.recordDigest;
154
+ }
155
+ let asked=false;await assert.rejects(recordDelivery(f.options,{confirm:async()=>{asked=true;return 'yes';}}),{code:'delivery_record_limit'});
156
+ assert.equal(asked,false);assert.equal(readDeliveryRecords(f.specsDir).length,1000);
157
+ });
158
+
159
+ test('R1 G8 environment casing and surrounding spaces cannot hide a later revocation',async()=>{
160
+ const f=await fixture();await recordDelivery(f.options,accept);
161
+ await recordDelivery({...f.options,statement:{...f.options.statement,environment:'Staging ',outcome:'revoked'}},accept);
162
+ const value=f.projection().productAcceptance;assert.equal(value.environments.length,1);
163
+ assert.equal(value.environments[0].environment,'staging');assert.equal(value.environments[0].statement.outcome,'revoked');
164
+ });
165
+
166
+ test('R1 G9 harmless Finder metadata does not hide delivery records while malformed entries still fail',async()=>{
167
+ const f=await fixture();await recordDelivery(f.options,accept);
168
+ const dir=path.join(f.specsDir,'.reviews','.delivery');fs.writeFileSync(path.join(dir,'.DS_Store'),'finder metadata');
169
+ assert.equal(readDeliveryRecords(f.specsDir).length,1);assert.equal(f.projection().productAcceptance.status,'recorded');
170
+ fs.mkdirSync(path.join(dir,'garbage'));assert.throws(()=>readDeliveryRecords(f.specsDir));
171
+ });
172
+
173
+ test('R1 G10 a display evidence budget reports unknown without hashing a large artifact',async()=>{
174
+ const f=await fixture();await recordDelivery(f.options,accept);const candidate=deliveryCandidate(f.options);
175
+ const value=deliveryProjection({...f.options,identity,packageDigest:candidate.packageDigest,specificationDigest:candidate.specificationDigest,maxEvidenceBytes:1});
176
+ assert.equal(value.productAcceptance.status,'unknown');assert.equal(value.productAcceptance.environments[0].reason,'delivery_evidence_budget_exceeded');
177
+ });
@@ -81,3 +81,9 @@ for(const mode of ['watchdog','unexpected-exit'])test(`owned same-group worker c
81
81
  await new Promise(resolve=>setTimeout(resolve,50));
82
82
  assert.throws(()=>process.kill(pid,0),{code:'ESRCH'});
83
83
  });
84
+
85
+ test('R1 G11 malformed optional completion display does not change the returned business result',t=>{
86
+ const out=run(t,`ready();process.stdin.once('data',()=>send({requestId:'drive',result:{state:'fixture_completed',completion:{version:1}}}));process.stdin.on('end',()=>process.exit(0));`);
87
+ assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.state,'fixture_completed');
88
+ assert.match(out.stderr,/完成摘要显示失败/);
89
+ });
@@ -0,0 +1,32 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath,pathToFileURL} from 'node:url';
8
+ import {CHECK_DRIVE_COPIED_FILES} from './cm-check-drive-files.mjs';
9
+
10
+ const root=fileURLToPath(new URL('..',import.meta.url));
11
+ test('R1 B1 shared driver imports from the original check-only runtime without runner dependencies',t=>{
12
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-light-driver-')));
13
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
14
+ for(const file of CHECK_DRIVE_COPIED_FILES){
15
+ const target=path.join(dir,file);fs.mkdirSync(path.dirname(target),{recursive:true});fs.copyFileSync(path.join(root,file),target);
16
+ }
17
+ for(const file of ['completion-summary.mjs','delivery-evidence.mjs','task-runner.mjs'])
18
+ assert.equal(fs.existsSync(path.join(dir,'runtime/js/cm-ai',file)),false,'test uses the original partial runtime inventory');
19
+ const source=`import {driveHost} from ${JSON.stringify(pathToFileURL(path.join(dir,'runtime/js/cm-ai/drive-core.mjs')).href)};
20
+ import {completionLines,deliveryLines} from ${JSON.stringify(pathToFileURL(path.join(dir,'runtime/js/cm-ai/operator-guidance.mjs')).href)};
21
+ if(typeof driveHost!=='function'||completionLines(null).length!==0||deliveryLines({}).length!==2)process.exitCode=1;`;
22
+ const run=spawnSync(process.execPath,['--input-type=module','-e',source],{cwd:dir,encoding:'utf8'});
23
+ assert.equal(run.status,0,run.stderr);assert.equal(run.stdout,'');
24
+ });
25
+
26
+ test('R1 B1 legacy formatter exports reuse the exact lightweight formatting functions',async()=>{
27
+ const light=await import('../runtime/js/cm-ai/operator-guidance.mjs');
28
+ const completion=await import('../runtime/js/cm-ai/completion-summary.mjs');
29
+ const delivery=await import('../runtime/js/cm-ai/delivery-evidence.mjs');
30
+ assert.equal(typeof light.completionLines,'function');assert.equal(typeof light.deliveryLines,'function');
31
+ assert.equal(completion.completionLines,light.completionLines);assert.equal(delivery.deliveryLines,light.deliveryLines);
32
+ });