@aibyzero/cm-workflow 0.10.5 → 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 (48) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +1 -0
  3. package/CHANGELOG.md +51 -0
  4. package/CONTRIBUTING.md +12 -1
  5. package/README.md +21 -5
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +40 -1
  8. package/docs/installation.md +19 -9
  9. package/docs/user-guide.md +8 -1
  10. package/install-codex.sh +1 -1
  11. package/package.json +2 -1
  12. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  13. package/runtime/js/cm-ai/review-result.schema.json +0 -1
  14. package/runtime/js/cm-fix/execution.mjs +2 -2
  15. package/runtime/js/cm-fix/repair.mjs +6 -2
  16. package/runtime/js/cm-test/branch-impact.mjs +145 -0
  17. package/runtime/js/cm-test/host.mjs +28 -8
  18. package/runtime/js/cm-test/unit-coverage.mjs +206 -0
  19. package/runtime/project-context.md +6 -0
  20. package/scripts/cm-check-runtime.sh +18 -0
  21. package/scripts/cm-evolution-analyze.py +576 -0
  22. package/scripts/cm-fix-repair-owner.test.mjs +24 -6
  23. package/scripts/cm-fix-repair.test.mjs +9 -2
  24. package/scripts/cm-fix-review-baseline.test.mjs +19 -1
  25. package/scripts/cm-release-smoke.sh +76 -0
  26. package/scripts/cm-review-schema.test.mjs +15 -0
  27. package/scripts/cm-test-branch-impact.test.mjs +186 -0
  28. package/scripts/cm-test-entry.mjs +6 -1
  29. package/scripts/cm-test-host.mjs +2 -2
  30. package/scripts/cm-unit-coverage.mjs +16 -0
  31. package/scripts/cm-unit-coverage.test.mjs +126 -0
  32. package/scripts/scan-public-safety.py +5 -5
  33. package/scripts/test-cm-evolution-analyze.py +870 -0
  34. package/scripts/test-scan-public-safety.py +59 -1
  35. package/scripts/validate-public-repo.py +25 -0
  36. package/skills/cm-ai/references/N3-execute-task.md +12 -1
  37. package/skills/cm-ai/references/N8-finish.md +5 -4
  38. package/skills/cm-doc-syncer/SKILL.md +22 -3
  39. package/skills/cm-fix/SKILL.md +11 -2
  40. package/skills/cm-fix/references/js-host.md +4 -0
  41. package/skills/cm-prd/SKILL.md +3 -3
  42. package/skills/cm-prd/references/context-scope.md +17 -13
  43. package/skills/cm-test/SKILL.md +24 -7
  44. package/skills/cm-test/references/branch-impact.md +70 -0
  45. package/skills/cm-test/references/js-host.md +14 -2
  46. package/skills/cm-test/references/unit-coverage.md +97 -0
  47. package/skills/codebase-context/SKILL.md +11 -24
  48. package/skills/codebase-context/references/writeback.md +66 -0
@@ -11,7 +11,7 @@ import {createFixRegression} from '../runtime/js/cm-fix/regression.mjs';
11
11
  import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
12
12
 
