@aibyzero/cm-workflow 0.10.6 → 0.12.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.
- package/.codex-plugin/plugin.json +1 -1
- package/AGENTS.md +2 -0
- package/CHANGELOG.md +58 -0
- package/README.md +17 -3
- package/VERSION +1 -1
- package/compat/claude-commands/cm-security.md +3 -0
- package/docs/architecture.md +62 -1
- package/docs/installation.md +14 -2
- package/docs/user-guide.md +31 -3
- package/install-codex.sh +1 -1
- package/package.json +3 -1
- package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
- package/runtime/js/cm-ai/review-result.schema.json +0 -1
- package/runtime/js/cm-fix/execution.mjs +2 -2
- package/runtime/js/cm-fix/repair.mjs +6 -2
- package/runtime/js/cm-security/scan.mjs +263 -0
- package/runtime/js/cm-test/branch-impact.mjs +151 -0
- package/runtime/js/cm-test/host.mjs +28 -8
- package/runtime/js/cm-test/unit-coverage.mjs +206 -0
- package/runtime/project-context.md +6 -0
- package/scripts/cm-check-runtime.sh +23 -1
- package/scripts/cm-check-update.mjs +200 -0
- package/scripts/cm-check-update.test.mjs +186 -0
- package/scripts/cm-fix-repair-owner.test.mjs +24 -6
- package/scripts/cm-fix-repair.test.mjs +9 -2
- package/scripts/cm-fix-review-baseline.test.mjs +19 -1
- package/scripts/cm-release-smoke.sh +3 -0
- package/scripts/cm-review-schema.test.mjs +15 -0
- package/scripts/cm-security.mjs +32 -0
- package/scripts/cm-security.test.mjs +203 -0
- package/scripts/cm-test-branch-impact.test.mjs +186 -0
- package/scripts/cm-test-entry.mjs +6 -1
- package/scripts/cm-test-host.mjs +2 -2
- package/scripts/cm-unit-coverage.mjs +16 -0
- package/scripts/cm-unit-coverage.test.mjs +126 -0
- package/scripts/validate-public-repo.py +2 -1
- package/skills/cm-ai/references/N3-execute-task.md +12 -1
- package/skills/cm-ai/references/N8-finish.md +5 -4
- package/skills/cm-check/SKILL.md +44 -7
- package/skills/cm-check/references/js-host.md +4 -1
- package/skills/cm-doc-syncer/SKILL.md +22 -3
- package/skills/cm-fix/SKILL.md +11 -2
- package/skills/cm-fix/references/js-host.md +4 -0
- package/skills/cm-prd/SKILL.md +3 -3
- package/skills/cm-prd/references/context-scope.md +17 -13
- package/skills/cm-security/SKILL.md +55 -0
- package/skills/cm-security/references/scan-contract.md +43 -0
- package/skills/cm-test/SKILL.md +24 -7
- package/skills/cm-test/references/branch-impact.md +70 -0
- package/skills/cm-test/references/js-host.md +14 -2
- package/skills/cm-test/references/unit-coverage.md +97 -0
- package/skills/codebase-context/SKILL.md +11 -24
- package/skills/codebase-context/references/writeback.md +66 -0
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import test 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 crypto from 'node:crypto';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
8
|
+
import {spawnSync,execFileSync} from 'node:child_process';
|
|
9
|
+
import {inventory,scan,normalize} from '../runtime/js/cm-security/scan.mjs';
|
|
10
|
+
import {main} from './cm-security.mjs';
|
|
11
|
+
|
|
12
|
+
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
|
13
|
+
const gitBin=execFileSync('/bin/sh',['-c','command -v git'],{encoding:'utf8'}).trim();
|
|
14
|
+
function fixture(t){
|
|
15
|
+
const base=fs.mkdtempSync(path.join(os.tmpdir(),'cm-security-test-'));
|
|
16
|
+
const project=path.join(base,'project with spaces');fs.mkdirSync(project);
|
|
17
|
+
t.after(()=>fs.rmSync(base,{recursive:true,force:true}));
|
|
18
|
+
const git=(...args)=>execFileSync(gitBin,['-c','core.fsmonitor=false','-C',project,...args],{stdio:['ignore','pipe','pipe']}).toString();
|
|
19
|
+
const put=(file,text)=>{fs.mkdirSync(path.dirname(path.join(project,file)),{recursive:true});fs.writeFileSync(path.join(project,file),text);};
|
|
20
|
+
git('init','-b','main');git('config','user.name','Fixture');git('config','user.email','fixture@example.test');
|
|
21
|
+
put('app.py','print("base")\n');git('add','.');git('commit','-m','base');git('switch','-c','feature');
|
|
22
|
+
return {base,project,git,put};
|
|
23
|
+
}
|
|
24
|
+
function isolatedPath(t,f,programs={}){
|
|
25
|
+
const old=process.env.PATH,bin=path.join(f.base,'bin');fs.mkdirSync(bin);
|
|
26
|
+
fs.symlinkSync(gitBin,path.join(bin,'git'));
|
|
27
|
+
for(const [name,body] of Object.entries(programs))fs.writeFileSync(path.join(bin,name),`#!${process.execPath}\n${body}`,{mode:0o700});
|
|
28
|
+
process.env.PATH=bin;t.after(()=>{process.env.PATH=old;});
|
|
29
|
+
}
|
|
30
|
+
const fakeLeak=(body='')=>`
|
|
31
|
+
const fs=require('fs'),path=require('path'),args=process.argv.slice(2);
|
|
32
|
+
if(args.includes('--version')){console.log('9.0.0');process.exit(0);}
|
|
33
|
+
${body}
|
|
34
|
+
`;
|
|
35
|
+
|
|
36
|
+
test('scope includes branch commits, working/index differences, deletes and renames; excludes untracked',t=>{
|
|
37
|
+
const f=fixture(t);f.put('app.py','print("feature")\n');f.put('renamed.py','ok\n');f.git('add','.');f.git('commit','-m','change');
|
|
38
|
+
f.git('mv','renamed.py','new name.py');f.put('app.py','print("staged")\n');f.git('add','app.py');f.put('app.py','print("worktree")\n');
|
|
39
|
+
f.put('untracked-private.txt','DO NOT READ');
|
|
40
|
+
const result=inventory(f.project);
|
|
41
|
+
assert.deepEqual(result.selected,['app.py','new name.py','renamed.py']);
|
|
42
|
+
assert.equal(result.untracked,1);assert.ok(!result.files.some(v=>v.path==='untracked-private.txt'));
|
|
43
|
+
assert.deepEqual(result.files.filter(v=>v.path==='app.py').map(v=>v.revision),['worktree','index']);
|
|
44
|
+
assert.ok(result.gaps.some(v=>v.path==='renamed.py'&&v.reason==='deleted_review_baseline'));
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('full scope works without main; ambiguous/missing branch base blocks default',t=>{
|
|
48
|
+
const f=fixture(t);f.git('branch','master');assert.throws(()=>inventory(f.project),/main_ambiguous/);
|
|
49
|
+
assert.equal(inventory(f.project,{all:true}).files.length,1);
|
|
50
|
+
f.git('branch','-D','main','master');assert.throws(()=>inventory(f.project),/main_missing/);
|
|
51
|
+
assert.equal(inventory(f.project,{all:true}).files.length,1);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('no change is distinct from partial and missing tools do not pass',t=>{
|
|
55
|
+
const f=fixture(t);isolatedPath(t,f);
|
|
56
|
+
assert.equal(scan(f.project).result,'NO_CHANGES');f.put('app.py','changed\n');
|
|
57
|
+
const r=scan(f.project);assert.equal(r.coverage,'PARTIAL');assert.equal(r.sourceUnchanged,true);
|
|
58
|
+
assert.ok(r.tools.every(v=>v.reason==='tool_missing'));assert.equal(r.aiReview,'pending');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('symlink ancestor, protected files and scanner controls are visible gaps',t=>{
|
|
62
|
+
const f=fixture(t);f.put('dir/file.py','ok');f.put('.env','private fixture');f.put('.gitleaks.toml','malicious rule');f.git('add','.');
|
|
63
|
+
fs.renameSync(path.join(f.project,'dir'),path.join(f.base,'outside'));
|
|
64
|
+
fs.symlinkSync(path.join(f.base,'outside'),path.join(f.project,'dir'));
|
|
65
|
+
const r=inventory(f.project,{all:true});
|
|
66
|
+
assert.ok(r.gaps.some(v=>v.path==='dir/file.py'&&v.reason==='symlink'));
|
|
67
|
+
assert.ok(r.gaps.some(v=>v.path==='.env'&&v.reason==='protected_path_not_read'));
|
|
68
|
+
assert.ok(r.gaps.some(v=>v.reason==='scanner_control_excluded_review_manually'));
|
|
69
|
+
assert.ok(!r.files.some(v=>v.path==='.env'||v.path==='.gitleaks.toml'));
|
|
70
|
+
assert.ok(!r.files.some(v=>v.path==='dir/file.py'&&v.revision==='worktree'));
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('source/config limits and malformed CLI are blocked',t=>{
|
|
74
|
+
const f=fixture(t);f.put('large.py',Buffer.alloc(1024*1024+1));f.git('add','.');
|
|
75
|
+
assert.ok(inventory(f.project).gaps.some(v=>v.reason==='oversize'));
|
|
76
|
+
assert.throws(()=>main(['--all','--all']),/duplicate/);
|
|
77
|
+
assert.throws(()=>main(['--project']),/required/);
|
|
78
|
+
assert.throws(()=>main(['--untrusted-shell-command']),/unknown/);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test('Git fsmonitor configuration never executes during main-ref or scope reads',t=>{
|
|
82
|
+
const f=fixture(t),marker=path.join(f.base,'called');
|
|
83
|
+
const monitor=path.join(f.base,'monitor');fs.writeFileSync(monitor,`#!/bin/sh\ntouch '${marker}'\n`,{mode:0o700});
|
|
84
|
+
f.git('config','core.fsmonitor',monitor);inventory(f.project);assert.ok(!fs.existsSync(marker));
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('normalization strips secrets and rejects foreign file/line references',()=>{
|
|
88
|
+
const files=[{path:'a.py',revision:'worktree',bytes:Buffer.from('a\nb\n')}];const base='/snapshot';
|
|
89
|
+
const r=normalize('gitleaks',[{File:'worktree/a.py',StartLine:1,RuleID:'generic-api-key',Secret:'DO_NOT_OUTPUT',Match:'DO_NOT_OUTPUT'}],files,base);
|
|
90
|
+
assert.equal(r.findings.length,1);assert.ok(!JSON.stringify(r).includes('DO_NOT_OUTPUT'));
|
|
91
|
+
for(const [File,StartLine] of [['../../outside',1],['worktree/a.py',99]]){
|
|
92
|
+
assert.throws(()=>normalize('gitleaks',[{File,StartLine,RuleID:'rule'}],files,base),/location/);
|
|
93
|
+
}
|
|
94
|
+
assert.throws(()=>normalize('semgrep',{results:[],errors:[{}],paths:{scanned:[]}},files,base),/errors/);
|
|
95
|
+
const s=normalize('semgrep',{results:[],errors:[],paths:{scanned:[]}},files,base);assert.equal(s.unscanned.length,1);
|
|
96
|
+
const o=normalize('osv',{results:[{source:{path:'worktree/a.py'},packages:[{vulnerabilities:[{id:'CVE-2099-1234',details:'DO_NOT_OUTPUT'}]}]}]},files,base);
|
|
97
|
+
assert.equal(o.findings[0].rule,'CVE-2099-1234');assert.ok(!JSON.stringify(o).includes('DO_NOT_OUTPUT'));
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test('adapter clears secrets/config environment and returns safe findings',t=>{
|
|
101
|
+
const f=fixture(t);f.put('app.py','new\n');
|
|
102
|
+
const prior=process.env.GITLEAKS_CONFIG,priorSecret=process.env.CM_TEST_PRIVATE_VALUE;
|
|
103
|
+
process.env.GITLEAKS_CONFIG='malicious';process.env.CM_TEST_PRIVATE_VALUE='private';
|
|
104
|
+
t.after(()=>{if(prior===undefined)delete process.env.GITLEAKS_CONFIG;else process.env.GITLEAKS_CONFIG=prior;
|
|
105
|
+
if(priorSecret===undefined)delete process.env.CM_TEST_PRIVATE_VALUE;else process.env.CM_TEST_PRIVATE_VALUE=priorSecret;});
|
|
106
|
+
isolatedPath(t,f,{gitleaks:fakeLeak(`
|
|
107
|
+
if(process.env.GITLEAKS_CONFIG||process.env.CM_TEST_PRIVATE_VALUE)process.exit(8);
|
|
108
|
+
if(!args.includes('--redact=100')||!args.includes('--ignore-gitleaks-allow'))process.exit(9);
|
|
109
|
+
fs.writeFileSync(args[args.indexOf('--report-path')+1],JSON.stringify([{File:'worktree/app.py',StartLine:1,RuleID:'fixture-rule',Secret:'PRIVATE_VALUE'}]));
|
|
110
|
+
console.error('PRIVATE_VALUE');process.exit(1);`)});
|
|
111
|
+
const r=scan(f.project);assert.equal(r.result,'FINDINGS');assert.equal(r.findings.length,1);
|
|
112
|
+
assert.equal(r.sourceUnchanged,true);assert.ok(!JSON.stringify(r).includes('PRIVATE_VALUE'));
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
for(const [name,body,reason] of [
|
|
116
|
+
['malformed',`fs.writeFileSync(args[args.indexOf('--report-path')+1],'{bad');`,'invalid_or_incomplete_report'],
|
|
117
|
+
['empty-nonzero',`fs.writeFileSync(args[args.indexOf('--report-path')+1],'[]');process.exit(1);`,'invalid_or_incomplete_report'],
|
|
118
|
+
['error',`console.error('sensitive-error');process.exit(2);`,'execution_failed'],
|
|
119
|
+
['timeout',`while(true){}`,'timeout'],
|
|
120
|
+
])test(`scanner ${name} cannot become a clean result`,t=>{
|
|
121
|
+
const f=fixture(t);f.put('app.py','new');isolatedPath(t,f,{gitleaks:fakeLeak(body)});
|
|
122
|
+
const r=scan(f.project,{timeoutMs:name==='timeout'?100:5000});
|
|
123
|
+
assert.equal(r.tools[0].status,'ERROR');assert.equal(r.tools[0].reason,reason);
|
|
124
|
+
assert.equal(r.coverage,'PARTIAL');assert.ok(!JSON.stringify(r).includes('sensitive-error'));
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test('source mutation by a faulty external scanner blocks the result',t=>{
|
|
128
|
+
const f=fixture(t);f.put('app.py','new');
|
|
129
|
+
isolatedPath(t,f,{gitleaks:fakeLeak(`fs.writeFileSync(${JSON.stringify(path.join(f.project,'app.py'))},'changed again');fs.writeFileSync(args[args.indexOf('--report-path')+1],'[]');`)});
|
|
130
|
+
const r=scan(f.project);assert.equal(r.result,'BLOCKED');assert.equal(r.sourceUnchanged,false);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test('optional scanners require explicit local inputs and OSV remains offline',t=>{
|
|
134
|
+
const f=fixture(t);f.put('package-lock.json','{}\n');f.git('add','.');
|
|
135
|
+
const rules=path.join(f.base,'rules.yaml');fs.writeFileSync(rules,'rules: []');const db=path.join(f.base,'db');fs.mkdirSync(db);
|
|
136
|
+
isolatedPath(t,f,{
|
|
137
|
+
semgrep:fakeLeak(`if(!args.includes('--metrics=off')||!args.includes('--disable-nosem'))process.exit(8);console.log(JSON.stringify({results:[],errors:[],paths:{scanned:[]}}));`),
|
|
138
|
+
'osv-scanner':fakeLeak(`if(!args.includes('--offline')||!process.env.OSV_SCANNER_LOCAL_DB_CACHE_DIRECTORY)process.exit(8);console.log(JSON.stringify({results:[]}));`),
|
|
139
|
+
});
|
|
140
|
+
let r=scan(f.project);assert.equal(r.tools[1].reason,'local_rules_required');assert.equal(r.tools[2].reason,'offline_database_required');
|
|
141
|
+
r=scan(f.project,{semgrepRules:rules,osvDb:db});assert.equal(r.tools[1].reason,'unscanned_files');
|
|
142
|
+
assert.equal(r.tools[2].reason,'offline_database_freshness_and_ecosystem_coverage_unverified');
|
|
143
|
+
f.put('rules.yaml','rules: []');assert.throws(()=>scan(f.project,{semgrepRules:path.join(f.project,'rules.yaml')}),/external/);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test('installed Gitleaks smoke: synthetic key, negative control, source unchanged, no raw secret',t=>{
|
|
147
|
+
const probe=spawnSync('gitleaks',['version'],{encoding:'utf8'});
|
|
148
|
+
if(probe.error||probe.status!==0){t.skip('Gitleaks not installed; adapter fixtures still run');return;}
|
|
149
|
+
const f=fixture(t),secret='gh'+'p_'+crypto.createHash('sha256').update('cm-security-inert-example').digest('hex').slice(0,36);
|
|
150
|
+
f.put('fixture.txt',`value = "${secret}"\n`);f.put('safe.py','import os\nvalue = os.getenv("ACCESS_TOKEN")\n');f.git('add','.');
|
|
151
|
+
const r=scan(f.project);
|
|
152
|
+
assert.equal(r.tools[0].status,'FINDINGS');assert.ok(r.findings.some(v=>v.path==='fixture.txt'));
|
|
153
|
+
assert.ok(!r.findings.some(v=>v.path==='safe.py'));assert.ok(!JSON.stringify(r).includes(secret));assert.equal(r.sourceUnchanged,true);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test('CLI returns a machine-readable blocked result without echoing bad arguments',()=>{
|
|
157
|
+
const r=spawnSync(process.execPath,[path.join(root,'scripts/cm-security.mjs'),'--arbitrary-sensitive-value'],{encoding:'utf8'});
|
|
158
|
+
assert.equal(r.status,2);assert.equal(JSON.parse(r.stdout).result,'BLOCKED');assert.ok(!r.stdout.includes('sensitive-value'));
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test('clean/process filters cannot execute and required filters are disabled',t=>{
|
|
162
|
+
const f=fixture(t),marker=path.join(f.base,'filter-called');
|
|
163
|
+
const driver=path.join(f.base,'driver');fs.writeFileSync(driver,`#!/bin/sh\ntouch '${marker}'\ncat\n`,{mode:0o700});
|
|
164
|
+
f.put('.gitattributes','app.py filter=probe\n');f.git('add','.');f.git('commit','-m','attributes');
|
|
165
|
+
f.put('app.py','modified raw content\n');
|
|
166
|
+
f.git('config','filter.probe.clean',driver);f.git('config','filter.probe.required','true');
|
|
167
|
+
assert.ok(inventory(f.project).selected.includes('app.py'));assert.ok(!fs.existsSync(marker));
|
|
168
|
+
f.git('config','filter.probe.process',driver);
|
|
169
|
+
assert.ok(inventory(f.project).selected.includes('app.py'));assert.ok(!fs.existsSync(marker));
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test('Git lookup skips project binaries and child PATH excludes project directories',t=>{
|
|
173
|
+
const f=fixture(t),marker=path.join(f.base,'git-called');
|
|
174
|
+
f.put('bin/git',`#!/bin/sh\ntouch '${marker}'\nexec '${gitBin}' "$@"\n`);fs.chmodSync(path.join(f.project,'bin/git'),0o700);
|
|
175
|
+
const old=process.env.PATH;process.env.PATH=path.join(f.project,'bin')+path.delimiter+old;t.after(()=>{process.env.PATH=old;});
|
|
176
|
+
inventory(f.project);assert.ok(!fs.existsSync(marker));
|
|
177
|
+
fs.mkdirSync(path.join(f.project,'nested'));
|
|
178
|
+
assert.throws(()=>inventory(path.join(f.project,'nested')),/root_required/);
|
|
179
|
+
assert.ok(!fs.existsSync(marker));
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
test('untracked and ignored business maps are never read or hashed',t=>{
|
|
183
|
+
const f=fixture(t);f.put('docs/architecture.md','private map');
|
|
184
|
+
let r=inventory(f.project,{all:true});assert.equal(r.mapEvidence[0].sha256,null);
|
|
185
|
+
assert.equal(r.mapEvidence[0].status,'untracked_or_nonregular_excluded');
|
|
186
|
+
f.put('.gitignore','docs/architecture.md\n');r=inventory(f.project,{all:true});assert.equal(r.mapEvidence[0].sha256,null);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test('deleted tracked paths cannot pull same-name untracked private content into a scan',t=>{
|
|
190
|
+
const f=fixture(t);f.git('rm','--cached','app.py');f.put('app.py','NEW_UNTRACKED_PRIVATE');
|
|
191
|
+
let r=inventory(f.project);assert.equal(r.untracked,1);assert.ok(!r.files.some(v=>v.path==='app.py'));
|
|
192
|
+
assert.ok(r.gaps.some(v=>v.path==='app.py'&&v.reason==='deleted_review_baseline'));
|
|
193
|
+
f.git('commit','-m','remove');r=inventory(f.project);assert.ok(!r.files.some(v=>v.path==='app.py'));
|
|
194
|
+
assert.ok(!JSON.stringify(r).includes('NEW_UNTRACKED_PRIVATE'));
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
test('empty initial scope never overrides concurrent source drift with NO_CHANGES',t=>{
|
|
198
|
+
const f=fixture(t);isolatedPath(t,f);
|
|
199
|
+
const original=fs.mkdtempSync;
|
|
200
|
+
fs.mkdtempSync=(...args)=>{const result=original(...args);f.put('app.py','changed during scan');return result;};
|
|
201
|
+
try{const r=scan(f.project);assert.equal(r.sourceUnchanged,false);assert.equal(r.result,'BLOCKED');}
|
|
202
|
+
finally{fs.mkdtempSync=original;}
|
|
203
|
+
});
|
|
@@ -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
|
|
package/scripts/cm-test-host.mjs
CHANGED
|
@@ -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
|
+
});
|
|
@@ -16,6 +16,7 @@ CORE_SKILLS = (
|
|
|
16
16
|
"cm-prd",
|
|
17
17
|
"cm-ai",
|
|
18
18
|
"cm-test",
|
|
19
|
+
"cm-security",
|
|
19
20
|
"cm-fix",
|
|
20
21
|
"cm-refactor",
|
|
21
22
|
"cm-check",
|
|
@@ -162,7 +163,7 @@ def main() -> int:
|
|
|
162
163
|
pi_manifest = {}
|
|
163
164
|
expected_pi_skills = [f"./skills/{name}" for name in sorted(CORE_SKILLS)]
|
|
164
165
|
if pi_manifest.get("skills") != expected_pi_skills:
|
|
165
|
-
fail("Pi package skills must expose exactly the
|
|
166
|
+
fail("Pi package skills must expose exactly the registered core Skills", failures)
|
|
166
167
|
if pi_manifest.get("prompts") != ["./compat/claude-commands"]:
|
|
167
168
|
fail("Pi package prompts must point to ./compat/claude-commands", failures)
|
|
168
169
|
|