@aibyzero/cm-workflow 0.16.2 → 0.16.3
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 +138 -0
- package/README.md +2 -2
- package/VERSION +1 -1
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +46 -7
- package/docs/next-steps.md +110 -0
- package/docs/untested-branches.md +24 -18
- package/package.json +1 -1
- package/runtime/js/cm-ai/claude-tool-preview.mjs +45 -6
- package/runtime/js/cm-ai/cm-ai-admission.mjs +5 -0
- 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 +2 -2
- 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-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 +53 -8
- package/runtime/js/cm-refactor/workflow.mjs +100 -19
- package/scripts/cm-ai-batch-drive.mjs +251 -0
- package/scripts/cm-ai-batch-drive.test.mjs +152 -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 +334 -0
- package/scripts/cm-ai-drive.test.mjs +251 -0
- package/scripts/cm-ai-fix-integration.test.mjs +1 -1
- package/scripts/cm-ai-host.mjs +41 -18
- package/scripts/cm-ai-host.test.mjs +37 -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 +93 -0
- package/scripts/cm-check-drive.test.mjs +62 -0
- package/scripts/cm-check-host.test.mjs +47 -0
- package/scripts/cm-claude-probe.test.mjs +117 -2
- 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-design-phase.test.mjs +355 -15
- package/scripts/cm-prd-drive.mjs +308 -0
- package/scripts/cm-prd-drive.test.mjs +154 -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 +48 -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-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/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 +80 -3
- package/skills/cm-check/references/js-host.md +2 -0
- 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 +41 -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
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// cm-refactor 单步驾驶员。表由 cm-refactor-host.mjs -> cm-refactor/workflow.mjs
|
|
3
|
+
// handle/flow/invoke 与 host-session.mjs operationNames 推出;不是其它宿主的表。
|
|
4
|
+
// operation possible host_request kinds proof
|
|
5
|
+
// start refactor_analyze, refactor_confirm(g0), workflow.mjs flow,
|
|
6
|
+
// refactor_prepare_tests (judge setup/repair), prepareJudges,
|
|
7
|
+
// refactor_batch (batch only), refactor_apply, batchFlow,
|
|
8
|
+
// refactor_retrospective (batch/writeback/memo), writeback,
|
|
9
|
+
// refactor_review, refactor_revise_tests review loop.
|
|
10
|
+
// resume start 的未记录部分;refactor_recover handle resume -> flow;
|
|
11
|
+
// only for unknown host/command effects records.mjs effect.
|
|
12
|
+
// finish 若尚未 awaiting_finish 同 resume; handle finish -> flow/finish;
|
|
13
|
+
// refactor_confirm(finish) finish confirm.
|
|
14
|
+
// prepare_judge_revision none(请求含 judgeRevision) handle -> prepareJudgeRevision.
|
|
15
|
+
// status, cancel none handle status/cancel.
|
|
16
|
+
// baseline/judge/mutation/cheap checks 均由 workflow.mjs command/createHostCheck
|
|
17
|
+
// 在项目内真实执行、记录退出码;没有可从答案文件填写的命令证据。
|
|
18
|
+
// unknown command/host 的恢复需原调用回执,本驾驶员没有回执 runner,预检拒绝。
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import {fileURLToPath} from 'node:url';
|
|
22
|
+
import {createCmRefactorHost} from '../runtime/js/cm-refactor/host.mjs';
|
|
23
|
+
import {openRefactorRecords} from '../runtime/js/cm-refactor/records.mjs';
|
|
24
|
+
import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
|
|
25
|
+
import {readLearningRetrospectiveContent} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
|
|
26
|
+
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
27
|
+
import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
|
|
28
|
+
|
|
29
|
+
const HOST=fileURLToPath(new URL('./cm-refactor-host.mjs',import.meta.url));
|
|
30
|
+
const KNOWN=new Set(['start','resume','finish','prepare_judge_revision','status','cancel']);
|
|
31
|
+
const FILES={refactor_analyze:'analyze.json',refactor_confirm:'confirm.json',refactor_apply:'apply.json',
|
|
32
|
+
refactor_review:'review.json',refactor_prepare_tests:'prepare-tests.json',refactor_revise_tests:'revise-tests.json',
|
|
33
|
+
refactor_batch:'batch.json',refactor_retrospective:'retrospective.json'};
|
|
34
|
+
const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
|
|
35
|
+
const nonempty=value=>typeof value==='string'&&value.trim().length>0;
|
|
36
|
+
const valid=(yes,label)=>{if(!yes)stop(2,`答案格式错误:${label}`);};
|
|
37
|
+
const ownFile=file=>fs.existsSync(file)&&fs.lstatSync(file).isFile()&&!fs.lstatSync(file).isSymbolicLink();
|
|
38
|
+
const exact=(value,keys,label)=>valid(object(value)&&Object.keys(value).sort().join(',')===keys.slice().sort().join(','),label);
|
|
39
|
+
function content(root,local,label){
|
|
40
|
+
valid(nonempty(local)&&!path.isAbsolute(local)&&!local.includes('\\')&&!local.split('/').includes('..'),`${label}.contentFile`);
|
|
41
|
+
const file=path.resolve(root,local);
|
|
42
|
+
valid(file.startsWith(fs.realpathSync(root)+path.sep)&&ownFile(file)&&fs.realpathSync(file)===file,`缺少安全的内容文件: ${file}`);
|
|
43
|
+
valid(fs.statSync(file).size<=1024*1024,`${label}.contentFile 过大: ${file}`);
|
|
44
|
+
return fs.readFileSync(file,'utf8');
|
|
45
|
+
}
|
|
46
|
+
function files(value,root,allowed,label,{deletion=false,empty=false}={}){
|
|
47
|
+
valid(Array.isArray(value)&&(empty||value.length>0),`${label}.files`);
|
|
48
|
+
const seen=new Set();for(const item of value){
|
|
49
|
+
exact(item,['path','contentFile'],`${label}.files[]`);
|
|
50
|
+
valid(allowed.includes(item.path)&&!seen.has(item.path),`${label} 越过 scope: ${item.path}`);seen.add(item.path);
|
|
51
|
+
if(item.contentFile===null)valid(deletion,`${label} 不允许删除: ${item.path}`);
|
|
52
|
+
else content(root,item.contentFile,`${label}.${item.path}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function materialize(value,payload,root,{deletion=false}={}){
|
|
56
|
+
return value.filter(item=>payload.some(file=>file.path===item.path)).map(item=>({path:item.path,beforeDigest:payload.find(file=>file.path===item.path)?.beforeDigest,
|
|
57
|
+
content:item.contentFile===null&&deletion?null:content(root,item.contentFile,item.path)}));
|
|
58
|
+
}
|
|
59
|
+
function review(value,label){
|
|
60
|
+
valid(object(value)&&['codex-subagent','codex-cli','claude-cli'].includes(value.reviewer)
|
|
61
|
+
&&['approved','changes_requested','blocked'].includes(value.verdict)
|
|
62
|
+
&&Number.isInteger(value.blocking_findings)&&value.blocking_findings>=0
|
|
63
|
+
&&(value.verdict==='approved'?value.blocking_findings===0:value.blocking_findings>0)
|
|
64
|
+
&&nonempty(value.body)&&nonempty(value.at)&&Number.isFinite(Date.parse(value.at))
|
|
65
|
+
&&/(Z|[+-]\d\d:\d\d)$/.test(value.at),label);
|
|
66
|
+
if(value.verdict==='approved')valid(/零发现|无阻塞发现|未发现阻塞|zero findings|no findings|no blocking findings/i.test(value.body),`${label}.body`);
|
|
67
|
+
if(value.judgeRevision)valid(Array.isArray(value.judgeRevision.paths)&&value.judgeRevision.paths.length>0
|
|
68
|
+
&&nonempty(value.judgeRevision.reason),`${label}.judgeRevision`);
|
|
69
|
+
valid(Object.keys(value).every(key=>['reviewer','verdict','blocking_findings','body','at','judgeRevision'].includes(key)),label);
|
|
70
|
+
}
|
|
71
|
+
function validate(kind,value,config,root){
|
|
72
|
+
if(kind==='refactor_analyze'){
|
|
73
|
+
valid(object(value)&&['proceed','no_refactor'].includes(value.decision)&&nonempty(value.reason)
|
|
74
|
+
&&object(value.metric)&&nonempty(value.metric.name)&&Number.isFinite(value.metric.before)
|
|
75
|
+
&&nonempty(value.metric.unit)&&Array.isArray(value.impact)&&Array.isArray(value.claimedMemos)
|
|
76
|
+
&&value.claimedMemos.every(nonempty),'analyze.json');
|
|
77
|
+
}else if(kind==='refactor_confirm'){
|
|
78
|
+
valid(object(value)&&['approved','rejected'].includes(value.g0)
|
|
79
|
+
&&(!Object.hasOwn(value,'finish')||['approved','rejected'].includes(value.finish))
|
|
80
|
+
&&(!Object.hasOwn(value,'rulebook')||['approved','rejected'].includes(value.rulebook)),'confirm.json');
|
|
81
|
+
}else if(kind==='refactor_apply'){
|
|
82
|
+
valid(object(value)&&nonempty(value.summary)&&Number.isFinite(value.metricAfter)
|
|
83
|
+
&&Array.isArray(value.unfixedDefects)&&Array.isArray(value.conventions)
|
|
84
|
+
&&nonempty(value.learningApplication)&&value.learningRetrospective!==undefined,'apply.json');
|
|
85
|
+
files(value.files,root,config.scope,'apply.json');
|
|
86
|
+
if(object(value.learningRetrospective))try{readLearningRetrospectiveContent(value.learningRetrospective);}
|
|
87
|
+
catch{stop(2,'答案格式错误:apply.json.learningRetrospective');}
|
|
88
|
+
}else if(kind==='refactor_review'){
|
|
89
|
+
review(value,'review.json');
|
|
90
|
+
if(value.judgeRevision)valid(value.judgeRevision.paths.every(name=>config.testSetup?.paths?.includes(name)),
|
|
91
|
+
'review.json.judgeRevision 越过测试 scope');
|
|
92
|
+
}else if(['refactor_prepare_tests','refactor_revise_tests'].includes(kind)){
|
|
93
|
+
exact(value,['files'],FILES[kind]);files(value.files,root,config.testSetup?.paths??[],FILES[kind]);
|
|
94
|
+
}else if(kind==='refactor_retrospective'){
|
|
95
|
+
valid(object(value)&&nonempty(value.learningApplication)&&Array.isArray(value.conventions)
|
|
96
|
+
&&Array.isArray(value.documentation)&&Array.isArray(value.resolved)
|
|
97
|
+
&&Array.isArray(value.unfixedDefects)&&Number.isFinite(value.metricAfter),'retrospective.json');
|
|
98
|
+
try{const learning=readLearningRetrospectiveContent(value.learning);
|
|
99
|
+
valid(learning.status!=='writeback_pending','retrospective.json.learning');}
|
|
100
|
+
catch{stop(2,'答案格式错误:retrospective.json.learning');}
|
|
101
|
+
for(const item of value.documentation){
|
|
102
|
+
valid(object(item)&&['README.md','CLAUDE.md'].includes(item.path)
|
|
103
|
+
&&(config.writebackPaths??[]).includes(item.path),'retrospective.json.documentation 越过 scope');
|
|
104
|
+
content(root,item.contentFile,`retrospective.${item.path}`);
|
|
105
|
+
}
|
|
106
|
+
}else if(kind==='refactor_batch'){
|
|
107
|
+
valid(object(value)&&object(value.plan)&&nonempty(value.plan.rulebook)&&Array.isArray(value.plan.units)
|
|
108
|
+
&&Array.isArray(value.plan.sample)&&Number.isFinite(value.plan.perFileEstimate)
|
|
109
|
+
&&nonempty(value.plan.reason),'batch.json.plan');
|
|
110
|
+
valid(object(value.bakeoff)&&object(value.bakeoff.guided)&&object(value.bakeoff.blind)
|
|
111
|
+
&&nonempty(value.bakeoff.guided.channelId)&&nonempty(value.bakeoff.blind.channelId)
|
|
112
|
+
&&value.bakeoff.guided.channelId!==value.bakeoff.blind.channelId,'batch.json.bakeoff');
|
|
113
|
+
for(const item of [value.bakeoff.guided,value.bakeoff.blind]){
|
|
114
|
+
files(item.files,root,config.scope,'batch.json.bakeoff',{deletion:true});
|
|
115
|
+
valid(value.plan.sample.every(name=>item.files.some(file=>file.path===name)),'batch.json.bakeoff 缺少 sample 文件');
|
|
116
|
+
}
|
|
117
|
+
valid(object(value.adjudicate)&&nonempty(value.adjudicate.channelId)
|
|
118
|
+
&&Array.isArray(value.adjudicate.decisions)&&nonempty(value.adjudicate.rulebook),'batch.json.adjudicate');
|
|
119
|
+
for(const action of ['generate','assemble']){
|
|
120
|
+
valid(object(value[action]),`batch.json.${action}`);
|
|
121
|
+
files(value[action].files,root,action==='assemble'?config.batch.assemblyFiles:config.scope,`batch.json.${action}`,
|
|
122
|
+
{deletion:true,empty:action==='assemble'&&config.batch.assemblyFiles.length===0});
|
|
123
|
+
}
|
|
124
|
+
valid(config.scope.filter(name=>!config.batch.assemblyFiles.includes(name)).every(name=>value.generate.files.some(file=>file.path===name)),
|
|
125
|
+
'batch.json.generate 缺少 scope 文件');
|
|
126
|
+
if(config.batch.assemblyFiles.length)valid(config.batch.assemblyFiles.every(name=>value.assemble.files.some(file=>file.path===name)),
|
|
127
|
+
'batch.json.assemble 缺少 assembly 文件');
|
|
128
|
+
valid(Array.isArray(value.generate.needs)&&nonempty(value.generate.summary)
|
|
129
|
+
&&Array.isArray(value.assemble.resolved)&&object(value.diagnose)
|
|
130
|
+
&&nonempty(value.diagnose.errorClass)&&nonempty(value.diagnose.reason),'batch.json actions');
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function answer(row,answers,root){
|
|
134
|
+
const {kind,payload}=row,value=answers[kind];
|
|
135
|
+
if(kind==='refactor_confirm')return {decision:value[payload.gate]};
|
|
136
|
+
if(kind==='refactor_review'){
|
|
137
|
+
const chosen=payload.attempt===2?answers.refactor_review_r2??value:value;
|
|
138
|
+
const scope=payload.files.map(item=>` - ${item.path}`).join('\n');
|
|
139
|
+
const markdown=`---\nat: ${chosen.at}\nreviewer: ${chosen.reviewer}\nindependent: true\ntask: ${payload.task}\nattempt: ${payload.attempt}\nround: ${payload.attempt}\nverdict: ${chosen.verdict}\nblocking_findings: ${chosen.blocking_findings}\nhandoff: ${path.basename(payload.handoff)}\nhandoff_sha256: ${payload.handoffSha256}\nscope:\n${scope}\n---\n\n${chosen.body}\n`;
|
|
140
|
+
return {markdown,...(chosen.judgeRevision?{judgeRevision:chosen.judgeRevision}:{})};
|
|
141
|
+
}
|
|
142
|
+
if(['refactor_prepare_tests','refactor_revise_tests'].includes(kind))return {files:materialize(value.files,payload.assets,root)};
|
|
143
|
+
if(kind==='refactor_apply')return {...value,files:materialize(value.files,payload.files,root)};
|
|
144
|
+
if(kind==='refactor_batch'){
|
|
145
|
+
const selected=payload.action==='bakeoff'?value.bakeoff[payload.variant]:value[payload.action];
|
|
146
|
+
if(!selected)return null;
|
|
147
|
+
if(['bakeoff','generate','assemble'].includes(payload.action))return {...selected,files:materialize(selected.files,payload.files,root,{deletion:true})};
|
|
148
|
+
return selected;
|
|
149
|
+
}
|
|
150
|
+
if(kind==='refactor_retrospective')return {...value,documentation:value.documentation.map(item=>({
|
|
151
|
+
path:item.path,beforeDigest:payload.files.find(file=>file.path===item.path)?.beforeDigest,
|
|
152
|
+
content:content(root,item.contentFile,`retrospective.${item.path}`)}))};
|
|
153
|
+
return value??null;
|
|
154
|
+
}
|
|
155
|
+
function main(){
|
|
156
|
+
if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
|
|
157
|
+
process.stdout.write('用法: cm-refactor-drive.mjs --plan PLAN.json <start|resume|finish|prepare_judge_revision|status|cancel>\nPLAN: config, answers;prepare_judge_revision 另需 judgeRevision。命令由宿主执行。\n');return;
|
|
158
|
+
}
|
|
159
|
+
const {operation,plan,base}=loadPlanFile({name:'cm-refactor-drive.mjs',known:KNOWN});
|
|
160
|
+
requireFields(plan,['config']);
|
|
161
|
+
const configPath=path.resolve(base,plan.config),config=readJson(configPath,'宿主配置');
|
|
162
|
+
if(config===undefined)stop(2,`宿主配置不存在: ${configPath}`);
|
|
163
|
+
valid(ownFile(configPath)&&fs.statSync(configPath).size<=64*1024,'宿主配置文件');
|
|
164
|
+
const root=fileURLToPath(new URL('..',import.meta.url));
|
|
165
|
+
valid(config.skillDir===path.join(root,'skills/cm-refactor'),'config.skillDir 必须指向当前 checkout');
|
|
166
|
+
try{createCmRefactorHost(config,{call:()=>{throw Error('preflight must not call host')}});}
|
|
167
|
+
catch(error){stop(2,`宿主配置无效: ${error.code??error.message}`);}
|
|
168
|
+
for(const [label,command] of [['judgeCommand',config.judgeCommand],...(config.baselineCommands??[]).map(item=>[item.id,item.command]),
|
|
169
|
+
...(config.batch?.cheapCommands??[]).map(item=>[item.id,item.command.map(arg=>arg.replaceAll('{file}',config.scope[0]))])]){
|
|
170
|
+
try{createHostCheck({cwd:config.project,commands:[{id:label,command}]});}
|
|
171
|
+
catch(error){stop(2,`命令定义无效 ${label}: ${error.code??error.message}`);}
|
|
172
|
+
}
|
|
173
|
+
for(const mutation of config.mutations){valid(config.scope.includes(mutation.path)&&nonempty(mutation.find)
|
|
174
|
+
&&typeof mutation.replace==='string'&&mutation.find!==mutation.replace,`config.mutations: ${mutation.path}`);}
|
|
175
|
+
const directory=path.join(config.specs??path.join(config.project,'docs'),'refactors',config.slug);
|
|
176
|
+
let records;try{records=openRefactorRecords(directory);}catch(error){stop(2,`恢复记录无效: ${error.code??error.message}`);}
|
|
177
|
+
if(operation==='start'&&records.context)stop(2,`start 已有运行记录,请用 resume: ${path.join(directory,'execution.jsonl')}`);
|
|
178
|
+
if(['resume','finish','prepare_judge_revision'].includes(operation)&&!records.context)
|
|
179
|
+
stop(2,`恢复记录不存在: ${path.join(directory,'execution.jsonl')}`);
|
|
180
|
+
if(records.context&&records.context.configDigest!==digest(config))stop(2,'resume 配置绑定不匹配');
|
|
181
|
+
if(['resume','finish','prepare_judge_revision'].includes(operation))for(const [key,entry] of records.effects)
|
|
182
|
+
if(['host','command'].includes(entry.kind)&&!Object.hasOwn(entry,'result'))
|
|
183
|
+
stop(2,`缺少原执行回执 runner: ${entry.kind} ${key};不能从静态答案文件恢复`);
|
|
184
|
+
if(operation==='prepare_judge_revision'){
|
|
185
|
+
requireFields(plan,['judgeRevision']);
|
|
186
|
+
valid(object(plan.judgeRevision)&&Array.isArray(plan.judgeRevision.paths)&&plan.judgeRevision.paths.length>0
|
|
187
|
+
&&plan.judgeRevision.paths.every(name=>config.testSetup?.paths?.includes(name))
|
|
188
|
+
&&nonempty(plan.judgeRevision.reason),'judgeRevision 越过测试 scope');
|
|
189
|
+
}
|
|
190
|
+
const answerRoot=plan.answers?path.resolve(base,plan.answers):null;
|
|
191
|
+
const batch=Boolean(config.batch)||config.scope.length>3||config.crossModule
|
|
192
|
+
||config.scope.some(name=>!fs.existsSync(path.join(config.project,name)));
|
|
193
|
+
const asks=[];
|
|
194
|
+
if(['start','resume'].includes(operation)||operation==='finish'&&records.progress?.stage!=='awaiting_finish'){
|
|
195
|
+
asks.push('refactor_analyze','refactor_confirm');
|
|
196
|
+
if(config.testSetup?.paths?.length)asks.push('refactor_prepare_tests');
|
|
197
|
+
if(batch)asks.push('refactor_batch');else asks.push('refactor_apply');
|
|
198
|
+
asks.push('refactor_review');
|
|
199
|
+
}
|
|
200
|
+
if(operation==='finish'&&records.progress?.stage==='awaiting_finish')asks.push('refactor_confirm');
|
|
201
|
+
const answers=preflightAnswers(asks,kind=>{
|
|
202
|
+
const file=path.join(answerRoot??'',FILES[kind]);
|
|
203
|
+
if(!answerRoot||!ownFile(file))stop(2,`步骤 ${operation} 会反问 ${kind},但答案文件不存在: ${file}`);
|
|
204
|
+
const value=readJson(file,kind);validate(kind,value,config,answerRoot);return value;
|
|
205
|
+
});
|
|
206
|
+
if(answers.refactor_analyze?.claimedMemos?.length||batch||config.writebackPaths?.length){
|
|
207
|
+
if(!answers.refactor_retrospective&&asks.length){
|
|
208
|
+
const file=path.join(answerRoot??'',FILES.refactor_retrospective);
|
|
209
|
+
if(!answerRoot||!ownFile(file))stop(2,`步骤 ${operation} 会反问 refactor_retrospective,但答案文件不存在: ${file}`);
|
|
210
|
+
answers.refactor_retrospective=readJson(file,'refactor_retrospective');
|
|
211
|
+
validate('refactor_retrospective',answers.refactor_retrospective,config,answerRoot);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if(answers.refactor_review?.judgeRevision){
|
|
215
|
+
const file=path.join(answerRoot,FILES.refactor_revise_tests);
|
|
216
|
+
if(!ownFile(file))stop(2,`步骤 ${operation} 会反问 refactor_revise_tests,但答案文件不存在: ${file}`);
|
|
217
|
+
answers.refactor_revise_tests=readJson(file,'refactor_revise_tests');
|
|
218
|
+
validate('refactor_revise_tests',answers.refactor_revise_tests,config,answerRoot);
|
|
219
|
+
}
|
|
220
|
+
if(answers.refactor_review?.verdict==='changes_requested'){
|
|
221
|
+
const file=path.join(answerRoot,'review-r2.json');
|
|
222
|
+
if(!ownFile(file))stop(2,`步骤 ${operation} 可能反问第二轮 refactor_review,但答案文件不存在: ${file}`);
|
|
223
|
+
answers.refactor_review_r2=readJson(file,'refactor_review_r2');review(answers.refactor_review_r2,'review-r2.json');
|
|
224
|
+
valid(answers.refactor_review_r2.verdict!=='changes_requested','review-r2.json 第二轮须 approved 或 blocked');
|
|
225
|
+
}
|
|
226
|
+
if(batch&&answers.refactor_confirm&&!answers.refactor_confirm.rulebook)
|
|
227
|
+
stop(2,'步骤可能反问 refactor_confirm(rulebook),但 confirm.json.rulebook 缺失');
|
|
228
|
+
if(operation==='finish'&&answers.refactor_confirm&&!answers.refactor_confirm.finish)
|
|
229
|
+
stop(2,'步骤 finish 会反问 refactor_confirm(finish),但 confirm.json.finish 缺失');
|
|
230
|
+
if(operation==='start'&&answers.refactor_confirm?.g0==='approved'&&!answers.refactor_review)
|
|
231
|
+
stop(2,'步骤 start 会反问 refactor_review,但 review.json 缺失');
|
|
232
|
+
stderr(`预检通过:${operation}`);
|
|
233
|
+
driveHost({host:HOST,args:['serve','--config',configPath],cwd:config.project,operation,
|
|
234
|
+
request:operation==='prepare_judge_revision'?{judgeRevision:plan.judgeRevision}:{},answers,paths:{},
|
|
235
|
+
answerFor:row=>answer(row,answers,answerRoot)});
|
|
236
|
+
}
|
|
237
|
+
main();
|
|
@@ -0,0 +1,77 @@
|
|
|
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 {fileURLToPath} from 'node:url';
|
|
7
|
+
import {fixture,replacement} from './fixtures/cm-refactor.mjs';
|
|
8
|
+
const root=fileURLToPath(new URL('..',import.meta.url));
|
|
9
|
+
const driver=path.join(root,'scripts/cm-refactor-drive.mjs');
|
|
10
|
+
const write=(file,value)=>fs.writeFileSync(file,JSON.stringify(value));
|
|
11
|
+
function setup(t){
|
|
12
|
+
const {temp,project,config}=fixture(t),answers=path.join(temp,'answers');fs.mkdirSync(answers);
|
|
13
|
+
const configPath=path.join(temp,'config.json');write(configPath,config);
|
|
14
|
+
write(path.join(answers,'analyze.json'),{decision:'proceed',metric:{name:'nesting',before:2,unit:'levels'},impact:[],claimedMemos:[],reason:'Extract function'});
|
|
15
|
+
write(path.join(answers,'confirm.json'),{g0:'approved',finish:'approved'});
|
|
16
|
+
fs.writeFileSync(path.join(answers,'replacement.mjs'),replacement);
|
|
17
|
+
write(path.join(answers,'apply.json'),{files:[{path:'input.mjs',contentFile:'replacement.mjs'}],summary:'Extract function',
|
|
18
|
+
metricAfter:1,unfixedDefects:[],conventions:[],learningApplication:'No relevant lesson',learningRetrospective:'no_new_lesson'});
|
|
19
|
+
write(path.join(answers,'review.json'),{at:'2026-09-08T18:00:00+00:00',reviewer:'codex-subagent',verdict:'approved',
|
|
20
|
+
blocking_findings:0,body:'Zero findings in independently authored fixture review.'});
|
|
21
|
+
const planPath=path.join(temp,'plan.json');write(planPath,{config:'config.json',answers:'answers'});
|
|
22
|
+
const store=path.join(project,'docs/refactors/extract/execution.jsonl');
|
|
23
|
+
const run=(operation,which=driver)=>spawnSync(process.execPath,[which,'--plan',planPath,operation],{encoding:'utf8',timeout:120000});
|
|
24
|
+
return {temp,project,config,answers,planPath,store,run};
|
|
25
|
+
}
|
|
26
|
+
test('real light host: start, status, new-process resume, finish',t=>{
|
|
27
|
+
const f=setup(t);let out=f.run('status');assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.stage,'ready');
|
|
28
|
+
assert.equal(fs.existsSync(f.store),false);
|
|
29
|
+
out=f.run('start');assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.stage,'awaiting_finish');
|
|
30
|
+
assert.equal(fs.readFileSync(path.join(f.project,'input.mjs'),'utf8'),replacement);
|
|
31
|
+
out=f.run('resume');assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.stage,'awaiting_finish');
|
|
32
|
+
out=f.run('finish');assert.equal(out.status,0,out.stderr);assert.equal(JSON.parse(out.stdout).result.stage,'done');
|
|
33
|
+
});
|
|
34
|
+
test('missing, malformed and out-of-scope answers refuse before store creation',t=>{
|
|
35
|
+
for(const change of ['missing','malformed','scope']){
|
|
36
|
+
const f=setup(t),file=path.join(f.answers,'apply.json');
|
|
37
|
+
if(change==='missing')fs.unlinkSync(file);
|
|
38
|
+
if(change==='malformed')write(file,{files:'invalid'});
|
|
39
|
+
if(change==='scope')write(file,{...JSON.parse(fs.readFileSync(file)),files:[{path:'outside.mjs',contentFile:'replacement.mjs'}]});
|
|
40
|
+
const out=f.run('start');assert.equal(out.status,2,out.stderr);assert.match(out.stderr,/apply\.json/);
|
|
41
|
+
assert.equal(fs.existsSync(f.store),false);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
test('unknown command evidence has no static recovery path',t=>{
|
|
45
|
+
const f=setup(t);let out=f.run('start');assert.equal(out.status,0,out.stderr);
|
|
46
|
+
const rows=fs.readFileSync(f.store,'utf8').trim().split('\n');
|
|
47
|
+
const last=rows.findLast(line=>JSON.parse(line).type==='result'&&JSON.parse(line).key.startsWith('command/'));
|
|
48
|
+
assert.ok(last);const key=JSON.parse(last).key;
|
|
49
|
+
const index=rows.findIndex(line=>JSON.parse(line).type==='intent'&&JSON.parse(line).key===key);
|
|
50
|
+
// Use a valid crash prefix: the original command intent has no result.
|
|
51
|
+
fs.writeFileSync(f.store,rows.slice(0,index+1).join('\n')+'\n');const before=fs.readFileSync(f.store);
|
|
52
|
+
write(path.join(f.answers,'recover.json'),{decision:'completed',result:{observed:{outcome:'passed',exitCode:0}}});
|
|
53
|
+
out=f.run('resume');assert.equal(out.status,2,out.stderr);assert.match(out.stderr,/缺少原执行回执 runner: command/);
|
|
54
|
+
assert.deepEqual(fs.readFileSync(f.store),before);
|
|
55
|
+
});
|
|
56
|
+
test('resume config digest remains bound before launch',t=>{
|
|
57
|
+
const f=setup(t);assert.equal(f.run('start').status,0);
|
|
58
|
+
const altered={...f.config,target:'Changed target'};write(path.join(f.temp,'config.json'),altered);
|
|
59
|
+
const before=fs.readFileSync(f.store),out=f.run('resume');assert.equal(out.status,2,out.stderr);
|
|
60
|
+
assert.match(out.stderr,/resume 配置绑定不匹配/);assert.deepEqual(fs.readFileSync(f.store),before);
|
|
61
|
+
});
|
|
62
|
+
test('mutation probes catch skipped answer preflight and dropped resume binding',t=>{
|
|
63
|
+
const f=setup(t),source=fs.readFileSync(driver,'utf8');
|
|
64
|
+
const mutant=(from,to)=>{
|
|
65
|
+
assert.ok(source.includes(from));const file=path.join(root,'scripts',`.cm-refactor-drive-mutant-${process.pid}-${Math.random().toString(36).slice(2)}.mjs`);
|
|
66
|
+
fs.writeFileSync(file,source.replace(from,to));t.after(()=>fs.rmSync(file,{force:true}));return file;
|
|
67
|
+
};
|
|
68
|
+
fs.unlinkSync(path.join(f.answers,'apply.json'));
|
|
69
|
+
let out=f.run('start');assert.equal(out.status,2);assert.equal(fs.existsSync(f.store),false);
|
|
70
|
+
out=f.run('start',mutant('preflightAnswers(asks,kind=>','preflightAnswers([],kind=>'));
|
|
71
|
+
assert.notEqual(out.status,2,'mutation escaped preflight and changed the refusal');
|
|
72
|
+
const g=setup(t);assert.equal(g.run('start').status,0);
|
|
73
|
+
write(path.join(g.temp,'config.json'),{...g.config,target:'Changed target'});
|
|
74
|
+
out=g.run('resume');assert.equal(out.status,2);
|
|
75
|
+
out=g.run('resume',mutant('records.context.configDigest!==digest(config)','false'));
|
|
76
|
+
assert.notEqual(out.status,2,'mutation reached host instead of rejecting resume binding');
|
|
77
|
+
});
|
|
@@ -0,0 +1,276 @@
|
|
|
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 {openRefactorRecords} from '../runtime/js/cm-refactor/records.mjs';
|
|
8
|
+
import {fixture,fullResponse,original,replacement} from './fixtures/cm-refactor.mjs';
|
|
9
|
+
|
|
10
|
+
const initialRules='Named functions; preserve values; do not fix bugs.';
|
|
11
|
+
const revisedRules=initialRules+' Preserve negative-input guards before additions.';
|
|
12
|
+
const generated=replacement+'// REFACTOR STATUS: confidence=high todos=0\n';
|
|
13
|
+
const foreign=Buffer.from('// foreign edit: 请保留\r\nexport const owner = "other";\r\n');
|
|
14
|
+
const batchKey='a1/batch-1-1';
|
|
15
|
+
const generationKey=`host/${batchKey}/unit-input.mjs`;
|
|
16
|
+
|
|
17
|
+
function batchFixture(t,names=['input.mjs']){
|
|
18
|
+
const value=fixture(t),{config,project}=value;
|
|
19
|
+
for(const name of names)if(name!=='input.mjs')fs.writeFileSync(path.join(project,name),'export const helper = 1;\n');
|
|
20
|
+
// Same isolated Git fixture as cm-refactor-host.test.mjs; never touches checkout Git state.
|
|
21
|
+
for(const args of [['init','-q'],['add','.'],['-c','user.name=Fixture','-c','user.email=fixture@example.invalid','commit','-qm','fixture']]){
|
|
22
|
+
const out=spawnSync('git',args,{cwd:project});assert.equal(out.status,0,out.stderr.toString());
|
|
23
|
+
}
|
|
24
|
+
config.scope=names;config.batch={assemblyFiles:[],cheapCommands:[{id:'syntax',command:[process.execPath,'--check','{file}']}],maxPasses:3};
|
|
25
|
+
return {...value,directory:path.join(project,'docs/refactors/extract')};
|
|
26
|
+
}
|
|
27
|
+
function answer(kind,payload){
|
|
28
|
+
const value=fullResponse(kind,payload);
|
|
29
|
+
// The shared full-track fixture normally requests entry assembly and AGENTS writeback.
|
|
30
|
+
// These tests authorize only source files, so return the same generator without those needs.
|
|
31
|
+
if(kind==='refactor_batch'&&payload.action==='generate')value.needs=[];
|
|
32
|
+
if(kind==='refactor_retrospective'){
|
|
33
|
+
value.learning={status:'no_new_lesson',candidates:[],reason:null};value.conventions=[];
|
|
34
|
+
}
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
const journal=directory=>fs.readFileSync(path.join(directory,'execution.jsonl'),'utf8').trimEnd().split('\n').map(line=>JSON.parse(line));
|
|
38
|
+
const report=(directory,name)=>JSON.parse(fs.readFileSync(path.join(directory,name),'utf8').replace(/^```json\n/,'').replace(/\n```\n$/,''));
|
|
39
|
+
|
|
40
|
+
for(const verdicts of [['rule_correct'],['rule_missing'],['rule_wrong'],['rule_correct','rule_missing','rule_wrong']]){
|
|
41
|
+
test(`bakeoff accepts ${verdicts.join('+')}, publishes all decisions and forwards adjudicated rules`,async t=>{
|
|
42
|
+
const names=['input.mjs','helper.mjs','other.mjs'].slice(0,verdicts.length);
|
|
43
|
+
const {config,directory}=batchFixture(t,names),calls=[];
|
|
44
|
+
const decisions=names.map((name,i)=>({path:name,verdict:verdicts[i],reason:`Preserve the boundary in ${name}`}));
|
|
45
|
+
const host=createCmRefactorHost(config,{call:async(kind,payload)=>{
|
|
46
|
+
calls.push({kind,payload});const value=answer(kind,payload);
|
|
47
|
+
if(payload.action==='plan')value.sample=names;
|
|
48
|
+
if(payload.action==='bakeoff'&&payload.variant==='blind')value.files.forEach(file=>{file.content+='// alternate structure\n';});
|
|
49
|
+
if(payload.action==='adjudicate')Object.assign(value,{rulebook:revisedRules,decisions});
|
|
50
|
+
return value;
|
|
51
|
+
}});
|
|
52
|
+
const result=await host.handle({operation:'start'});
|
|
53
|
+
assert.equal(result.stage,'awaiting_finish',JSON.stringify(result));
|
|
54
|
+
assert.equal(calls.find(row=>row.payload.gate==='g0').payload.analysis.decision,'proceed');
|
|
55
|
+
assert.ok(result.reports.includes(path.join(directory,'a1-bakeoff.md')));
|
|
56
|
+
assert.deepEqual(report(directory,'a1-bakeoff.md').adjudication,{channelId:'third',rulebook:revisedRules,decisions});
|
|
57
|
+
const index=calls.findIndex(row=>row.payload.action==='adjudicate');
|
|
58
|
+
assert.equal(calls[index].payload.rulebook,initialRules);
|
|
59
|
+
const next=calls.slice(index+1).find(row=>Object.hasOwn(row.payload,'rulebook'));
|
|
60
|
+
assert.equal(next.payload.action,'generate');assert.equal(next.payload.rulebook,revisedRules);
|
|
61
|
+
assert.ok(calls.slice(index+1).filter(row=>Object.hasOwn(row.payload,'rulebook')).every(row=>row.payload.rulebook===revisedRules));
|
|
62
|
+
assert.equal(Object.hasOwn(calls.find(row=>row.payload.variant==='blind').payload,'rulebook'),false);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const revisionRefusals=[
|
|
67
|
+
{name:'rule_missing with unchanged rules',verdicts:['rule_missing']},
|
|
68
|
+
{name:'rule_wrong with unchanged rules',verdicts:['rule_wrong']},
|
|
69
|
+
{name:'mixed verdicts with unchanged rules',verdicts:['rule_correct','rule_missing']},
|
|
70
|
+
{name:'rule_missing with trailing whitespace only',transform:rules=>rules.split('\n').map(line=>line+' \t').join('\n')},
|
|
71
|
+
{name:'rule_missing with CRLF only',transform:rules=>rules.replaceAll('\n','\r\n')},
|
|
72
|
+
{name:'rule_missing with outer blank lines only',transform:rules=>'\n\n'+rules+'\n\n'},
|
|
73
|
+
{name:'rule_missing with combined whitespace only',transform:rules=>' \t\r\n\r\n'+rules.replaceAll('\n',' \t\r\n')+' \t\r\n\r\n'}
|
|
74
|
+
];
|
|
75
|
+
for(const scenario of revisionRefusals)test(`bakeoff refuses ${scenario.name} with refactor_rule_revision_required`,async t=>{
|
|
76
|
+
const verdicts=scenario.verdicts??['rule_missing'];
|
|
77
|
+
const names=['input.mjs','helper.mjs'].slice(0,verdicts.length);
|
|
78
|
+
const {config,project,directory}=batchFixture(t,names),calls=[];
|
|
79
|
+
const rules=initialRules+'\nKeep boundary behavior.';
|
|
80
|
+
const host=createCmRefactorHost(config,{call:async(kind,payload)=>{
|
|
81
|
+
calls.push({kind,payload});const value=answer(kind,payload);
|
|
82
|
+
if(payload.action==='plan')Object.assign(value,{sample:names,rulebook:rules});
|
|
83
|
+
if(payload.action==='bakeoff'&&payload.variant==='blind')value.files.forEach(file=>{file.content+='// different\n';});
|
|
84
|
+
if(payload.action==='adjudicate')Object.assign(value,{rulebook:scenario.transform?.(rules)??rules,
|
|
85
|
+
decisions:names.map((name,i)=>({path:name,verdict:verdicts[i],reason:'Check negative bounds'}))});
|
|
86
|
+
return value;
|
|
87
|
+
}});
|
|
88
|
+
const result=await host.handle({operation:'start'});
|
|
89
|
+
assert.equal(result.reason,'refactor_rule_revision_required');assert.equal(result.stage,'blocked');
|
|
90
|
+
assert.equal(fs.existsSync(path.join(directory,'a1-bakeoff.md')),false);
|
|
91
|
+
assert.equal(result.reports.some(file=>file.endsWith('a1-bakeoff.md')),false);
|
|
92
|
+
assert.equal(calls.some(row=>row.payload.action==='generate'),false,'no pilot request');
|
|
93
|
+
const rows=journal(directory);
|
|
94
|
+
assert.equal(rows.some(row=>row.key?.includes('/pilot-')),false);
|
|
95
|
+
assert.equal(rows.some(row=>row.key==='publish/a1-bakeoff'),false);
|
|
96
|
+
assert.equal(fs.readFileSync(path.join(project,'input.mjs'),'utf8'),original);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('bakeoff accepts all rule_correct with unchanged rules',async t=>{
|
|
100
|
+
const {config,directory}=batchFixture(t),calls=[];
|
|
101
|
+
const host=createCmRefactorHost(config,{call:async(kind,payload)=>{
|
|
102
|
+
calls.push({kind,payload});const value=answer(kind,payload);
|
|
103
|
+
if(payload.action==='bakeoff'&&payload.variant==='blind')value.files[0].content+='// different\n';
|
|
104
|
+
if(payload.action==='adjudicate')Object.assign(value,{rulebook:initialRules,
|
|
105
|
+
decisions:[{path:'input.mjs',verdict:'rule_correct',reason:'Keep existing guard order'}]});
|
|
106
|
+
return value;
|
|
107
|
+
}});
|
|
108
|
+
const result=await host.handle({operation:'start'});
|
|
109
|
+
assert.equal(result.stage,'awaiting_finish',JSON.stringify(result));
|
|
110
|
+
assert.equal(report(directory,'a1-bakeoff.md').adjudication.rulebook,initialRules);
|
|
111
|
+
assert.ok(calls.some(row=>row.payload.action==='generate'));
|
|
112
|
+
assert.ok(calls.filter(row=>Object.hasOwn(row.payload,'rulebook')).every(row=>row.payload.rulebook===initialRules));
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const refusals=[
|
|
116
|
+
{name:'fourth verdict',code:'refactor_bakeoff_coverage',judge:value=>{value.decisions[0].verdict='rule_ok';}},
|
|
117
|
+
{name:'uppercase verdict',code:'refactor_bakeoff_coverage',judge:value=>{value.decisions[0].verdict='RULE_CORRECT';}},
|
|
118
|
+
{name:'empty reason',code:'refactor_bakeoff_coverage',judge:value=>{value.decisions[0].reason='';}},
|
|
119
|
+
{name:'whitespace reason',code:'refactor_bakeoff_coverage',judge:value=>{value.decisions[0].reason=' \t\n';}},
|
|
120
|
+
{name:'missing differing-file decision',code:'refactor_bakeoff_coverage',judge:value=>{value.decisions=[];}},
|
|
121
|
+
...['guided','blind'].map(variant=>({name:`missing ${variant} file`,code:'refactor_bakeoff_coverage',author:(value,payload)=>{
|
|
122
|
+
if(payload.variant===variant)value.files=[];
|
|
123
|
+
}})),
|
|
124
|
+
{name:'same author channel',code:'refactor_bakeoff_not_independent',author:value=>{value.channelId='shared';}},
|
|
125
|
+
...['guided','blind'].map(channel=>({name:`adjudicator reuses ${channel} channel`,code:'refactor_bakeoff_invalid',judge:value=>{value.channelId=channel;}})),
|
|
126
|
+
{name:'empty adjudicated rulebook',code:'refactor_bakeoff_invalid',judge:value=>{value.rulebook='';}},
|
|
127
|
+
{name:'whitespace adjudicated rulebook',code:'refactor_bakeoff_invalid',judge:value=>{value.rulebook=' \n';}},
|
|
128
|
+
{name:'missing decisions array',code:'refactor_bakeoff_invalid',judge:value=>{delete value.decisions;}}
|
|
129
|
+
];
|
|
130
|
+
for(const scenario of refusals)test(`bakeoff refuses ${scenario.name} with ${scenario.code}`,async t=>{
|
|
131
|
+
const {config,project,directory}=batchFixture(t);let generations=0;
|
|
132
|
+
const host=createCmRefactorHost(config,{call:async(kind,payload)=>{
|
|
133
|
+
const value=answer(kind,payload);
|
|
134
|
+
if(payload.action==='generate')generations++;
|
|
135
|
+
if(payload.action==='bakeoff'){
|
|
136
|
+
if(payload.variant==='blind')value.files[0].content+='// different\n';
|
|
137
|
+
scenario.author?.(value,payload);
|
|
138
|
+
}
|
|
139
|
+
if(payload.action==='adjudicate'){
|
|
140
|
+
Object.assign(value,{rulebook:revisedRules,decisions:[{path:'input.mjs',verdict:'rule_correct',reason:'Keep guard order'}]});
|
|
141
|
+
scenario.judge?.(value);
|
|
142
|
+
}
|
|
143
|
+
return value;
|
|
144
|
+
}});
|
|
145
|
+
const result=await host.handle({operation:'start'});
|
|
146
|
+
assert.equal(result.stage,'blocked');assert.equal(result.reason,scenario.code);
|
|
147
|
+
assert.equal(generations,0);assert.equal(fs.existsSync(path.join(directory,'a1-bakeoff.md')),false);
|
|
148
|
+
assert.equal(fs.readFileSync(path.join(project,'input.mjs'),'utf8'),original);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test('bakeoff identical outputs require no decision',async t=>{
|
|
152
|
+
const {config,directory}=batchFixture(t),host=createCmRefactorHost(config,{call:async(kind,payload)=>answer(kind,payload)});
|
|
153
|
+
const result=await host.handle({operation:'start'});assert.equal(result.stage,'awaiting_finish',JSON.stringify(result));
|
|
154
|
+
const value=report(directory,'a1-bakeoff.md');
|
|
155
|
+
assert.deepEqual(value.trial.guided.files,value.trial.blind.files);assert.deepEqual(value.adjudication.decisions,[]);
|
|
156
|
+
assert.equal(value.adjudication.rulebook,initialRules);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
function assertHalted(result,directory,code,target,calls){
|
|
160
|
+
assert.equal(result.stage,'blocked',JSON.stringify(result));assert.equal(result.reason,code);
|
|
161
|
+
assert.deepEqual(fs.readFileSync(target),foreign,'foreign bytes must survive');
|
|
162
|
+
assert.equal(fs.existsSync(path.join(directory,'a1-batch-1-1-failure.md')),false);
|
|
163
|
+
assert.equal(result.reports.some(file=>file.endsWith('a1-batch-1-1-failure.md')),false);
|
|
164
|
+
const rows=journal(directory);
|
|
165
|
+
assert.equal(rows.some(row=>row.key?.includes(`${batchKey}/failed-restore`)),false);
|
|
166
|
+
assert.equal(rows.some(row=>/a1\/(?:batch-1-[2-9]|batch-2-|pilot-2)/.test(row.key??'')),false);
|
|
167
|
+
assert.deepEqual(rows.filter(row=>row.type==='intent'&&row.kind==='log'&&row.input.event==='task_start')
|
|
168
|
+
.map(row=>[row.input.data.batch,row.input.data.cycle]),[[1,1]]);
|
|
169
|
+
assert.equal(calls.some(row=>['diagnose','plan','generate','assemble'].includes(row.payload.action)),false,'no further batch/cycle');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Interrupt a real production invocation. Pilot, judge and rulebook approval have completed.
|
|
173
|
+
async function interruptGeneration(config){
|
|
174
|
+
let generations=0,pending;
|
|
175
|
+
const host=createCmRefactorHost(config,{call:async(kind,payload)=>{
|
|
176
|
+
if(payload.action==='generate'&&++generations===2){pending={kind,payload};throw Error('fixture connection lost');}
|
|
177
|
+
return answer(kind,payload);
|
|
178
|
+
}});
|
|
179
|
+
const result=await host.handle({operation:'start'});
|
|
180
|
+
assert.equal(result.stage,'blocked');assert.equal(result.reason,'fixture connection lost');assert.ok(pending);
|
|
181
|
+
return pending;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
for(const code of ['refactor_source_changed','refactor_out_of_scope_change','refactor_unknown_effect']){
|
|
185
|
+
test(`${code} during production recovery preserves foreign bytes and halts without retry`,async t=>{
|
|
186
|
+
const {config,project,directory}=batchFixture(t,['input.mjs','helper.mjs']);
|
|
187
|
+
const pending=await interruptGeneration(config),calls=[];
|
|
188
|
+
const target=path.join(project,code==='refactor_source_changed'?'input.mjs':'foreign.mjs');
|
|
189
|
+
const resumed=createCmRefactorHost(config,{call:async(kind,payload)=>{
|
|
190
|
+
calls.push({kind,payload});assert.equal(kind,'refactor_recover');
|
|
191
|
+
assert.equal(payload.kind,'host');assert.deepEqual(payload.input,{kind:pending.kind,payload:pending.payload});
|
|
192
|
+
fs.writeFileSync(target,foreign);
|
|
193
|
+
if(code==='refactor_unknown_effect')return {decision:'unknown',evidence:'Original invocation receipt unavailable'};
|
|
194
|
+
// recover() validates before calling the host. A completed receipt is persisted, then
|
|
195
|
+
// the real pre-apply guard sees this edit, with no pending host/command to mask the code.
|
|
196
|
+
return {decision:'completed',evidence:'Synthetic original invocation receipt',result:{value:answer(pending.kind,pending.payload),durationMs:1}};
|
|
197
|
+
}});
|
|
198
|
+
const result=await resumed.handle({operation:'resume'});
|
|
199
|
+
assertHalted(result,directory,code,target,calls);assert.equal(calls.length,1);
|
|
200
|
+
const rows=journal(directory),completed=rows.some(row=>row.type==='result'&&row.key===generationKey);
|
|
201
|
+
assert.equal(completed,code!=='refactor_unknown_effect');
|
|
202
|
+
assert.equal(fs.readFileSync(path.join(project,'helper.mjs'),'utf8'),'export const helper = 1;\n');
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
test('refactor_write_conflict during atomic batch write preserves the third value and halts',async t=>{
|
|
207
|
+
const {config,project,directory}=batchFixture(t,['input.mjs','helper.mjs']);
|
|
208
|
+
const target=path.join(project,'input.mjs');let generations=0,armed=false,injections=0;const afterConflict=[];
|
|
209
|
+
const realFsync=fs.fsyncSync;
|
|
210
|
+
// Fault injection at the real atomic-write boundary, not a mocked guard or synthetic error.
|
|
211
|
+
// The journal intent and staged replacement have been fsynced; another writer wins before
|
|
212
|
+
// replaceText's second comparison. Match the real staged inode without touching its fd.
|
|
213
|
+
t.mock.method(fs,'fsyncSync',function(fd){
|
|
214
|
+
const result=realFsync(fd);
|
|
215
|
+
if(armed&&fs.fstatSync(fd).isFile()&&fs.fstatSync(fd).size===Buffer.byteLength(generated)){
|
|
216
|
+
const stat=fs.fstatSync(fd),staged=fs.readdirSync(project).filter(name=>name.startsWith('.cm-refactor-'))
|
|
217
|
+
.map(name=>path.join(project,name)).find(file=>fs.statSync(file).ino===stat.ino&&fs.statSync(file).dev===stat.dev);
|
|
218
|
+
if(staged&&fs.readFileSync(staged,'utf8')===generated){armed=false;injections++;fs.writeFileSync(target,foreign);}
|
|
219
|
+
}
|
|
220
|
+
return result;
|
|
221
|
+
});
|
|
222
|
+
const host=createCmRefactorHost(config,{call:async(kind,payload)=>{
|
|
223
|
+
if(injections)afterConflict.push({kind,payload});
|
|
224
|
+
if(payload.action==='generate'&&++generations===2)armed=true;
|
|
225
|
+
return answer(kind,payload);
|
|
226
|
+
}});
|
|
227
|
+
const result=await host.handle({operation:'start'});
|
|
228
|
+
assert.equal(injections,1);assertHalted(result,directory,'refactor_write_conflict',target,afterConflict);
|
|
229
|
+
assert.equal(afterConflict.length,0);
|
|
230
|
+
const key=`write/${batchKey}/unit-input.mjs/input.mjs`,rows=journal(directory);
|
|
231
|
+
const intent=rows.find(row=>row.type==='intent'&&row.key===key);
|
|
232
|
+
assert.equal(intent.input.before,original);assert.equal(intent.input.after,generated);
|
|
233
|
+
assert.equal(rows.some(row=>row.type==='result'&&row.key===key),false);
|
|
234
|
+
// Startup guard must also refuse this authentic interrupted write before replay or host calls.
|
|
235
|
+
const reopened=createCmRefactorHost(config,{call:async()=>assert.fail('conflicted write cannot resume')});
|
|
236
|
+
assertHalted(await reopened.handle({operation:'resume'}),directory,'refactor_write_conflict',target,[]);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test('ordinary cheap-check failure restores the production batch, reports it and retries successfully',async t=>{
|
|
240
|
+
const {config,project,directory}=batchFixture(t,['input.mjs','helper.mjs']);let generations=0,diagnoses=0;
|
|
241
|
+
const host=createCmRefactorHost(config,{call:async(kind,payload)=>{
|
|
242
|
+
const value=answer(kind,payload);
|
|
243
|
+
if(payload.action==='generate'&&payload.files[0].path==='input.mjs'){
|
|
244
|
+
generations++;
|
|
245
|
+
if(generations===2)value.files[0].content='export const calc = ;\n// REFACTOR STATUS: confidence=low todos=0\n';
|
|
246
|
+
if(generations===3){assert.equal(fs.readFileSync(path.join(project,'input.mjs'),'utf8'),original);assert.equal(payload.files[0].content,original);}
|
|
247
|
+
}
|
|
248
|
+
if(payload.action==='diagnose'){
|
|
249
|
+
diagnoses++;assert.equal(payload.failure,'refactor_cheap_check_failed');
|
|
250
|
+
assert.equal(fs.readFileSync(path.join(project,'input.mjs'),'utf8'),original);
|
|
251
|
+
const failure=report(directory,'a1-batch-1-1-failure.md');
|
|
252
|
+
assert.equal(failure.failure,'refactor_cheap_check_failed');assert.equal(failure.output.observed.outcome,'failed');assert.equal(failure.pilot,false);
|
|
253
|
+
}
|
|
254
|
+
return value;
|
|
255
|
+
}});
|
|
256
|
+
const result=await host.handle({operation:'start'});
|
|
257
|
+
assert.equal(result.stage,'awaiting_finish',JSON.stringify(result));assert.equal(generations,3);assert.equal(diagnoses,1);
|
|
258
|
+
assert.equal(fs.readFileSync(path.join(project,'input.mjs'),'utf8'),generated);
|
|
259
|
+
assert.ok(result.reports.includes(path.join(directory,'a1-batch-1-1-failure.md')));
|
|
260
|
+
const rows=journal(directory);
|
|
261
|
+
assert.ok(rows.some(row=>row.type==='result'&&row.key===`write/${batchKey}/failed-restore/input.mjs`));
|
|
262
|
+
assert.ok(rows.some(row=>row.type==='result'&&row.key==='host/a1/batch-1-2/unit-input.mjs'));
|
|
263
|
+
assert.ok(rows.some(row=>row.type==='result'&&row.key==='host/a1/batch-2-1/unit-helper.mjs'));
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
test('records refuses recovery of an interrupted effect without a recovery handler',async t=>{
|
|
267
|
+
const {temp}=fixture(t),directory=path.join(temp,'records'),target=path.join(temp,'foreign.txt');
|
|
268
|
+
const first=openRefactorRecords(directory);first.acquire();
|
|
269
|
+
try{await assert.rejects(first.effect('hash','hash',{},()=>{throw Error('interrupted');}),/interrupted/);}finally{first.release();}
|
|
270
|
+
fs.writeFileSync(target,foreign);
|
|
271
|
+
const reopened=openRefactorRecords(directory);reopened.acquire();
|
|
272
|
+
try{
|
|
273
|
+
await assert.rejects(reopened.effect('hash','hash',{},()=>assert.fail('must not repeat')),{code:'refactor_unknown_effect'});
|
|
274
|
+
assert.deepEqual(fs.readFileSync(target),foreign);
|
|
275
|
+
}finally{reopened.release();}
|
|
276
|
+
});
|