@aibyzero/cm-workflow 0.16.1 → 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 +179 -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 +79 -0
- 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 +38 -5
- 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/metrics-table.mjs +22 -0
- 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 +369 -83
- package/runtime/js/cm-fix/host.mjs +7 -3
- package/runtime/js/cm-fix/layout.mjs +34 -0
- package/runtime/js/cm-fix/metrics.mjs +2 -4
- 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-fix/walkthrough.mjs +8 -2
- 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 +103 -21
- package/scripts/audit-untested-enums.mjs +59 -0
- 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-execution-diagnostic.test.mjs +25 -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 +67 -0
- package/scripts/cm-fix-host.mjs +4 -2
- package/scripts/cm-fix-metrics.test.mjs +32 -0
- 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-release-smoke.sh +14 -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
|
@@ -11,9 +11,11 @@ import {writeImmutableWorkflowFile} from '../cm-ai/review-evidence-file.mjs';
|
|
|
11
11
|
import {mergeLessons} from '../cm-ai/cm-ai-learning-writer.mjs';
|
|
12
12
|
import {readLearningRetrospectiveContent} from '../cm-ai/cm-ai-context-refresh.mjs';
|
|
13
13
|
import {need,shape,json,digest} from '../cm-ai/effect-contract.mjs';
|
|
14
|
+
import {METRICS_HEADER,hasMetricsHeader} from '../cm-ai/metrics-table.mjs';
|
|
14
15
|
import {inside,canonicalFuture,snapshotSource} from '../cm-test/source-snapshot.mjs';
|
|
15
16
|
import {openRefactorRecords,readText,replaceText,sha} from './records.mjs';
|
|
16
17
|
const nonempty=value=>typeof value==='string'&&value.trim().length>0;
|
|
18
|
+
const normalizedRulebook=value=>value.replace(/\r\n?/g,'\n').split('\n').map(line=>line.trimEnd()).join('\n').replace(/^\n+|\n+$/g,'');
|
|
17
19
|
const markdown=value=>'```json\n'+JSON.stringify(value,null,2)+'\n```\n';
|
|
18
20
|
const relative=name=>typeof name==='string'&&!path.isAbsolute(name)&&!name.includes('\\')
|
|
19
21
|
&&name.split('/').every(part=>part&&part!=='.'&&part!=='..');
|
|
@@ -182,15 +184,48 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
182
184
|
}
|
|
183
185
|
async function restore(key,before){for(const [name,value] of Object.entries(before))if(!name.startsWith('__')&&files[name]!==value)
|
|
184
186
|
await write(`${key}/${name}`,absolute(name),files[name],value,context.modes[name]??0o644);}
|
|
185
|
-
async function
|
|
186
|
-
|
|
187
|
+
async function restoreBusiness(key,before){for(const name of config.scope)if(files[name]!==before[name])
|
|
188
|
+
await write(`${key}/${name}`,absolute(name),files[name],before[name],context.modes[name]??0o644);}
|
|
189
|
+
function checkJudgeRevision(revision){
|
|
190
|
+
need(revision&&Array.isArray(revision.paths)&&revision.paths.length>0&&nonempty(revision.reason)
|
|
191
|
+
&&new Set(revision.paths).size===revision.paths.length&&revision.paths.every(name=>setup.paths.includes(name)),
|
|
192
|
+
'refactor_judge_revision_scope');
|
|
193
|
+
shape(revision,['paths','reason']);
|
|
194
|
+
}
|
|
195
|
+
const saveJudgeRegistration=input=>records.effect('judge-revision-registration','checkpoint',input,
|
|
196
|
+
()=>({prepared:true}),()=>({prepared:true}));
|
|
197
|
+
async function prepareJudgeRevision(revision){
|
|
198
|
+
checkJudgeRevision(revision);
|
|
199
|
+
const existing=records.effects.get('judge-revision-registration');
|
|
200
|
+
if(existing){
|
|
201
|
+
need(digest(existing.input.revision)===digest(revision),'refactor_judge_revision_conflict');
|
|
202
|
+
await saveJudgeRegistration(existing.input);return status();
|
|
203
|
+
}
|
|
204
|
+
need(!unknown(),'refactor_unknown_effect');
|
|
205
|
+
const first=records.effects.get('host/a1/review');
|
|
206
|
+
need(first?.result?.value&&!Object.hasOwn(first.result.value,'judgeRevision'),'refactor_judge_revision_unavailable');
|
|
207
|
+
const review=path.join(reviews,`${feature}-${task}-r1.md`),content=readText(review);
|
|
208
|
+
need(content===first.result.value.markdown,'refactor_judge_revision_unavailable');
|
|
209
|
+
const checked=validateReview(review,{task,attempt:1,handoff:first.input.payload.handoff,
|
|
210
|
+
changedFiles:first.input.payload.files.map(file=>file.path)});
|
|
211
|
+
need(checked.verdict==='changes_requested','refactor_judge_revision_unavailable');
|
|
212
|
+
// Only an unconsumed round 2 can be extended. A rejected text-only proposal is historical, not a write.
|
|
213
|
+
const consumed=[...records.effects].some(([key])=>/^(host|write|command|publish)\/a2(?:[/-]|$)/.test(key)&&key!=='host/a2/apply');
|
|
214
|
+
need(!consumed,'refactor_judge_revision_unavailable');
|
|
215
|
+
const old=records.effects.get('host/a2/apply');
|
|
216
|
+
await saveJudgeRegistration({revision,review,reviewSha256:sha(content),reviewResultDigest:digest(first.result),
|
|
217
|
+
supersededApply:old?{key:'host/a2/apply',inputDigest:digest(old.input),resultDigest:digest(old.result)}:null});
|
|
218
|
+
attempt=2;progress('judge_revision_prepared');return status();
|
|
219
|
+
}
|
|
220
|
+
async function prepareJudges(prefix='',maxRevisions=3){
|
|
221
|
+
if(!prefix&&setup.paths.some(name=>files[name]===null)){
|
|
187
222
|
const result=await invoke('judge-prepare','refactor_prepare_tests',{target:config.target,files:source(config.scope),assets:source(setup.paths),
|
|
188
223
|
baselineCommands:config.baselineCommands,judgeCommand:config.judgeCommand,route:routes.tester,
|
|
189
224
|
instructions:'Return {files:[{path,beforeDigest,content}]} only for declared test assets. Lock current behavior including bugs and boundary cases; preserve original environment resolution. No direct writes or commands, no new dependencies.'});
|
|
190
225
|
await apply('judge-prepare',result.files,setup.paths);
|
|
191
226
|
}
|
|
192
|
-
for(let revision=1;revision<=
|
|
193
|
-
const key
|
|
227
|
+
for(let revision=1;revision<=maxRevisions;revision++){
|
|
228
|
+
const key=`${prefix}judge-${revision}`;let failure=null;const mutations=[];
|
|
194
229
|
try{
|
|
195
230
|
await baseline(`${key}/baseline`);judgeBefore=await judge(`${key}/original`);
|
|
196
231
|
for(let n=0;n<config.mutations.length;n++){
|
|
@@ -200,7 +235,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
200
235
|
const old=files[mutation.path];need(typeof old==='string'&&old.split(mutation.find).length===2,'refactor_mutation_not_unique');
|
|
201
236
|
await write(`${key}-mutant-${n}`,absolute(mutation.path),old,old.replace(mutation.find,mutation.replace),context.modes[mutation.path]);
|
|
202
237
|
let observed;try{observed=await judge(`${key}/mutant-${n}`);}finally{
|
|
203
|
-
|
|
238
|
+
// New revision commands with unknown outcomes must keep their execution source for reconciliation.
|
|
239
|
+
if(!prefix||!unknown())await write(`${key}-restore-${n}`,absolute(mutation.path),files[mutation.path],old,context.modes[mutation.path]);}
|
|
204
240
|
const inputs=value=>value.cases.map(({id,input})=>({id,input}));
|
|
205
241
|
const detected=digest(inputs(observed))===digest(inputs(judgeBefore))&&digest(observed)!==digest(judgeBefore);
|
|
206
242
|
mutations.push({mutation,detected,observed});need(detected,'refactor_judge_missed_mutation');
|
|
@@ -208,13 +244,33 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
208
244
|
}catch(error){if(unknown())throw error;failure=error.code??error.message;}
|
|
209
245
|
await publish(key,path.join(directory,`${key}-report.md`),markdown({judgeBefore,mutations,failure}));
|
|
210
246
|
if(!failure)return;
|
|
211
|
-
need(!controller.signal.aborted,'cancelled');need(setup.paths.length&&revision<
|
|
247
|
+
need(!controller.signal.aborted,'cancelled');need(setup.paths.length&&revision<maxRevisions,failure);
|
|
212
248
|
const result=await invoke(`${key}-repair`,'refactor_prepare_tests',{failure,mutations,files:source(config.scope),assets:source(setup.paths),
|
|
213
249
|
baselineCommands:config.baselineCommands,judgeCommand:config.judgeCommand,route:routes.tester,
|
|
214
250
|
instructions:'Diagnose judge first; correct only declared test harness, never production behavior or configured mutations. Return {files:[{path,beforeDigest,content}]}. No commands or direct writes.'});
|
|
215
251
|
await apply(`${key}-repair`,result.files,setup.paths);await event(`${key}-repair`,'decision','judge_repair',{reason:failure});
|
|
216
252
|
}
|
|
217
253
|
}
|
|
254
|
+
async function reviseJudges(revision){
|
|
255
|
+
const key='a2/judge-revision';
|
|
256
|
+
const result=await invoke(key,'refactor_revise_tests',{attempt:2,findings:reviewResult,revision,
|
|
257
|
+
files:source(config.scope),assets:source(revision.paths),baselineCommands:config.baselineCommands,
|
|
258
|
+
judgeCommand:config.judgeCommand,route:routes.tester,
|
|
259
|
+
instructions:'Address the round-1 test/judge findings. Return {files:[{path,beforeDigest,content}]} only within assets. Preserve original behavior including bugs; the owner will validate against the startup business snapshot and the revised candidate. No direct writes, commands, dependencies, configuration or business edits.'});
|
|
260
|
+
need(Array.isArray(result.files)&&result.files.some(item=>item.content!==(files[item.path]??null)),'refactor_judge_revision_empty');
|
|
261
|
+
await publish('a2-judge-revision',path.join(directory,'a2-judge-revision.md'),markdown({
|
|
262
|
+
review:path.join(reviews,`${feature}-${task}-r1.md`),reviewSha256:sha(reviewResult.markdown),revision,files:result.files,
|
|
263
|
+
...(records.effects.has('judge-revision-registration')?{registration:records.effects.get('judge-revision-registration').input}:{})}));
|
|
264
|
+
await apply(key,result.files,revision.paths);
|
|
265
|
+
const candidate=Object.fromEntries(config.scope.map(name=>[name,files[name]]));
|
|
266
|
+
try{
|
|
267
|
+
await restoreBusiness('a2-judge-original',context.original);
|
|
268
|
+
// Rebuild answers and self-validation on the ORIGINAL business version, never on the candidate.
|
|
269
|
+
await prepareJudges('a2-',1);
|
|
270
|
+
}finally{
|
|
271
|
+
if(!unknown())await restoreBusiness('a2-judge-candidate',candidate);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
218
274
|
async function defineRules(key,previous=null,findings=null){
|
|
219
275
|
const plan=await invoke(key,'refactor_batch',{action:'plan',target:config.target,project,
|
|
220
276
|
files:source(config.scope).map(({path,content,beforeDigest})=>({path,exists:content!==null,beforeDigest})),assemblyFiles:batch.assemblyFiles,
|
|
@@ -226,7 +282,9 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
226
282
|
&&plan.sample.every(name=>config.scope.includes(name)&&files[name]!==null),'refactor_sample_invalid');
|
|
227
283
|
return {...plan,units};
|
|
228
284
|
}
|
|
229
|
-
async function batchFlow(prefix,findings){
|
|
285
|
+
async function batchFlow(prefix,findings,revisedJudges=false){
|
|
286
|
+
// The new path restores only business text; durable batch logs must remain append-only.
|
|
287
|
+
const restoreBatch=revisedJudges?restoreBusiness:restore;
|
|
230
288
|
const denies=JSON.parse(readText(path.join(workflowRoot,'templates/refactor/cm-refactor-denies.json')));
|
|
231
289
|
let plan=prefix==='a1'?{...initialPlan}:await defineRules(`${prefix}/plan`,rulebook,findings),revision=1;
|
|
232
290
|
const trial={};
|
|
@@ -241,13 +299,16 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
241
299
|
for(const name of plan.sample){const a=trial.guided.files.find(item=>item.path===name),b=trial.blind.files.find(item=>item.path===name);
|
|
242
300
|
need(a&&b,'refactor_bakeoff_coverage');if(digest(a.content)!==digest(b.content))need(adjudication.decisions.some(row=>row.path===name
|
|
243
301
|
&&['rule_correct','rule_missing','rule_wrong'].includes(row.verdict)&&nonempty(row.reason)),'refactor_bakeoff_coverage');}
|
|
302
|
+
// Require a textual revision; whether it fixes the problem remains for later independent review.
|
|
303
|
+
if(adjudication.decisions.some(row=>['rule_missing','rule_wrong'].includes(row?.verdict)))
|
|
304
|
+
need(normalizedRulebook(adjudication.rulebook)!==normalizedRulebook(plan.rulebook),'refactor_rule_revision_required');
|
|
244
305
|
plan.rulebook=adjudication.rulebook;
|
|
245
306
|
await publish(`${prefix}-bakeoff`,path.join(directory,`${prefix}-bakeoff.md`),markdown({trial,adjudication}));
|
|
246
307
|
// Pilot uses the same generation/cheap checks/assembly/equivalence pipeline; discard its products.
|
|
247
308
|
let pilotPassed=false;
|
|
248
309
|
for(let cycle=1;cycle<=3;cycle++){
|
|
249
|
-
const pilotBefore={...files},trialResult=await runBatch(`${prefix}/pilot-${cycle}`,plan.sample,plan.rulebook,revision,[],true);
|
|
250
|
-
await
|
|
310
|
+
const pilotBefore={...files},trialResult=await runBatch(`${prefix}/pilot-${cycle}`,plan.sample,plan.rulebook,revision,[],true,revisedJudges);
|
|
311
|
+
await restoreBatch(`${prefix}/pilot-discard-${cycle}`,pilotBefore);files.__needs=pilotBefore.__needs??[];
|
|
251
312
|
if(trialResult.passed){pilotPassed=true;break;}
|
|
252
313
|
if(cycle<3){const revised=await defineRules(`${prefix}/pilot-revise-${cycle}`,plan.rulebook,trialResult);
|
|
253
314
|
need(digest(revised.units)===digest(plan.units),'refactor_revision_scope_changed');plan.rulebook=revised.rulebook;}
|
|
@@ -265,9 +326,9 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
265
326
|
for(let cycle=1;cycle<=batch.maxPasses;cycle++){
|
|
266
327
|
const key=`${prefix}/batch-${index+1}-${cycle}`,before={...files};
|
|
267
328
|
await event(`${key}-start`,'task_start',null,{batch:index+1,total:plan.units.length,cycle});
|
|
268
|
-
const result=await runBatch(key,unit.files,rulebook,revision,[],false);
|
|
329
|
+
const result=await runBatch(key,unit.files,rulebook,revision,[],false,revisedJudges);
|
|
269
330
|
if(result.passed){passed=true;await event(`${key}-done`,'task_done',null,{batch:index+1,total:plan.units.length,differential_groups:judgeBefore.cases.length});break;}
|
|
270
|
-
await
|
|
331
|
+
await restoreBatch(`${key}-rollback`,before);await publish(`${key}-rollback`,path.join(directory,`${key.replaceAll('/','-')}-rollback.md`),markdown({unit,cycle,failure:result.failure,baselineHead:context.baseline.gitState?.head??null}));
|
|
271
332
|
await event(`${key}-rollback`,'error','rollback',{batch:index+1,cycle,reason:result.failure});
|
|
272
333
|
const diagnosed=await invoke(`${key}-diagnose`,'refactor_batch',{action:'diagnose',failure:result.failure,output:result.output,rulebook,
|
|
273
334
|
instructions:'Return {errorClass,reason}; identify root error category, not individual filename/line; judge-wide anomalies must be treated as judge faults first. No writes.'});
|
|
@@ -285,7 +346,7 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
285
346
|
}
|
|
286
347
|
files.__rulebook=readVirtualRulebook;return true;
|
|
287
348
|
}
|
|
288
|
-
async function runBatch(key,names,rules,revision,needs=[],pilot=false){
|
|
349
|
+
async function runBatch(key,names,rules,revision,needs=[],pilot=false,revisedJudges=false){
|
|
289
350
|
const before={...files},rows=[];let output=null;
|
|
290
351
|
try{
|
|
291
352
|
for(const name of names){
|
|
@@ -319,7 +380,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
319
380
|
return {passed:true};
|
|
320
381
|
}catch(error){
|
|
321
382
|
if(unknown()||controller.signal.aborted||['refactor_unknown_effect','refactor_source_changed','refactor_out_of_scope_change','refactor_write_conflict'].includes(error.code))throw error;
|
|
322
|
-
await
|
|
383
|
+
if(revisedJudges)await restoreBusiness(`${key}/failed-restore`,before);
|
|
384
|
+
else await restore(`${key}/failed-restore`,Object.fromEntries(Object.entries(before).filter(([name])=>!name.startsWith('__'))));
|
|
323
385
|
const failure=error.code??error.message;await publish(`${key}-failure`,path.join(directory,`${key.replaceAll('/','-')}-failure.md`),markdown({failure,output,rows,pilot}));
|
|
324
386
|
return {passed:false,failure,output};
|
|
325
387
|
}
|
|
@@ -362,6 +424,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
362
424
|
const dossierPath=()=>context.batch?path.join(directory,'dossier.md'):path.join(archiveRoot,`${context.startedAt.slice(0,10).replaceAll('-','')}-${config.slug}.md`);
|
|
363
425
|
async function flow(){
|
|
364
426
|
files={...context.original};reports=[];commandCount=0;hostCalls=0;humanCalls=0;interceptions=0;rulebook=null;reviewResult=null;proposal=null;judgeBefore=null;attempt=1;
|
|
427
|
+
let judgeRevision=null;const registration=records.effects.get('judge-revision-registration');
|
|
428
|
+
if(registration?.input.supersededApply)hostCalls++;
|
|
365
429
|
await event('start','run_start',null);await event('g0','node_enter',null);
|
|
366
430
|
for(const [role,route] of Object.entries(routes))await event(`route-${role}`,'decision','route',{role,adapter:route.adapter,requested_model:route.model,source:route.source,route_state:route.route_state});
|
|
367
431
|
analysis=await invoke('analysis','refactor_analyze',{target:config.target,project,scope:config.scope,
|
|
@@ -378,14 +442,18 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
378
442
|
await event('rejected','run_done',null,{result:'rejected'});progress('rejected');return false;}
|
|
379
443
|
await event('judge','node_enter',null);await prepareJudges();
|
|
380
444
|
for(attempt=1;attempt<=2;attempt++){
|
|
445
|
+
if(attempt===2&&judgeRevision)await reviseJudges(judgeRevision);
|
|
381
446
|
const prefix=`a${attempt}`;await event(`${prefix}-execute`,'node_enter',null);progress('implementing');
|
|
382
447
|
if(!context.batch)await event(`${prefix}-task`,'task_start',null,{attempt});
|
|
383
|
-
if(context.batch){if(!await batchFlow(prefix,reviewResult)){progress('rulebook_rejected');return false;}}
|
|
448
|
+
if(context.batch){if(!await batchFlow(prefix,reviewResult,Boolean(judgeRevision))){progress('rulebook_rejected');return false;}}
|
|
384
449
|
else{
|
|
385
|
-
|
|
450
|
+
const applyKey=attempt===2&®istration?'a2-after-judge-revision/apply':`${prefix}/apply`;
|
|
451
|
+
proposal=await invoke(applyKey,'refactor_apply',{target:config.target,analysis,attempt,files:source(config.scope),findings:reviewResult,route:routes.coder,
|
|
386
452
|
instructions:'Propose structure-only replacements, no file writes/commands/bug fixes. Return {files:[{path,beforeDigest,content}],summary,metricAfter,unfixedDefects:[],conventions:[],learningApplication,learningRetrospective}. New lessons must be reported, not hidden.'});
|
|
387
|
-
need(proposal.files.every(item=>item.content!==null),'refactor_deletion_requires_batch');await apply(
|
|
388
|
-
try{await equivalents(prefix);}catch(error){if(!unknown())
|
|
453
|
+
need(proposal.files.every(item=>item.content!==null),'refactor_deletion_requires_batch');await apply(applyKey,proposal.files,config.scope);
|
|
454
|
+
try{await equivalents(prefix);}catch(error){if(!unknown()){
|
|
455
|
+
if(judgeRevision)await restoreBusiness(`${prefix}/rollback`,context.original);
|
|
456
|
+
else await restore(`${prefix}/rollback`,Object.fromEntries(config.scope.map(name=>[name,context.original[name]])));}throw error;}
|
|
389
457
|
}
|
|
390
458
|
const retrospective=await writeback(prefix);
|
|
391
459
|
const changed=managedNames.filter(name=>(files[name]??null)!==context.original[name]);
|
|
@@ -407,6 +475,18 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
407
475
|
instructions:'Fresh independent reviewer per runtime/review.md, no author history. Review ALL diff including tests/Learning/rules/docs/LESSONS and judge coverage. Return {markdown} with original N4 header binding exact handoff SHA, attempt=round, scope, findings. No writes or unapproved provider. Missing channel is blocked, never invent approval.'});
|
|
408
476
|
const review=await publish(`${prefix}-review`,path.join(reviews,`${feature}-${task}-r${attempt}.md`),reviewed.markdown);
|
|
409
477
|
reviewResult=validateReview(review,{task,attempt,handoff,changedFiles:changed});interceptions+=Number(reviewResult.blocking_findings);
|
|
478
|
+
if(Object.hasOwn(reviewed,'judgeRevision')){
|
|
479
|
+
need(attempt===1&&reviewResult.verdict==='changes_requested','refactor_judge_revision_unavailable');
|
|
480
|
+
checkJudgeRevision(reviewed.judgeRevision);judgeRevision=reviewed.judgeRevision;
|
|
481
|
+
}
|
|
482
|
+
if(attempt===1&®istration){
|
|
483
|
+
need(!judgeRevision&&reviewResult.verdict==='changes_requested'
|
|
484
|
+
&®istration.input.reviewSha256===sha(reviewed.markdown)
|
|
485
|
+
&®istration.input.reviewResultDigest===digest(records.effects.get('host/a1/review').result),
|
|
486
|
+
'refactor_judge_revision_binding');
|
|
487
|
+
checkJudgeRevision(registration.input.revision);await saveJudgeRegistration(registration.input);
|
|
488
|
+
judgeRevision=registration.input.revision;
|
|
489
|
+
}
|
|
410
490
|
await event(`${prefix}-review-complete`,'review','complete',{attempt,verdict:reviewResult.verdict,blocking_findings:Number(reviewResult.blocking_findings)});
|
|
411
491
|
if(reviewResult.verdict==='changes_requested'&&attempt===1){reviewResult={...reviewResult,markdown:reviewed.markdown};continue;}
|
|
412
492
|
guard();checkN5(options);proposal={...retrospective,changed,options};progress('awaiting_finish');return true;
|
|
@@ -431,8 +511,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
431
511
|
await publish('dossier',dossierPath(),'# Refactor dossier\n\n'+markdown({analysis,metricAfter:proposal.metricAfter,changed:proposal.changed,reports,
|
|
432
512
|
delivery:'diff',hostCalls,commandCount,baselineCount:config.baselineCommands.length,differentialCount:judgeBefore.cases.length,
|
|
433
513
|
learning:proposal.learning,unfixedDefects:proposal.unfixedDefects,deviations:[],usage}));
|
|
434
|
-
if(specs){const header=
|
|
435
|
-
need(!old||old
|
|
514
|
+
if(specs){const header=METRICS_HEADER,old=context.metrics;
|
|
515
|
+
need(!old||hasMetricsHeader(old),'refactor_metrics_format');
|
|
436
516
|
const at=await records.effect('finish-time','clock',{},()=>new Date().toISOString());
|
|
437
517
|
const line=`| ${task} | refactor | ${context.startedAt} | ${at} | ${attempt} | ${interceptions} | 等价通过 | ${calls.filter(entry=>entry.input.kind==='refactor_confirm').length}:人门; delivery-diff; agents=${usage.agentCalls}; host_ms=${usage.hostDurationMs}; estimate_tokens=${usage.estimatedTokens??'unavailable'}; actual_tokens=unavailable; commands=${commandCount} |\n`;
|
|
438
518
|
await write('metrics',path.join(specs,'METRICS.md'),old,(old??`${header}\n| --- | --- | --- | --- | --- | --- | --- | --- |\n`)+(old&&!old.endsWith('\n')?'\n':'')+line,context.metricsMode);}
|
|
@@ -446,7 +526,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
446
526
|
if(request.operation==='cancel'){controller.abort();return {...status(),stage:'cancelled'};}
|
|
447
527
|
need(!active,'refactor_busy');active=true;controller=new AbortController();
|
|
448
528
|
try{
|
|
449
|
-
need(['start','resume','finish'].includes(request.operation),'invalid_request');
|
|
529
|
+
need(['start','resume','finish','prepare_judge_revision'].includes(request.operation),'invalid_request');
|
|
530
|
+
need(request.operation!=='prepare_judge_revision'||context,'refactor_not_started');records.acquire();
|
|
450
531
|
if(!context){
|
|
451
532
|
need(request.operation==='start','refactor_not_started');
|
|
452
533
|
need(fs.readdirSync(directory).every(name=>name==='.writer.json'),'refactor_legacy_recovery_required');
|
|
@@ -458,7 +539,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
458
539
|
modes:Object.fromEntries(managedNames.map(name=>[name,original[name]===null?0o644:fs.statSync(absolute(name)).mode&0o777])),
|
|
459
540
|
baseline:baselineSnapshot,batch:batchTrack,lessons:readText(lessons),lessonsMode:fs.existsSync(lessons)?fs.statSync(lessons).mode&0o777:0o644,
|
|
460
541
|
metrics:specs?readText(path.join(specs,'METRICS.md')):null,metricsMode:specs&&fs.existsSync(path.join(specs,'METRICS.md'))?fs.statSync(path.join(specs,'METRICS.md')).mode&0o777:0o600};records.initialize(context);
|
|
461
|
-
}else{guard();if(
|
|
542
|
+
}else{guard();if(request.operation==='prepare_judge_revision')return await prepareJudgeRevision(request.judgeRevision);
|
|
543
|
+
if(view.stage==='done')return status();need(request.operation!=='start','refactor_resume_required');}
|
|
462
544
|
if(await flow()){
|
|
463
545
|
if(request.operation==='resume'){
|
|
464
546
|
const rounds=[...records.effects.keys()].map(key=>/^command\/resume-check\/(\d+)\//.exec(key)).filter(Boolean).map(match=>Number(match[1]));
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 盘点 runtime 里「只能取这几个值」的枚举,逐个看测试有没有碰过。
|
|
3
|
+
//
|
|
4
|
+
// 为什么要有这个:一轮真实实跑里修掉的四个缺陷是同一个形状——文档承诺了某个选项,
|
|
5
|
+
// 代码里也确实有那条分支,但从来没有测试走过它。交付方式三选一只测了一种、统计表
|
|
6
|
+
// 列名「语义升级」只测了新名字、跨会话恢复一条都没有、iOS 软链接没测过。它们不是
|
|
7
|
+
// 被写坏的,是没人走过。这个脚本把同一形状的其余候选一次性列出来。
|
|
8
|
+
//
|
|
9
|
+
// 输出是候选,不是待办:内部记录类型和 typeof 判断也会被匹配到,人得自己分类。
|
|
10
|
+
// 分好类的结果见 docs/untested-branches.md;改完代码后重跑本脚本对照。
|
|
11
|
+
//
|
|
12
|
+
// node scripts/audit-untested-enums.mjs 列出所有缺覆盖的枚举取值
|
|
13
|
+
// node scripts/audit-untested-enums.mjs --summary 只报数字
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import {fileURLToPath} from 'node:url';
|
|
17
|
+
|
|
18
|
+
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
|
19
|
+
const summaryOnly=process.argv.includes('--summary');
|
|
20
|
+
|
|
21
|
+
const walk=dir=>fs.readdirSync(dir,{withFileTypes:true}).flatMap(entry=>{
|
|
22
|
+
const full=path.join(dir,entry.name);
|
|
23
|
+
return entry.isDirectory()?walk(full):full.endsWith('.mjs')?[full]:[];
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const tests=fs.readdirSync(path.join(root,'scripts'))
|
|
27
|
+
.filter(name=>name.endsWith('.test.mjs'))
|
|
28
|
+
.map(name=>fs.readFileSync(path.join(root,'scripts',name),'utf8')).join('\n');
|
|
29
|
+
const covered=value=>tests.includes(`'${value}'`)||tests.includes(`"${value}"`);
|
|
30
|
+
|
|
31
|
+
// 只认最常见的一种写法:['a','b'].includes(x)。漏掉别的写法好过误报一堆。
|
|
32
|
+
const pattern=/\[((?:'[a-z][a-z0-9_.-]*',\s*){1,8}'[a-z][a-z0-9_.-]*')\]\.includes\(/g;
|
|
33
|
+
const findings=[];
|
|
34
|
+
for(const file of walk(path.join(root,'runtime/js'))) {
|
|
35
|
+
fs.readFileSync(file,'utf8').split('\n').forEach((line,index)=>{
|
|
36
|
+
for(const match of line.matchAll(pattern)) {
|
|
37
|
+
const values=match[1].split(',').map(value=>value.trim().slice(1,-1));
|
|
38
|
+
const missing=values.filter(value=>!covered(value));
|
|
39
|
+
if(missing.length)findings.push({file:path.relative(root,file),line:index+1,values,missing});
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const values=new Set(findings.flatMap(finding=>finding.missing));
|
|
45
|
+
if(!summaryOnly) {
|
|
46
|
+
const byModule=new Map();
|
|
47
|
+
for(const finding of findings) {
|
|
48
|
+
const module=finding.file.split('/')[2]??finding.file;
|
|
49
|
+
byModule.set(module,[...(byModule.get(module)??[]),finding]);
|
|
50
|
+
}
|
|
51
|
+
for(const [module,list] of [...byModule].sort((a,b)=>b[1].length-a[1].length)) {
|
|
52
|
+
process.stdout.write(`\n${module} (${list.length} 处)\n`);
|
|
53
|
+
for(const finding of list)
|
|
54
|
+
process.stdout.write(` ${finding.file}:${finding.line} 缺 ${finding.missing.join(',')}`
|
|
55
|
+
+` 枚举 ${finding.values.join('|')}\n`);
|
|
56
|
+
}
|
|
57
|
+
process.stdout.write('\n');
|
|
58
|
+
}
|
|
59
|
+
process.stdout.write(`缺覆盖的枚举取值 ${values.size} 个,分布在 ${findings.length} 处\n`);
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// cm-ai-batch-host 的单步驾驶员;PLAN 路径相对 PLAN 文件。
|
|
3
|
+
// operation -> possible host_request kinds (conservative over all batch tasks):
|
|
4
|
+
// advance -> develop, check: cm-ai-batch-run.mjs handle/driveMember -> start,
|
|
5
|
+
// host-conversation-execution.mjs worker/check. Protected config makes check
|
|
6
|
+
// host-owned in createProjectExecution; provider development makes develop host-owned.
|
|
7
|
+
// advance -> qa_assess, qa_logic, qa_browser, documentation_sync,
|
|
8
|
+
// documentation_inspect: host-workflow-capabilities.mjs createHostWorkflowCapabilities;
|
|
9
|
+
// batch-run.mjs driveMember/handle can reach qa, context_refresh and finalization.
|
|
10
|
+
// advance -> verification_precheck: host-conversation-execution.mjs verificationGate.
|
|
11
|
+
// advance -> init_generate, init_verify: host-bootstrap.mjs via batch-host.mjs
|
|
12
|
+
// bootstraps; init_verify contains execution evidence, so this driver refuses.
|
|
13
|
+
// status/cancel -> none: batch-run.mjs handle routes only these and advance;
|
|
14
|
+
// host-session.mjs operationNames admits all three. Other operationNames belong
|
|
15
|
+
// to child/single-task hosts and are not batch operations.
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import {fileURLToPath} from 'node:url';
|
|
19
|
+
import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
|
|
20
|
+
import {decideHostQaPolicy} from '../runtime/js/cm-ai/host-qa-policy.mjs';
|
|
21
|
+
import {validateHostWorkflowConfiguration} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
|
|
22
|
+
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
23
|
+
import {validateRunDefinition} from './cm-ai-run.mjs';
|
|
24
|
+
import {createCmAiBatch} from './cm-ai-batch-run.mjs';
|
|
25
|
+
import {readConversationReviewConfiguration,readConversationProtection} from './cm-ai-host.mjs';
|
|
26
|
+
import {validateCmAiAnswer} from './cm-ai-drive.mjs';
|
|
27
|
+
import {stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
|
|
28
|
+
|
|
29
|
+
const HOST=fileURLToPath(new URL('./cm-ai-batch-host.mjs',import.meta.url));
|
|
30
|
+
const KINDS={develop:'develop.json',qa_assess:'qa-assess.json',
|
|
31
|
+
documentation_sync:'documentation-sync.json',documentation_inspect:'documentation-inspect.json'};
|
|
32
|
+
const PAIRS=new Set(['--runtime','--review-config','--browser-qa','--protected-conversation-config',
|
|
33
|
+
'--protected-config','--allow-provider-development','--allow-review']);
|
|
34
|
+
const FLAGS=new Set(['--allow-qa','--rerun-unknown-qa','--rerun-blocked-qa','--verification-precheck',
|
|
35
|
+
'--allow-bootstrap-write']);
|
|
36
|
+
const isObject=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
|
37
|
+
const nonempty=x=>typeof x==='string'&&x.trim().length>0;
|
|
38
|
+
function taskKey(task){return `${task.feature}/${task.taskId}`;}
|
|
39
|
+
function actualCwd(bundle,key,generation=1){
|
|
40
|
+
if(generation===2)return bundle.batch.codeProject;
|
|
41
|
+
const group=bundle.batch.parallel?.find(group=>group.includes(key));
|
|
42
|
+
if(!group)return bundle.batch.codeProject;
|
|
43
|
+
const id=key.slice(key.lastIndexOf('/')+1);
|
|
44
|
+
return path.resolve(bundle.batch.codeProject,'..','.cm-worktrees',bundle.batch.batchId.slice(0,8),id);
|
|
45
|
+
}
|
|
46
|
+
function checkCommandShape(commands,key){
|
|
47
|
+
if(!Array.isArray(commands)||!commands.length||commands.length>32)stop(2,`任务 ${key} 会反问 check,但 PLAN.checks.${key} 缺少真实命令列表`);
|
|
48
|
+
const ids=new Set();
|
|
49
|
+
for(const item of commands){
|
|
50
|
+
if(!isObject(item)||Object.keys(item).sort().join()!=='command,id'
|
|
51
|
+
||!nonempty(item.id)||ids.has(item.id)||!Array.isArray(item.command)||!item.command.length
|
|
52
|
+
||item.command.some(arg=>typeof arg!=='string'||arg.includes('\0')))
|
|
53
|
+
stop(2,`PLAN.checks.${key} 格式错误`);
|
|
54
|
+
ids.add(item.id);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function preflight(){
|
|
58
|
+
if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
|
|
59
|
+
process.stdout.write('用法: cm-ai-batch-drive.mjs --plan PLAN.json <operation>\n'
|
|
60
|
+
+'operation: advance, status, cancel。PLAN: config, mode, hostContext, permissions, answers, checks。\n');
|
|
61
|
+
process.exit(0);
|
|
62
|
+
}
|
|
63
|
+
const loaded=loadPlanFile({name:'cm-ai-batch-drive.mjs',known:new Set(['advance','status','cancel'])});
|
|
64
|
+
const {plan,base,operation}=loaded;
|
|
65
|
+
requireFields(plan,['config','mode','hostContext','permissions']);
|
|
66
|
+
if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
|
|
67
|
+
if(!nonempty(plan.hostContext))stop(2,'hostContext 必须是当前真实会话 ID');
|
|
68
|
+
if(plan.mode==='resume'&&plan.originalHostContext!==plan.hostContext)
|
|
69
|
+
stop(2,'batch 宿主没有跨会话恢复入口;resume 需要 originalHostContext 等于 hostContext');
|
|
70
|
+
if(plan.mode==='create'&&plan.originalHostContext)stop(2,'originalHostContext 只在 resume 时有意义');
|
|
71
|
+
if(!Array.isArray(plan.permissions))stop(2,'permissions 必须是宿主参数数组');
|
|
72
|
+
const permissions=[];
|
|
73
|
+
for(let i=0;i<plan.permissions.length;i++){
|
|
74
|
+
const name=plan.permissions[i];
|
|
75
|
+
if(FLAGS.has(name))permissions.push(name);
|
|
76
|
+
else if(PAIRS.has(name)&&nonempty(plan.permissions[i+1]))permissions.push(name,plan.permissions[++i]);
|
|
77
|
+
else stop(2,`permissions 无效或缺少参数: ${name}`);
|
|
78
|
+
}
|
|
79
|
+
const config=path.resolve(base,plan.config),bundle=readJson(config,'批次定义');
|
|
80
|
+
if(bundle===undefined)stop(2,`批次定义不存在: ${config}`);
|
|
81
|
+
const configInfo=fs.lstatSync(config);
|
|
82
|
+
if(!configInfo.isFile()||configInfo.isSymbolicLink()||configInfo.size>64*1024)
|
|
83
|
+
stop(2,`批次定义不是安全的普通文件: ${config}`);
|
|
84
|
+
if(!isObject(bundle)||!isObject(bundle.batch)||!isObject(bundle.workflows)
|
|
85
|
+
||!Array.isArray(bundle.batch.tasks)||!bundle.batch.tasks.length)stop(2,`批次定义格式错误: ${config}`);
|
|
86
|
+
const batch=bundle.batch,keys=batch.tasks.map(taskKey);
|
|
87
|
+
if(new Set(keys).size!==keys.length||keys.length!==Object.keys(bundle.workflows).length
|
|
88
|
+
||keys.some(key=>!Object.hasOwn(bundle.workflows,key)))stop(2,'批次定义 workflows 与 tasks 不匹配');
|
|
89
|
+
const definitions=new Map(),runs=new Map();
|
|
90
|
+
try{
|
|
91
|
+
for(const task of batch.tasks){
|
|
92
|
+
const key=taskKey(task);
|
|
93
|
+
definitions.set(key,validateRunDefinition({version:1,specsDir:batch.specsDir,
|
|
94
|
+
codeProject:batch.codeProject,...(batch.codeProjects?{codeProjects:batch.codeProjects}:{}),
|
|
95
|
+
feature:task.feature,identity:{repositoryId:batch.repositoryId,
|
|
96
|
+
runId:`task-${digest({batchId:batch.batchId,task:key}).slice(0,48)}`,
|
|
97
|
+
taskId:task.taskId,attempt:1},scope:task.scope,requirements:task.requirements}));
|
|
98
|
+
runs.set(definitions.get(key).identity.runId,{key,generation:1});
|
|
99
|
+
runs.set(`task-${digest({batchId:batch.batchId,task:key,generation:2}).slice(0,48)}`,
|
|
100
|
+
{key,generation:2});
|
|
101
|
+
if(bundle.workflows[key]!==null)validateHostWorkflowConfiguration(bundle.workflows[key]);
|
|
102
|
+
}
|
|
103
|
+
// Use the batch owner's selection/parallel-group validator without opening a run.
|
|
104
|
+
createCmAiBatch({configuration:batch,executionFor:async()=>({}),
|
|
105
|
+
logHome:path.join(batch.specsDir,'.reviews','host-log-mirror')});
|
|
106
|
+
}catch(error){stop(2,`批次定义、scope 或 workflow 无效: ${error.code??error.message}`);}
|
|
107
|
+
const log=path.join(batch.specsDir,'运行日志.jsonl');
|
|
108
|
+
const stores=Array.from(definitions.values(),d=>path.join(batch.specsDir,'.reviews','.execution',d.identity.runId,'state.json'));
|
|
109
|
+
const hasLog=fs.existsSync(log),hasStore=stores.some(file=>fs.existsSync(file));
|
|
110
|
+
if(plan.mode==='resume'&&!hasLog&&!hasStore)
|
|
111
|
+
stop(2,`恢复存档不存在: ${log} / ${stores.join(', ')}`);
|
|
112
|
+
if(plan.mode==='create'&&operation==='advance'&&(hasLog||hasStore))
|
|
113
|
+
stop(2,`批次已有存档,请用 resume: ${log}`);
|
|
114
|
+
if(operation==='status'&&!hasStore)stop(2,`只读 status 需要已有任务存档: ${stores.join(', ')}`);
|
|
115
|
+
for(let i=0;i<permissions.length;i++)if(PAIRS.has(permissions[i])){
|
|
116
|
+
const name=permissions[i],value=permissions[++i];
|
|
117
|
+
if(['--review-config','--protected-conversation-config','--protected-config'].includes(name)){
|
|
118
|
+
const file=path.resolve(base,value),data=readJson(file,name);
|
|
119
|
+
if(data===undefined)stop(2,`${name} 文件不存在: ${file}`);
|
|
120
|
+
try{
|
|
121
|
+
if(name==='--review-config')readConversationReviewConfiguration(file);
|
|
122
|
+
else if(name==='--protected-conversation-config')readConversationProtection(file);
|
|
123
|
+
else {
|
|
124
|
+
if(!isObject(data)||Object.keys(data).sort().join()!=='checkCommands,model,timeoutMs'
|
|
125
|
+
||!nonempty(data.model)||!/^[A-Za-z0-9._-]+$/.test(data.model)
|
|
126
|
+
||!Number.isSafeInteger(data.timeoutMs)||data.timeoutMs<=0||data.timeoutMs>3600000)
|
|
127
|
+
throw Error('invalid_protected_config');
|
|
128
|
+
createHostCheck({cwd:batch.codeProject,commands:data.checkCommands,timeoutMs:data.timeoutMs});
|
|
129
|
+
}
|
|
130
|
+
}catch(error){stop(2,`${name} 配置无效: ${file}: ${error.code??error.message}`);}
|
|
131
|
+
permissions[i]=file;
|
|
132
|
+
}else if(['--allow-review','--allow-provider-development'].includes(name)){
|
|
133
|
+
const cut=value.lastIndexOf(':');
|
|
134
|
+
if(!keys.includes(value.slice(0,cut))||!['1','2'].includes(value.slice(cut+1)))
|
|
135
|
+
stop(2,`${name} 任务授权无效: ${value}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const argument=(name)=>permissions[permissions.indexOf(name)+1];
|
|
139
|
+
if(permissions.includes('--runtime')&&!['codex','claude'].includes(argument('--runtime')))
|
|
140
|
+
stop(2,'--runtime 只能是 codex 或 claude');
|
|
141
|
+
if(permissions.includes('--browser-qa')&&!['available','unavailable'].includes(argument('--browser-qa')))
|
|
142
|
+
stop(2,'--browser-qa 只能是 available 或 unavailable');
|
|
143
|
+
if(permissions.includes('--allow-review')&&!permissions.includes('--review-config'))
|
|
144
|
+
stop(2,'--allow-review 需要 --review-config');
|
|
145
|
+
if(permissions.includes('--allow-provider-development')&&!permissions.includes('--protected-config'))
|
|
146
|
+
stop(2,'--allow-provider-development 需要 --protected-config');
|
|
147
|
+
if(Object.values(bundle.workflows).some(workflow=>workflow?.qa)&&!permissions.includes('--allow-qa'))
|
|
148
|
+
stop(2,'有 QA 工作流时缺少 --allow-qa');
|
|
149
|
+
const protectedMode=permissions.includes('--protected-config')||permissions.includes('--protected-conversation-config');
|
|
150
|
+
const providerAll=permissions.includes('--protected-config')&&keys.every(key=>
|
|
151
|
+
permissions.includes(`${key}:1`)&&permissions[permissions.indexOf(`${key}:1`)-1]==='--allow-provider-development');
|
|
152
|
+
if(operation==='advance'&&permissions.includes('--verification-precheck'))
|
|
153
|
+
stop(2,'缺少真实执行 runner: verification_precheck;不能从静态答案文件应答');
|
|
154
|
+
if(operation==='advance'&&bundle.bootstraps&&Object.keys(bundle.bootstraps).length)
|
|
155
|
+
stop(2,'缺少真实执行 runner: init_verify;不能从静态答案文件应答');
|
|
156
|
+
const root=plan.answers?path.resolve(base,plan.answers):null,answers={};
|
|
157
|
+
if(operation==='advance')for(const task of batch.tasks){
|
|
158
|
+
const key=taskKey(task),workflow=bundle.workflows[key],kinds=[];
|
|
159
|
+
if(!providerAll)kinds.push('develop');
|
|
160
|
+
if(!protectedMode){
|
|
161
|
+
kinds.push('check');
|
|
162
|
+
if(workflow?.documentationPaths?.length)kinds.push('documentation_sync');
|
|
163
|
+
}
|
|
164
|
+
if(workflow?.qa){
|
|
165
|
+
if(!batch.parallel?.some(group=>group.includes(key)))kinds.push('qa_assess');
|
|
166
|
+
const cases=readJson(path.join(batch.specsDir,task.feature,'test-cases.json'),'test-cases');
|
|
167
|
+
for(const kind of ['logic','browser'])if(cases?.cases?.some(item=>item.kind===kind))kinds.push(`qa_${kind}`);
|
|
168
|
+
}
|
|
169
|
+
if(workflow)kinds.push('documentation_inspect');
|
|
170
|
+
const evidence=kinds.filter(kind=>['qa_logic','qa_browser'].includes(kind));
|
|
171
|
+
if(evidence.length)stop(2,`缺少真实执行 runner: ${evidence.join(', ')};不能从静态答案文件应答`);
|
|
172
|
+
if(kinds.includes('check'))checkCommandShape(plan.checks?.[key],key);
|
|
173
|
+
const taskRoot=root&&path.join(root,task.feature,task.taskId);
|
|
174
|
+
answers[key]=preflightAnswers(kinds.filter(kind=>KINDS[kind]),kind=>{
|
|
175
|
+
const file=path.join(taskRoot??'',KINDS[kind]);
|
|
176
|
+
if(!taskRoot||!fs.existsSync(file))stop(2,`任务 ${key} 会反问 ${kind},但答案文件不存在: ${file}`);
|
|
177
|
+
const value=readJson(file,kind);
|
|
178
|
+
validateCmAiAnswer(kind,value,taskRoot);
|
|
179
|
+
return value;
|
|
180
|
+
});
|
|
181
|
+
const develop=answers[key].develop;
|
|
182
|
+
if(develop?.status==='succeeded')for(const target of Object.keys(develop.edits))
|
|
183
|
+
if(!definitions.get(key).scope.includes(target))stop(2,`任务 ${key} develop.json.edits 越过批准 scope: ${target}`);
|
|
184
|
+
if(answers[key].documentation_sync)for(const target of Object.keys(answers[key].documentation_sync.edits))
|
|
185
|
+
if(!workflow.documentationPaths.includes(target))stop(2,`任务 ${key} documentation-sync.json.edits 越过文档 scope: ${target}`);
|
|
186
|
+
}
|
|
187
|
+
return {...loaded,bundle,definitions,runs,config,permissions,answers,answerRoot:root};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
let loaded;
|
|
191
|
+
function safeWrite(map,root,cwd,allowed){
|
|
192
|
+
for(const [target,local] of Object.entries(map)){
|
|
193
|
+
if(!allowed.includes(target))throw Error(`编辑越过本次 scope: ${target}`);
|
|
194
|
+
const file=path.resolve(cwd,target);
|
|
195
|
+
if(!file.startsWith(cwd+path.sep))throw Error('编辑路径越界');
|
|
196
|
+
for(let parent=path.dirname(file);parent!==cwd;parent=path.dirname(parent))
|
|
197
|
+
if(fs.existsSync(parent)&&fs.lstatSync(parent).isSymbolicLink())throw Error('编辑路径经过符号链接');
|
|
198
|
+
if(fs.existsSync(file)&&fs.lstatSync(file).isSymbolicLink())throw Error('编辑路径是符号链接');
|
|
199
|
+
fs.mkdirSync(path.dirname(file),{recursive:true});
|
|
200
|
+
fs.writeFileSync(file,fs.readFileSync(path.join(root,local)));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
async function answerFor(row){
|
|
204
|
+
const identity=row.payload.identity??row.payload.request?.identity;
|
|
205
|
+
const binding=loaded.runs.get(identity?.runId),key=binding?.key;
|
|
206
|
+
if(!Object.hasOwn(loaded.answers,key))return null;
|
|
207
|
+
const cwd=actualCwd(loaded.bundle,key,binding.generation);
|
|
208
|
+
const task=loaded.bundle.batch.tasks.find(task=>taskKey(task)===key);
|
|
209
|
+
const root=path.join(loaded.answerRoot,task.feature,task.taskId);
|
|
210
|
+
const value=loaded.answers[key][row.kind];
|
|
211
|
+
if(row.kind==='check'){
|
|
212
|
+
if(row.payload.codeProject!==cwd)return null;
|
|
213
|
+
const results=[];
|
|
214
|
+
for(const command of loaded.plan.checks[key]){
|
|
215
|
+
const run=createHostCheck({cwd,commands:[command],onOutput:({stream,chunk})=>{
|
|
216
|
+
process.stderr.write(`[drive check ${key} ${command.id} ${stream}] ${chunk.toString('utf8')}`);
|
|
217
|
+
}});
|
|
218
|
+
const [result]=await run({identity},{signal:new AbortController().signal});
|
|
219
|
+
results.push(result);if(result.outcome!=='passed')break;
|
|
220
|
+
}
|
|
221
|
+
return results;
|
|
222
|
+
}
|
|
223
|
+
if(row.kind==='develop'){
|
|
224
|
+
if(row.payload.codeProject!==cwd)return null;
|
|
225
|
+
if(value.status!=='succeeded')return {status:'failed',code:value.code};
|
|
226
|
+
if(row.payload.editMode==='protected-text-v1')return {status:'succeeded',value:value.value,
|
|
227
|
+
edits:Object.entries(value.edits).map(([target,local])=>({path:target,
|
|
228
|
+
beforeSha256:row.payload.expected?.[target]??null,content:fs.readFileSync(path.join(root,local),'utf8')}))};
|
|
229
|
+
safeWrite(value.edits,root,cwd,row.payload.request.payload.scope);
|
|
230
|
+
return {status:'succeeded',value:value.value};
|
|
231
|
+
}
|
|
232
|
+
if(row.kind==='documentation_sync'){
|
|
233
|
+
safeWrite(value.edits,root,cwd,row.payload.paths);return {status:'completed'};
|
|
234
|
+
}
|
|
235
|
+
if(row.kind==='documentation_inspect')return {...value,syncId:row.payload.syncId,
|
|
236
|
+
identity:row.payload.identity,packageDigest:row.payload.packageDigest,
|
|
237
|
+
contextDigest:row.payload.contextDigest,
|
|
238
|
+
at:value.at??new Date().toISOString().replace(/\.\d{3}Z$/,'Z')};
|
|
239
|
+
if(row.kind==='qa_assess'){
|
|
240
|
+
decideHostQaPolicy({assessment:value,pending:1,mergeEligible:false,unassessedTasks:1});return value;
|
|
241
|
+
}
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
function main(){
|
|
245
|
+
loaded=preflight();
|
|
246
|
+
const {plan,operation,bundle,config,permissions}=loaded;
|
|
247
|
+
driveHost({host:HOST,args:['serve','--config',config,'--host-context',plan.hostContext,
|
|
248
|
+
'--allow-development',...permissions],cwd:bundle.batch.codeProject,operation,
|
|
249
|
+
answers:loaded.answers,answerFor});
|
|
250
|
+
}
|
|
251
|
+
if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))main();
|