13
13
  test('host minimal repair preserves tests and real red-to-green regression, rejecting unauthorized/no-op/test edits',async()=>{
14
- for(const mode of ['repaired','test-edit','no-op','not-ready']){
14
+ for(const mode of ['repaired','test-edit','map-outside','no-op','not-ready']){
15
15
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-repair-')));
16
16
  const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);fs.mkdirSync(path.join(specsRoot,'.reviews'));
17
17
  fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
@@ -26,6 +26,10 @@ test('host minimal repair preserves tests and real red-to-green regression, reje
26
26
  writes++;
27
27
  if(mode!=='no-op')fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=2;');
28
28
  if(mode==='test-edit')fs.writeFileSync(path.join(cwd,'red.mjs'),'// fake passing test');
29
+ if(mode==='map-outside'){
30
+ fs.mkdirSync(path.join(cwd,'docs/codebase-context'),{recursive:true});
31
+ fs.writeFileSync(path.join(cwd,'docs/codebase-context/00-index.md'),'# Unapproved map');
32
+ }
29
33
  bridge.accept({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result:{outcome:'repaired'}});
30
34
  });
31
35
  try{
@@ -35,6 +39,9 @@ test('host minimal repair preserves tests and real red-to-green regression, reje
35
39
  diagnosis:{status:'diagnosed',affectedPaths:['value.mjs','red.mjs'],rootCause:'Wrong constant'},redTest,baseline,redEvidence,beforeBaseline};
36
40
  const capabilities={bridge,assertReviewReady(){ready++;if(mode==='not-ready')throw Object.assign(new Error('not ready'),{code:'review_unavailable'});}};
37
41
  assert.throws(()=>prepareFixRepair({...options,scope:['red.mjs']},capabilities),{code:'repair_test_scope_forbidden'});
42
+ for(const file of ['docs/unrelated.md','docs/codebase-context/extra.md','docs/codebase-context/.scan-meta.json']){
43
+ assert.throws(()=>prepareFixRepair({...options,scope:['value.mjs',file]},capabilities),{code:'repair_scope_mismatch'});
44
+ }
38
45
  const repair=prepareFixRepair(options,capabilities);
39
46
  const control={authorized:true,signal,register(value){registered++;assert.equal(value.baselineDigest,repair.baseline.baselineDigest);}};
40
47
  await assert.rejects(repair.execute({...control,authorized:false}),{code:'repair_authorization_required'});
@@ -44,7 +51,7 @@ test('host minimal repair preserves tests and real red-to-green regression, reje
44
51
  assert.equal(regression.status,'passed');assert.equal(regression.completionEligible,false);
45
52
  await assert.rejects(repair.execute(control),{code:'repair_already_attempted'});
46
53
  }else{
47
- await assert.rejects(repair.execute(control),{code:mode==='test-edit'?'red_test_files_changed':mode==='no-op'?'repair_no_changes':'review_unavailable'});
54
+ await assert.rejects(repair.execute(control),{code:mode==='test-edit'?'red_test_files_changed':mode==='map-outside'?'out_of_scope':mode==='no-op'?'repair_no_changes':'review_unavailable'});
48
55
  if(mode==='not-ready'){assert.equal(writes,0);assert.equal(registered,0);}
49
56
  }
50
57
  }finally{bridge.close();fs.rmSync(root,{recursive:true,force:true});}
@@ -15,6 +15,9 @@ test('one original review baseline includes authored test and business repair, r
15
15
  const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(cwd);fs.mkdirSync(specsRoot);
16
16
  fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
17
17
  fs.writeFileSync(path.join(cwd,'requirements.md'),'fixture');
18
+ fs.mkdirSync(path.join(cwd,'docs'));
19
+ const mapPath='docs/map.md',mapBody='# Map\nA caller reads the numeric value; the relationship is unchanged.\n';
20
+ fs.writeFileSync(path.join(cwd,mapPath),mapBody);
18
21
  const identity={repositoryId:'fixture',runId:'combined-review',taskId:'T-FIX-demo',attempt:1};
19
22
  const options={codeProject:cwd,specsRoot,identity,testFiles:['red.mjs'],requirements:['requirements.md'],defect:'Constant bug',diagnosis:{},reproduction:{}};
20
23
  try{
@@ -22,7 +25,7 @@ test('one original review baseline includes authored test and business repair, r
22
25
  fs.writeFileSync(path.join(cwd,'red.mjs'),"import {value} from './value.mjs';if(value!==2)process.exit(1)");return {outcome:'authored'};
23
26
  }}});
24
27
  const authorResult=await author.execute({authorized:true,signal:new AbortController().signal,register(){}});
25
- const capture=()=>captureReviewBaseline({root:cwd,specsRoot,identity,scope:['value.mjs'],requirements:['value.mjs']});
28
+ const capture=()=>captureReviewBaseline({root:cwd,specsRoot,identity,scope:['value.mjs'],requirements:['value.mjs',mapPath]});
26
29
  const repairBaseline=capture();
27
30
  const input={authorBaseline:author.baseline,authorResult,repairBaseline};
28
31
  const combined=composeFixReviewBaseline(input);
@@ -32,6 +35,13 @@ test('one original review baseline includes authored test and business repair, r
32
35
  const checks=await createHostCheck({cwd,commands:[{id:'target',command:[process.execPath,'red.mjs']}]})({identity},{signal:new AbortController().signal});
33
36
  assert.equal(checks[0].outcome,'passed');
34
37
  const pkg=createReviewPackage({root:cwd,baseline:combined,checks});
38
+ const map=pkg.requirements.find(file=>file.path===mapPath);
39
+ assert(map,'unchanged referenced maps must reach independent Review as read-only material');
40
+ assert.equal(Buffer.from(map.contentBase64,'base64').toString(),mapBody);
41
+ assert(!pkg.scope.includes(mapPath));assert(!pkg.changes.some(change=>change.path===mapPath));
42
+ fs.writeFileSync(path.join(cwd,mapPath),'unapproved rewrite');
43
+ assert.throws(()=>createReviewPackage({root:cwd,baseline:combined,checks}),{code:'out_of_scope'});
44
+ fs.writeFileSync(path.join(cwd,mapPath),mapBody);
35
45
  assert.deepEqual(pkg.changes.map(change=>change.path),['red.mjs','value.mjs']);
36
46
  assert.equal(pkg.changes[0].before,null);assert.equal(pkg.changes[1].before.contentBase64,Buffer.from('export const value=1;').toString('base64'));
37
47
  assert.throws(()=>composeFixReviewBaseline({...input,repairBaseline:capture()}),{code:'fix_review_interstage_drift'});
@@ -43,6 +53,7 @@ test('one original review baseline includes authored test and business repair, r
43
53
  const continued=continueFixReviewBaseline(expanded,nextIdentity);
44
54
  assert.deepEqual(continued.files,expanded.files);assert.deepEqual(continued.scope,expanded.scope);
45
55
  const cumulative=createReviewPackage({root:cwd,baseline:continued,checks});
56
+ assert.equal(Buffer.from(cumulative.requirements.find(file=>file.path===mapPath).contentBase64,'base64').toString(),mapBody);
46
57
  assert.equal(cumulative.identity.attempt,2);
47
58
  assert.deepEqual(cumulative.changes.map(change=>change.path),['AGENTS.md','red.mjs','value.mjs']);
48
59
  assert.equal(cumulative.changes[0].before,null);assert.equal(cumulative.changes[1].before,null);
@@ -50,5 +61,12 @@ test('one original review baseline includes authored test and business repair, r
50
61
  assert.match(Buffer.from(cumulative.changes[2].after.contentBase64,'base64').toString(),/second repair/);
51
62
  assert.throws(()=>continueFixReviewBaseline(expanded,{...nextIdentity,runId:'different'}),{code:'fix_review_baseline_mismatch'});
52
63
  assert.throws(()=>continueFixReviewBaseline(continued,nextIdentity),{code:'fix_review_baseline_mismatch'});
64
+ // An approved map deletion needs its before image, not an after-file requirement.
65
+ const deletionBaseline=captureReviewBaseline({root:cwd,specsRoot,identity,scope:[mapPath],requirements:['value.mjs']});
66
+ fs.unlinkSync(path.join(cwd,mapPath));
67
+ const deleted=createReviewPackage({root:cwd,baseline:deletionBaseline,checks});
68
+ assert.equal(deleted.changes.length,1);assert.equal(deleted.changes[0].after,null);
69
+ assert.equal(Buffer.from(deleted.changes[0].before.contentBase64,'base64').toString(),mapBody);
70
+ assert(!deleted.requirements.some(file=>file.path===mapPath));
53
71
  }finally{fs.rmSync(root,{recursive:true,force:true});}
54
72
  });
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env bash
2
+ # Release-only smoke for the BYZ-managed package and Codex plugin surfaces.
3
+ set -euo pipefail
4
+
5
+ ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
6
+ SOURCE_CODEX_HOME="${CODEX_HOME:-$HOME/.codex}"
7
+ SOURCE_CREATOR="$SOURCE_CODEX_HOME/skills/.system/plugin-creator"
8
+ TMP_ROOT=""
9
+ PYTHON_BIN=""
10
+
11
+ blocked() {
12
+ echo "cm release surface smoke: BLOCKED ($1)" >&2
13
+ exit 2
14
+ }
15
+
16
+ fail() {
17
+ echo "cm release surface smoke: FAILED ($1)" >&2
18
+ exit 1
19
+ }
20
+
21
+ cleanup() {
22
+ status=$?
23
+ trap - EXIT HUP INT TERM
24
+ if [ -n "$TMP_ROOT" ] && [ -d "$TMP_ROOT" ]; then
25
+ rm -rf "$TMP_ROOT"
26
+ fi
27
+ exit "$status"
28
+ }
29
+ trap cleanup EXIT
30
+ trap 'exit 129' HUP
31
+ trap 'exit 130' INT
32
+ trap 'exit 143' TERM
33
+
34
+ command -v byz >/dev/null 2>&1 || blocked "byz command not found"
35
+ command -v codex >/dev/null 2>&1 || blocked "codex command not found"
36
+ [ -d "$SOURCE_CREATOR" ] || blocked "Codex plugin creator not found at $SOURCE_CREATOR"
37
+ for candidate in python3 python; do
38
+ if command -v "$candidate" >/dev/null 2>&1 &&
39
+ "$candidate" -c 'import sys; raise SystemExit(sys.version_info < (3, 9))' >/dev/null 2>&1; then
40
+ PYTHON_BIN="$(command -v "$candidate")"
41
+ break
42
+ fi
43
+ done
44
+ [ -n "$PYTHON_BIN" ] || blocked "Python 3.9+ not found"
45
+
46
+ printf '%s\n' '==> Validating the public Pi/BYZ package manifest'
47
+ "$PYTHON_BIN" "$ROOT/scripts/validate-public-repo.py"
48
+
49
+ printf '%s\n' '==> Checking the local workflow root through BYZ'
50
+ BYZ_CM_WORKFLOW_ROOT="$ROOT" byz workflow check cm
51
+
52
+ TMP_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/cm-release-smoke.XXXXXX")"
53
+ TEMP_HOME="$TMP_ROOT/home"
54
+ TEMP_CODEX_HOME="$TEMP_HOME/.codex"
55
+ mkdir -p "$TEMP_CODEX_HOME/skills/.system"
56
+ cp -R "$SOURCE_CREATOR" "$TEMP_CODEX_HOME/skills/.system/plugin-creator"
57
+
58
+ printf '%s\n' '==> Installing the Codex plugin in a disposable home'
59
+ HOME="$TEMP_HOME" CODEX_HOME="$TEMP_CODEX_HOME" \
60
+ "$ROOT/install-codex.sh" --yes
61
+
62
+ PLUGIN_LIST="$(HOME="$TEMP_HOME" CODEX_HOME="$TEMP_CODEX_HOME" codex plugin list)"
63
+ printf '%s\n' "$PLUGIN_LIST"
64
+ printf '%s\n' "$PLUGIN_LIST" |
65
+ grep -Eq '^cm-workflow@personal[[:space:]]+installed, enabled' ||
66
+ fail "Codex did not report cm-workflow@personal as installed and enabled"
67
+
68
+ HOME="$TEMP_HOME" CODEX_HOME="$TEMP_CODEX_HOME" \
69
+ "$TEMP_HOME/plugins/cm-workflow/scripts/cm-check-runtime.sh" \
70
+ --project "$TEMP_HOME/plugins/cm-workflow"
71
+
72
+ [ -f "$TEMP_HOME/plugins/cm-workflow/CHANGELOG.md" ] || fail "installed changelog missing"
73
+ cmp -s "$ROOT/CHANGELOG.md" "$TEMP_HOME/plugins/cm-workflow/CHANGELOG.md" || fail "installed changelog differs from source"
74
+
75
+ VERSION="$(tr -d '[:space:]' < "$ROOT/VERSION")"
76
+ echo "cm release surface smoke: PASSED (v${VERSION})"
@@ -0,0 +1,15 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import {reviewResult} from '../runtime/js/cm-ai/review-runner.mjs';
5
+
6
+ test('provider schema avoids unsupported uniqueness keyword; local gate rejects duplicate or missing paths',()=>{
7
+ const schema=JSON.parse(fs.readFileSync(new URL('../runtime/js/cm-ai/review-result.schema.json',import.meta.url),'utf8'));
8
+ assert.equal(Object.hasOwn(schema.properties.examinedPaths,'uniqueItems'),false);
9
+ const pkg={packageDigest:'a'.repeat(64),changes:[{path:'code.mjs'}],requirements:[{path:'requirements.md'}]};
10
+ const result={verdict:'approved',packageDigest:pkg.packageDigest,examinedPaths:['code.mjs','requirements.md'],findings:[],summary:'Reviewed both files'};
11
+ assert.equal(reviewResult(result,pkg).verdict,'approved');
12
+ for(const examinedPaths of [['code.mjs','code.mjs','requirements.md'],['code.mjs'],['code.mjs','requirements.md','other.mjs']]){
13
+ assert.throws(()=>reviewResult({...result,examinedPaths},pkg),/missing_material/);
14
+ }
15
+ });
@@ -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
+ });
@@ -11,10 +11,10 @@ from pathlib import Path
11
11
 
