@aibyzero/cm-workflow 0.10.6 → 0.11.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 (41) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +51 -0
  3. package/README.md +2 -2
  4. package/VERSION +1 -1
  5. package/docs/architecture.md +40 -1
  6. package/docs/installation.md +1 -1
  7. package/docs/user-guide.md +8 -1
  8. package/install-codex.sh +1 -1
  9. package/package.json +2 -1
  10. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  11. package/runtime/js/cm-ai/review-result.schema.json +0 -1
  12. package/runtime/js/cm-fix/execution.mjs +2 -2
  13. package/runtime/js/cm-fix/repair.mjs +6 -2
  14. package/runtime/js/cm-test/branch-impact.mjs +145 -0
  15. package/runtime/js/cm-test/host.mjs +28 -8
  16. package/runtime/js/cm-test/unit-coverage.mjs +206 -0
  17. package/runtime/project-context.md +6 -0
  18. package/scripts/cm-check-runtime.sh +17 -0
  19. package/scripts/cm-fix-repair-owner.test.mjs +24 -6
  20. package/scripts/cm-fix-repair.test.mjs +9 -2
  21. package/scripts/cm-fix-review-baseline.test.mjs +19 -1
  22. package/scripts/cm-release-smoke.sh +3 -0
  23. package/scripts/cm-review-schema.test.mjs +15 -0
  24. package/scripts/cm-test-branch-impact.test.mjs +186 -0
  25. package/scripts/cm-test-entry.mjs +6 -1
  26. package/scripts/cm-test-host.mjs +2 -2
  27. package/scripts/cm-unit-coverage.mjs +16 -0
  28. package/scripts/cm-unit-coverage.test.mjs +126 -0
  29. package/skills/cm-ai/references/N3-execute-task.md +12 -1
  30. package/skills/cm-ai/references/N8-finish.md +5 -4
  31. package/skills/cm-doc-syncer/SKILL.md +22 -3
  32. package/skills/cm-fix/SKILL.md +11 -2
  33. package/skills/cm-fix/references/js-host.md +4 -0
  34. package/skills/cm-prd/SKILL.md +3 -3
  35. package/skills/cm-prd/references/context-scope.md +17 -13
  36. package/skills/cm-test/SKILL.md +24 -7
  37. package/skills/cm-test/references/branch-impact.md +70 -0
  38. package/skills/cm-test/references/js-host.md +14 -2
  39. package/skills/cm-test/references/unit-coverage.md +97 -0
  40. package/skills/codebase-context/SKILL.md +11 -24
  41. package/skills/codebase-context/references/writeback.md +66 -0
