@aibyzero/cm-workflow 0.18.0 → 0.19.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.
@@ -5,8 +5,9 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
- import {parseFeatureTaskText,validDependencies,identifyApprovedBootstrapFeature} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
8
+ import {parseFeatureTaskText,validDependencies,identifyApprovedBootstrapFeature,approveCmAiSpecs} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
9
9
  import {validateRunDefinition} from './cm-ai-run.mjs';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
10
11
 
11
12
  const entry=fileURLToPath(new URL('./cm-ai-admission.mjs',import.meta.url));
12
13
  function fixture(run){
@@ -69,6 +70,152 @@ test('approve writes only after a whitelisted reply and preserves the original r
69
70
  assert.equal(JSON.parse(fs.readFileSync(status,'utf8')).approval.response,'开始吧!');
70
71
  }));
71
72
 
73
+ test('approve bound to a change proposal writes only for that saved proposal and its unchanged bytes',()=>fixture(({specs,code})=>{
74
+ const status=path.join(specs,'.cm-specs-status'),digest='a'.repeat(64),other='b'.repeat(64);
75
+ const saved=()=>fs.writeFileSync(status,JSON.stringify({status:'awaiting_review',revisionDigest:digest,
76
+ features:['1.login'],specFiles:buildManifest(specs),testCases:[]}));
77
+ const invoke=(...extra)=>spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,
78
+ '--approve','--approval-response','开始',...extra],{encoding:'utf8'});
79
+ const refused=(result,reason)=>{assert.equal(result.status,1,result.stderr);assert.equal(JSON.parse(result.stdout).approveRefused,reason);};
80
+ saved();const before=fs.readFileSync(status);
81
+ refused(invoke('--expect-revision-digest',other),'revision_digest_mismatch');
82
+ assert.deepEqual(fs.readFileSync(status),before);
83
+ // Bytes edited after the save are not the proposal the user confirmed.
84
+ fs.appendFileSync(path.join(specs,'1.login','tasks.md'),'- [ ] T-002: unreviewed\n');
85
+ refused(invoke('--expect-revision-digest',digest),'revision_files_changed');
86
+ assert.deepEqual(fs.readFileSync(status),before);
87
+ fs.writeFileSync(path.join(specs,'1.login','tasks.md'),'- [ ] T-001: implement login\n');
88
+ // An unbound status (no revisionDigest) is refused rather than approved under the flag.
89
+ fs.writeFileSync(status,JSON.stringify({status:'awaiting_review',features:['1.login'],specFiles:buildManifest(specs),testCases:[]}));
90
+ refused(invoke('--expect-revision-digest',digest),'revision_digest_mismatch');
91
+ // An approved status that only reopened because the feature list changed is not this proposal's save.
92
+ fs.writeFileSync(status,JSON.stringify({status:'approved',revisionDigest:digest,features:['0.old'],
93
+ specFiles:buildManifest(specs),testCases:[]}));
94
+ refused(invoke('--expect-revision-digest',digest),'revision_digest_mismatch');
95
+ saved();
96
+ const accepted=invoke('--expect-revision-digest',digest);
97
+ assert.equal(accepted.status,0,`stdout: ${accepted.stdout}\nstderr: ${accepted.stderr}`);
98
+ assert.equal(JSON.parse(accepted.stdout).state,'ready');
99
+ const approved=JSON.parse(fs.readFileSync(status,'utf8'));
100
+ assert.equal(approved.status,'approved');assert.equal(approved.revisionDigest,digest);assert.equal(approved.approval.response,'开始');
101
+ // Already approved: the same reply cannot approve again or rewrite the record.
102
+ const once=fs.readFileSync(status),again=invoke('--expect-revision-digest',digest);
103
+ assert.equal(again.status,1);assert.ok(JSON.parse(again.stdout).approveRefused);assert.deepEqual(fs.readFileSync(status),once);
104
+ // The flag only binds an explicit approval; it never stands alone or takes a malformed digest.
105
+ for(const args of [['--expect-revision-digest',digest],['--approve','--approval-response','开始','--expect-revision-digest','ABC']]){
106
+ const result=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,...args],{encoding:'utf8'});
107
+ assert.equal(result.status,2);assert.match(result.stderr,/--expect-revision-digest requires --approve/);
108
+ }
109
+ }));
110
+
111
+ test('bound approve refuses changes made after its first check, before the approval is written',()=>fixture(({specs,code})=>{
112
+ const status=path.join(specs,'.cm-specs-status'),digest='a'.repeat(64);
113
+ const saved=(revision=digest)=>JSON.stringify({status:'awaiting_review',revisionDigest:revision,
114
+ features:['1.login'],specFiles:buildManifest(specs),testCases:[]});
115
+ const approve=beforeApprovalWrite=>approveCmAiSpecs({specsDir:specs,codeProjects:[code],approvalResponse:'开始',
116
+ expectRevisionDigest:digest,beforeApprovalWrite});
117
+ const requirements=path.join(specs,'1.login','requirements.md'),original=fs.readFileSync(requirements);
118
+ const interleavings={
119
+ 'spec edited':()=>fs.appendFileSync(requirements,'unreviewed\n'),
120
+ 'another proposal saved':()=>fs.writeFileSync(status,saved('b'.repeat(64))),
121
+ 'duplicate approval landed':()=>assert.equal(approve().approveRefused,undefined)};
122
+ for(const [name,interleave] of Object.entries(interleavings)){
123
+ fs.writeFileSync(requirements,original);fs.writeFileSync(status,saved());
124
+ let after;
125
+ const result=approve(()=>{interleave();after=fs.readFileSync(status);});
126
+ assert.equal(result.approveRefused,'revision_changed_during_approval',name);
127
+ // The late writer never replaces what the interleaved writer left.
128
+ assert.deepEqual(fs.readFileSync(status),after,name);
129
+ assert.equal(fs.readdirSync(specs).filter(file=>file.startsWith('.cm-specs-status-')).length,0,name);
130
+ }
131
+ // Undisturbed, it approves with the manifest that was checked.
132
+ fs.writeFileSync(requirements,original);fs.writeFileSync(status,saved());
133
+ const checked=JSON.parse(fs.readFileSync(status,'utf8')).specFiles;
134
+ assert.equal(approve().approveRefused,undefined);
135
+ assert.deepEqual(JSON.parse(fs.readFileSync(status,'utf8')).specFiles,checked);
136
+ }));
137
+
138
+ test('bound approve compares against the exact status bytes it validated',()=>fixture(({specs,code})=>{
139
+ const status=path.join(specs,'.cm-specs-status'),digest='a'.repeat(64);
140
+ const saved=revision=>JSON.stringify({status:'awaiting_review',revisionDigest:revision,
141
+ features:['1.login'],specFiles:buildManifest(specs),testCases:[]});
142
+ const approve=()=>approveCmAiSpecs({specsDir:specs,codeProjects:[code],approvalResponse:'开始',expectRevisionDigest:digest});
143
+ // Swap the status right after the bound check has parsed it (its first read of
144
+ // the status in the approval), before anything else of the approval runs.
145
+ const swapped={'another proposal saved':()=>fs.writeFileSync(status,saved('b'.repeat(64))),
146
+ 'duplicate approval landed':()=>assert.equal(approve().approveRefused,undefined)};
147
+ const read=fs.readFileSync;
148
+ for(const [name,swap] of Object.entries(swapped)){
149
+ fs.writeFileSync(status,saved(digest));
150
+ let reads=0,armed=true,after;
151
+ fs.readFileSync=function(file,...rest){
152
+ const result=read.call(this,file,...rest);
153
+ // The inspections before the approval read the status too; count from the approval's own read.
154
+ if(armed&&String(file).endsWith('.cm-specs-status')&&++reads===2){armed=false;swap();after=read(status);}
155
+ return result;
156
+ };
157
+ let result;
158
+ try{result=approveCmAiSpecs({specsDir:specs,codeProjects:[code],approvalResponse:'开始',expectRevisionDigest:digest});}
159
+ finally{fs.readFileSync=read;}
160
+ assert.equal(armed,false,name);
161
+ assert.equal(result.approveRefused,'revision_changed_during_approval',name);
162
+ assert.deepEqual(read(status),after,name);
163
+ }
164
+ }));
165
+
166
+ test('standing authorization approves a bound scope-only change and nothing else',()=>fixture(({root,specs,code})=>{
167
+ const status=path.join(specs,'.cm-specs-status'),digest='c'.repeat(64),home=path.join(root,'cm-home');
168
+ fs.mkdirSync(home);
169
+ const env={...process.env,CM_WORKFLOW_HOME:home};
170
+ const read=name=>fs.readFileSync(path.join(specs,'1.login',name),'utf8');
171
+ const requirements=read('requirements.md'),design=read('design.md');
172
+ const archive=(over={})=>{fs.mkdirSync(path.join(specs,'.reviews'),{recursive:true});
173
+ fs.writeFileSync(path.join(specs,'.reviews',`prd-change-${digest}.json`),JSON.stringify({version:1,
174
+ before:{directories:['1.login'],files:{'1.login/requirements.md':requirements,'1.login/design.md':design,'1.login/tasks.md':'- [ ] T-001: old\n'}},
175
+ proposal:{proposalDigest:digest,changedUserCases:[],removed:[],files:{'1.login/requirements.md':requirements,'1.login/design.md':design,
176
+ '1.login/tasks.md':'- [ ] T-001: implement login\n'},...over},selected:['1.login']}));};
177
+ const saved=()=>fs.writeFileSync(status,JSON.stringify({status:'awaiting_review',revisionDigest:digest,
178
+ features:['1.login'],specFiles:buildManifest(specs),testCases:[]}));
179
+ const invoke=(...extra)=>spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,'--approve',
180
+ '--standing-authorization','--expect-revision-digest',digest,...extra],{encoding:'utf8',env});
181
+ const refused=(result,reason)=>{assert.equal(result.status,1,result.stderr);assert.equal(JSON.parse(result.stdout).approveRefused,reason);};
182
+ saved();archive();const before=fs.readFileSync(status);
183
+ refused(invoke(),'standing_authorization_off');
184
+ fs.writeFileSync(path.join(home,'autonomy.json'),JSON.stringify({version:1,mode:'until_fatal',response:'就按这份',at:'2026-11-01T00:00:00.000Z'}));
185
+ for(const [over,why] of [[{files:{'1.login/requirements.md':'# changed\n','1.login/design.md':design,'1.login/tasks.md':'- [ ] T-001: implement login\n'}},/改了需求/],[{changedUserCases:[{id:'TC-001'}]},/用户用例/],
186
+ [{proposalDigest:'d'.repeat(64)},/找不到/],[{files:[]},/不完整/]]){
187
+ archive(over);const result=invoke();refused(result,'standing_authorization_not_applicable');
188
+ assert.match(JSON.parse(result.stdout).approveReason,why);assert.deepEqual(fs.readFileSync(status),before);
189
+ }
190
+ // The archive must be what the specs hold: a requirement edited on disk, or an extra feature, is not this proposal.
191
+ archive();
192
+ fs.writeFileSync(path.join(specs,'1.login','requirements.md'),'# Requirements\nnew rule\n');saved();
193
+ let result=invoke();refused(result,'standing_authorization_not_applicable');assert.match(JSON.parse(result.stdout).approveReason,/规格文件与提案不一致/);
194
+ fs.writeFileSync(path.join(specs,'1.login','requirements.md'),requirements);
195
+ const extra=path.join(specs,'2.new');fs.mkdirSync(extra);
196
+ for(const name of ['requirements.md','design.md','tasks.md'])fs.writeFileSync(path.join(extra,name),'- [ ] T-001: x\n');
197
+ fs.writeFileSync(status,JSON.stringify({status:'awaiting_review',revisionDigest:digest,features:['1.login','2.new'],specFiles:buildManifest(specs),testCases:[]}));
198
+ result=invoke();refused(result,'standing_authorization_not_applicable');assert.match(JSON.parse(result.stdout).approveReason,/功能与提案不一致/);
199
+ fs.rmSync(extra,{recursive:true});
200
+ // A spec file the archive does not list (here a test contract with a user case) cannot ride along.
201
+ fs.writeFileSync(path.join(specs,'1.login','test-cases.json'),JSON.stringify({schemaVersion:1,feature:'login',cases:[]}));saved();
202
+ result=invoke();refused(result,'standing_authorization_not_applicable');assert.match(JSON.parse(result.stdout).approveReason,/规格文件与提案不一致/);
203
+ fs.rmSync(path.join(specs,'1.login','test-cases.json'));saved();
204
+ fs.rmSync(path.join(specs,'.reviews',`prd-change-${digest}.json`));
205
+ refused(invoke(),'standing_authorization_not_applicable');
206
+ // Standing authorization never mixes with a reply or stands alone without a bound proposal.
207
+ for(const args of [['--approval-response','开始'],['--yes']]){
208
+ const result=invoke(...args);assert.equal(result.status,2);assert.match(result.stderr,/--standing-authorization requires/);
209
+ }
210
+ const unbound=spawnSync(process.execPath,[entry,'--specs-dir',specs,'--code-project',code,'--approve','--standing-authorization'],{encoding:'utf8',env});
211
+ assert.equal(unbound.status,2);
212
+ archive();
213
+ const accepted=invoke();assert.equal(accepted.status,0,`stdout: ${accepted.stdout}\nstderr: ${accepted.stderr}`);
214
+ const approved=JSON.parse(fs.readFileSync(status,'utf8'));
215
+ assert.equal(approved.status,'approved');assert.equal(approved.revisionDigest,digest);
216
+ assert.equal(approved.approval.response,'常设授权(2026-11-01T00:00:00.000Z):就按这份');
217
+ }));
218
+
72
219
  test('ready admission prints a directly valid run definition without writing the project',()=>fixture(({root,specs,code})=>{
73
220
  fs.writeFileSync(path.join(specs,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.login'],testCases:[]}));
74
221
  fs.writeFileSync(path.join(code,'package.json'),JSON.stringify({name:'login-app'}));
@@ -0,0 +1,94 @@
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
+ problem=standingProposalProblem({directories,files},proposal);
74
+ }catch{problem='读不到提案或规格目录';}
75
+ stdout.write(problem?`不能自行批准:${problem}。这是致命停车:不要发送 decision,先提醒用户。\n`:'可以按常设授权自行批准。\n');
76
+ return problem?1:0;
77
+ }
78
+ if(input.command==='reopen'){
79
+ if(!readAutonomy(env).on){stdout.write('常设授权没开:重开要用户本人同意。\n');return 1;}
80
+ let taken;
81
+ try{taken=takeReopen(input.project,input.task,{env});}catch(error){stderr.write(`ERROR: ${error.message}\n`);return 2;}
82
+ stdout.write(taken.refused?`${input.task} 已自动重开 ${taken.count} 次(上限 ${AUTO_REOPEN_LIMIT}):这是致命停车,先提醒用户。\n`
83
+ :`可以自动重开:这是 ${input.task} 第 ${taken.count} 次自动重开(上限 ${AUTO_REOPEN_LIMIT})。--supersede-reason 以「常设授权自动重开第 ${taken.count} 次:」开头。\n`);
84
+ return taken.refused?1:0;
85
+ }
86
+ const state=readAutonomy(env);
87
+ stdout.write(state.on
88
+ ?`常设授权:开启(${autonomyHome(env)}/autonomy.json)\n用户原话:${state.value.response}\n时间:${state.value.at}\n同一任务自动重开上限:${AUTO_REOPEN_LIMIT} 次\n`
89
+ +Object.entries(readReopensSafe(env)).map(([key,count])=>`已自动重开:${key.split('|').pop()} ${count} 次(${key.split('|')[0]})\n`).join('')
90
+ :`常设授权:关闭(${state.reason==='missing'?'未开启':'文件无效,按关闭处理'})\n`);
91
+ return 0;
92
+ }
93
+
94
+ if(import.meta.main)process.exitCode=main();
@@ -0,0 +1,162 @@
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 covers design, tasks and generated cases, never requirements, features or user cases',()=>{
75
+ const cases=list=>JSON.stringify({schemaVersion:1,feature:'login',cases:list});
76
+ const user={id:'TC-001',origin:'user',title:'login works'},generated={id:'TC-002',origin:'generated',title:'g'};
77
+ const before={directories:['1.login'],files:{'1.login/requirements.md':'R','1.login/design.md':'D','1.login/tasks.md':'T',
78
+ '1.login/test-cases.json':cases([user,generated])}};
79
+ const proposal=(files={},over={})=>({changedUserCases:[],removed:[],...over,files:{...before.files,'1.login/tasks.md':'T2',...files}});
80
+ assert.equal(standingProposalProblem(before,proposal()),null);
81
+ assert.equal(standingProposalProblem(before,proposal({'1.login/design.md':'D2','1.login/test-cases.json':cases([user])})),null);
82
+ const refused=[
83
+ [proposal({'1.login/requirements.md':'R2'}),'提案改了需求'],
84
+ [proposal({},{changedUserCases:[{id:'TC-001'}]}),'提案删除或减弱了用户用例'],
85
+ [proposal({'1.login/test-cases.json':cases([generated])}),'提案删除或减弱了用户用例'],
86
+ [proposal({'1.login/test-cases.json':cases([{...user,title:'weaker'}])}),'提案删除或减弱了用户用例'],
87
+ [(()=>{const value=proposal();delete value.files['1.login/test-cases.json'];return value;})(),'提案删除或减弱了用户用例'],
88
+ [proposal({'1.login/test-cases.json':'not json'}),'提案的测试用例无法解析'],
89
+ [proposal({},{removed:['1.login']}),'提案删除了功能'],
90
+ [proposal({'2.new/requirements.md':'R','2.new/design.md':'D','2.new/tasks.md':'T'}),'提案新增了功能'],
91
+ [proposal({'1.login/assets/x.png':'b'}),'提案改了规格以外的文件(1.login/assets/x.png)'],
92
+ [(()=>{const value=proposal();delete value.files['1.login/design.md'];return value;})(),'提案内容不完整,无法判断'],
93
+ [{changedUserCases:[],removed:[],files:[]},'提案内容不完整,无法判断'],
94
+ [{changedUserCases:[],removed:[],files:{}},'提案内容不完整,无法判断'],
95
+ [{changedUserCases:[],removed:[],files:null},'提案内容不完整,无法判断'],
96
+ [proposal({'1.login/tasks.md':5}),'提案内容不完整,无法判断']];
97
+ for(const [value,reason] of refused)assert.equal(standingProposalProblem(before,value),reason,JSON.stringify(value).slice(0,120));
98
+ });
99
+
100
+ test('check-proposal judges against the specs on disk and reopen counts to the limit',t=>{
101
+ const h=home(t),specs=path.join(h.dir,'specs'),feature=path.join(specs,'1.login');
102
+ fs.mkdirSync(feature,{recursive:true});
103
+ for(const [name,content] of [['requirements.md','R'],['design.md','D'],['tasks.md','T']])fs.writeFileSync(path.join(feature,name),content);
104
+ const file=path.join(h.dir,'proposal.json'),check=files=>{
105
+ fs.writeFileSync(file,JSON.stringify({result:{proposal:{changedUserCases:[],removed:[],files}}}));
106
+ return h.run('check-proposal','--specs-dir',specs,'--proposal',file);
107
+ };
108
+ const ok=check({'1.login/requirements.md':'R','1.login/design.md':'D','1.login/tasks.md':'T2'});
109
+ assert.equal(ok.code,0);assert.match(ok.out,/可以按常设授权自行批准/);
110
+ const no=check({'1.login/requirements.md':'R2','1.login/design.md':'D','1.login/tasks.md':'T2'});
111
+ assert.equal(no.code,1);assert.match(no.out,/提案改了需求.*不要发送 decision/);
112
+ assert.equal(h.run('check-proposal','--specs-dir',specs,'--proposal',path.join(h.dir,'missing.json')).code,1);
113
+ const reopen=()=>h.run('reopen','--project',h.dir,'--task','1.login/T-004');
114
+ assert.equal(reopen().code,1,'off: the person decides');
115
+ h.run('on','--response','就按这份');
116
+ assert.equal(h.run('reopen','--project',h.dir,'--task','T-004').code,2);
117
+ assert.match(reopen().out,/第 1 次/);assert.match(reopen().out,/第 2 次/);
118
+ const third=reopen();assert.equal(third.code,1);assert.match(third.out,/上限 2.*致命停车/);
119
+ assert.match(h.run('reopen','--project',h.dir,'--task','1.login/T-005').out,/第 1 次/);
120
+ assert.match(h.run('show').out,/1\.login\/T-004 2 次/);
121
+ });
122
+
123
+ test('a deferred stop that comes due is not lost to the window limit',async t=>{
124
+ const h=home(t),sent=path.join(h.dir,'sent.jsonl'),script=path.join(h.dir,'fake.mjs');
125
+ 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);});`);
126
+ fs.writeFileSync(path.join(h.dir,'notify.json'),JSON.stringify({version:1,command:[process.execPath,script]}));
127
+ 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'};
128
+ assert.equal((await notifyLater(fields,{env:h.env,delayMs:5*60000})).scheduled,true);
129
+ const pending=path.join(h.dir,'notify-pending'),[name]=fs.readdirSync(pending);
130
+ const token=JSON.parse(fs.readFileSync(path.join(pending,name),'utf8')).token,now=Date.now();
131
+ // Both the window and the daily limit are already used up.
132
+ fs.writeFileSync(path.join(h.dir,'notify-state.json'),JSON.stringify({version:2,keys:{},attention:{},
133
+ sends:Array.from({length:150},(_,i)=>now-1000-i*1000),suppressed:0}));
134
+ assert.deepEqual(await sendPendingNotice(fields,token,{env:h.env}),{sent:true,reason:'launched'});
135
+ });
136
+
137
+ test('concurrent reopen takers never pass the limit',async t=>{
138
+ const h=home(t),cli=fileURLToPath(new URL('./cm-autonomy.mjs',import.meta.url));
139
+ h.run('on','--response','就按这份');
140
+ const take=()=>new Promise(resolve=>{
141
+ const child=spawn(process.execPath,[cli,'reopen','--project',h.dir,'--task','1.login/T-004'],{env:h.env,stdio:'ignore'});
142
+ child.on('exit',code=>resolve(code));
143
+ });
144
+ const codes=await Promise.all(Array.from({length:8},take));
145
+ assert.deepEqual(codes.sort(),[0,0,1,1,1,1,1,1]);
146
+ assert.equal(readReopens(h.env)[`${h.dir}|1.login/T-004`],2);
147
+ });
148
+
149
+ test('a reopen slot left half-written by a crash still counts',t=>{
150
+ const h=home(t);
151
+ assert.deepEqual(takeReopen(h.dir,'1.login/T-004',{env:h.env}),{count:1});
152
+ const dir=path.join(h.dir,'autonomy-reopens'),[first]=fs.readdirSync(dir);
153
+ // The second slot exists but its content never got written.
154
+ fs.writeFileSync(path.join(dir,first.replace(/-1$/,'-2')),'');
155
+ assert.deepEqual(takeReopen(h.dir,'1.login/T-004',{env:h.env}),{refused:true,count:2});
156
+ assert.equal(readReopens(h.env)[`${h.dir}|1.login/T-004`],2,'show counts the half-written slot too');
157
+ fs.writeFileSync(path.join(dir,first),'');
158
+ assert.deepEqual(Object.values(readReopens(h.env)),[2],'a group with no readable slot is still shown');
159
+ // A count kept in any other file stops the take instead of starting over.
160
+ fs.writeFileSync(path.join(h.dir,'autonomy-reopens.json'),'{}');
161
+ assert.throws(()=>takeReopen(h.dir,'1.login/T-009',{env:h.env}),/autonomy_reopens_legacy/);
162
+ });
@@ -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"
@@ -7,6 +7,12 @@ import path from 'node:path';
7
7
  import {spawn,spawnSync} from 'node:child_process';
8
8
  import {notify,notifyLater,cancelPendingNotice,clearAttention,sessionTitle,scheduleWaitNotice,driveProgressKey,readNotifyConfig,writeHostRegistry,scheduleIdleNotice,parseNotifyConfig,buildNotifyMessage,normalizeNotifyText,driveNotice,NOTIFY_LIMITS,NOTIFY_WORKFLOWS,DEFAULT_NOTIFY_TEXT} from '../runtime/js/notify.mjs';
9
9
 
10
+ // driveNotice and spawned drivers read the standing authorization from the default
11
+ // home: point it at an empty directory, never the tester's own ~/.cm-workflow.
12
+ if(!process.env.CM_WORKFLOW_HOME){
13
+ process.env.CM_WORKFLOW_HOME=fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-default-home-'));
14
+ process.on('exit',()=>fs.rmSync(process.env.CM_WORKFLOW_HOME,{recursive:true,force:true}));
15
+ }
10
16
  const NOW=Date.parse('2026-10-08T08:00:00.000Z');
11
17
  const DRIVE_CORE=new URL('../runtime/js/cm-ai/drive-core.mjs',import.meta.url).href;
12
18
  const BRIDGE=new URL('../runtime/js/cm-ai/host-tool-bridge.mjs',import.meta.url).href;
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // Read-only start check for a cm-ai single-task drive PLAN. It reports the blocks that
3
- // are already knowable before create: protected scope, check budget, dirty scope files.
3
+ // are already knowable before create: protected scope, check budget, affected old UI tests
4
+ // left out of the checks, dirty scope files.
4
5
  // It never writes a file, never starts a host and never runs a check command.
5
6
  import fs from 'node:fs';
6
7
  import path from 'node:path';
@@ -26,6 +27,8 @@ const usage = '用法: cm-start-check.mjs --plan PLAN.json [--json] [--strict]\n
26
27
  + ' 1. scope 是否含受保护路径(AGENTS.md、tasks.md、.reviews、.cm-* 等)——error;\n'
27
28
  + ' scope 为空、重复、绝对路径、含 ../反斜杠/冒号等创建必拒的写法——输入不合法,退出 2\n'
28
29
  + ' 2. PLAN.checks 是否重复、是否重复跑全量测试、各检查超时之和是否超过整步 30 分钟——warn\n'
30
+ + ' scope 改到代码根 TESTING.md「## 牵连测试」表里的路径,却没跑表里对应的旧界面测试——warn;\n'
31
+ + ' 只跑了部分界面测试(-only-testing)而项目没有这张表——info(没能核对)\n'
29
32
  + ' 3. scope 内文件在代码根是否已有未提交改动——warn(Git 不可用时是 warn,不是 Git 仓库时是 info)\n'
30
33
  + '退出码:0 无 error(warn 只提示);1 有 error,或加 --strict 时有 warn;2 输入读不了或不支持。\n';
31
34
 
@@ -80,7 +83,38 @@ function checkProtectedScope(scope) {
80
83
  }
81
84
 
82
85
  const isXcodebuild = tokens => tokens.some(token => path.basename(token) === 'xcodebuild');
83
- const isTestAction = tokens => tokens.some(token => token === 'test' || token === 'test-without-building');
86
+ // xcodebuild options that take no value (xcodebuild -help, Xcode 26). A bare word counts as an
87
+ // action only right after xcodebuild, another bare word (an action or an option's value), an
88
+ // -option:value, or one of these. After any other option it may be that option's value
89
+ // (`-resultBundlePath test`), so it is not an action: an unknown flag then makes the coverage
90
+ // check warn instead of passing, never the other way round.
91
+ const XCODE_FLAGS = new Set(['-usage', '-help', '-verbose', '-license', '-checkFirstLaunchStatus', '-runFirstLaunch',
92
+ '-checkForNewerComponents', '-downloadAllPlatforms', '-prepareDeviceSupport', '-alltargets', '-parallelizeTargets', '-quiet',
93
+ '-hideShellScriptEnvironment', '-showsdks', '-showdestinations', '-showTestPlans', '-showBuildSettings', '-showBuildSettingsForIndex',
94
+ '-list', '-version', '-exportArchive', '-exportNotarizedApp', '-skipUnavailableActions', '-exportLocalizations', '-importLocalizations',
95
+ '-retry-tests-on-failure', '-run-tests-until-failure', '-disable-concurrent-destination-testing', '-enumerate-tests',
96
+ '-resolvePackageDependencies', '-disableAutomaticPackageResolution', '-onlyUsePackageVersionsFromResolvedFile', '-skipPackageUpdates',
97
+ '-disablePackageRepositoryCache', '-skipPackagePluginValidation', '-skipMacroValidation', '-skipPackageSignatureValidation', '-json',
98
+ '-allowProvisioningUpdates', '-allowProvisioningDeviceRegistration', '-showBuildTimingSummary']);
99
+ function xcodeActions(tokens) {
100
+ const start = tokens.findIndex(token => path.basename(token) === 'xcodebuild');
101
+ if (start === -1) return [];
102
+ return tokens.slice(start + 1).filter((token, index, rest) => {
103
+ if (token.startsWith('-')) return false;
104
+ const before = index === 0 ? null : rest[index - 1];
105
+ return before === null || !before.startsWith('-') || before.includes(':') || XCODE_FLAGS.has(before);
106
+ });
107
+ }
108
+ // Modes that list, show, export or set up instead of running the scheme action: a `test` beside them
109
+ // selects what to show (xcodebuild -showBuildSettings test) and runs nothing.
110
+ const XCODE_NON_RUNNING = new Set(['-usage', '-help', '-license', '-checkFirstLaunchStatus', '-runFirstLaunch', '-downloadAllPlatforms',
111
+ '-prepareDeviceSupport', '-downloadPlatform', '-importPlatform', '-downloadComponent', '-importComponent', '-deleteComponent',
112
+ '-showComponent', '-showsdks', '-showdestinations', '-showTestPlans', '-showBuildSettings', '-showBuildSettingsForIndex', '-list',
113
+ '-find-executable', '-find-library', '-version', '-exportArchive', '-exportNotarizedApp', '-exportLocalizations', '-importLocalizations',
114
+ '-enumerate-tests', '-resolvePackageDependencies', '-create-xcframework']);
115
+ // Whether a direct xcodebuild actually runs tests; shared by the overlap and the coverage checks.
116
+ const isTestAction = tokens => !tokens.some(token => XCODE_NON_RUNNING.has(token))
117
+ && xcodeActions(tokens).some(action => action === 'test' || action === 'test-without-building');
84
118
  const optionValue = (tokens, name) => {
85
119
  const at = tokens.indexOf(name);
86
120
  return at === -1 ? '' : tokens[at + 1] ?? '';
@@ -122,10 +156,91 @@ function checkChecks(plan) {
122
156
  const totalMs = own.reduce((sum, entry) => sum + entry.timeoutMs, 0);
123
157
  if (totalMs > CHECK_CALL_LIMIT_MS)
124
158
  findings.push({level: 'warn', code: 'check_budget_over_call_limit', totalMs, limitMs: CHECK_CALL_LIMIT_MS,
125
- message: `各检查超时之和 ${Math.round(totalMs / 60000)} 分钟,超过检查整步的 ${CHECK_CALL_LIMIT_MS / 60000} 分钟期限;这是最坏情况,实际可能更短。拆成多次运行,或缩减检查`});
159
+ message: `各检查超时之和 ${Math.round(totalMs / 60000)} 分钟,超过检查整步的 ${CHECK_CALL_LIMIT_MS / 60000} 分钟期限;这是最坏情况,实际可能更短。`
160
+ + '按分层缩减(单元测试全跑,界面测试只跑本任务新写的和牵连的,其余留到功能末尾回归任务),或拆成多次运行'});
126
161
  return findings;
127
162
  }
128
163
 
164
+ // The project's own record of which old UI tests a change reaches: a "## 牵连测试" table in
165
+ // TESTING.md (code root first, then docs/). After the header row, each row is
166
+ // | changed paths (a trailing / is a directory) | test identifiers as the check command names them |.
167
+ const AFFECTED_HEADING = /^##\s+牵连测试\s*$/;
168
+ const TESTING_FILES = ['TESTING.md', path.join('docs', 'TESTING.md')];
169
+ // Backticks are optional and may be mixed with plain items in one cell; a backticked item is
170
+ // kept whole (it may hold spaces), the plain rest is split on 、 , ; and spaces.
171
+ const cellItems = cell => [...[...cell.matchAll(/`([^`]+)`/g)].map(match => match[1].trim()),
172
+ ...cell.replace(/`[^`]*`/g, ' ').split(/[、,,;;\s]+/)].filter(Boolean);
173
+
174
+ export function readAffectedMap(root) {
175
+ for (const name of TESTING_FILES) {
176
+ let text;
177
+ try { text = fs.readFileSync(path.join(root, name), 'utf8'); } catch { continue; }
178
+ const lines = text.split(/\r?\n/);
179
+ const start = lines.findIndex(line => AFFECTED_HEADING.test(line.trim()));
180
+ if (start === -1) continue;
181
+ const rows = [];
182
+ let header = true;
183
+ for (const line of lines.slice(start + 1)) {
184
+ if (/^#{1,2}\s/.test(line)) break;
185
+ const cells = line.trim().match(/^\|(.*)\|$/)?.[1].split('|').map(cell => cell.trim());
186
+ if (!cells || cells.length < 2) continue;
187
+ if (cells.every(cell => /^:?-+:?$/.test(cell))) { header = false; continue; }
188
+ if (header) continue;
189
+ const paths = cellItems(cells[0]).map(item => item.replace(/^\.\//, '')), tests = cellItems(cells[1]);
190
+ if (paths.length > 0 && tests.length > 0) rows.push({paths, tests});
191
+ }
192
+ // A heading with no usable row is not a table: report it like a missing one, not as "nothing affected".
193
+ if (rows.length > 0) return {file: name, rows};
194
+ }
195
+ return null;
196
+ }
197
+
198
+ const ONLY = '-only-testing:', SKIP = '-skip-testing:';
199
+ const within = (id, target) => id === target || id.startsWith(`${target}/`);
200
+ // Whether one check command runs all of test `id`. A direct xcodebuild counts only with a test
201
+ // action and only through its selection: unnarrowed, or an -only-testing naming `id` or an
202
+ // ancestor. Any other command (wrapper script, other runner) counts when an argument contains
203
+ // `id`; the start check cannot see inside it. An -skip-testing on `id`, an ancestor or a part
204
+ // of it (one method of the class) means it does not run all of it.
205
+ function runsTest(tokens, id) {
206
+ if (tokens.some(token => token.startsWith(SKIP)
207
+ && (within(id, token.slice(SKIP.length)) || within(token.slice(SKIP.length), id)))) return false;
208
+ if (isXcodebuild(tokens)) {
209
+ if (!isTestAction(tokens)) return false;
210
+ const only = tokens.filter(token => token.startsWith(ONLY)).map(token => token.slice(ONLY.length));
211
+ return !tokens.some(token => token.startsWith('-only-testing')) || only.some(target => within(id, target));
212
+ }
213
+ return tokens.some(token => !token.startsWith('-skip-testing') && token.includes(id));
214
+ }
215
+
216
+ function checkAffectedTests(plan, definition) {
217
+ const commands = (Array.isArray(plan.checks) ? plan.checks : [])
218
+ .map(item => item?.command).filter(tokens => Array.isArray(tokens) && tokens.every(token => typeof token === 'string'));
219
+ const map = fs.existsSync(definition.codeProject) ? readAffectedMap(definition.codeProject) : null;
220
+ if (map === null) {
221
+ if (!commands.some(tokens => tokens.some(token => token.startsWith('-only-testing')))) return [];
222
+ return [{level: 'info', code: 'affected_map_missing',
223
+ message: '只跑了部分界面测试(-only-testing),但代码根 TESTING.md/docs/TESTING.md 没有「## 牵连测试」表,'
224
+ + '没能核对本任务改动牵连的旧界面测试是否都跑了'}];
225
+ }
226
+ const touches = (scopePath, rowPath) => rowPath.endsWith('/') ? scopePath.startsWith(rowPath) : scopePath === rowPath;
227
+ const missing = new Map();
228
+ for (const row of map.rows) {
229
+ const hit = definition.scope.filter(scopePath => row.paths.some(rowPath => touches(scopePath, rowPath)));
230
+ if (hit.length === 0) continue;
231
+ for (const id of row.tests) {
232
+ if (commands.some(tokens => runsTest(tokens, id))) continue;
233
+ missing.set(id, [...new Set([...(missing.get(id) ?? []), ...hit])]);
234
+ }
235
+ }
236
+ if (missing.size === 0) return [];
237
+ const tests = [...missing.keys()], paths = [...new Set([...missing.values()].flat())];
238
+ return [{level: 'warn', code: 'affected_tests_not_run', file: map.file, tests: tests.slice(0, MAX_LISTED), paths: paths.slice(0, MAX_LISTED),
239
+ message: `scope 改到 ${paths.slice(0, MAX_LISTED).join('、')}${paths.length > MAX_LISTED ? '…' : ''},按 ${map.file} 的牵连测试表,`
240
+ + `要在本任务当场跑 ${tests.slice(0, MAX_LISTED).join('、')}${tests.length > MAX_LISTED ? '…' : ''},PLAN.checks 里没有跑它们的检查。`
241
+ + '改了共用模块不能只跑新测试、留到功能末尾回归;补上这些测试,确实不牵连就改 TESTING.md 的表'}];
242
+ }
243
+
129
244
  function hasGitMarker(root) {
130
245
  for (let current = root; ; current = path.dirname(current)) {
131
246
  if (fs.existsSync(path.join(current, '.git'))) return true;
@@ -176,7 +291,7 @@ function checkDirtyScope(definition) {
176
291
 
177
292
  export function startCheck(planFile) {
178
293
  const {plan, definition} = loadStartInputs(planFile);
179
- return [...checkProtectedScope(definition.scope), ...checkChecks(plan), ...checkDirtyScope(definition)];
294
+ return [...checkProtectedScope(definition.scope), ...checkChecks(plan), ...checkAffectedTests(plan, definition), ...checkDirtyScope(definition)];
180
295
  }
181
296
 
182
297
  export function main(argv = process.argv.slice(2), out = process.stdout, err = process.stderr) {