12
12
  ROOT = Path(__file__).resolve().parent.parent
13
13
  SELF = Path(__file__).resolve()
14
- SKIP_DIRS = {".git", ".omx"}
14
+ SKIP_DIRS = {".git"}
15
15
  SKIP_SUFFIXES = {".png", ".gif", ".jpg", ".jpeg", ".mp4", ".woff", ".woff2"}
16
16
  PATTERNS = {
17
- "private key": re.compile(r"-----BEGIN (?:RSA|EC|OPENSSH|DSA|PGP) PRIVATE KEY-----"),
17
+ "private key": re.compile(r"-----BEGIN (?:(?:RSA|EC|OPENSSH|DSA|PGP|ENCRYPTED) )?PRIVATE KEY-----"),
18
18
  "AWS access key": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
19
19
  "GitHub token": re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})\b"),
20
20
  "OpenAI-style key": re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b"),
@@ -66,7 +66,7 @@ def reviewed_loopback(relative: Path, text: str, offset: int) -> bool:
66
66
  def main() -> int:
67
67
  findings: list[str] = []
68
68
  tracked_result = subprocess.run(
69
- ["git", "ls-files", "-z", "--", ".omx"],
69
+ ["git", "ls-files", "-z"],
70
70
  cwd=ROOT,
71
71
  stdout=subprocess.PIPE,
72
72
  stderr=subprocess.DEVNULL,
@@ -81,9 +81,9 @@ def main() -> int:
81
81
  }
82
82
 
83
83
  for path in sorted(ROOT.rglob("*")):
84
- if path == SELF or not path.is_file() or any(part in SKIP_DIRS for part in path.parts):
85
- continue
86
84
  relative = path.relative_to(ROOT)
85
+ if path == SELF or not path.is_file() or any(part in SKIP_DIRS for part in relative.parts):
86
+ continue
87
87
  # OMX execution state is machine-local and normally ignored. Skip only
88
88
  # untracked state; an accidentally tracked `.omx` file remains public
89
89
  # package content and must still be scanned. If Git lookup fails, scan