@@ -0,0 +1,186 @@
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 {spawn,spawnSync} from 'node:child_process';
7
+ import {once} from 'node:events';
8
+ import {createInterface} from 'node:readline';
9
+ import {fileURLToPath} from 'node:url';
10
+ import {inspectCmTestAdmission} from './cm-test-entry.mjs';
11
+ import {inspectBranchComparison,collectBranchImpact,inspectImpactAnalysis} from '../runtime/js/cm-test/branch-impact.mjs';
12
+ import {createCmTestHost} from '../runtime/js/cm-test/host.mjs';
13
+ import {openTestSession} from '../runtime/js/cm-test/session.mjs';
14
+ import {inspectCmTestRecovery} from '../runtime/js/cm-test/recovery.mjs';
15
+
16
+ const root=fileURLToPath(new URL('..',import.meta.url));
17
+ function fixture(t,main='main'){
18
+ const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-impact-'))),project=path.join(temp,'project');
19
+ fs.mkdirSync(project);t.after(()=>fs.rmSync(temp,{recursive:true,force:true}));
20
+ const git=(...args)=>{
21
+ const output=spawnSync('git',['-C',project,...args],{encoding:'utf8'});
22
+ assert.equal(output.status,0,output.stderr);return output.stdout.trim();
23
+ };
24
+ const write=(file,content)=>{const target=path.join(project,file);fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,content);};
25
+ const commit=()=>{git('add','.');return git('-c','user.name=Fixture','-c','user.email=fixture@example.invalid','commit','-qm','fixture');};
26
+ git('init','-q','-b',main);write('src/input.mjs','export const valid = value => value !== null;\n');
27
+ write('docs/architecture.md','# Map\nValidation: src/input.mjs -> request rejection.\n');commit();
28
+ const config={skillDir:path.join(root,'skills/cm-test'),project,runtime:'codex',arguments:{},sources:[],commands:[],environment:null,logHome:path.join(temp,'logs')};
29
+ const branch=()=>{git('checkout','-qb','topic');write('src/input.mjs','export const valid = value => value != null;\n');commit();};
30
+ return {temp,project,git,write,commit,config,branch};
31
+ }
32
+ const reply=payload=>({summary:'Reject both null and undefined; regression: request validation and existing callers.',
33
+ mapStatus:'verified',mapEvidence:[{revision:'head',path:'docs/architecture.md',line:2}],gaps:[],
34
+ results:payload.changes.map(change=>({id:change.id,status:'analyzed',scenarios:['Request validation and callers'],
35
+ regression:['P1: null, undefined and valid request inputs'],explanation:'Input -> validator -> request rejection',
36
+ evidence:[...change.before?[{revision:'base',path:change.before.path,line:1}]:[],
37
+ ...change.after?[{revision:'head',path:change.after.path,line:1}]:[]]}))});
38
+ const run=(config,call)=>createCmTestHost(config,{call}).handle({requestId:'run',operation:'start'});
39
+
40
+ test('bare admission detects local main/master; explicit test target retains old default all',t=>{
41
+ for(const main of ['main','master']){
42
+ const f=fixture(t,main);f.branch();
43
+ const bare=inspectCmTestAdmission({skillDir:f.config.skillDir,project:f.project});
44
+ assert.equal(bare.operation,'impact');assert.equal(bare.comparison.baseRef,`refs/heads/${main}`);
45
+ assert.deepEqual(bare.requiredRoles,['tester']);assert.deepEqual(bare.modes,[]);
46
+ const explicit=inspectCmTestAdmission({skillDir:f.config.skillDir,project:f.project,description:'Validation'});
47
+ assert.deepEqual(explicit.modes,['logic','commands','browser']);assert.equal(explicit.operation,'execute');
48
+ assert.throws(()=>inspectCmTestAdmission({skillDir:f.config.skillDir,project:f.project,logic:true}),/test_target_required/);
49
+ }
50
+ });
51
+ test('remote default selects main unpushed commits; detached HEAD works; ambiguous/missing main fails',t=>{
52
+ const f=fixture(t),base=f.git('rev-parse','HEAD');
53
+ f.git('update-ref','refs/remotes/origin/main',base);f.git('symbolic-ref','refs/remotes/origin/HEAD','refs/remotes/origin/main');
54
+ f.write('src/input.mjs','export const changed = true;\n');f.commit();
55
+ const c=inspectBranchComparison(f.project);assert.equal(c.base,base);assert.equal(c.branchOnlyCommits,1);
56
+ assert.equal(c.remoteFreshness,'local_tracking_ref_not_fetched');
57
+ f.git('checkout','--detach','-q');assert.equal(inspectBranchComparison(f.project).branch,null);
58
+ f.git('symbolic-ref','--delete','refs/remotes/origin/HEAD');f.git('update-ref','-d','refs/remotes/origin/main');
59
+ f.git('branch','master');assert.throws(()=>inspectBranchComparison(f.project),/cm_test_main_ambiguous/);
60
+ f.git('branch','-D','main','master');assert.throws(()=>inspectBranchComparison(f.project),/cm_test_main_missing/);
61
+ });
62
+ test('non-Git and unborn repositories do not fall back to whole-worktree analysis',t=>{
63
+ const f=fixture(t);fs.rmSync(path.join(f.project,'.git'),{recursive:true});
64
+ assert.throws(()=>inspectBranchComparison(f.project),/cm_test_git_required/);
65
+ f.git('init','-q','-b','main');assert.throws(()=>inspectBranchComparison(f.project),/cm_test_head_required/);
66
+ });
67
+ test('two-tip diff includes main-only additions and tracks rename/deletion plus both committed sides',t=>{
68
+ const f=fixture(t);f.write('old name.txt','old content\n');f.write('gone.txt','removed content\n');f.commit();
69
+ f.git('checkout','-qb','topic');f.git('mv','old name.txt','新 name.txt');f.git('rm','gone.txt');f.commit();
70
+ f.git('checkout','-q','main');f.write('main-only.txt','new on main\n');f.commit();f.git('checkout','-q','topic');
71
+ f.write('新 name.txt','dirty text must not be used');
72
+ const c=inspectBranchComparison(f.project),input=collectBranchImpact(f.project,c);
73
+ assert.equal(c.mainOnlyCommits,1);assert.equal(c.branchOnlyCommits,1);assert.equal(c.dirty,true);
74
+ assert.ok(input.changes.some(row=>row.status.startsWith('R')&&row.before.path==='old name.txt'&&row.after.path==='新 name.txt'));
75
+ assert.ok(input.changes.some(row=>row.status==='D'&&row.before.path==='main-only.txt'));
76
+ assert.ok(input.sources.some(row=>row.revision==='base'&&row.path==='gone.txt'));
77
+ assert.equal(input.sources.find(row=>row.revision==='head'&&row.path==='新 name.txt').content,'old content\n');
78
+ assert.ok(!JSON.stringify(input).includes('dirty text'));
79
+ });
80
+ test('binary, protected, symlink and large files remain in inventory with explicit material gaps',t=>{
81
+ const f=fixture(t);f.write('credentials_prod.json','DO_NOT_READ_BASE');f.commit();f.git('checkout','-qb','topic');
82
+ f.write('credentials_prod.json','DO_NOT_READ_HEAD');
83
+ f.write('binary.dat',Buffer.from([0,1,2]));f.write('.env','DO_NOT_READ=fixture\n');f.write('credentials-prod.json','DO_NOT_READ');f.write('large.txt','x'.repeat(129*1024));
84
+ fs.symlinkSync('src/input.mjs',path.join(f.project,'link'));f.commit();
85
+ const input=collectBranchImpact(f.project,inspectBranchComparison(f.project));
86
+ assert.equal(input.changes.length,6);assert.deepEqual(new Set(input.gaps.map(row=>row.reason)),new Set(['binary','protected_path','material_budget','non_regular_blob']));
87
+ assert.ok(!JSON.stringify(input).includes('DO_NOT_READ'));
88
+ assert.throws(()=>collectBranchImpact(f.project,input.comparison,['../escape']),/cm_test_sources_invalid/);
89
+ });
90
+ test('repository diff settings cannot hide changed submodule pointers from the inventory',t=>{
91
+ const f=fixture(t),first=f.git('rev-parse','HEAD');f.write('version.txt','next\n');f.commit();const second=f.git('rev-parse','HEAD');
92
+ f.write('.gitmodules','[submodule "module"]\npath = module\nurl = ../local-only\n');f.git('add','.gitmodules');
93
+ f.git('update-index','--add','--cacheinfo',`160000,${first},module`);
94
+ f.git('-c','user.name=Fixture','-c','user.email=fixture@example.invalid','commit','-qm','base submodule');
95
+ f.git('checkout','-qb','topic');f.git('update-index','--cacheinfo',`160000,${second},module`);
96
+ f.git('-c','user.name=Fixture','-c','user.email=fixture@example.invalid','commit','-qm','changed submodule');
97
+ for(const setting of ['diff.ignoreSubmodules','submodule.module.ignore']){
98
+ f.git('config',setting,'all');
99
+ const input=collectBranchImpact(f.project,inspectBranchComparison(f.project));
100
+ assert.equal(input.changes.length,1);assert.equal(input.changes[0].before.path,'module');
101
+ assert.equal(input.gaps.length,2);assert.ok(input.gaps.every(item=>item.reason==='non_regular_blob'));
102
+ f.git('config','--unset',setting);
103
+ }
104
+ });
105
+ test('verified map requires selected HEAD map evidence; ordinary source cannot substitute',t=>{
106
+ const f=fixture(t);f.branch();const c=inspectBranchComparison(f.project),input=collectBranchImpact(f.project,c);
107
+ const response=reply(input);response.mapEvidence=[{revision:'head',path:'src/input.mjs',line:1}];
108
+ assert.throws(()=>inspectImpactAnalysis(input,response),/cm_test_map_evidence_required/);
109
+ response.mapEvidence=[{revision:'base',path:'docs/architecture.md',line:1}];
110
+ assert.throws(()=>inspectImpactAnalysis(input,response),/cm_test_map_evidence_required/);
111
+ f.write('docs/custom-map.md','# Map\nValidation pipeline\n');f.commit();
112
+ const custom=collectBranchImpact(f.project,inspectBranchComparison(f.project),[],['docs/custom-map.md']);
113
+ const valid=reply(custom);valid.mapEvidence=[{revision:'head',path:'docs/custom-map.md',line:1}];
114
+ assert.equal(inspectImpactAnalysis(custom,valid).mapStatus,'verified');
115
+ });
116
+ test('host returns NO_CHANGES without model or execution, logs close and historical recovery works',async t=>{
117
+ const f=fixture(t);f.write('src/input.mjs','dirty user work');
118
+ const result=await run(f.config,()=>assert.fail('no changes need no callback'));
119
+ assert.equal(result.overall,'NO_CHANGES',JSON.stringify(result));assert.equal(result.executionPassed,0);
120
+ assert.equal(result.impact.comparison.dirty,true);assert.equal(result.completionAuthorized,false);
121
+ assert.equal(inspectCmTestRecovery(f.config,result).overall,'NO_CHANGES');
122
+ assert.equal(fs.readFileSync(path.join(f.project,'src/input.mjs'),'utf8'),'dirty user work');
123
+ });
124
+ test('shared CLI dispatches impact for both runtimes; committed source, report, no execution',async t=>{
125
+ for(const runtime of ['codex','claude']){
126
+ const f=fixture(t);f.branch();f.config.runtime=runtime;f.write('src/input.mjs','dirty version');
127
+ const configPath=path.join(f.temp,'config.json');fs.writeFileSync(configPath,JSON.stringify(f.config));
128
+ const child=spawn(process.execPath,[path.join(root,'scripts/cm-test-host.mjs'),'serve','--config',configPath],{stdio:['pipe','pipe','pipe']});
129
+ const closed=once(child,'close');t.after(()=>child.kill());let result,calls=0,stderr='';
130
+ const send=value=>child.stdin.write(JSON.stringify(value)+'\n');child.stderr.on('data',data=>stderr+=data);
131
+ for await(const line of createInterface({input:child.stdout})){
132
+ const message=JSON.parse(line);
133
+ if(message.type==='host_ready')send({requestId:'run',operation:'start'});
134
+ else if(message.type==='host_request'){
135
+ calls++;assert.equal(message.kind,'change_impact');assert.ok(!JSON.stringify(message.payload.sources).includes('dirty version'));
136
+ send({type:'host_result',sessionId:message.sessionId,callId:message.callId,requestDigest:message.requestDigest,result:reply(message.payload)});
137
+ }else if(message.requestId==='run'){result=message.result;child.stdin.end();}
138
+ }
139
+ assert.equal((await closed)[0],0,stderr);assert.equal(calls,1);assert.equal(result.overall,'ANALYZED',JSON.stringify(result));
140
+ assert.equal(result.executionPassed,0);assert.equal(result.completionAuthorized,false);
141
+ assert.equal(inspectCmTestRecovery(f.config,result).status,'recovered');
142
+ }
143
+ });
144
+ test('missing/stale maps and untraced callers are partial; missing rows/false lines or moved refs block',async t=>{
145
+ for(const mode of ['missing','stale','callers','coverage','line','ref','source','map-spoof']){
146
+ const f=fixture(t);
147
+ if(mode==='map-spoof'){f.git('rm','docs/architecture.md');f.commit();}
148
+ f.branch();
149
+ const result=await run(f.config,async(kind,payload)=>{
150
+ assert.equal(kind,'change_impact');const response=reply(payload);
151
+ if(['missing','stale'].includes(mode)){response.mapStatus=mode;response.mapEvidence=[];}
152
+ if(mode==='callers')response.gaps=['Could not trace an indirect caller'];
153
+ if(mode==='coverage')response.results=[];
154
+ if(mode==='line')response.results[0].evidence[0].line=999;
155
+ if(mode==='ref')f.git('update-ref','refs/heads/main',payload.comparison.head);
156
+ if(mode==='source')f.write('src/input.mjs','concurrent user change');
157
+ if(mode==='map-spoof')response.mapEvidence=[{revision:'head',path:'src/input.mjs',line:1}];
158
+ return response;
159
+ });
160
+ assert.equal(result.overall,['missing','stale','callers'].includes(mode)?'PARTIAL':'BLOCKED',JSON.stringify(result));
161
+ if(mode==='source')assert.equal(fs.readFileSync(path.join(f.project,'src/input.mjs'),'utf8'),'concurrent user change');
162
+ }
163
+ });
164
+ test('impact refuses commands/environment and does not allow generated PASS replies',async t=>{
165
+ const f=fixture(t);f.branch();
166
+ assert.throws(()=>createCmTestHost({...f.config,commands:[{}]},{call:()=>{}}),/cm_test_impact_readonly/);
167
+ assert.throws(()=>createCmTestHost({...f.config,environment:{}},{call:()=>{}}),/cm_test_impact_readonly/);
168
+ assert.equal((await run(f.config,async()=>({overall:'PASS'}))).overall,'BLOCKED');
169
+ });
170
+ test('interrupted impact resumes original result and comparison; no callback replay or historical reanalysis',async t=>{
171
+ const f=fixture(t);f.branch();const directory=path.join(f.temp,'session');let response;
172
+ let session=openTestSession(directory,f.config);
173
+ let host=createCmTestHost(f.config,{session,call:async(kind,payload)=>{response=reply(payload);throw Error('disconnect');}});
174
+ const interrupted=await host.handle({requestId:'run',operation:'start'});assert.equal(interrupted.stage,'interrupted');session.close();
175
+ session=openTestSession(directory,f.config);
176
+ host=createCmTestHost(f.config,{session,call:()=>assert.fail('no callback replay')});
177
+ const result=await host.handle({requestId:'resume',operation:'resume',resolution:{key:interrupted.pending.key,
178
+ requestDigest:interrupted.pending.requestDigest,result:response,evidence:'Original synthetic receipt',cleanup:'completed'}});
179
+ assert.equal(result.overall,'ANALYZED',JSON.stringify(result));session.close();
180
+ session=openTestSession(directory,f.config);
181
+ host=createCmTestHost(f.config,{session,call:()=>assert.fail()});
182
+ assert.equal((await host.handle({requestId:'history',operation:'resume',resolution:null})).historical,true);session.close();
183
+ f.git('update-ref','refs/heads/main',f.git('rev-parse','HEAD'));
184
+ session=openTestSession(directory,f.config);
185
+ assert.throws(()=>createCmTestHost(f.config,{session,call:()=>{}}),/cm_test_session_binding_changed/);session.close();
186
+ });
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {fileURLToPath} from 'node:url';
5
+ import {inspectBranchComparison} from '../runtime/js/cm-test/branch-impact.mjs';
5
6
 
