@aibyzero/cm-workflow 0.16.2 → 0.16.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/AGENTS.md +4 -0
- package/CHANGELOG.md +147 -0
- package/README.md +44 -3
- package/VERSION +1 -1
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +46 -7
- package/docs/next-steps.md +100 -0
- package/docs/untested-branches.md +24 -18
- package/package.json +1 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +18 -0
- package/runtime/js/cm-ai/claude-tool-preview.mjs +45 -6
- package/runtime/js/cm-ai/cm-ai-admission.mjs +7 -1
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +22 -12
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +70 -5
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +5 -5
- package/runtime/js/cm-ai/drive-core.mjs +68 -0
- package/runtime/js/cm-ai/durable-runner-state.mjs +42 -9
- package/runtime/js/cm-ai/effect-contract.mjs +4 -3
- package/runtime/js/cm-ai/execution-snapshot.mjs +40 -0
- package/runtime/js/cm-ai/host-conversation-execution.mjs +8 -5
- package/runtime/js/cm-ai/host-handoff.mjs +9 -14
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +12 -7
- package/runtime/js/cm-ai/host-session.mjs +10 -3
- package/runtime/js/cm-ai/host.mjs +1 -1
- package/runtime/js/cm-ai/qa-config-revision.mjs +85 -0
- package/runtime/js/cm-ai/review-evidence-file.mjs +18 -1
- package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +144 -0
- package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +34 -0
- package/runtime/js/cm-ai/task-runner.mjs +41 -8
- package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
- package/runtime/js/cm-fix/cause-invocation.mjs +9 -5
- package/runtime/js/cm-fix/cause-package.mjs +21 -0
- package/runtime/js/cm-fix/dossier.mjs +40 -1
- package/runtime/js/cm-fix/execution.mjs +360 -83
- package/runtime/js/cm-fix/host.mjs +7 -3
- package/runtime/js/cm-fix/layout.mjs +14 -6
- package/runtime/js/cm-fix/progress.mjs +14 -0
- package/runtime/js/cm-fix/protected-edits.mjs +1 -1
- package/runtime/js/cm-fix/red-test.mjs +7 -6
- package/runtime/js/cm-fix/regression-evidence.mjs +6 -3
- package/runtime/js/cm-fix/regression.mjs +16 -10
- package/runtime/js/cm-fix/repair.mjs +16 -13
- package/runtime/js/cm-fix/test-author.mjs +2 -1
- package/runtime/js/cm-fix/test-extension.mjs +45 -0
- package/runtime/js/cm-prd/accepted-design.mjs +28 -9
- package/runtime/js/cm-prd/analysis.mjs +68 -16
- package/runtime/js/cm-prd/change.mjs +21 -1
- package/runtime/js/cm-prd/draft-save.mjs +96 -2
- package/runtime/js/cm-prd/failed-correction.mjs +51 -0
- package/runtime/js/cm-prd/inputs-replaced.mjs +122 -0
- package/runtime/js/cm-prd/review-correction.mjs +3 -0
- package/runtime/js/cm-prd/review-disposition.mjs +33 -15
- package/runtime/js/cm-prd/review-findings.mjs +2 -2
- package/runtime/js/cm-prd/review-host.mjs +2 -0
- package/runtime/js/cm-prd/review-preparation.mjs +28 -1
- package/runtime/js/cm-prd/review-publication.mjs +4 -2
- package/runtime/js/cm-prd/self-check-revision.mjs +81 -0
- package/runtime/js/cm-prd/session.mjs +5 -5
- package/runtime/js/cm-prd/split-design.mjs +67 -0
- package/runtime/js/cm-prd/summary.mjs +57 -10
- package/runtime/js/cm-refactor/workflow.mjs +100 -19
- package/runtime/js/specs-status.mjs +6 -2
- package/scripts/cm-ai-admission.mjs +2 -0
- package/scripts/cm-ai-batch-drive.mjs +251 -0
- package/scripts/cm-ai-batch-drive.test.mjs +159 -0
- package/scripts/cm-ai-batch-host.mjs +13 -5
- package/scripts/cm-ai-batch-host.test.mjs +25 -0
- package/scripts/cm-ai-contracts.test.mjs +30 -0
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +62 -0
- package/scripts/cm-ai-drive.mjs +335 -0
- package/scripts/cm-ai-drive.test.mjs +258 -0
- package/scripts/cm-ai-fix-integration.test.mjs +1 -1
- package/scripts/cm-ai-host.mjs +48 -20
- package/scripts/cm-ai-host.test.mjs +79 -0
- package/scripts/cm-ai-qa-config-revision.test.mjs +328 -0
- package/scripts/cm-ai-qa-fix-cross-session.test.mjs +255 -0
- package/scripts/cm-ai-qa-fix-policy.test.mjs +79 -0
- package/scripts/cm-ai-review-timeout.test.mjs +30 -0
- package/scripts/cm-ai-run.mjs +59 -11
- package/scripts/cm-ai-runner-error-code-regression.test.mjs +29 -0
- package/scripts/cm-ai-session-chain.test.mjs +261 -0
- package/scripts/cm-ai-supersede.test.mjs +320 -0
- package/scripts/cm-check-drive.mjs +94 -0
- package/scripts/cm-check-drive.test.mjs +78 -0
- package/scripts/cm-check-entry.mjs +13 -2
- package/scripts/cm-check-host.mjs +2 -2
- package/scripts/cm-check-host.test.mjs +103 -0
- package/scripts/cm-check-runtime.sh +15 -6
- package/scripts/cm-claude-developer-worker.test.mjs +40 -1
- package/scripts/cm-claude-probe.test.mjs +117 -2
- package/scripts/cm-claude-review-stream.test.mjs +43 -0
- package/scripts/cm-fix-abandon.test.mjs +383 -0
- package/scripts/cm-fix-cause-package.test.mjs +31 -1
- package/scripts/cm-fix-cross-session-host.test.mjs +17 -5
- package/scripts/cm-fix-drive.mjs +168 -0
- package/scripts/cm-fix-drive.test.mjs +117 -0
- package/scripts/cm-fix-escalation.test.mjs +214 -0
- package/scripts/cm-fix-execution.test.mjs +26 -0
- package/scripts/cm-fix-host.mjs +4 -2
- package/scripts/cm-fix-observation-dossier.test.mjs +34 -9
- package/scripts/cm-fix-qa-source.test.mjs +3 -3
- package/scripts/cm-fix-session-chain.test.mjs +244 -0
- package/scripts/cm-fix-test-extension.test.mjs +246 -0
- package/scripts/cm-fix-visual-carrier.test.mjs +66 -0
- package/scripts/cm-host-handoff.test.mjs +37 -0
- package/scripts/cm-idea-drive.mjs +99 -0
- package/scripts/cm-idea-drive.test.mjs +50 -0
- package/scripts/cm-init-drive.mjs +191 -0
- package/scripts/cm-init-drive.test.mjs +59 -0
- package/scripts/cm-log-event.mjs +9 -0
- package/scripts/cm-prd-completion.test.mjs +30 -2
- package/scripts/cm-prd-design-phase.test.mjs +355 -15
- package/scripts/cm-prd-drive.mjs +314 -0
- package/scripts/cm-prd-drive.test.mjs +164 -0
- package/scripts/cm-prd-host.mjs +46 -17
- package/scripts/cm-prd-inputs-replaced.test.mjs +237 -0
- package/scripts/cm-prd-review-disposition.test.mjs +133 -7
- package/scripts/cm-prd-review-gate.mjs +23 -4
- package/scripts/cm-prd-self-check-revision.test.mjs +302 -0
- package/scripts/cm-prd-summary.test.mjs +79 -4
- package/scripts/cm-refactor-drive.mjs +237 -0
- package/scripts/cm-refactor-drive.test.mjs +77 -0
- package/scripts/cm-refactor-gaps.test.mjs +276 -0
- package/scripts/cm-refactor-host.test.mjs +1 -48
- package/scripts/cm-refactor-judge-revision.test.mjs +253 -0
- package/scripts/cm-specs-status.test.mjs +19 -0
- package/scripts/cm-test-drive.mjs +132 -0
- package/scripts/cm-test-drive.test.mjs +91 -0
- package/scripts/cm-test-session.test.mjs +117 -0
- package/scripts/correction-check.test.mjs +38 -0
- package/scripts/fixtures/claude-model-marker.mjs +6 -0
- package/scripts/fixtures/claude-review-process.mjs +7 -0
- package/scripts/fixtures/cm-refactor.mjs +56 -0
- package/scripts/test-shell-compat.sh +67 -0
- package/skills/cm-ai/SKILL.md +1 -1
- package/skills/cm-ai/references/N4-review.md +2 -0
- package/skills/cm-ai/references/N8-finish.md +1 -0
- package/skills/cm-ai/references/js-host.md +85 -3
- package/skills/cm-check/SKILL.md +6 -1
- package/skills/cm-check/references/js-host.md +4 -2
- package/skills/cm-fix/SKILL.md +11 -4
- package/skills/cm-fix/references/js-host.md +67 -2
- package/skills/cm-fix/references/test-extension.md +57 -0
- package/skills/cm-idea/references/js-host.md +2 -0
- package/skills/cm-init/references/js-host.md +2 -0
- package/skills/cm-prd/SKILL.md +8 -8
- package/skills/cm-prd/references/js-change-recovery.md +71 -0
- package/skills/cm-prd/references/js-host.md +64 -2
- package/skills/cm-prd/references/spec-self-check.md +14 -2
- package/skills/cm-refactor/SKILL.md +5 -0
- package/skills/cm-refactor/references/js-batch.md +3 -1
- package/skills/cm-refactor/references/js-host.md +49 -0
- package/skills/cm-test/references/js-host.md +5 -0
- package/skills/cm-test/references/unit-coverage.md +2 -2
|
@@ -15,6 +15,7 @@ import {METRICS_HEADER,hasMetricsHeader} from '../cm-ai/metrics-table.mjs';
|
|
|
15
15
|
import {inside,canonicalFuture,snapshotSource} from '../cm-test/source-snapshot.mjs';
|
|
16
16
|
import {openRefactorRecords,readText,replaceText,sha} from './records.mjs';
|
|
17
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,'');
|
|
18
19
|
const markdown=value=>'```json\n'+JSON.stringify(value,null,2)+'\n```\n';
|
|
19
20
|
const relative=name=>typeof name==='string'&&!path.isAbsolute(name)&&!name.includes('\\')
|
|
20
21
|
&&name.split('/').every(part=>part&&part!=='.'&&part!=='..');
|
|
@@ -183,15 +184,48 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
183
184
|
}
|
|
184
185
|
async function restore(key,before){for(const [name,value] of Object.entries(before))if(!name.startsWith('__')&&files[name]!==value)
|
|
185
186
|
await write(`${key}/${name}`,absolute(name),files[name],value,context.modes[name]??0o644);}
|
|
186
|
-
async function
|
|
187
|
-
|
|
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)){
|
|
188
222
|
const result=await invoke('judge-prepare','refactor_prepare_tests',{target:config.target,files:source(config.scope),assets:source(setup.paths),
|
|
189
223
|
baselineCommands:config.baselineCommands,judgeCommand:config.judgeCommand,route:routes.tester,
|
|
190
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.'});
|
|
191
225
|
await apply('judge-prepare',result.files,setup.paths);
|
|
192
226
|
}
|
|
193
|
-
for(let revision=1;revision<=
|
|
194
|
-
const key
|
|
227
|
+
for(let revision=1;revision<=maxRevisions;revision++){
|
|
228
|
+
const key=`${prefix}judge-${revision}`;let failure=null;const mutations=[];
|
|
195
229
|
try{
|
|
196
230
|
await baseline(`${key}/baseline`);judgeBefore=await judge(`${key}/original`);
|
|
197
231
|
for(let n=0;n<config.mutations.length;n++){
|
|
@@ -201,7 +235,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
201
235
|
const old=files[mutation.path];need(typeof old==='string'&&old.split(mutation.find).length===2,'refactor_mutation_not_unique');
|
|
202
236
|
await write(`${key}-mutant-${n}`,absolute(mutation.path),old,old.replace(mutation.find,mutation.replace),context.modes[mutation.path]);
|
|
203
237
|
let observed;try{observed=await judge(`${key}/mutant-${n}`);}finally{
|
|
204
|
-
|
|
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]);}
|
|
205
240
|
const inputs=value=>value.cases.map(({id,input})=>({id,input}));
|
|
206
241
|
const detected=digest(inputs(observed))===digest(inputs(judgeBefore))&&digest(observed)!==digest(judgeBefore);
|
|
207
242
|
mutations.push({mutation,detected,observed});need(detected,'refactor_judge_missed_mutation');
|
|
@@ -209,13 +244,33 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
209
244
|
}catch(error){if(unknown())throw error;failure=error.code??error.message;}
|
|
210
245
|
await publish(key,path.join(directory,`${key}-report.md`),markdown({judgeBefore,mutations,failure}));
|
|
211
246
|
if(!failure)return;
|
|
212
|
-
need(!controller.signal.aborted,'cancelled');need(setup.paths.length&&revision<
|
|
247
|
+
need(!controller.signal.aborted,'cancelled');need(setup.paths.length&&revision<maxRevisions,failure);
|
|
213
248
|
const result=await invoke(`${key}-repair`,'refactor_prepare_tests',{failure,mutations,files:source(config.scope),assets:source(setup.paths),
|
|
214
249
|
baselineCommands:config.baselineCommands,judgeCommand:config.judgeCommand,route:routes.tester,
|
|
215
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.'});
|
|
216
251
|
await apply(`${key}-repair`,result.files,setup.paths);await event(`${key}-repair`,'decision','judge_repair',{reason:failure});
|
|
217
252
|
}
|
|
218
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
|
+
}
|
|
219
274
|
async function defineRules(key,previous=null,findings=null){
|
|
220
275
|
const plan=await invoke(key,'refactor_batch',{action:'plan',target:config.target,project,
|
|
221
276
|
files:source(config.scope).map(({path,content,beforeDigest})=>({path,exists:content!==null,beforeDigest})),assemblyFiles:batch.assemblyFiles,
|
|
@@ -227,7 +282,9 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
227
282
|
&&plan.sample.every(name=>config.scope.includes(name)&&files[name]!==null),'refactor_sample_invalid');
|
|
228
283
|
return {...plan,units};
|
|
229
284
|
}
|
|
230
|
-
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;
|
|
231
288
|
const denies=JSON.parse(readText(path.join(workflowRoot,'templates/refactor/cm-refactor-denies.json')));
|
|
232
289
|
let plan=prefix==='a1'?{...initialPlan}:await defineRules(`${prefix}/plan`,rulebook,findings),revision=1;
|
|
233
290
|
const trial={};
|
|
@@ -242,13 +299,16 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
242
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);
|
|
243
300
|
need(a&&b,'refactor_bakeoff_coverage');if(digest(a.content)!==digest(b.content))need(adjudication.decisions.some(row=>row.path===name
|
|
244
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');
|
|
245
305
|
plan.rulebook=adjudication.rulebook;
|
|
246
306
|
await publish(`${prefix}-bakeoff`,path.join(directory,`${prefix}-bakeoff.md`),markdown({trial,adjudication}));
|
|
247
307
|
// Pilot uses the same generation/cheap checks/assembly/equivalence pipeline; discard its products.
|
|
248
308
|
let pilotPassed=false;
|
|
249
309
|
for(let cycle=1;cycle<=3;cycle++){
|
|
250
|
-
const pilotBefore={...files},trialResult=await runBatch(`${prefix}/pilot-${cycle}`,plan.sample,plan.rulebook,revision,[],true);
|
|
251
|
-
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??[];
|
|
252
312
|
if(trialResult.passed){pilotPassed=true;break;}
|
|
253
313
|
if(cycle<3){const revised=await defineRules(`${prefix}/pilot-revise-${cycle}`,plan.rulebook,trialResult);
|
|
254
314
|
need(digest(revised.units)===digest(plan.units),'refactor_revision_scope_changed');plan.rulebook=revised.rulebook;}
|
|
@@ -266,9 +326,9 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
266
326
|
for(let cycle=1;cycle<=batch.maxPasses;cycle++){
|
|
267
327
|
const key=`${prefix}/batch-${index+1}-${cycle}`,before={...files};
|
|
268
328
|
await event(`${key}-start`,'task_start',null,{batch:index+1,total:plan.units.length,cycle});
|
|
269
|
-
const result=await runBatch(key,unit.files,rulebook,revision,[],false);
|
|
329
|
+
const result=await runBatch(key,unit.files,rulebook,revision,[],false,revisedJudges);
|
|
270
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;}
|
|
271
|
-
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}));
|
|
272
332
|
await event(`${key}-rollback`,'error','rollback',{batch:index+1,cycle,reason:result.failure});
|
|
273
333
|
const diagnosed=await invoke(`${key}-diagnose`,'refactor_batch',{action:'diagnose',failure:result.failure,output:result.output,rulebook,
|
|
274
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.'});
|
|
@@ -286,7 +346,7 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
286
346
|
}
|
|
287
347
|
files.__rulebook=readVirtualRulebook;return true;
|
|
288
348
|
}
|
|
289
|
-
async function runBatch(key,names,rules,revision,needs=[],pilot=false){
|
|
349
|
+
async function runBatch(key,names,rules,revision,needs=[],pilot=false,revisedJudges=false){
|
|
290
350
|
const before={...files},rows=[];let output=null;
|
|
291
351
|
try{
|
|
292
352
|
for(const name of names){
|
|
@@ -320,7 +380,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
320
380
|
return {passed:true};
|
|
321
381
|
}catch(error){
|
|
322
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;
|
|
323
|
-
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('__'))));
|
|
324
385
|
const failure=error.code??error.message;await publish(`${key}-failure`,path.join(directory,`${key.replaceAll('/','-')}-failure.md`),markdown({failure,output,rows,pilot}));
|
|
325
386
|
return {passed:false,failure,output};
|
|
326
387
|
}
|
|
@@ -363,6 +424,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
363
424
|
const dossierPath=()=>context.batch?path.join(directory,'dossier.md'):path.join(archiveRoot,`${context.startedAt.slice(0,10).replaceAll('-','')}-${config.slug}.md`);
|
|
364
425
|
async function flow(){
|
|
365
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++;
|
|
366
429
|
await event('start','run_start',null);await event('g0','node_enter',null);
|
|
367
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});
|
|
368
431
|
analysis=await invoke('analysis','refactor_analyze',{target:config.target,project,scope:config.scope,
|
|
@@ -379,14 +442,18 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
379
442
|
await event('rejected','run_done',null,{result:'rejected'});progress('rejected');return false;}
|
|
380
443
|
await event('judge','node_enter',null);await prepareJudges();
|
|
381
444
|
for(attempt=1;attempt<=2;attempt++){
|
|
445
|
+
if(attempt===2&&judgeRevision)await reviseJudges(judgeRevision);
|
|
382
446
|
const prefix=`a${attempt}`;await event(`${prefix}-execute`,'node_enter',null);progress('implementing');
|
|
383
447
|
if(!context.batch)await event(`${prefix}-task`,'task_start',null,{attempt});
|
|
384
|
-
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;}}
|
|
385
449
|
else{
|
|
386
|
-
|
|
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,
|
|
387
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.'});
|
|
388
|
-
need(proposal.files.every(item=>item.content!==null),'refactor_deletion_requires_batch');await apply(
|
|
389
|
-
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;}
|
|
390
457
|
}
|
|
391
458
|
const retrospective=await writeback(prefix);
|
|
392
459
|
const changed=managedNames.filter(name=>(files[name]??null)!==context.original[name]);
|
|
@@ -408,6 +475,18 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
408
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.'});
|
|
409
476
|
const review=await publish(`${prefix}-review`,path.join(reviews,`${feature}-${task}-r${attempt}.md`),reviewed.markdown);
|
|
410
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
|
+
}
|
|
411
490
|
await event(`${prefix}-review-complete`,'review','complete',{attempt,verdict:reviewResult.verdict,blocking_findings:Number(reviewResult.blocking_findings)});
|
|
412
491
|
if(reviewResult.verdict==='changes_requested'&&attempt===1){reviewResult={...reviewResult,markdown:reviewed.markdown};continue;}
|
|
413
492
|
guard();checkN5(options);proposal={...retrospective,changed,options};progress('awaiting_finish');return true;
|
|
@@ -447,7 +526,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
447
526
|
if(request.operation==='cancel'){controller.abort();return {...status(),stage:'cancelled'};}
|
|
448
527
|
need(!active,'refactor_busy');active=true;controller=new AbortController();
|
|
449
528
|
try{
|
|
450
|
-
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();
|
|
451
531
|
if(!context){
|
|
452
532
|
need(request.operation==='start','refactor_not_started');
|
|
453
533
|
need(fs.readdirSync(directory).every(name=>name==='.writer.json'),'refactor_legacy_recovery_required');
|
|
@@ -459,7 +539,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
459
539
|
modes:Object.fromEntries(managedNames.map(name=>[name,original[name]===null?0o644:fs.statSync(absolute(name)).mode&0o777])),
|
|
460
540
|
baseline:baselineSnapshot,batch:batchTrack,lessons:readText(lessons),lessonsMode:fs.existsSync(lessons)?fs.statSync(lessons).mode&0o777:0o644,
|
|
461
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);
|
|
462
|
-
}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');}
|
|
463
544
|
if(await flow()){
|
|
464
545
|
if(request.operation==='resume'){
|
|
465
546
|
const rounds=[...records.effects.keys()].map(key=>/^command\/resume-check\/(\d+)\//.exec(key)).filter(Boolean).map(match=>Number(match[1]));
|
|
@@ -3,9 +3,10 @@ import fs from 'node:fs';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import {randomUUID} from 'node:crypto';
|
|
5
5
|
|
|
6
|
-
const fields=['status','summaryDigest','at','features','specFiles','testCases','approval'];
|
|
6
|
+
const fields=['status','summaryDigest','at','features','specFiles','testCases','approval','revisionDigest'];
|
|
7
7
|
const record=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
|
|
8
8
|
const hex=value=>typeof value==='string'&&/^[a-fA-F0-9]{64}$/.test(value);
|
|
9
|
+
const revisionHex=value=>typeof value==='string'&&/^[a-f0-9]{64}$/.test(value);
|
|
9
10
|
const iso=value=>typeof value==='string'&&/^\d{4}-\d\d-\d\dT/.test(value)&&Number.isFinite(Date.parse(value));
|
|
10
11
|
const need=condition=>{if(!condition)throw new Error('spec_status_invalid');};
|
|
11
12
|
|
|
@@ -20,6 +21,7 @@ export function readSpecsStatus(specsDir){
|
|
|
20
21
|
need(relative!==''&&relative!=='..'&&!relative.startsWith(`..${path.sep}`)&&!path.isAbsolute(relative));
|
|
21
22
|
const source=JSON.parse(fs.readFileSync(real,'utf8'));
|
|
22
23
|
need(record(source)&&['approved','awaiting_review'].includes(source.status));
|
|
24
|
+
if(Object.hasOwn(source,'revisionDigest'))need(revisionHex(source.revisionDigest));
|
|
23
25
|
// Keep optional fields absent: admission distinguishes legacy omissions.
|
|
24
26
|
const value=Object.fromEntries(fields.filter(key=>Object.hasOwn(source,key)).map(key=>[key,source[key]]));
|
|
25
27
|
if(record(value.approval))value.approval=Object.fromEntries(['response','at']
|
|
@@ -32,6 +34,7 @@ export function writeSpecsStatus(specsDir,value,{beforeRename=()=>{}}={}){
|
|
|
32
34
|
need(record(value)&&['approved','awaiting_review'].includes(value.status));
|
|
33
35
|
const summaryDigest=value.summaryDigest===undefined?null:value.summaryDigest;
|
|
34
36
|
need(summaryDigest===null||hex(summaryDigest));
|
|
37
|
+
if(Object.hasOwn(value,'revisionDigest'))need(revisionHex(value.revisionDigest));
|
|
35
38
|
need(iso(value.at)&&Array.isArray(value.features)&&value.features.length>0
|
|
36
39
|
&&value.features.every(name=>typeof name==='string'&&/^\d+\.[^/\\]+$/.test(name))
|
|
37
40
|
&&new Set(value.features).size===value.features.length);
|
|
@@ -49,7 +52,8 @@ export function writeSpecsStatus(specsDir,value,{beforeRename=()=>{}}={}){
|
|
|
49
52
|
&&typeof approval.response==='string'&&approval.response.trim()!==''&&iso(approval.at)));
|
|
50
53
|
const canonical={status:value.status,summaryDigest,at:value.at,features:[...value.features],
|
|
51
54
|
specFiles:manifest(value.specFiles),testCases:manifest(value.testCases),
|
|
52
|
-
approval:approval===null?null:{response:approval.response,at:approval.at}
|
|
55
|
+
approval:approval===null?null:{response:approval.response,at:approval.at},
|
|
56
|
+
...(Object.hasOwn(value,'revisionDigest')?{revisionDigest:value.revisionDigest}:{})};
|
|
53
57
|
const bytes=Buffer.from(JSON.stringify(canonical)+'\n'),target=path.join(specsDir,'.cm-specs-status');
|
|
54
58
|
const temporary=path.join(specsDir,`.cm-specs-status-${randomUUID()}`);let fd;
|
|
55
59
|
try{
|
|
@@ -74,6 +74,8 @@ export function main(argv=process.argv.slice(2)){
|
|
|
74
74
|
const result={...selected,...(approval?.approveRefused?{approveRefused:approval.approveRefused}:{}),codeProject:input.codeProjects.length===1?selected.codeProject:null,
|
|
75
75
|
codeProjects:projectResults.map(item=>item.codeProject),
|
|
76
76
|
projectAdmissions:projectResults.map(item=>({codeProject:item.codeProject,state:item.state,reason:item.reason}))};
|
|
77
|
+
if(result.state==='awaiting_spec_approval'&&(result.approvalIntent!=='explicit'||input.assumeYes))
|
|
78
|
+
result.message='确认规格摘要后,请在 --approval-response 后准确输入“开始”。';
|
|
77
79
|
if(input.printRunDefinition&&!result.approveRefused&&result.state==='ready'){
|
|
78
80
|
try{process.stdout.write(`${JSON.stringify(buildRunDefinition(result,input))}\n`);return 0;}
|
|
79
81
|
catch(error){process.stderr.write(`${JSON.stringify({error:{code:error.code??error.message}})}\n`);return 1;}
|
|
@@ -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','--input-limit']);
|
|
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();
|