@aibyzero/cm-workflow 0.16.2 → 0.16.4
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 +4 -0
- package/CHANGELOG.md +147 -0
- package/README.md +44 -3
- package/VERSION +1 -1
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +46 -7
- package/docs/next-steps.md +100 -0
- package/docs/untested-branches.md +24 -18
- package/package.json +1 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +18 -0
- package/runtime/js/cm-ai/claude-tool-preview.mjs +45 -6
- package/runtime/js/cm-ai/cm-ai-admission.mjs +7 -1
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +22 -12
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +70 -5
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +5 -5
- package/runtime/js/cm-ai/drive-core.mjs +68 -0
- package/runtime/js/cm-ai/durable-runner-state.mjs +42 -9
- package/runtime/js/cm-ai/effect-contract.mjs +4 -3
- package/runtime/js/cm-ai/execution-snapshot.mjs +40 -0
- package/runtime/js/cm-ai/host-conversation-execution.mjs +8 -5
- package/runtime/js/cm-ai/host-handoff.mjs +9 -14
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +12 -7
- package/runtime/js/cm-ai/host-session.mjs +10 -3
- package/runtime/js/cm-ai/host.mjs +1 -1
- package/runtime/js/cm-ai/qa-config-revision.mjs +85 -0
- package/runtime/js/cm-ai/review-evidence-file.mjs +18 -1
- package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +144 -0
- package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +34 -0
- package/runtime/js/cm-ai/task-runner.mjs +41 -8
- package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
- package/runtime/js/cm-fix/cause-invocation.mjs +9 -5
- package/runtime/js/cm-fix/cause-package.mjs +21 -0
- package/runtime/js/cm-fix/dossier.mjs +40 -1
- package/runtime/js/cm-fix/execution.mjs +360 -83
- package/runtime/js/cm-fix/host.mjs +7 -3
- package/runtime/js/cm-fix/layout.mjs +14 -6
- package/runtime/js/cm-fix/progress.mjs +14 -0
- package/runtime/js/cm-fix/protected-edits.mjs +1 -1
- package/runtime/js/cm-fix/red-test.mjs +7 -6
- package/runtime/js/cm-fix/regression-evidence.mjs +6 -3
- package/runtime/js/cm-fix/regression.mjs +16 -10
- package/runtime/js/cm-fix/repair.mjs +16 -13
- package/runtime/js/cm-fix/test-author.mjs +2 -1
- package/runtime/js/cm-fix/test-extension.mjs +45 -0
- package/runtime/js/cm-prd/accepted-design.mjs +28 -9
- package/runtime/js/cm-prd/analysis.mjs +68 -16
- package/runtime/js/cm-prd/change.mjs +21 -1
- package/runtime/js/cm-prd/draft-save.mjs +96 -2
- package/runtime/js/cm-prd/failed-correction.mjs +51 -0
- package/runtime/js/cm-prd/inputs-replaced.mjs +122 -0
- package/runtime/js/cm-prd/review-correction.mjs +3 -0
- package/runtime/js/cm-prd/review-disposition.mjs +33 -15
- package/runtime/js/cm-prd/review-findings.mjs +2 -2
- package/runtime/js/cm-prd/review-host.mjs +2 -0
- package/runtime/js/cm-prd/review-preparation.mjs +28 -1
- package/runtime/js/cm-prd/review-publication.mjs +4 -2
- package/runtime/js/cm-prd/self-check-revision.mjs +81 -0
- package/runtime/js/cm-prd/session.mjs +5 -5
- package/runtime/js/cm-prd/split-design.mjs +67 -0
- package/runtime/js/cm-prd/summary.mjs +57 -10
- package/runtime/js/cm-refactor/workflow.mjs +100 -19
- package/runtime/js/specs-status.mjs +6 -2
- package/scripts/cm-ai-admission.mjs +2 -0
- package/scripts/cm-ai-batch-drive.mjs +251 -0
- package/scripts/cm-ai-batch-drive.test.mjs +159 -0
- package/scripts/cm-ai-batch-host.mjs +13 -5
- package/scripts/cm-ai-batch-host.test.mjs +25 -0
- package/scripts/cm-ai-contracts.test.mjs +30 -0
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +62 -0
- package/scripts/cm-ai-drive.mjs +335 -0
- package/scripts/cm-ai-drive.test.mjs +258 -0
- package/scripts/cm-ai-fix-integration.test.mjs +1 -1
- package/scripts/cm-ai-host.mjs +48 -20
- package/scripts/cm-ai-host.test.mjs +79 -0
- package/scripts/cm-ai-qa-config-revision.test.mjs +328 -0
- package/scripts/cm-ai-qa-fix-cross-session.test.mjs +255 -0
- package/scripts/cm-ai-qa-fix-policy.test.mjs +79 -0
- package/scripts/cm-ai-review-timeout.test.mjs +30 -0
- package/scripts/cm-ai-run.mjs +59 -11
- package/scripts/cm-ai-runner-error-code-regression.test.mjs +29 -0
- package/scripts/cm-ai-session-chain.test.mjs +261 -0
- package/scripts/cm-ai-supersede.test.mjs +320 -0
- package/scripts/cm-check-drive.mjs +94 -0
- package/scripts/cm-check-drive.test.mjs +78 -0
- package/scripts/cm-check-entry.mjs +13 -2
- package/scripts/cm-check-host.mjs +2 -2
- package/scripts/cm-check-host.test.mjs +103 -0
- package/scripts/cm-check-runtime.sh +15 -6
- package/scripts/cm-claude-developer-worker.test.mjs +40 -1
- package/scripts/cm-claude-probe.test.mjs +117 -2
- package/scripts/cm-claude-review-stream.test.mjs +43 -0
- package/scripts/cm-fix-abandon.test.mjs +383 -0
- package/scripts/cm-fix-cause-package.test.mjs +31 -1
- package/scripts/cm-fix-cross-session-host.test.mjs +17 -5
- package/scripts/cm-fix-drive.mjs +168 -0
- package/scripts/cm-fix-drive.test.mjs +117 -0
- package/scripts/cm-fix-escalation.test.mjs +214 -0
- package/scripts/cm-fix-execution.test.mjs +26 -0
- package/scripts/cm-fix-host.mjs +4 -2
- package/scripts/cm-fix-observation-dossier.test.mjs +34 -9
- package/scripts/cm-fix-qa-source.test.mjs +3 -3
- package/scripts/cm-fix-session-chain.test.mjs +244 -0
- package/scripts/cm-fix-test-extension.test.mjs +246 -0
- package/scripts/cm-fix-visual-carrier.test.mjs +66 -0
- package/scripts/cm-host-handoff.test.mjs +37 -0
- package/scripts/cm-idea-drive.mjs +99 -0
- package/scripts/cm-idea-drive.test.mjs +50 -0
- package/scripts/cm-init-drive.mjs +191 -0
- package/scripts/cm-init-drive.test.mjs +59 -0
- package/scripts/cm-log-event.mjs +9 -0
- package/scripts/cm-prd-completion.test.mjs +30 -2
- package/scripts/cm-prd-design-phase.test.mjs +355 -15
- package/scripts/cm-prd-drive.mjs +314 -0
- package/scripts/cm-prd-drive.test.mjs +164 -0
- package/scripts/cm-prd-host.mjs +46 -17
- package/scripts/cm-prd-inputs-replaced.test.mjs +237 -0
- package/scripts/cm-prd-review-disposition.test.mjs +133 -7
- package/scripts/cm-prd-review-gate.mjs +23 -4
- package/scripts/cm-prd-self-check-revision.test.mjs +302 -0
- package/scripts/cm-prd-summary.test.mjs +79 -4
- package/scripts/cm-refactor-drive.mjs +237 -0
- package/scripts/cm-refactor-drive.test.mjs +77 -0
- package/scripts/cm-refactor-gaps.test.mjs +276 -0
- package/scripts/cm-refactor-host.test.mjs +1 -48
- package/scripts/cm-refactor-judge-revision.test.mjs +253 -0
- package/scripts/cm-specs-status.test.mjs +19 -0
- package/scripts/cm-test-drive.mjs +132 -0
- package/scripts/cm-test-drive.test.mjs +91 -0
- package/scripts/cm-test-session.test.mjs +117 -0
- package/scripts/correction-check.test.mjs +38 -0
- package/scripts/fixtures/claude-model-marker.mjs +6 -0
- package/scripts/fixtures/claude-review-process.mjs +7 -0
- package/scripts/fixtures/cm-refactor.mjs +56 -0
- package/scripts/test-shell-compat.sh +67 -0
- package/skills/cm-ai/SKILL.md +1 -1
- package/skills/cm-ai/references/N4-review.md +2 -0
- package/skills/cm-ai/references/N8-finish.md +1 -0
- package/skills/cm-ai/references/js-host.md +85 -3
- package/skills/cm-check/SKILL.md +6 -1
- package/skills/cm-check/references/js-host.md +4 -2
- package/skills/cm-fix/SKILL.md +11 -4
- package/skills/cm-fix/references/js-host.md +67 -2
- package/skills/cm-fix/references/test-extension.md +57 -0
- package/skills/cm-idea/references/js-host.md +2 -0
- package/skills/cm-init/references/js-host.md +2 -0
- package/skills/cm-prd/SKILL.md +8 -8
- package/skills/cm-prd/references/js-change-recovery.md +71 -0
- package/skills/cm-prd/references/js-host.md +64 -2
- package/skills/cm-prd/references/spec-self-check.md +14 -2
- package/skills/cm-refactor/SKILL.md +5 -0
- package/skills/cm-refactor/references/js-batch.md +3 -1
- package/skills/cm-refactor/references/js-host.md +49 -0
- package/skills/cm-test/references/js-host.md +5 -0
- package/skills/cm-test/references/unit-coverage.md +2 -2
|
@@ -1,37 +1,14 @@
|
|
|
1
1
|
import test from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
3
|
import fs from 'node:fs';
|
|
4
|
-
import os from 'node:os';
|
|
5
4
|
import path from 'node:path';
|
|
6
5
|
import {spawn,spawnSync} from 'node:child_process';
|
|
7
6
|
import {once} from 'node:events';
|
|
8
7
|
import {createInterface} from 'node:readline';
|
|
9
8
|
import {fileURLToPath} from 'node:url';
|
|
10
9
|
import {createCmRefactorHost} from '../runtime/js/cm-refactor/host.mjs';
|
|
11
|
-
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
12
10
|
const root=fileURLToPath(new URL('..',import.meta.url));
|
|
13
|
-
|
|
14
|
-
const replacement='export function calc(x) { if (x < 0) return 0; return x + 1; }\n';
|
|
15
|
-
function fixture(t){
|
|
16
|
-
const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-refactor-host-'))),project=path.join(temp,'project');
|
|
17
|
-
fs.mkdirSync(project);fs.writeFileSync(path.join(project,'input.mjs'),original);
|
|
18
|
-
fs.writeFileSync(path.join(project,'baseline.mjs'),"import assert from 'node:assert/strict'; import {calc} from './input.mjs'; assert.equal(calc(-1),0); assert.equal(calc(2),3);\n");
|
|
19
|
-
fs.writeFileSync(path.join(project,'judge.mjs'),"import {calc} from './input.mjs'; console.log(JSON.stringify({cases:[-2,0,2].map((x,i)=>({id:String(i),input:x,output:calc(x)}))}));\n");
|
|
20
|
-
t.after(()=>fs.rmSync(temp,{recursive:true,force:true}));
|
|
21
|
-
return {temp,project,config:{skillDir:path.join(root,'skills/cm-refactor'),project,specs:null,runtime:'codex',
|
|
22
|
-
target:'Synthetic structure-only refactor',slug:'extract',scope:['input.mjs'],crossModule:false,
|
|
23
|
-
baselineCommands:[{id:'baseline',command:[process.execPath,'baseline.mjs']}],judgeCommand:[process.execPath,'judge.mjs'],
|
|
24
|
-
mutations:[{path:'input.mjs',find:'x + 1',replace:'x + 2'},{path:'input.mjs',find:'x < 0',replace:'x < -5'}],logHome:path.join(temp,'logs')}};
|
|
25
|
-
}
|
|
26
|
-
function response(kind,payload,mode='normal'){
|
|
27
|
-
if(kind==='refactor_analyze')return {decision:'proceed',metric:{name:'Synthetic nesting',before:2,unit:'levels'},impact:[],claimedMemos:[],reason:'Synthetic simplification'};
|
|
28
|
-
if(kind==='refactor_confirm')return {decision:mode==='reject'?'rejected':'approved'};
|
|
29
|
-
if(kind==='refactor_apply')return {files:[{path:'input.mjs',beforeDigest:digest(original),content:mode==='behavior-change'?replacement.replace('x + 1','x + 9'):replacement}],
|
|
30
|
-
summary:'Synthetic explicit function extraction',metricAfter:1,unfixedDefects:[],conventions:[],
|
|
31
|
-
learningApplication:'No additional relevant project lesson in this fixture',learningRetrospective:'no_new_lesson'};
|
|
32
|
-
assert.equal(kind,'refactor_review');
|
|
33
|
-
return {markdown:`---\nat: 2026-09-08T18:00:00+00:00\nreviewer: codex-subagent\nindependent: true\ntask: ${payload.task}\nattempt: ${payload.attempt}\nround: ${payload.attempt}\nverdict: approved\nblocking_findings: 0\nhandoff: ${path.basename(payload.handoff)}\nhandoff_sha256: ${mode==='stale-review'?'0'.repeat(64):payload.handoffSha256}\nscope:\n - input.mjs\n---\n\nZero findings in synthetic review; not a live independent reviewer invocation.\n`};
|
|
34
|
-
}
|
|
11
|
+
import {fixture,response,fullResponse,original,replacement} from './fixtures/cm-refactor.mjs';
|
|
35
12
|
test('light-track actual CLI: both runtimes use real baseline/mutations/differential and original gates',async t=>{
|
|
36
13
|
for(const runtime of ['codex','claude']){
|
|
37
14
|
const {config,temp,project}=fixture(t);config.runtime=runtime;
|
|
@@ -75,30 +52,6 @@ test('stale independent-review header cannot bypass existing N5',async t=>{
|
|
|
75
52
|
assert.equal(result.stage,'blocked');assert.match(result.reason,/digest/);
|
|
76
53
|
});
|
|
77
54
|
|
|
78
|
-
function fullResponse(kind,payload){
|
|
79
|
-
if(kind==='refactor_review'){
|
|
80
|
-
const value=response(kind,payload);value.markdown=value.markdown.replace(' - input.mjs',payload.files.map(file=>' - '+file.path).join('\n'));return value;
|
|
81
|
-
}
|
|
82
|
-
if(kind==='refactor_prepare_tests')return {files:payload.assets.map(file=>({...file,content:file.path==='baseline.mjs'
|
|
83
|
-
?"import assert from 'node:assert/strict'; import {calc} from './input.mjs'; assert.equal(calc(2),3);\n"
|
|
84
|
-
:"import {calc} from './input.mjs'; console.log(JSON.stringify({cases:[-2,0,2].map((x,i)=>({id:String(i),input:x,output:calc(x)}))}));\n"}))};
|
|
85
|
-
if(kind==='refactor_retrospective')return {learningApplication:'Apply original behavior contract',learning:{status:'lesson_candidate',reason:null,
|
|
86
|
-
candidates:[{classification:'structured',trigger:'Boundary-sensitive refactor',action:'Keep negative inputs in differential judge',evidence:['judge.mjs']}]},
|
|
87
|
-
conventions:[{path:'.claude/rules/shape.md',text:'Use named function exports.',evidence:['input.mjs']}],documentation:payload.files.filter(file=>file.path==='README.md')
|
|
88
|
-
.map(file=>({...file,content:(file.content??'')+'\nRefactored module structure.\n'})),resolved:(payload.needs??[]).map(item=>item.id),unfixedDefects:[],metricAfter:1};
|
|
89
|
-
if(kind==='refactor_batch'){
|
|
90
|
-
if(payload.action==='plan')return {rulebook:'Named functions; preserve values; do not fix bugs.',units:payload.files.filter(file=>!payload.assemblyFiles.includes(file.path))
|
|
91
|
-
.map((file,i)=>({id:`unit-${i}`,files:[file.path],dependsOn:i?[`unit-${i-1}`]:[]})),sample:['input.mjs'],perFileEstimate:300,reason:'Reduce nesting'};
|
|
92
|
-
if(payload.action==='bakeoff')return {channelId:payload.variant,files:payload.files.map(file=>({...file,content:replacement}))};
|
|
93
|
-
if(payload.action==='adjudicate')return {channelId:'third',rulebook:payload.rulebook,decisions:[]};
|
|
94
|
-
if(payload.action==='assemble')return {files:payload.files.map(file=>({...file,content:'export {calc} from "./input.mjs";\n'})),resolved:payload.needs.map(item=>item.id)};
|
|
95
|
-
if(payload.action==='generate')return {files:payload.files.map(file=>({...file,content:file.path==='old.mjs'?null:
|
|
96
|
-
(file.path==='input.mjs'?replacement:'export const helper = 1;\n')+'// REFACTOR STATUS: confidence=high todos=0\n'})),
|
|
97
|
-
needs:payload.files[0].path==='input.mjs'?[{id:'entry-wire',path:'entry.mjs',instruction:'Preserve entry export'}]:[],summary:'Structure only'};
|
|
98
|
-
if(payload.action==='diagnose')return {errorClass:'syntax',reason:'Same generator rule produces invalid syntax'};
|
|
99
|
-
}
|
|
100
|
-
return response(kind,payload);
|
|
101
|
-
}
|
|
102
55
|
async function finishInProcess(t,config,temp){
|
|
103
56
|
const configPath=path.join(temp,'resume-config.json');fs.writeFileSync(configPath,JSON.stringify(config));
|
|
104
57
|
const child=spawn(process.execPath,[path.join(root,'scripts/cm-refactor-host.mjs'),'serve','--config',configPath],{stdio:['pipe','pipe','pipe']});
|
|
@@ -0,0 +1,253 @@
|
|
|
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 {spawnSync} from 'node:child_process';
|
|
6
|
+
import {createCmRefactorHost} from '../runtime/js/cm-refactor/host.mjs';
|
|
7
|
+
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
8
|
+
import {fixture,fullResponse,original,replacement} from './fixtures/cm-refactor.mjs';
|
|
9
|
+
|
|
10
|
+
const revisedJudge="import {calc} from './input.mjs'; console.log(JSON.stringify({cases:[-2,0,2,3].map((x,i)=>({id:String(i),input:x,output:calc(x)}))}));\n";
|
|
11
|
+
const regression=replacement.replace('if (x < 0)', 'if (x === 3) return 99; if (x < 0)');
|
|
12
|
+
const request={paths:['judge.mjs'],reason:'Add missing boundary input 3 to judge.mjs.'};
|
|
13
|
+
function scenario(t,{first=replacement,second=first,revision=request,edit,reviewVerdict='changes_requested',hook}={}){
|
|
14
|
+
const value=fixture(t),{config,project}=value;config.testSetup={paths:['judge.mjs','baseline.mjs']};
|
|
15
|
+
const calls=[],directory=path.join(project,'docs/refactors/extract');
|
|
16
|
+
async function call(kind,payload){
|
|
17
|
+
calls.push({kind,payload});const override=await hook?.(kind,payload);if(override!==undefined)return override;
|
|
18
|
+
if(kind==='refactor_apply')return {...fullResponse(kind,payload),files:payload.files.map(file=>({...file,content:payload.attempt===1?first:second}))};
|
|
19
|
+
if(kind==='refactor_revise_tests')return edit?edit(payload):{files:payload.assets.map(file=>({...file,content:revisedJudge}))};
|
|
20
|
+
const result=fullResponse(kind,payload);
|
|
21
|
+
if(kind==='refactor_review'&&payload.attempt===1){
|
|
22
|
+
result.markdown=result.markdown.replace('verdict: approved',`verdict: ${reviewVerdict}`).replace('blocking_findings: 0',`blocking_findings: ${reviewVerdict==='approved'?0:1}`)+'\n'+request.reason+'\n';
|
|
23
|
+
if(revision!==undefined&&revision!==false)result.judgeRevision=revision;
|
|
24
|
+
}
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
return {...value,directory,calls,call,host:createCmRefactorHost(config,{call})};
|
|
28
|
+
}
|
|
29
|
+
const rows=directory=>fs.readFileSync(path.join(directory,'execution.jsonl'),'utf8').trimEnd().split('\n').map(JSON.parse);
|
|
30
|
+
const report=(directory,name)=>JSON.parse(fs.readFileSync(path.join(directory,name),'utf8').replace(/^```json\n/,'').replace(/\n```\n$/,''));
|
|
31
|
+
|
|
32
|
+
test('round 2 revises declared judge assets and rebuilds original and refactored evidence',async t=>{
|
|
33
|
+
const s=scenario(t);const result=await s.host.handle({operation:'start'});
|
|
34
|
+
assert.equal(result.stage,'awaiting_finish',JSON.stringify(result));
|
|
35
|
+
assert.equal(s.calls.filter(c=>c.kind==='refactor_revise_tests').length,1,'review-requested judge revision must run');
|
|
36
|
+
const request=s.calls.find(c=>c.kind==='refactor_revise_tests').payload;
|
|
37
|
+
assert.deepEqual(request.assets.map(a=>a.path),['judge.mjs']);
|
|
38
|
+
assert.equal(fs.readFileSync(path.join(s.project,'judge.mjs'),'utf8'),revisedJudge);
|
|
39
|
+
const old=report(s.directory,'judge-1-report.md'),fresh=report(s.directory,'a2-judge-1-report.md');
|
|
40
|
+
assert.equal(old.judgeBefore.cases.length,3);assert.equal(fresh.judgeBefore.cases.length,4);
|
|
41
|
+
assert.equal(fresh.judgeBefore.cases.at(-1).output,4);assert.equal(fresh.mutations.length,2);
|
|
42
|
+
assert.ok(fresh.mutations.every(m=>m.detected));
|
|
43
|
+
const comparison=report(s.directory,'a2-diff.md');assert.deepEqual(comparison.before,comparison.after);
|
|
44
|
+
assert.deepEqual(comparison.before,fresh.judgeBefore);
|
|
45
|
+
const reviewed=s.calls.find(c=>c.kind==='refactor_review'&&c.payload.attempt===2).payload;
|
|
46
|
+
assert.ok(reviewed.files.some(f=>f.path==='judge.mjs'&&f.after===revisedJudge));
|
|
47
|
+
assert.ok(reviewed.reports.includes(path.join(s.directory,'a2-judge-revision.md')));
|
|
48
|
+
const history=fs.readFileSync(path.join(s.directory,'execution.jsonl'),'utf8');
|
|
49
|
+
const evidence=Object.fromEntries(result.reports.map(file=>[file,fs.readFileSync(file,'utf8')]));
|
|
50
|
+
const reopened=createCmRefactorHost(s.config,{call:async()=>{throw Error('must replay without another author/review');}});
|
|
51
|
+
const resumed=await reopened.handle({operation:'resume'});assert.equal(resumed.stage,'awaiting_finish',JSON.stringify(resumed));
|
|
52
|
+
assert.ok(fs.readFileSync(path.join(s.directory,'execution.jsonl'),'utf8').startsWith(history));
|
|
53
|
+
for(const [file,bytes] of Object.entries(evidence))assert.equal(fs.readFileSync(file,'utf8'),bytes);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test('new boundary must not absorb a round-1 behavior regression into expected answers',async t=>{
|
|
57
|
+
const s=scenario(t,{first:regression});const result=await s.host.handle({operation:'start'});
|
|
58
|
+
assert.equal(result.reason,'refactor_behavior_changed');
|
|
59
|
+
assert.equal(s.calls.filter(c=>c.kind==='refactor_review').length,1);
|
|
60
|
+
assert.equal(report(s.directory,'a2-judge-1-report.md').judgeBefore.cases.at(-1).output,4);
|
|
61
|
+
assert.equal(report(s.directory,'a2-diff.md').after.cases.at(-1).output,99);
|
|
62
|
+
assert.equal(fs.readFileSync(path.join(s.project,'input.mjs'),'utf8'),original);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('round 2 can repair a newly exposed business regression before comparison',async t=>{
|
|
66
|
+
const s=scenario(t,{first:regression,second:replacement});const result=await s.host.handle({operation:'start'});
|
|
67
|
+
assert.equal(result.stage,'awaiting_finish',JSON.stringify(result));
|
|
68
|
+
assert.equal(result.differentialCount,4);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('revised judge must repeat mutation self-validation on the original business version',async t=>{
|
|
72
|
+
const s=scenario(t,{edit:payload=>({files:payload.assets.map(file=>({...file,content:"console.log(JSON.stringify({cases:[-2,0,2,3].map((x,i)=>({id:String(i),input:x,output:x<0?0:x+1}))}));\n"}))})});
|
|
73
|
+
const result=await s.host.handle({operation:'start'});assert.equal(result.reason,'refactor_judge_missed_mutation');
|
|
74
|
+
assert.equal(s.calls.filter(c=>c.kind==='refactor_review').length,1);
|
|
75
|
+
assert.equal(fs.readFileSync(path.join(s.project,'input.mjs'),'utf8'),replacement);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
for(const [label,revision] of [['business file',{...request,paths:['input.mjs']}],['undeclared asset',{...request,paths:['other.mjs']}],['duplicate path',{...request,paths:['judge.mjs','judge.mjs']}],['empty scope',{...request,paths:[]}],['missing reason',{paths:['judge.mjs'],reason:''}]]){
|
|
79
|
+
test(`reject judge revision request: ${label}`,async t=>{
|
|
80
|
+
const s=scenario(t,{revision});const result=await s.host.handle({operation:'start'});
|
|
81
|
+
assert.equal(result.reason,'refactor_judge_revision_scope');assert.equal(s.calls.some(c=>c.kind==='refactor_revise_tests'),false);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
for(const [label,edit] of [
|
|
85
|
+
['outside declared subset',payload=>({files:[{path:'baseline.mjs',beforeDigest:digest(null),content:'bad'}]})],
|
|
86
|
+
['stale digest',payload=>({files:[{...payload.assets[0],beforeDigest:'stale',content:revisedJudge}]})],
|
|
87
|
+
['business file',()=>({files:[{path:'input.mjs',beforeDigest:digest(replacement),content:regression}]})]
|
|
88
|
+
])test(`reject judge text proposal: ${label}`,async t=>{
|
|
89
|
+
const s=scenario(t,{edit});const before=fs.readFileSync(path.join(s.project,'judge.mjs'),'utf8');
|
|
90
|
+
const result=await s.host.handle({operation:'start'});assert.equal(result.reason,'refactor_proposal_scope');
|
|
91
|
+
assert.equal(fs.readFileSync(path.join(s.project,'judge.mjs'),'utf8'),before);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test('approved review cannot authorize judge revision',async t=>{
|
|
95
|
+
const s=scenario(t,{reviewVerdict:'approved'});const result=await s.host.handle({operation:'start'});
|
|
96
|
+
assert.equal(result.reason,'refactor_judge_revision_unavailable');assert.equal(s.calls.some(c=>c.kind==='refactor_revise_tests'),false);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('interrupted judge author reconciles its original result and preserves history',async t=>{
|
|
100
|
+
let pending;const s=scenario(t,{hook:(kind,payload)=>{if(kind==='refactor_revise_tests'){pending=payload;throw Error('lost judge author response');}}});
|
|
101
|
+
const result=await s.host.handle({operation:'start'});assert.equal(result.reason,'lost judge author response');
|
|
102
|
+
const history=fs.readFileSync(path.join(s.directory,'execution.jsonl'),'utf8');let recoveries=0;
|
|
103
|
+
const reopened=createCmRefactorHost(s.config,{call:async(kind,payload)=>{
|
|
104
|
+
if(kind==='refactor_recover'){recoveries++;assert.equal(payload.input.kind,'refactor_revise_tests');
|
|
105
|
+
return {decision:'completed',evidence:'Synthetic original author response receipt',result:{durationMs:1,value:{files:pending.assets.map(a=>({...a,content:revisedJudge}))}}};}
|
|
106
|
+
assert.notEqual(kind,'refactor_revise_tests');return s.call(kind,payload);
|
|
107
|
+
}});
|
|
108
|
+
const resumed=await reopened.handle({operation:'resume'});assert.equal(resumed.stage,'awaiting_finish',JSON.stringify(resumed));
|
|
109
|
+
assert.equal(recoveries,1);assert.ok(fs.readFileSync(path.join(s.directory,'execution.jsonl'),'utf8').startsWith(history));
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test('revised baseline must pass on the original business version',async t=>{
|
|
113
|
+
const s=scenario(t,{first:regression,revision:{...request,paths:['judge.mjs','baseline.mjs']},edit:payload=>({files:payload.assets.map(a=>({...a,content:a.path==='judge.mjs'?revisedJudge:
|
|
114
|
+
"import assert from 'node:assert/strict';import {calc} from './input.mjs';assert.equal(calc(3),99);\n"}))})});
|
|
115
|
+
const result=await s.host.handle({operation:'start'});assert.equal(result.reason,'refactor_baseline_failed');
|
|
116
|
+
assert.equal(s.calls.filter(c=>c.kind==='refactor_review').length,1);
|
|
117
|
+
assert.equal(fs.readFileSync(path.join(s.project,'input.mjs'),'utf8'),regression);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test('judge author direct disk writes remain forbidden',async t=>{
|
|
121
|
+
const s=scenario(t,{hook:(kind)=>{if(kind==='refactor_revise_tests')fs.appendFileSync(path.join(s.project,'judge.mjs'),'// outside controlled edit\n');}});
|
|
122
|
+
const result=await s.host.handle({operation:'start'});assert.equal(result.reason,'refactor_source_changed');
|
|
123
|
+
assert.equal(s.calls.filter(c=>c.kind==='refactor_review').length,1);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test('crash prefixes resume judge swaps, pending mutation and candidate restoration',async t=>{
|
|
127
|
+
const s=scenario(t);const result=await s.host.handle({operation:'start'});
|
|
128
|
+
assert.equal(result.stage,'awaiting_finish',JSON.stringify(result));
|
|
129
|
+
const journalPath=path.join(s.directory,'execution.jsonl'),text=fs.readFileSync(journalPath,'utf8'),lines=text.trimEnd().split('\n'),all=rows(s.directory);
|
|
130
|
+
const points=[
|
|
131
|
+
['write/a2/judge-revision/judge.mjs','before'],['write/a2/judge-revision/judge.mjs','after'],
|
|
132
|
+
['write/a2-judge-original/input.mjs','after'],['command/a2-judge-1/original','before'],
|
|
133
|
+
['command/a2-judge-1/mutant-0','before'],['write/a2-judge-candidate/input.mjs','after']
|
|
134
|
+
];
|
|
135
|
+
for(const [key,side] of points){
|
|
136
|
+
const index=all.findIndex(row=>row.type==='intent'&&row.key===key);assert.ok(index>=0,`missing durable effect ${key}`);
|
|
137
|
+
const prefix=all.slice(0,index+1),context=all.find(row=>row.type==='context').value;
|
|
138
|
+
const disk=new Map(Object.entries(context.original).map(([name,content])=>[path.join(s.project,name),content]));
|
|
139
|
+
for(let i=0;i<prefix.length;i++)if(prefix[i].type==='intent'&&prefix[i].kind==='write'){
|
|
140
|
+
const entry=prefix[i],completed=prefix.some(row=>row.type==='result'&&row.key===entry.key);
|
|
141
|
+
disk.set(entry.input.target,completed||i===index&&side==='after'?entry.input.after:entry.input.before);
|
|
142
|
+
}
|
|
143
|
+
for(const [file,content] of disk){if(content===null)fs.rmSync(file,{force:true});else fs.writeFileSync(file,content);}
|
|
144
|
+
const history=lines.slice(0,index+1).join('\n')+'\n';fs.writeFileSync(journalPath,history);
|
|
145
|
+
let reconciled=0;
|
|
146
|
+
const reopened=createCmRefactorHost(s.config,{call:async(kind,payload)=>{
|
|
147
|
+
if(kind==='refactor_recover'){
|
|
148
|
+
reconciled++;assert.equal(payload.kind,'command');
|
|
149
|
+
// No command dispatch occurred at this synthetic cut. Replay must run against the correct swapped source.
|
|
150
|
+
return {decision:'not_started',evidence:'Synthetic cut before command dispatch'};
|
|
151
|
+
}
|
|
152
|
+
return s.call(kind,payload);
|
|
153
|
+
}});
|
|
154
|
+
const resumed=await reopened.handle({operation:'resume'});assert.equal(resumed.stage,'awaiting_finish',`${key}: ${JSON.stringify(resumed)}`);
|
|
155
|
+
assert.equal(reconciled,key.startsWith('command/')?1:0);assert.equal(fs.readFileSync(path.join(s.project,'input.mjs'),'utf8'),replacement);
|
|
156
|
+
assert.ok(fs.readFileSync(journalPath,'utf8').startsWith(history));
|
|
157
|
+
assert.equal(report(s.directory,'a2-diff.md').before.cases.at(-1).output,4);
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
test('batch judge revision restores original additions and deletions before building answers',async t=>{
|
|
163
|
+
const s=scenario(t,{hook:(kind,payload)=>{
|
|
164
|
+
if(kind==='refactor_batch'||kind==='refactor_retrospective'){
|
|
165
|
+
const result=fullResponse(kind,payload);
|
|
166
|
+
if(payload.action==='generate')result.needs=[];
|
|
167
|
+
if(kind==='refactor_retrospective'){result.learning={status:'no_new_lesson',candidates:[],reason:null};result.conventions=[];}
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
}});
|
|
171
|
+
fs.writeFileSync(path.join(s.project,'old.mjs'),'export const old = 1;\n');
|
|
172
|
+
for(const args of [['init','-q'],['add','.'],['-c','user.name=Fixture','-c','user.email=fixture@example.invalid','commit','-qm','fixture']]){
|
|
173
|
+
const out=spawnSync('git',args,{cwd:s.project});assert.equal(out.status,0,out.stderr.toString());
|
|
174
|
+
}
|
|
175
|
+
s.config.scope=['input.mjs','new.mjs','old.mjs'];
|
|
176
|
+
s.config.batch={assemblyFiles:[],cheapCommands:[],maxPasses:3};
|
|
177
|
+
const host=createCmRefactorHost(s.config,{call:s.call}),result=await host.handle({operation:'start'});
|
|
178
|
+
assert.equal(result.stage,'awaiting_finish',JSON.stringify(result));
|
|
179
|
+
const events=rows(s.directory);
|
|
180
|
+
for(const [name,content] of [['new.mjs',null],['old.mjs','export const old = 1;\n']]){
|
|
181
|
+
const write=events.find(row=>row.key===`write/a2-judge-original/${name}`&&row.type==='intent');
|
|
182
|
+
assert.ok(write,`must restore ${name} from startup snapshot`);assert.equal(write.input.after,content);
|
|
183
|
+
}
|
|
184
|
+
assert.equal(report(s.directory,'a2-judge-1-report.md').judgeBefore.cases.length,4);
|
|
185
|
+
assert.equal(fs.existsSync(path.join(s.project,'old.mjs')),false);assert.ok(fs.existsSync(path.join(s.project,'new.mjs')));
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
test('original restoration includes legal business filenames starting with double underscore',async t=>{
|
|
189
|
+
const s=scenario(t,{first:regression,edit:payload=>({files:payload.assets.map(a=>({...a,content:revisedJudge.replace('./input.mjs','./__input.mjs')}))})});
|
|
190
|
+
fs.renameSync(path.join(s.project,'input.mjs'),path.join(s.project,'__input.mjs'));
|
|
191
|
+
for(const name of ['judge.mjs','baseline.mjs']){
|
|
192
|
+
const file=path.join(s.project,name);fs.writeFileSync(file,fs.readFileSync(file,'utf8').replace('./input.mjs','./__input.mjs'));
|
|
193
|
+
}
|
|
194
|
+
s.config.scope=['__input.mjs'];s.config.mutations.forEach(m=>{m.path='__input.mjs';});
|
|
195
|
+
const host=createCmRefactorHost(s.config,{call:s.call}),result=await host.handle({operation:'start'});
|
|
196
|
+
assert.equal(result.reason,'refactor_behavior_changed');
|
|
197
|
+
assert.equal(report(s.directory,'a2-judge-1-report.md').judgeBefore.cases.at(-1).output,4);
|
|
198
|
+
assert.equal(s.calls.filter(c=>c.kind==='refactor_review').length,1);
|
|
199
|
+
assert.equal(fs.readFileSync(path.join(s.project,'__input.mjs'),'utf8'),original);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
function legacyBlocked(t){
|
|
204
|
+
let attempts=0;
|
|
205
|
+
const s=scenario(t,{revision:false,hook:(kind,payload)=>{
|
|
206
|
+
if(kind==='refactor_apply'&&payload.attempt===2&&attempts++===0)
|
|
207
|
+
return {...fullResponse(kind,payload),files:[{path:'judge.mjs',beforeDigest:digest(fs.readFileSync(path.join(s.project,'judge.mjs'),'utf8')),content:revisedJudge}]};
|
|
208
|
+
}});
|
|
209
|
+
return s;
|
|
210
|
+
}
|
|
211
|
+
for(const interrupted of [false,true])test(`legacy rejected judge proposal can register bounded revision and resume (interrupted=${interrupted})`,async t=>{
|
|
212
|
+
const s=legacyBlocked(t);assert.equal((await s.host.handle({operation:'start'})).reason,'refactor_proposal_scope');
|
|
213
|
+
const file=path.join(s.directory,'execution.jsonl'),history=fs.readFileSync(file,'utf8');
|
|
214
|
+
const first=path.join(s.project,'docs/refactors/.reviews/refactor-extract-T-REFACTOR-extract-r1.md'),reviewBytes=fs.readFileSync(first,'utf8');
|
|
215
|
+
const prepared=await s.host.handle({operation:'prepare_judge_revision',judgeRevision:request});
|
|
216
|
+
assert.equal(prepared.stage,'judge_revision_prepared',JSON.stringify(prepared));
|
|
217
|
+
const registered=fs.readFileSync(file,'utf8');
|
|
218
|
+
assert.equal((await s.host.handle({operation:'prepare_judge_revision',judgeRevision:request})).stage,'judge_revision_prepared');
|
|
219
|
+
assert.equal(fs.readFileSync(file,'utf8'),registered,'identical registration is read-only');
|
|
220
|
+
if(interrupted){
|
|
221
|
+
const lines=registered.trimEnd().split('\n'),index=lines.findIndex(line=>{const row=JSON.parse(line);return row.key==='judge-revision-registration'&&row.type==='intent';});
|
|
222
|
+
assert.ok(index>=0);fs.writeFileSync(file,lines.slice(0,index+1).join('\n')+'\n');
|
|
223
|
+
}
|
|
224
|
+
const reopened=createCmRefactorHost(s.config,{call:s.call}),resumed=await reopened.handle({operation:'resume'});
|
|
225
|
+
assert.equal(resumed.stage,'awaiting_finish',JSON.stringify(resumed));assert.equal(resumed.attempt,2);assert.equal(resumed.differentialCount,4);
|
|
226
|
+
assert.ok(fs.readFileSync(file,'utf8').startsWith(history));assert.equal(fs.readFileSync(first,'utf8'),reviewBytes);
|
|
227
|
+
const events=rows(s.directory),registration=events.find(row=>row.key==='judge-revision-registration'&&row.type==='intent');
|
|
228
|
+
assert.equal(registration.input.supersededApply.key,'host/a2/apply');
|
|
229
|
+
assert.ok(events.some(row=>row.key==='host/a2-after-judge-revision/apply'));
|
|
230
|
+
assert.equal(events.filter(row=>row.key==='host/a2/apply'&&row.type==='intent').length,1);
|
|
231
|
+
assert.equal(s.calls.filter(c=>c.kind==='refactor_review').length,2);
|
|
232
|
+
const changed=await reopened.handle({operation:'prepare_judge_revision',judgeRevision:{...request,paths:['baseline.mjs']}});
|
|
233
|
+
assert.equal(changed.reason,'refactor_judge_revision_conflict');
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
test('legacy revision registration rejects undeclared assets',async t=>{
|
|
237
|
+
const s=legacyBlocked(t);await s.host.handle({operation:'start'});
|
|
238
|
+
const result=await s.host.handle({operation:'prepare_judge_revision',judgeRevision:{...request,paths:['input.mjs']}});
|
|
239
|
+
assert.equal(result.reason,'refactor_judge_revision_scope');assert.equal(rows(s.directory).some(row=>row.key==='judge-revision-registration'),false);
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
for(const reviewVerdict of ['approved','changes_requested'])test(`legacy revision registration refuses a consumed review stage (${reviewVerdict})`,async t=>{
|
|
243
|
+
const s=scenario(t,{revision:false,reviewVerdict});assert.equal((await s.host.handle({operation:'start'})).stage,'awaiting_finish');
|
|
244
|
+
const result=await s.host.handle({operation:'prepare_judge_revision',judgeRevision:request});
|
|
245
|
+
assert.equal(result.reason,'refactor_judge_revision_unavailable');assert.equal(s.calls.some(c=>c.kind==='refactor_revise_tests'),false);
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
test('judge registration before start refuses without poisoning the future run',async t=>{
|
|
249
|
+
const s=scenario(t,{revision:false,reviewVerdict:'approved'});
|
|
250
|
+
assert.equal((await s.host.handle({operation:'prepare_judge_revision',judgeRevision:request})).reason,'refactor_not_started');
|
|
251
|
+
const result=await s.host.handle({operation:'start'});
|
|
252
|
+
assert.equal(result.stage,'awaiting_finish',JSON.stringify(result));
|
|
253
|
+
});
|
|
@@ -64,6 +64,24 @@ test('shared status storage roundtrips canonically and reads legacy metadata wit
|
|
|
64
64
|
fs.symlinkSync(external,f.target);assert.equal(readSpecsStatus(f.specs).kind,'invalid');
|
|
65
65
|
});
|
|
66
66
|
|
|
67
|
+
test('revision digest is optional, validated, and retained by shared status storage',t=>{
|
|
68
|
+
const f=fixture(t),expected=f.initial(),revisionDigest='a'.repeat(64);
|
|
69
|
+
const withRevision={...expected,revisionDigest};
|
|
70
|
+
assert.deepEqual(writeSpecsStatus(f.specs,withRevision),withRevision);
|
|
71
|
+
assert.deepEqual(readSpecsStatus(f.specs),{kind:'valid',value:withRevision});
|
|
72
|
+
assert.equal(f.value().revisionDigest,revisionDigest);
|
|
73
|
+
const before=fs.readFileSync(f.target);
|
|
74
|
+
for(const invalid of ['A'.repeat(64),'f'.repeat(63),null]){
|
|
75
|
+
assert.throws(()=>writeSpecsStatus(f.specs,{...expected,revisionDigest:invalid}),/spec_status_invalid/);
|
|
76
|
+
assert.deepEqual(fs.readFileSync(f.target),before);
|
|
77
|
+
f.raw({...expected,revisionDigest:invalid});
|
|
78
|
+
assert.equal(readSpecsStatus(f.specs).kind,'invalid');
|
|
79
|
+
fs.writeFileSync(f.target,before);
|
|
80
|
+
}
|
|
81
|
+
writeSpecsStatus(f.specs,expected);
|
|
82
|
+
assert.equal(Object.hasOwn(f.value(),'revisionDigest'),false);
|
|
83
|
+
});
|
|
84
|
+
|
|
67
85
|
test('--approve writes only the three permitted reasons with explicit human input and reruns admission',t=>{
|
|
68
86
|
const f=fixture(t),approve=['--approve','--approval-response','开始'];
|
|
69
87
|
f.raw(f.initial());
|
|
@@ -83,6 +101,7 @@ test('--approve writes only the three permitted reasons with explicit human inpu
|
|
|
83
101
|
f.raw({...f.value(),status:'awaiting_review',approval:null});const before=fs.readFileSync(f.target);
|
|
84
102
|
const original=f.run(...args.filter(arg=>arg!=='--approve')).result;
|
|
85
103
|
result=f.run(...args);assert.equal(result.exit,1);assert(result.result.approveRefused);
|
|
104
|
+
assert.match(result.result.message,/--approval-response.*开始/);
|
|
86
105
|
const {approveRefused,...rest}=result.result;assert.deepEqual(rest,original);
|
|
87
106
|
assert.deepEqual(fs.readFileSync(f.target),before);
|
|
88
107
|
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// cm-test 单步驾驶员。表由 cm-test-host.mjs -> cm-test/host.mjs 的 handle/run/invoke
|
|
3
|
+
// 及 host-session.mjs operationNames 推出;只列此宿主接受的 operation。
|
|
4
|
+
// operation possible host_request kinds proof
|
|
5
|
+
// start change_impact (impact,有变更), test_cases host.mjs run: impact/generation;
|
|
6
|
+
// (缺合同或 generate), qa_logic (logic cases), host.mjs run: logic/browser.
|
|
7
|
+
// qa_browser (browser cases/explore)
|
|
8
|
+
// resume 同 start 的剩余种类,或无新反问 host.mjs handle resume -> run;
|
|
9
|
+
// 已记录 effect 直接回放 session.mjs effect.
|
|
10
|
+
// status, none host.mjs handle status/cancel.
|
|
11
|
+
// cancel
|
|
12
|
+
// host.mjs 自己运行 config.commands 并记录真实退出码;没有 host_request 命令证据。
|
|
13
|
+
// qa_browser 要执行浏览器/设备并写本轮证据,本驾驶员没有该 runner,发送前拒绝。
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import {fileURLToPath} from 'node:url';
|
|
17
|
+
import {inspectCmTestAdmission} from './cm-test-entry.mjs';
|
|
18
|
+
import {createCmTestHost} from '../runtime/js/cm-test/host.mjs';
|
|
19
|
+
import {validateTestCases} from './validate-test-cases.mjs';
|
|
20
|
+
import {inspectCmTestLogicResults} from '../runtime/js/cm-test/logic-results.mjs';
|
|
21
|
+
import {collectBranchImpact,inspectImpactAnalysis} from '../runtime/js/cm-test/branch-impact.mjs';
|
|
22
|
+
import {readSourceFiles,snapshotSource,selectReportDirectory,checkSourceEvidence} from '../runtime/js/cm-test/source-snapshot.mjs';
|
|
23
|
+
import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
|
|
24
|
+
import {inspectDeclaredTestCommand} from '../runtime/js/cm-test/declared-command.mjs';
|
|
25
|
+
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
26
|
+
import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
|
|
27
|
+
|
|
28
|
+
const HOST=fileURLToPath(new URL('./cm-test-host.mjs',import.meta.url));
|
|
29
|
+
const KNOWN=new Set(['start','resume','status','cancel']);
|
|
30
|
+
const FILES={change_impact:'change-impact.json',test_cases:'test-cases.json',qa_logic:'qa-logic.json'};
|
|
31
|
+
const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
|
|
32
|
+
const valid=(condition,label)=>{if(!condition)stop(2,`答案格式错误:${label}`);};
|
|
33
|
+
const safeFile=file=>fs.existsSync(file)&&fs.lstatSync(file).isFile()&&!fs.lstatSync(file).isSymbolicLink();
|
|
34
|
+
|
|
35
|
+
function main(){
|
|
36
|
+
if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
|
|
37
|
+
process.stdout.write('用法: cm-test-drive.mjs --plan PLAN.json <start|resume|status|cancel>\nPLAN: config, answers, sessionDir (resume), resolution:null。浏览器执行证据无 runner,预检拒绝。\n');return;
|
|
38
|
+
}
|
|
39
|
+
const {operation,plan,base}=loadPlanFile({name:'cm-test-drive.mjs',known:KNOWN});
|
|
40
|
+
requireFields(plan,['config']);
|
|
41
|
+
const configPath=path.resolve(base,plan.config),config=readJson(configPath,'宿主配置');
|
|
42
|
+
if(config===undefined)stop(2,`宿主配置不存在: ${configPath}`);
|
|
43
|
+
valid(safeFile(configPath)&&fs.statSync(configPath).size<=64*1024,'宿主配置文件');
|
|
44
|
+
const root=fileURLToPath(new URL('..',import.meta.url));
|
|
45
|
+
valid(config.skillDir===path.join(root,'skills/cm-test'),'config.skillDir 必须指向当前 checkout');
|
|
46
|
+
let admission;
|
|
47
|
+
try{admission=inspectCmTestAdmission({...config.arguments,skillDir:config.skillDir,project:config.project});}
|
|
48
|
+
catch(error){stop(2,`宿主配置准入失败: ${error.code??error.message}`);}
|
|
49
|
+
valid(admission.status==='ready','宿主配置准入');
|
|
50
|
+
try{createCmTestHost(config,{call:()=>{throw Error('preflight must not call host')}});}
|
|
51
|
+
catch(error){stop(2,`宿主配置无效: ${error.code??error.message}`);}
|
|
52
|
+
valid(['codex','claude'].includes(config.runtime)&&Array.isArray(config.sources)&&Array.isArray(config.commands)
|
|
53
|
+
&&config.commands.length<=32&&path.isAbsolute(config.logHome),'config.runtime/sources/commands/logHome');
|
|
54
|
+
if(admission.operation==='impact')valid(config.commands.length===0&&config.environment===null,'impact 只读配置');
|
|
55
|
+
if(operation==='resume'){
|
|
56
|
+
requireFields(plan,['sessionDir','resolution']);
|
|
57
|
+
valid(plan.resolution===null,'resume 只接受 resolution:null;原动作回执不能由静态答案伪造');
|
|
58
|
+
const session=path.resolve(base,plan.sessionDir);
|
|
59
|
+
if(!safeFile(path.join(session,'execution.jsonl')))stop(2,`恢复记录不存在: ${path.join(session,'execution.jsonl')}`);
|
|
60
|
+
const rows=fs.readFileSync(path.join(session,'execution.jsonl'),'utf8').trim().split('\n').map(JSON.parse);
|
|
61
|
+
const context=rows.find(row=>row.type==='context')?.value;
|
|
62
|
+
valid(context?.workflow==='cm-test'&&context.configDigest===digest(config),'resume 配置绑定不匹配');
|
|
63
|
+
const pending=new Map();for(const row of rows){if(row.type==='intent')pending.set(row.key,row.kind);if(row.type==='result')pending.delete(row.key);}
|
|
64
|
+
for(const [key,kind] of pending)if(['host','command'].includes(kind))stop(2,`缺少原执行回执 runner: ${kind} ${key};不能从静态文件恢复`);
|
|
65
|
+
}else if(operation==='start'&&plan.sessionDir){
|
|
66
|
+
const session=path.resolve(base,plan.sessionDir);
|
|
67
|
+
valid(!fs.existsSync(path.join(session,'execution.jsonl')),'start 的 sessionDir 已有记录,请用 resume');
|
|
68
|
+
}
|
|
69
|
+
const existingSession=plan.sessionDir&&safeFile(path.join(path.resolve(base,plan.sessionDir),'execution.jsonl'));
|
|
70
|
+
const answerRoot=plan.answers?path.resolve(base,plan.answers):null;
|
|
71
|
+
const asks=[];let contract=null,impact=null,sources=[];
|
|
72
|
+
if(['start','resume'].includes(operation)){
|
|
73
|
+
if(admission.operation==='impact'){
|
|
74
|
+
try{impact=collectBranchImpact(admission.project,admission.comparison,config.sources,config.mapPaths??[]);}
|
|
75
|
+
catch(error){stop(2,`impact 定义无效: ${error.code??error.message}`);}
|
|
76
|
+
if(impact.changes.length)asks.push('change_impact');
|
|
77
|
+
}else{
|
|
78
|
+
const runId='test-drive-preflight';
|
|
79
|
+
let snapshot;try{snapshot=snapshotSource(admission.project,selectReportDirectory(admission,runId));
|
|
80
|
+
sources=readSourceFiles(admission.project,config.sources,snapshot);}catch(error){stop(2,`sources 定义无效: ${error.code??error.message}`);}
|
|
81
|
+
const caseFile=admission.cases??(admission.specs&&admission.feature?path.join(admission.specs,admission.feature,'test-cases.json'):null);
|
|
82
|
+
if(caseFile&&safeFile(caseFile)){
|
|
83
|
+
if(path.extname(caseFile)==='.json'){
|
|
84
|
+
contract=readJson(caseFile,'用例合同');const failures=validateTestCases(contract);
|
|
85
|
+
valid(failures.length===0,`用例合同 ${caseFile}: ${failures.join('; ')}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if(admission.operation==='generate_cases'||contract===null)asks.push('test_cases');
|
|
89
|
+
for(const item of config.commands){
|
|
90
|
+
try{inspectDeclaredTestCommand(item,sources);createHostCheck({cwd:admission.project,commands:[{id:item.id,command:item.command}]});}
|
|
91
|
+
catch(error){stop(2,`声明命令无效 ${item?.id??'?'}: ${error.code??error.message}`);}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const loadAnswer=kind=>{
|
|
96
|
+
const file=path.join(answerRoot??'',FILES[kind]);
|
|
97
|
+
if(!answerRoot||!safeFile(file))stop(2,`步骤 ${operation} 会反问 ${kind},但答案文件不存在: ${file}`);
|
|
98
|
+
const value=readJson(file,kind);valid(value!==undefined,`${kind}: ${file}`);
|
|
99
|
+
try{
|
|
100
|
+
if(kind==='change_impact')inspectImpactAnalysis(impact,value);
|
|
101
|
+
if(kind==='test_cases'){
|
|
102
|
+
valid(object(value)&&Object.keys(value).sort().join(',')==='contract,report'&&typeof value.report==='string'&&value.report.trim(),'test_cases.report');
|
|
103
|
+
const errors=validateTestCases(value.contract);valid(errors.length===0,`test_cases.contract: ${errors.join('; ')}`);
|
|
104
|
+
contract=value.contract;
|
|
105
|
+
if(admission.operation!=='generate_cases'&&!admission.cases)
|
|
106
|
+
contract={...contract,cases:contract.cases.map(item=>({...item,origin:'inferred',
|
|
107
|
+
expected:item.expected.map(text=>text.startsWith('[需确认]')?text:`[需确认] 当前行为刻画: ${text}`)}))};
|
|
108
|
+
}
|
|
109
|
+
if(kind==='qa_logic'){
|
|
110
|
+
const selected=admission.cases?{...contract,cases:contract.cases.map(item=>({...item,origin:'user'}))}:contract;
|
|
111
|
+
inspectCmTestLogicResults(selected,{...value,contractDigest:digest(selected)});
|
|
112
|
+
valid(value.contractDigest===digest(selected),'qa_logic.contractDigest');
|
|
113
|
+
checkSourceEvidence(value.results,sources);
|
|
114
|
+
}
|
|
115
|
+
}catch(error){stop(2,`答案格式错误:${kind}: ${error.code??error.message}`);}
|
|
116
|
+
return value;
|
|
117
|
+
};
|
|
118
|
+
const answers=preflightAnswers(asks,loadAnswer);
|
|
119
|
+
if(['start','resume'].includes(operation)&&admission.operation!=='impact'){
|
|
120
|
+
if(admission.modes.includes('browser')&&(admission.operation==='explore'||contract?.cases?.some(item=>item.kind==='browser')))
|
|
121
|
+
stop(2,'缺少真实执行 runner: qa_browser;不能从静态答案文件应答');
|
|
122
|
+
if(admission.modes.includes('logic')&&contract?.cases?.some(item=>item.kind==='logic'))
|
|
123
|
+
answers.qa_logic=loadAnswer('qa_logic');
|
|
124
|
+
}
|
|
125
|
+
stderr(`预检通过:${operation}`);
|
|
126
|
+
driveHost({host:HOST,args:['serve','--config',configPath,...(plan.sessionDir
|
|
127
|
+
&&(['start','resume'].includes(operation)||operation==='status'&&existingSession)
|
|
128
|
+
?['--session-dir',path.resolve(base,plan.sessionDir)]:[])],
|
|
129
|
+
cwd:admission.project,operation,request:operation==='resume'?{resolution:null}:{},answers,paths:{},
|
|
130
|
+
answerFor:row=>answers[row.kind]??null});
|
|
131
|
+
}
|
|
132
|
+
main();
|
|
@@ -0,0 +1,91 @@
|
|
|
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 {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
9
|
+
const root=fileURLToPath(new URL('..',import.meta.url));
|
|
10
|
+
const driver=path.join(root,'scripts/cm-test-drive.mjs');
|
|
11
|
+
const write=(file,value)=>fs.writeFileSync(file,JSON.stringify(value));
|
|
12
|
+
const contract=(kind='logic')=>({schemaVersion:'1.0',feature:'guide',cases:[{id:'TC-001',origin:'user',kind,blocking:true,
|
|
13
|
+
acIds:[],taskIds:[],title:'Invalid input',preconditions:[],steps:['Call invalid input'],expected:['Returns error'],cleanup:[]}]});
|
|
14
|
+
function setup(t,kind='logic'){
|
|
15
|
+
const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-test-drive-'))),project=path.join(temp,'project');
|
|
16
|
+
fs.mkdirSync(project);fs.writeFileSync(path.join(project,'input.mjs'),'export const valid = value => value !== null;\n');
|
|
17
|
+
const cases=path.join(temp,'cases.json');write(cases,contract(kind));
|
|
18
|
+
const config={skillDir:path.join(root,'skills/cm-test'),project,runtime:'codex',arguments:{cases,...(kind==='browser'?{browser:true}:{logic:true})},
|
|
19
|
+
sources:['input.mjs'],commands:[],environment:{scope:'local',kind:'web',carrier:'browser',target:'fixture-local-ui'},
|
|
20
|
+
logHome:path.join(temp,'logs')};
|
|
21
|
+
write(path.join(temp,'config.json'),config);const answers=path.join(temp,'answers');fs.mkdirSync(answers);
|
|
22
|
+
const selected=contract(kind);write(path.join(answers,'qa-logic.json'),{contractDigest:digest(selected),results:[{id:'TC-001',verdict:'SUPPORTED',
|
|
23
|
+
evidence:[{path:'input.mjs',line:1}],explanation:'Code rejects null input'}]});
|
|
24
|
+
const session=path.join(temp,'session'),planPath=path.join(temp,'plan.json');
|
|
25
|
+
write(planPath,{config:'config.json',answers:'answers',sessionDir:'session'});
|
|
26
|
+
const run=(operation,which=driver)=>spawnSync(process.execPath,[which,'--plan',planPath,operation],{encoding:'utf8',timeout:120000});
|
|
27
|
+
t.after(()=>fs.rmSync(temp,{recursive:true,force:true}));
|
|
28
|
+
return {temp,project,config,answers,session,planPath,run};
|
|
29
|
+
}
|
|
30
|
+
test('real host: status is read-only, logic start and historical resume',t=>{
|
|
31
|
+
const f=setup(t);let out=f.run('status');assert.equal(out.status,0,out.stderr);
|
|
32
|
+
assert.equal(JSON.parse(out.stdout).result.stage,'ready');assert.equal(fs.existsSync(f.session),false);
|
|
33
|
+
out=f.run('start');assert.equal(out.status,0,out.stderr);
|
|
34
|
+
const result=JSON.parse(out.stdout).result;assert.equal(result.overall,'REVIEWED');assert.equal(result.executionPassed,0);
|
|
35
|
+
const journal=path.join(f.session,'execution.jsonl'),before=fs.readFileSync(journal);
|
|
36
|
+
out=f.run('status');assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.stage,'reported');
|
|
37
|
+
assert.deepEqual(fs.readFileSync(journal),before);
|
|
38
|
+
write(f.planPath,{config:'config.json',answers:'answers',sessionDir:'session',resolution:null});
|
|
39
|
+
out=f.run('resume');assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.historical,true);
|
|
40
|
+
});
|
|
41
|
+
test('missing, malformed and out-of-scope judgement refuse without session',t=>{
|
|
42
|
+
for(const change of ['missing','malformed','scope']){
|
|
43
|
+
const f=setup(t),file=path.join(f.answers,'qa-logic.json');
|
|
44
|
+
if(change==='missing')fs.unlinkSync(file);
|
|
45
|
+
if(change==='malformed')write(file,{contractDigest:digest(contract()),results:[{id:'TC-001',verdict:'PASS',evidence:[],explanation:'bad'}]});
|
|
46
|
+
if(change==='scope')write(file,{contractDigest:digest(contract()),results:[{id:'TC-001',verdict:'SUPPORTED',
|
|
47
|
+
evidence:[{path:'../outside.mjs',line:1}],explanation:'bad citation'}]});
|
|
48
|
+
const out=f.run('start');assert.equal(out.status,2,out.stderr);assert.match(out.stderr,/qa_logic|qa-logic/);
|
|
49
|
+
assert.equal(fs.existsSync(f.session),false);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
test('browser execution evidence cannot come from a static answer file',t=>{
|
|
53
|
+
const f=setup(t,'browser');write(path.join(f.answers,'qa-browser.json'),{verdict:'PASS',evidence:['fake.md'],
|
|
54
|
+
environment:f.config.environment,cleanup:'completed'});
|
|
55
|
+
const out=f.run('start');assert.equal(out.status,2,out.stderr);assert.match(out.stderr,/缺少真实执行 runner: qa_browser/);
|
|
56
|
+
assert.equal(fs.existsSync(f.session),false);
|
|
57
|
+
});
|
|
58
|
+
test('resume requires original session binding and explicit null resolution',t=>{
|
|
59
|
+
const f=setup(t);assert.equal(f.run('start').status,0);
|
|
60
|
+
let out=f.run('resume');assert.equal(out.status,2,out.stderr);assert.match(out.stderr,/PLAN 缺少字段 resolution/);
|
|
61
|
+
write(f.planPath,{config:'config.json',answers:'answers',sessionDir:'session',resolution:{result:{overall:'PASS'}}});
|
|
62
|
+
out=f.run('resume');assert.equal(out.status,2,out.stderr);assert.match(out.stderr,/原动作回执不能由静态答案伪造/);
|
|
63
|
+
write(f.planPath,{config:'config.json',answers:'answers',sessionDir:'session',resolution:null});
|
|
64
|
+
write(path.join(f.temp,'config.json'),{...f.config,runtime:'claude'});
|
|
65
|
+
out=f.run('resume');assert.equal(out.status,2,out.stderr);assert.match(out.stderr,/resume 配置绑定不匹配/);
|
|
66
|
+
});
|
|
67
|
+
test('mutation probes catch static browser answer, omitted schema check, dropped resume binding',t=>{
|
|
68
|
+
const source=fs.readFileSync(driver,'utf8');
|
|
69
|
+
const mutant=(from,to)=>{
|
|
70
|
+
assert.ok(source.includes(from));const file=path.join(root,'scripts',`.cm-test-drive-mutant-${process.pid}-${Math.random().toString(36).slice(2)}.mjs`);
|
|
71
|
+
fs.writeFileSync(file,source.replace(from,to));t.after(()=>fs.rmSync(file,{force:true}));return file;
|
|
72
|
+
};
|
|
73
|
+
const browser=setup(t,'browser');let out=browser.run('start');assert.equal(out.status,2);
|
|
74
|
+
const changed=source.replace("if(admission.modes.includes('browser')&&(admission.operation==='explore'||contract?.cases?.some(item=>item.kind==='browser')))","if(false)")
|
|
75
|
+
.replace('answerFor:row=>answers[row.kind]??null',"answerFor:row=>row.kind==='qa_browser'?readJson(path.join(answerRoot,'qa-browser.json'),'qa_browser'):answers[row.kind]??null");
|
|
76
|
+
const staticFile=path.join(root,'scripts',`.cm-test-drive-static-mutant-${process.pid}.mjs`);fs.writeFileSync(staticFile,changed);
|
|
77
|
+
t.after(()=>fs.rmSync(staticFile,{force:true}));
|
|
78
|
+
const report=path.join(browser.project,'docs/test-reports','fake.md');fs.mkdirSync(path.dirname(report),{recursive:true});fs.writeFileSync(report,'Fabricated browser result');
|
|
79
|
+
write(path.join(browser.answers,'qa-browser.json'),{verdict:'PASS',evidence:[report],environment:browser.config.environment,cleanup:'completed'});
|
|
80
|
+
out=browser.run('start',staticFile);assert.notEqual(out.status,2,'static evidence mutation bypassed refusal');
|
|
81
|
+
const malformed=setup(t);write(path.join(malformed.answers,'qa-logic.json'),{contractDigest:digest(contract()),results:[{id:'TC-001',verdict:'PASS',evidence:[],explanation:'bad'}]});
|
|
82
|
+
out=malformed.run('start');assert.equal(out.status,2);
|
|
83
|
+
out=malformed.run('start',mutant("if(kind==='qa_logic'){","if(false&&kind==='qa_logic'){"));
|
|
84
|
+
assert.notEqual(out.status,2,'schema mutation escaped preflight');
|
|
85
|
+
const resumed=setup(t);assert.equal(resumed.run('start').status,0);
|
|
86
|
+
write(resumed.planPath,{config:'config.json',answers:'answers',sessionDir:'session',resolution:null});
|
|
87
|
+
write(path.join(resumed.temp,'config.json'),{...resumed.config,runtime:'claude'});
|
|
88
|
+
out=resumed.run('resume');assert.equal(out.status,2);
|
|
89
|
+
out=resumed.run('resume',mutant("context?.workflow==='cm-test'&&context.configDigest===digest(config)","true"));
|
|
90
|
+
assert.notEqual(out.status,2,'binding mutation reached host');
|
|
91
|
+
});
|