6
7
  const FEATURE=/^(\d+)\.(.+)$/;
7
8
  const OPTIONAL=new Set(['description','specs','feature','cases','reportDir','generateCases',
@@ -167,6 +168,8 @@ export function inspectCmTestAdmission(raw) {
167
168
  operation='generate_cases';modes=[];hardStopAfterGeneration=true;
168
169
  }else if(explore){
169
170
  operation='explore';modes=['browser'];
171
+ }else if(description===null&&specs===null&&cases===null&&!explicitExecution){
172
+ operation='impact';modes=[];
170
173
  }else{
171
174
  if(description===null&&specs===null&&cases===null)reject('test_target_required');
172
175
  operation='execute';
@@ -174,12 +177,14 @@ export function inspectCmTestAdmission(raw) {
174
177
  ['logic','commands','browser'].filter(mode=>flags[mode]);
175
178
  }
176
179
  const requiredRoles=[];
180
+ if(operation==='impact')requiredRoles.push('tester');
177
181
  if(modes.includes('logic')||modes.includes('commands'))requiredRoles.push('tester');
178
182
  if(modes.includes('browser'))requiredRoles.push('browser_qa');
179
183
  return frozen({
180
184
  schemaVersion:1,workflow:'cm-test',status:'ready',reason:null,operation,modes,requiredRoles,
181
185
  workflowRoot:root,skillDir:skill,runtimeLayout:layout,project,specs,feature,features,cases,requestedReportDir,
182
- reportDirBoundary:'pending',hardStopAfterGeneration,executionAuthorized:false,writeAuthorized:false
186
+ reportDirBoundary:'pending',hardStopAfterGeneration,executionAuthorized:false,writeAuthorized:false,
187
+ ...(operation==='impact'?{comparison:inspectBranchComparison(project)}:{})
183
188
  });
184
189
  }
185
190
 
@@ -16,7 +16,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
16
16
  try{
17
17
  if(argv.length===1&&argv[0]==='--help'){
18
18
  output.write('Optional serve trailing --session-dir ABS_PRIVATE_DIR preserves the original run and effects. Explicit JSONL resume {resolution:null} consumes recorded results; unknown original host/command results require {key,requestDigest,result,evidence,cleanup:"completed"}. Never redispatch unknown actions. Unknown log/publication writes require manual reconciliation. inspect remains read-only history.\n');
19
- output.write('cm-test-host.mjs serve --config ABSOLUTE_JSON\ncm-test-host.mjs inspect --config ABSOLUTE_JSON --run-id ID --log-file ABSOLUTE_LOG\nInspect is read-only historical recovery, never command replay. Config: {skillDir,project,runtime,arguments,sources,commands,environment,logHome}. Commands are trusted startup capabilities, not model output. JSONL start/status/cancel; host replies test_cases/qa_logic/qa_browser. No provider or repair. See skills/cm-test/references/js-host.md.\n');return 0;
19
+ output.write('cm-test-host.mjs serve --config ABSOLUTE_JSON\ncm-test-host.mjs inspect --config ABSOLUTE_JSON --run-id ID --log-file ABSOLUTE_LOG\nInspect is read-only historical recovery, never command replay. Config: {skillDir,project,runtime,arguments,sources,commands,environment,logHome}. Commands are trusted startup capabilities, not model output. JSONL start/status/cancel; Empty arguments selects committed branch impact (commands [], environment null, optional mapPaths for project-selected maps); host replies change_impact/test_cases/qa_logic/qa_browser. No provider or repair. See skills/cm-test/references/js-host.md.\n');return 0;
20
20
  }
21
21
  const sessionDir=argv[0]==='serve'&&argv.at(-2)==='--session-dir'?argv.at(-1):null;
22
22
  if(sessionDir!==null)argv=argv.slice(0,-2);
@@ -28,7 +28,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
28
28
  output.write(JSON.stringify(inspectCmTestRecovery(configuration,{runId:argv[4],logFile:argv[6]}))+'\n');return 0;
29
29
  }
30
30
  need(path.resolve(configuration.skillDir,'../..','scripts/cm-test-host.mjs')===fileURLToPath(import.meta.url),'entry_path_invalid');
31
- bridge=createHostToolBridge();
31
+ bridge=createHostToolBridge({responseLimit:256*1024});
32
32
  if(sessionDir!==null)session=openTestSession(sessionDir,configuration);
33
33
  const host=createCmTestHost(configuration,{call:(...args)=>bridge.call(...args),session});
34
34
  const rawMode=input.isTTY&&typeof input.setRawMode==='function';if(rawMode)input.setRawMode(true);
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {runUnitCoverage,prepareUnitSupplement,verifyUnitSupplement} from '../runtime/js/cm-test/unit-coverage.mjs';
5
+ try{
6
+ const [operation,flag,file]=process.argv.slice(2);
7
+ if(operation==='--help')console.log('cm-unit-coverage.mjs run|prepare|verify --config ABS_JSON\nrun: project, target head|working-tree, optional comparison/scope/command/report/format/outputDir/exclusions. command requires id, argv in command, declaration. prepare: authorized:true, project, tests, outputDir. verify: immutable prepare output. JSON stdout is evidence, never review approval.');
8
+ else{
9
+ if(!['run','prepare','verify'].includes(operation)||flag!=='--config'||!path.isAbsolute(file)||process.argv.length!==5)throw Error('invalid_arguments');
10
+ const stat=fs.lstatSync(file);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>8*1024*1024)throw Error('invalid_config');
11
+ const config=JSON.parse(fs.readFileSync(file,'utf8'));
12
+ const result=operation==='run'?await runUnitCoverage(config):operation==='prepare'?prepareUnitSupplement(config):verifyUnitSupplement(config);
13
+ console.log(JSON.stringify(result));
14
+ if(['TESTS_FAILED','BLOCKED'].includes(result.status))process.exitCode=2;
15
+ }
16
+ }catch(error){console.error(JSON.stringify({status:'BLOCKED',reason:error.code??error.message,completionAuthorized:false}));process.exitCode=2;}
@@ -0,0 +1,126 @@
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} from 'node:url';
8
+ import {parseUnitCoverage,summarizeUnitCoverage,runUnitCoverage,prepareUnitSupplement,verifyUnitSupplement,changedUnitLines} from '../runtime/js/cm-test/unit-coverage.mjs';
9
+ const root=fileURLToPath(new URL('..',import.meta.url));
10
+ function fixture(t){
11
+ const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-unit-'))),project=path.join(temp,'project');fs.mkdirSync(project);
12
+ t.after(()=>fs.rmSync(temp,{recursive:true,force:true}));
13
+ const git=(...args)=>{const r=spawnSync('git',['-C',project,...args],{encoding:'utf8'});assert.equal(r.status,0,r.stderr);return r.stdout.trim();};
14
+ const write=(file,text)=>{const p=path.join(project,file);fs.mkdirSync(path.dirname(p),{recursive:true});fs.writeFileSync(p,text);};
15
+ const commit=()=>{git('add','.');git('-c','user.name=Fixture','-c','user.email=fixture@example.invalid','commit','-qm','fixture');};
16
+ git('init','-q','-b','main');write('.gitignore','coverage/\n');
17
+ write('source.mjs',"export function classify(value) {\n if (value < 0) return 'negative';\n return 'positive';\n}\n");
18
+ write('source.test.mjs',"import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport {classify} from './source.mjs';\ntest('positive',()=>assert.equal(classify(1),'positive'));\n");
19
+ write('package.json',JSON.stringify({scripts:{'test:coverage':'node --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test source.test.mjs'}}));
20
+ fs.mkdirSync(path.join(project,'coverage'));commit();git('checkout','-qb','topic');
21
+ write('source.mjs',"export function classify(value) {\n if (value < 0) return 'negative';\n if (value === 0) return 'zero';\n return 'positive';\n}\n");commit();
22
+ const config={project,target:'head',outputDir:'coverage',report:'coverage/lcov.info',format:'lcov',command:{id:'unit',command:['npm','run','test:coverage'],declaration:{path:'package.json',line:1}}};
23
+ return {temp,project,write,git,commit,config};
24
+ }
25
+
26
+ test('LCOV computes actual changed-line/branch hits, gaps and exclusions without invented 100%',()=>{
27
+ const files=parseUnitCoverage('TN:\nSF:source.mjs\nDA:2,1\nDA:3,0\nBRDA:3,0,0,1\nBRDA:3,0,1,-\nend_of_record\n','lcov','/project');
28
+ const result=summarizeUnitCoverage([{path:'source.mjs',lines:[2,3,4]},{path:'unmeasured.mjs',lines:[1]},{path:'README.md',lines:[1]}],files,[{path:'README.md',reason:'documentation'}]);
29
+ assert.equal(result.status,'PARTIAL');assert.deepEqual(result.lines,{total:2,covered:1,percent:50});
30
+ assert.equal(result.branches.percent,null);assert.equal(result.branches.measuredPercent,50);
31
+ assert.deepEqual(result.files[0].uncoveredLines,[3]);assert.deepEqual(result.files[0].unmappedLines,[4]);assert.equal(result.files[1].status,'missing');
32
+ const empty=summarizeUnitCoverage([{path:'source.mjs',lines:[8]}],files);assert.equal(empty.lines.percent,null);assert.equal(empty.branches.percent,null);
33
+ });
34
+ test('mixed LCOV branch evidence stays unknown; explicit zero branches is distinct',()=>{
35
+ const known='SF:a.mjs\nDA:1,1\nBRDA:1,0,0,1\nBRDA:1,0,1,1\nBRF:2\nend_of_record\n';
36
+ const selection=[{path:'a.mjs',lines:[1]},{path:'b.mjs',lines:[1]}];
37
+ for(const missing of ['', 'BRF:2\n']){
38
+ const report=known+`SF:b.mjs\nDA:1,1\n${missing}end_of_record\n`;
39
+ const result=summarizeUnitCoverage(selection,parseUnitCoverage(report,'lcov','/project'));
40
+ assert.equal(result.status,'PARTIAL');assert.equal(result.branches.percent,null);assert.equal(result.branches.measuredPercent,100);
41
+ assert.deepEqual(result.branchGaps,['b.mjs']);assert.equal(result.files[1].branchStatus,'missing');
42
+ }
43
+ const zero=known+'SF:b.mjs\nDA:1,1\nBRF:0\nend_of_record\n';
44
+ const result=summarizeUnitCoverage(selection,parseUnitCoverage(zero,'lcov','/project'));
45
+ assert.equal(result.status,'MEASURED');assert.equal(result.branches.percent,100);assert.equal(result.files[1].branchStatus,'not_applicable');
46
+ });
47
+ test('Istanbul statement start-line max and branch counts; malformed reports rejected',()=>{
48
+ const item={path:'/project/input.ts',statementMap:{0:{start:{line:2}},1:{start:{line:2}}},s:{0:0,1:2},
49
+ branchMap:{0:{line:2,locations:[{},{}]}},b:{0:[1,0]}};
50
+ const result=summarizeUnitCoverage([{path:'input.ts',lines:[2]}],parseUnitCoverage(JSON.stringify({x:item}),'istanbul','/project'));
51
+ assert.equal(result.lines.percent,100);assert.equal(result.branches.percent,50);
52
+ for(const bad of ['SF:input.ts\nDA:2,NaN\nend_of_record','SF:input.ts\nDA:2,1','DA:1,0'])assert.throws(()=>parseUnitCoverage(bad,'lcov','/project'));
53
+ assert.throws(()=>parseUnitCoverage(JSON.stringify({x:{...item,b:{0:[-1,0]}}}),'istanbul','/project'));
54
+ });
55
+ test('actual Node coverage runner -> identify missing branch -> test-only supplement -> rerun',async t=>{
56
+ const f=fixture(t),before=await runUnitCoverage(f.config);
57
+ assert.ok(['MEASURED','PARTIAL'].includes(before.status),JSON.stringify(before));assert.equal(before.testsExecuted,true);
58
+ assert.ok(before.files[0].uncoveredBranches.length>0,JSON.stringify(before));assert.equal(before.completionAuthorized,false);
59
+ const baseline=prepareUnitSupplement({project:f.project,authorized:true,tests:['source.test.mjs'],outputDir:'coverage'});
60
+ fs.appendFileSync(path.join(f.project,'source.test.mjs'),"test('zero',()=>assert.equal(classify(0),'zero'));\n");
61
+ assert.equal(verifyUnitSupplement(baseline).status,'REVIEW_REQUIRED');
62
+ const after=await runUnitCoverage({...f.config,supplement:baseline});assert.equal(after.observed.exitCode,0);
63
+ assert.ok(after.branches.covered>before.branches.covered,JSON.stringify({before,after}));assert.equal(after.completionAuthorized,false);
64
+ });
65
+ test('no runner is NOT_MEASURED; dirty production cannot be measured as committed HEAD',async t=>{
66
+ const f=fixture(t);const result=await runUnitCoverage({project:f.project});assert.equal(result.status,'NOT_MEASURED');assert.equal(result.testsExecuted,false);
67
+ f.write('source.mjs','dirty source');await assert.rejects(runUnitCoverage(f.config),/coverage_dirty_head/);
68
+ });
69
+ test('HEAD rejects new execution inputs; only exact reports and authorized new tests are allowed',async t=>{
70
+ const f=fixture(t);
71
+ f.write('package.json',JSON.stringify({scripts:{'test:coverage':'node --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test'}}));f.commit();
72
+ f.write('extra.test.mjs',"import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport {classify} from './source.mjs';\ntest('zero',()=>assert.equal(classify(0),'zero'));\n");
73
+ await assert.rejects(runUnitCoverage(f.config),/coverage_untracked_head/);
74
+ assert.equal(fs.existsSync(path.join(f.project,'coverage/lcov.info')),false);
75
+ fs.unlinkSync(path.join(f.project,'extra.test.mjs'));
76
+ f.write('extra.mjs','export const newProductInput = 1;\n');
77
+ await assert.rejects(runUnitCoverage(f.config),/coverage_untracked_head/);fs.unlinkSync(path.join(f.project,'extra.mjs'));
78
+ f.write('docs/test-reports/run/impact.md','# Current impact\n');
79
+ await assert.rejects(runUnitCoverage(f.config),/coverage_untracked_head/);
80
+ const config={...f.config,auditFiles:['docs/test-reports/run/impact.md']};
81
+ assert.equal((await runUnitCoverage(config)).testsExecuted,true);
82
+ f.write('docs/test-reports/run/extra.mjs','export const x=1;\n');
83
+ await assert.rejects(runUnitCoverage(config),/coverage_untracked_head/);
84
+ await assert.rejects(runUnitCoverage({...config,auditFiles:[...config.auditFiles,'docs/test-reports/run/extra.mjs']}),/coverage_audit_files_invalid/);
85
+ fs.unlinkSync(path.join(f.project,'docs/test-reports/run/extra.mjs'));
86
+ const baseline=prepareUnitSupplement({project:f.project,authorized:true,tests:['extra.test.mjs'],outputDir:'coverage'});
87
+ f.write('extra.test.mjs',"import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport {classify} from './source.mjs';\ntest('zero',()=>assert.equal(classify(0),'zero'));\n");
88
+ assert.equal((await runUnitCoverage({...config,supplement:baseline})).testsExecuted,true);
89
+ });
90
+ test('stale coverage and failing tests never count as a successful measurement',async t=>{
91
+ const f=fixture(t);await runUnitCoverage(f.config);
92
+ f.write('package.json',JSON.stringify({scripts:{'test:coverage':'node --version'}}));f.commit();
93
+ await assert.rejects(runUnitCoverage(f.config),/coverage_report_not_fresh/);
94
+ f.write('package.json',JSON.stringify({scripts:{'test:coverage':'node missing-file.mjs'}}));f.commit();
95
+ const result=await runUnitCoverage(f.config);assert.equal(result.status,'TESTS_FAILED');assert.ok(!Object.hasOwn(result,'lines'));
96
+ });
97
+ test('working-tree scope includes new uncommitted files and excludes other user work',t=>{
98
+ const f=fixture(t);f.write('new.mjs','export const x = 1;\n');f.write('other.mjs','user work');
99
+ const changes=changedUnitLines(f.project,{base:f.git('rev-parse','main'),head:f.git('rev-parse','HEAD'),target:'working-tree',scope:['new.mjs']});
100
+ assert.deepEqual(changes.map(row=>row.path),['new.mjs']);assert.ok(changes[0].lines.includes(1));
101
+ assert.throws(()=>changedUnitLines(f.project,{base:f.git('rev-parse','main'),target:'working-tree',scope:[]}),/coverage_worktree_scope_required/);
102
+ });
103
+ test('supplement refuses missing authorization, product paths, symlinks, deletion, staging and source edits',t=>{
104
+ const f=fixture(t),config={project:f.project,authorized:true,tests:['source.test.mjs'],outputDir:'coverage'};
105
+ assert.throws(()=>prepareUnitSupplement({...config,authorized:false}),/authorization_required/);
106
+ assert.throws(()=>prepareUnitSupplement({...config,tests:['source.mjs']}),/scope_invalid/);
107
+ assert.throws(()=>prepareUnitSupplement({...config,tests:['.codex/tests/hook.mjs']}),/scope_invalid/);
108
+ fs.symlinkSync('source.mjs',path.join(f.project,'alias.test.mjs'));assert.throws(()=>prepareUnitSupplement({...config,tests:['alias.test.mjs']}),/scope_invalid/);fs.unlinkSync(path.join(f.project,'alias.test.mjs'));
109
+ const b=prepareUnitSupplement(config);fs.appendFileSync(path.join(f.project,'source.test.mjs'),'// test addition\n');
110
+ f.write('source.mjs','product edit');assert.throws(()=>verifyUnitSupplement(b),/out_of_scope/);f.git('restore','source.mjs');
111
+ f.git('add','source.test.mjs');assert.throws(()=>verifyUnitSupplement(b),/unit_git_changed/);f.git('reset','-q','HEAD','source.test.mjs');
112
+ fs.unlinkSync(path.join(f.project,'source.test.mjs'));assert.throws(()=>verifyUnitSupplement(b),/unit_test_missing/);
113
+ });
114
+ test('runner output cannot whitelist tracked source, report aliases or mutate product files',async t=>{
115
+ const f=fixture(t);
116
+ await assert.rejects(runUnitCoverage({...f.config,outputDir:'.'}),/coverage_output_invalid/);
117
+ f.write('coverage/owned.txt','tracked');f.git('add','-f','coverage/owned.txt');await assert.rejects(runUnitCoverage(f.config),/coverage_output_tracked/);f.git('reset','-q','HEAD','coverage/owned.txt');
118
+ f.write('mutate.mjs',"import fs from 'node:fs';fs.writeFileSync('source.mjs','changed');\n");
119
+ f.write('package.json',JSON.stringify({scripts:{'test:coverage':'node mutate.mjs'}}));f.commit();
120
+ await assert.rejects(runUnitCoverage(f.config),/coverage_source_changed/);assert.equal(fs.readFileSync(path.join(f.project,'source.mjs'),'utf8'),'changed');
121
+ });
122
+ test('public CLI executes existing runner and emits bound machine result',t=>{
123
+ const f=fixture(t),file=path.join(f.temp,'config.json');fs.writeFileSync(file,JSON.stringify(f.config));
124
+ const r=spawnSync(process.execPath,[path.join(root,'scripts/cm-unit-coverage.mjs'),'run','--config',file],{encoding:'utf8'});
125
+ assert.equal(r.status,0,r.stderr);const result=JSON.parse(r.stdout);assert.equal(result.testsExecuted,true);assert.ok(result.reportDigest);
126
+ });
@@ -74,14 +74,25 @@
74
74
 
75
75
  接入示例和退出码约定见 [项目安全检查接入](../../../docs/js-workflow-control.md#项目安全检查接入)。扫描结果进入已有 verification;原始敏感输出不复制进 Review。
76
76
 
77
+ ## 单测覆盖缺口
78
+
79
+ 开发期间同步补本任务已授权的单测;在最终 handoff 前按
80
+ `../../cm-test/references/unit-coverage.md` 检查本 task working-tree scope 的增量覆盖率,
81
+ 补关键正常/异常/边界场景并重跑,测试与代码一起交 N4。复用现有框架/命令;
82
+ 工具或分支证据缺失如实记未测得,不估算、不为 100% 弱化断言,保留既有项目门禁。
83
+
77
84
  ## 结构化交接门禁
78
85
 
79
86
  若这是全部 feature 的最后一个待完成任务,在定稿 handoff 前调用 `cm-doc-syncer`
80
- 同步项目文档及已有 codebase-context 参考文档;仅修改本任务事先批准的文档范围,
87
+ 同步项目文档,并按 `../../codebase-context/references/writeback.md` 增量更新业务地图
88
+ (不存在时建最小局部地图,项目指定文档优先);仅修改本任务事先批准的文档范围,
81
89
  缺范围先走规格变更批准,不自动扩 scope。文档与代码一起检查、定稿并交给 N4 审查。
82
90
  项目指令仍由主执行者按原权限及 Learning 合同处理,不向开发子 agent 开放受保护目录。
83
91
  JS 宿主可通过 `execution.documentationSync` 接入此步骤,写入处于原持久开发调用内;
84
92
  重启中的未知调用不得重发。最后任务是否成立必须核对所有 feature,不能只看当前 feature。
93
+ 同步输入汇总本 specs 批次所有 feature/task 的变更证据(包括前面任务仍未提交的修改),
94
+ 不只看最后任务;只读汇总不扩大最后任务的文档写 scope。JS 启动前按共享回写合同把参考的
95
+ 现有地图加入 run definition 的 `requirements`;新建/删除/改名改由 diff 携带,未改地图仍须正文可见。
85
96
 
86
97
  写 handoff 前按 `../../../runtime/project-learning.md` 完成本任务复盘与必要的
87
98
  AGENTS.md 增量写回;将学习结果、文件摘要记入已有交接字段,变更文件进入
@@ -15,11 +15,12 @@
15
15
  文档仍需修改时保持 BLOCKED,经规格变更批准回到正常任务路径;不重开旧任务、
16
16
  不扩大已批准范围、不覆盖旧 Review。生产发布和 Git 交付权限不由同步结果产生。
17
17
 
18
- ## 1.5 核验代码库参考文档回写(存在时强制)
18
+ ## 1.5 核验业务地图回写
19
19
 
20
- `{项目根}/docs/codebase-context/` 存在时,按 `codebase-context` 的回写映射核验本次
21
- 全部 feature 已在 N3 回写,09-changelog 类型标 `dev回写`;不存在则跳过。
22
- 缺项保持 BLOCKED,不在此处绕过已审查的项目文件快照。
20
+ 按 `../../codebase-context/references/writeback.md` 核验本次全部 feature 的地图评估及
21
+ 必要回写已在 N3、Review 前完成;无地图不能静默跳过,局部地图不能声称全仓覆盖。
22
+ 允许有依据的“无需更新”或项目规则豁免;标准目录实际更新时核验 `dev回写` 条目。
23
+ 缺评估、待同步或审后漂移保持 BLOCKED,不在此处绕过已审查的项目文件快照补写。
23
24
 
24
25
  ## 1.7 最终工作树与交付策略
25
26
 
@@ -9,13 +9,14 @@ description: 文档同步 Skill,开发完成后自动更新 README、.claude/
9
9
 
10
10
  ## 触发条件
11
11
 
12
- 由 `/cm-ai` 在所有 feature 开发完成后自动调用。
12
+ 由 `/cm-ai` 在最后任务的独立审查前调用;收口阶段只核验已审文档。
13
13
 
14
14
  ## 输入
15
15
 
16
16
  - specs 文件夹路径
17
17
  - 代码项目路径(可多个)
18
18
  - LESSONS.md 中积累的架构决策
19
+ - 本 specs 批次全部 feature/task 的原始改动证据、开工快照和最后任务的批准文档写范围
19
20
 
20
21
  ## 执行步骤
21
22
 
@@ -23,16 +24,33 @@ description: 文档同步 Skill,开发完成后自动更新 README、.claude/
23
24
 
24
25
  对每个代码项目,先读其 CLAUDE.md「版本控制」字段,按值选变更识别方式(显式分支,不得自行发明):
25
26
 
26
- - `remote` / `local` → `git diff {基线}..HEAD` 获取变更文件。基线按序尝试:① 上一份 CHANGELOG 头部记录的 `base-commit`(见步骤 5)→ ② 无则取首个 scaffold/初始 commit → ③ 仍无法确定则按全量文件清单处理,并在输出中注明「基线不明,按全量」
27
- - `none` 或项目无 `.git` → **降级为文件扫描**:遍历源码目录,结合 specs 各 feature 的 tasks.md 勾选项反推本次变更集(与 cm:init 的 none 降级约定对齐)
27
+ - `remote` / `local` → `git diff {基线}..HEAD` 获取已提交候选;基线先取上一份 CHANGELOG 的 `base-commit`,无则取已确认的 scaffold/初始 commit。无法确认时记录基线缺口,改用下述本批次任务证据,不把全量文件当变更集
28
+ - `none` 或项目无 `.git` → 用本批次 handoff/diff 和开工快照定位文件,再核实当前内容;tasks 只确定任务清单,不能仅凭勾选项推断真实改动
28
29
  - 字段缺失但有 `.git` → 按 `local` 处理
29
30
 
31
+ **本轮范围是当前 specs 批次的全部 feature/task,恢复后仍按同一批次;不等于最后一个任务。**
32
+ 从有效批准清单、tasks 和各任务已有 handoff/diff 记录汇总变更路径;旧任务只读已绑定记录,
33
+ 最后任务使用正在定稿的真实 diff。不能只凭 checkbox、时间、文件名或任意旧 Review 认定归属。
34
+
35
+ 将本轮已提交差异与所有任务尚未提交的 staged、unstaged、新建/删除文件合并,按当前代码净变化去重。
36
+ 早期任务已完成却仍未提交的改动属于本轮,不能因它出现在最后任务的开工快照里就当作用户原改动排除。
37
+ 对照各任务开工快照和实际 diff 按片段排除用户原有改动;同文件混有他人修改、来源或批次不明时只报告缺口,不猜归属。
38
+
39
+ 汇总仅用于读取;最后任务仍只写事先批准的文档范围,不重新修改旧任务源码、状态或凭证。
40
+ 没有可信证据时明确“同步范围待确认”,不得按全量文件清单替代变更归属证明或宣称全部同步。
41
+
30
42
  随后(与版本控制方式无关):
31
43
 
32
44
  - 识别新增的目录、模块、API、数据模型
33
45
  - 从 specs 的 requirements.md 获取功能描述;requirements.md 缺失 → 该 feature 跳过描述提取并在最终输出中上报「specs 不完整」,不得凭 tasks.md 猜功能描述
34
46
  - 从 LESSONS.md 获取架构决策和踩坑记录;文件不存在 → 按 0 条处理,不报错不中断
35
47
 
48
+ ### 1.5 增量同步业务地图
49
+
50
+ 按 `../codebase-context/references/writeback.md` 复用本次变更证据:更新相关章节,
51
+ 没有地图时创建最小局部地图,项目指定文档优先。不得因目录不存在直接跳过,
52
+ 不得触发全量 scan;所需文档必须在本任务批准范围内,结果进入同一 handoff 与 Review。
53
+
36
54
  ### 2. 更新 README.md
37
55
 
38
56
  对每个代码项目的 README 进行精炼更新:
@@ -146,5 +164,6 @@ README: {更新/新建} {N} 个项目
146
164
  CLAUDE.md: {更新/无变化}
147
165
  Rules: {新增 N 个 / 更新 N 个 / 无变化}
148
166
  CHANGELOG: {N} 个 feature
167
+ 业务地图: {已更新/已建局部地图/无需更新/项目规则豁免/待同步} {路径或原因}
149
168
  一致性: {PASSED / 有 N 处已修复 / 发现 N 处待人工} # 三态可并存,如「2 处已修复,1 处待人工」
150
169
  ```
@@ -92,7 +92,7 @@ diff、回归结果和对应规则;不重复投喂整仓、完整历史日志
92
92
 
93
93
  ### 2. 定位(先找根因,不是找改哪行能让现象消失)
94
94
 
95
- - 有业务地图(`docs/codebase-context/`)→ 先查 07 业务线路定位所在链路,08 修改影响映射表查波及面
95
+ - 按 `../codebase-context/references/writeback.md` 确定项目地图及本次文档范围;有地图先读相关链路与影响映射,项目指定架构文档同样适用
96
96
  - 无地图 → 从失败点向上追调用链,找到**根因层**(现象在 UI,根因可能在数据层)
97
97
  - 命中跨边界证据条件 → 将调用链、每条边的最小证据、**最后正常边**与**首个失败边**写入缺陷档案;同时写“假设 → 支持证据 → 反证试验 → 结果”,一次只检验一个假设。日志与试验必须本地且脱敏,**不自动联网、不外发日志、不安装依赖、不重启服务、不清理缓存**。
98
98
  - 输出一句话根因结论 + 波及面清单(本次修改会牵连哪些模块)——写进缺陷档案(第 7 步)
@@ -109,6 +109,7 @@ diff、回归结果和对应规则;不重复投喂整仓、完整历史日志
109
109
 
110
110
  - **写一个能复现此 bug 的失败测试**(红)——它是"修好了"的客观定义,也是永久回归资产;**红的原始输出落进档案**(第 5 步审查要核对红证据,从未红过的测试转绿是空话)
111
111
  - 项目有存量测试 → 先跑一遍记录基线(修完对照,防止修 A 坏 B)
112
+ - JS owner:影响面所需补测在原获准 test-author 阶段完成,再固定红测和存量基线;修复回调不得改这些测试。
112
113
  - 写不了自动化测试的形态(如纯视觉)→ 截图/录屏留"修前"证据
113
114
 
114
115
  ### 4. 修复(最小改动)
@@ -119,6 +120,12 @@ diff、回归结果和对应规则;不重复投喂整仓、完整历史日志
119
120
 
120
121
  ### 5. 审查(独立审查同 N4)
121
122
 
123
+ - 修后按 `../cm-test/references/unit-coverage.md` 检查已授权修复范围的增量单测覆盖率,
124
+ 核对正常/异常/边界及相邻场景并重跑,纳入下面的同一份 handoff;原失败测试红绿证据必须保留。
125
+ 普通流程在审前补足授权测试;JS owner 若修后才发现补测缺口,按上述指南报告接线受阻并走原受控流程,
126
+ 不在 owner 外修改冻结测试或重建基线。
127
+
128
+ - 先按 `../codebase-context/references/writeback.md` 完成地图评估与必要回写;无地图建本次局部地图,有地图只更新受影响章节。普通流程记 handoff evidence,JS 复用已绑定的 plan、修后文件与 Review;改动纳入摘要与独立审查,不能等第 7 步再写。
122
129
  - 审查前按 `../../runtime/project-learning.md` 复盘并完成必要的 AGENTS.md 增量写回,纳入本次审查 diff;无新增记入缺陷档案。微缺陷通道也必须复盘,新增 AGENTS.md 改动导致不再满足单文件门槛时走完整流程。
123
130
  - 失败测试转绿 + 存量基线不退化后,按 `runtime/review.md` 审查本缺陷 diff(重点:根因是否真被修掉、有无只治症状、波及面有无遗漏)
124
131
  - **防护网测试本身是审查对象**(实测最大问题类:测试是戏台):红的原因是否=该缺陷、断言测的是根因还是症状、有无安慰剂/前提共谋;**核对第 3 步落档的红证据**——没有红过的记录,测试可信度按不成立处理
@@ -159,6 +166,7 @@ python3 {CM_WORKFLOW_ROOT}/scripts/cm-task-gate.py check-n5 \
159
166
 
160
167
  ### 7. 落盘(审计链闭合)
161
168
 
169
+ - 核验地图评估结果和已审文件版本,缺评估、待同步或审后变化不写成功 `task_done`;遵守回写合同的项目规则豁免,不把缺失地图静默跳过。
162
170
  - 收口前核对复盘记录、AGENTS.md 的审查范围与磁盘摘要;有新增则回读确认,无新增如实记录。缺记录、无法写回或批准后变化时不写成功 `task_done`,按学习合同与第 5 步处理。
163
171
  - **缺陷档案**:`{SPECS_DIR}/fixes/{YYYYMMDD}-{简短slug}.md`——现象 / 复现步骤 / 根因 / 修法(含放弃的方案)/ 波及面与回归结果 / 测试文件路径;命中跨边界证据条件时追加“证据链与假设”(调用链、边证据、最后正常边、首个失败边、反证结果)。这是缺陷知识库,同类 bug 再犯先查这里
164
172
  - **METRICS.md 追加一行**:Feature 列写 `fix`,任务列写档案文件名,其余列同口径(轮次/拦截数/人工介入)
@@ -177,7 +185,7 @@ python3 {CM_WORKFLOW_ROOT}/scripts/cm-task-gate.py check-n5 \
177
185
  - [ ] 有截图/文案前后对照可作验收证据
178
186
 
179
187
  **快速通道可省**:第 3 步防护网测试、第 6 步全量回归(用前后对照截图代替)。
180
- **不可省**:独立审查(凭证照落)、缺陷档案(显式标注 `快速通道`)、METRICS 行(Feature 列写 `fix-lite`)。
188
+ **不可省**:独立审查(凭证照落)、地图评估(回写导致多文件则走完整流程)、缺陷档案(显式标注 `快速通道`)、METRICS 行(Feature 列写 `fix-lite`)。
181
189
  **快速通道的审查特化**:独立审查是该通道的主要质量防线,第一职责是复核四个客观门槛;diff 任一项不符或波及面存疑即打回完整七步。
182
190
  > fix-lite 的占比进运行日志——快速通道被滥用(占比异常高/出现分支改动混入)时收紧门槛,数据说了算。
183
191
 
@@ -191,6 +199,7 @@ python3 {CM_WORKFLOW_ROOT}/scripts/cm-task-gate.py check-n5 \
191
199
  审查: 独立审查({channel}) {通过/N轮N条} | 回归: 波及面 {N} 项通过
192
200
  档案: fixes/{文件名} METRICS 已记
193
201
  学习: {AGENTS.md已写回并回读/已复盘,无新增}
202
+ 业务地图: {已更新/已建局部地图/无需更新/项目规则豁免/待同步} {路径或原因}
194
203
  ```
195
204
 
196
205
  ## 边界
@@ -17,6 +17,10 @@
17
17
  可选 `redTest`、`baseline`、`testAuthor`、`repair`、`walkthrough`、`applicableAgentFiles`
18
18
  必须先按 `../../../runtime/js/cm-fix/` 中对应模块的实际合同配置,不能临场发明字段。
19
19
  首次启动前固定所需配置;持久运行不支持通过改配置文件解除阻断。
20
+ 地图同步按 `../../codebase-context/references/writeback.md` 在启动前确定文档路径并纳入
21
+ 已批准的 `repair.scope`;`fix_repair` 内完成回写,缺范围不在宿主外补写。
22
+ 本次参考且保留路径的现有地图加入 `repair.requirements` 作为只读审核材料;新建或已批准删除/改名
23
+ 的地图只进写 scope,由真实 diff 的 after/before 携带;不能为审核把只读材料变成写权限。
20
24
  4. 根因/最终 reviewer 配置及诊断沿用 `../../../scripts/cm-ai-host.mjs` 的
21
25
  `readConversationReviewConfiguration` 和对应 runtime preflight 合同;诊断输入是该脚本
22
26
  所要求的 cm-ai 配置,不把 fix 配置直接当作诊断配置。诊断不等于真实模型可用或外发批准。
@@ -150,9 +150,9 @@ node {CM_WORKFLOW_ROOT}/scripts/cm-workflow-config.mjs \
150
150
  `CONTEXT_SCOPE=targeted|full`、加载对应地图/代码,并写 `decision/context_scope` 日志
151
151
  - **B1 代码库参考文档判定**:先读代码项目根 CLAUDE.md 的「业务地图」字段(多层仓库
152
152
  下以代码项目根为准,仓库根 CLAUDE.md 无此字段再看地图 00-index 头部;init 已判定过,
153
- 不重复判断)。字段=已生成/已刷新或目录存在 → 按 context-scope 清单渐进加载;字段=
154
- 跳过(小项目) → 不建议 scan,按范围直接读代码;字段缺失且文档不存在 → 建议先执行
155
- `/codebase-context scan`,本轮按直接代码搜索继续;skill 未安装 → 提示重装最新包并按
153
+ 仍须核对相关内容与当前代码)。字段=已生成/已刷新或目录存在 → 按 context-scope 渐进加载并核实;字段=
154
+ 跳过(小项目) → 不建议 scan,按范围直接读代码;字段缺失且文档不存在 → 按共享回写合同
155
+ 定向还原本次链路,将必要地图文档纳入后续任务范围,不强制先全量 scan;skill 未安装 → 提示重装最新包并按
156
156
  直接代码搜索继续。任何路径都不得因追求 targeted 猜测波及面
157
157
 
158
158
  **二开模式追加规则**(GREENFIELD=false 且本次需求会修改存量代码时生效)→ **读取 `references/brownfield.md`** 执行 B2 波及面 / B3 防护网基线 / B4 增量 specs / B5 拆分锚定地图。