@aibyzero/cm-workflow 0.13.3 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +26 -0
- package/README.md +22 -1
- package/VERSION +1 -1
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +2 -0
- package/docs/user-guide.md +3 -0
- package/package.json +1 -1
- package/runtime/js/cm-ai/claude-developer-proposal.schema.json +1 -0
- package/runtime/js/cm-ai/cm-ai-admission.mjs +53 -22
- package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +4 -5
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +40 -17
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +103 -23
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -4
- package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +5 -2
- package/runtime/js/cm-ai/codex-developer-output.schema.json +2 -1
- package/runtime/js/cm-ai/developer-adapter.mjs +17 -5
- package/runtime/js/cm-ai/durable-runner-state.mjs +7 -2
- package/runtime/js/cm-ai/effect-contract.mjs +8 -1
- package/runtime/js/cm-ai/execution-store.mjs +25 -5
- package/runtime/js/cm-ai/host-check.mjs +20 -1
- package/runtime/js/cm-ai/host-conversation-execution.mjs +5 -4
- package/runtime/js/cm-ai/host-documentation.mjs +2 -2
- package/runtime/js/cm-ai/host-qa-executor.mjs +43 -21
- package/runtime/js/cm-ai/host-qa-policy.mjs +3 -1
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +41 -3
- package/runtime/js/cm-ai/task-runner.mjs +1 -0
- package/runtime/js/cm-ai/worker-claude-developer.mjs +2 -1
- package/runtime/js/cm-fix/cause-package.mjs +3 -1
- package/runtime/js/cm-fix/dossier.mjs +7 -2
- package/runtime/js/cm-fix/reproduce.mjs +26 -5
- package/runtime/js/cm-init/draft-generation.mjs +3 -2
- package/runtime/js/cm-init/draft-inspection.mjs +17 -3
- package/runtime/js/cm-init/review-evidence.mjs +1 -1
- package/runtime/js/cm-prd/summary.mjs +6 -8
- package/runtime/js/cm-security/finalize.mjs +164 -0
- package/runtime/js/specs-status.mjs +66 -0
- package/scripts/cm-ai-admission.mjs +46 -7
- package/scripts/cm-ai-admission.test.mjs +50 -0
- package/scripts/cm-ai-batch-host.mjs +72 -10
- package/scripts/cm-ai-batch-host.test.mjs +128 -4
- package/scripts/cm-ai-batch-run.mjs +351 -17
- package/scripts/cm-ai-batch-run.test.mjs +190 -13
- package/scripts/cm-ai-bootstrap.test.mjs +3 -2
- package/scripts/cm-ai-host.mjs +38 -21
- package/scripts/cm-ai-host.test.mjs +68 -4
- package/scripts/cm-ai-nested-execution.test.mjs +1 -1
- package/scripts/cm-ai-run.mjs +25 -15
- package/scripts/cm-ai-run.test.mjs +48 -0
- package/scripts/cm-blocked-reason.test.mjs +104 -0
- package/scripts/cm-capability-gate.test.mjs +179 -0
- package/scripts/cm-codex-developer-adapter.test.mjs +70 -0
- package/scripts/cm-fix-cause-package.test.mjs +18 -1
- package/scripts/cm-fix-execution.test.mjs +31 -0
- package/scripts/cm-fix-host-review.test.mjs +2 -1
- package/scripts/cm-fix-host.test.mjs +2 -1
- package/scripts/cm-fix-observation-dossier.test.mjs +2 -0
- package/scripts/cm-fix-qa-source.test.mjs +1 -3
- package/scripts/cm-fix-reproduce.test.mjs +53 -2
- package/scripts/cm-fix-review-recovery.test.mjs +4 -3
- package/scripts/cm-host-check.test.mjs +22 -0
- package/scripts/cm-host-qa-executor.test.mjs +302 -3
- package/scripts/cm-host-qa-policy.test.mjs +34 -0
- package/scripts/cm-init-draft-generation.test.mjs +24 -3
- package/scripts/cm-init-draft-inspection.test.mjs +80 -0
- package/scripts/cm-init-host.mjs +2 -2
- package/scripts/cm-init-host.test.mjs +3 -1
- package/scripts/cm-init-session.test.mjs +37 -0
- package/scripts/cm-log-event.mjs +28 -7
- package/scripts/cm-prd-design-phase.test.mjs +2 -1
- package/scripts/cm-prd-host.test.mjs +3 -2
- package/scripts/cm-prd-session-recovery.test.mjs +5 -4
- package/scripts/cm-security.mjs +12 -4
- package/scripts/cm-security.test.mjs +109 -0
- package/scripts/cm-specs-status.test.mjs +130 -0
- package/scripts/cm-workflow-config.mjs +4 -0
- package/scripts/test-shell-compat.sh +0 -0
- package/skills/cm-ai/references/N1-init.md +20 -15
- package/skills/cm-ai/references/N6-qa-eval.md +9 -4
- package/skills/cm-ai/references/js-host.md +10 -0
- package/skills/cm-fix/SKILL.md +5 -4
- package/skills/cm-fix/references/js-host.md +13 -0
- package/skills/cm-idea/SKILL.md +2 -0
- package/skills/cm-init/references/runtime-declaration.md +2 -0
- package/skills/cm-prd/SKILL.md +9 -8
- package/skills/cm-prd/references/spec-self-check.md +1 -0
- package/skills/cm-security/SKILL.md +11 -6
- package/skills/cm-security/references/scan-contract.md +45 -1
|
@@ -7,16 +7,20 @@ import {fileURLToPath} from 'node:url';
|
|
|
7
7
|
import {openControlRun,validateRunDefinition} from './cm-ai-run.mjs';
|
|
8
8
|
import {digest,json,shape,need,id,hex} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
9
9
|
import {scanRows,findCmAiQaDecision,latestCmAiQaRun} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
|
|
10
|
+
import {checkParallelWrite} from './cm-task-gate.mjs';
|
|
11
|
+
import {parseFeatureTaskText} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
|
|
12
|
+
import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
|
|
10
13
|
import {inspectRunClosure} from './cm-log-event.mjs';
|
|
11
14
|
|
|
12
15
|
const writer=fileURLToPath(new URL('./cm-log-event.py',import.meta.url));
|
|
13
16
|
const key=task=>`${task.feature}/${task.taskId}`;
|
|
14
|
-
export function createCmAiBatch({configuration,executionFor,logHome}){
|
|
17
|
+
export function createCmAiBatch({configuration,executionFor,logHome,runtime='codex',checkCommands=null,checkTimeoutMs=60000}){
|
|
15
18
|
const config=json(configuration);
|
|
16
|
-
shape(config,['version','repositoryId','batchId','specsDir','codeProject','tasks',...(Object.hasOwn(config,
|
|
19
|
+
shape(config,['version','repositoryId','batchId','specsDir','codeProject','tasks',...['codeProjects','parallel'].filter(name=>Object.hasOwn(config,name))]);
|
|
17
20
|
need(config.version===1);id(config.repositoryId);id(config.batchId);need(config.batchId.length>=8);
|
|
18
21
|
need(typeof executionFor==='function'&&typeof logHome==='string'&&path.isAbsolute(logHome));
|
|
19
22
|
need(Array.isArray(config.tasks)&&config.tasks.length>0&&config.tasks.length<=256);
|
|
23
|
+
need(['codex','claude'].includes(runtime),'invalid_runtime');
|
|
20
24
|
const plans=new Map();
|
|
21
25
|
for(const task of config.tasks){
|
|
22
26
|
shape(task,['feature','taskId','scope','requirements']);
|
|
@@ -27,12 +31,15 @@ export function createCmAiBatch({configuration,executionFor,logHome}){
|
|
|
27
31
|
need(definition.specsDir===config.specsDir&&definition.codeProject===config.codeProject,'invalid_path');
|
|
28
32
|
plans.set(key(task),definition);
|
|
29
33
|
}
|
|
34
|
+
const groups=validateGroups(config,plans),membership=new Map(groups.flatMap(group=>group.map(key=>[key,group])));
|
|
35
|
+
const originalMembership=new Map(membership),originalPlans=new Map(plans);
|
|
30
36
|
const first=plans.keys().next().value,planDigest=digest(config),log=path.join(config.specsDir,'运行日志.jsonl');
|
|
31
37
|
let active=null,busy=false,cancelled=false,liveKey=first;
|
|
32
|
-
const executions=new Map();
|
|
38
|
+
const executions=new Map(),members=new Map();
|
|
39
|
+
let releaseLock=null,completeTail=Promise.resolve();
|
|
33
40
|
async function executionForKey(taskKey){
|
|
34
41
|
if(!executions.has(taskKey)){
|
|
35
|
-
const execution=await executionFor(json(plans.get(taskKey)));
|
|
42
|
+
const execution=await executionFor(json(plans.get(taskKey)),{parallelMember:membership.has(taskKey)});
|
|
36
43
|
need(execution!==null&&typeof execution==='object','execution_adapter_required');
|
|
37
44
|
// Preserve fixed protected-factory provenance; never clone protected callbacks.
|
|
38
45
|
if(Object.isFrozen(execution)){
|
|
@@ -45,8 +52,9 @@ export function createCmAiBatch({configuration,executionFor,logHome}){
|
|
|
45
52
|
const rows=[];
|
|
46
53
|
if(fs.existsSync(log))scanRows(log,row=>{
|
|
47
54
|
if(row?.workflow==='cm-ai'&&row.event==='decision'&&row.run_id===config.batchId
|
|
48
|
-
&&['batch_start','batch_handoff','batch_cancel'].includes(row.phase))rows.push(row);
|
|
55
|
+
&&['batch_start','batch_task_committed','batch_handoff','batch_cancel','batch_member_ready','batch_member_blocked','batch_merge_conflict','batch_merge_started','batch_merge_blocked'].includes(row.phase))rows.push(row);
|
|
49
56
|
});
|
|
57
|
+
if(groups.length)return parallelProgress(rows);
|
|
50
58
|
let current=first,stopped=false;const seen=new Set();
|
|
51
59
|
for(const [index,row] of rows.entries()){
|
|
52
60
|
need(row.schema_version===1&&row.repository_id===config.repositoryId
|
|
@@ -54,6 +62,9 @@ export function createCmAiBatch({configuration,executionFor,logHome}){
|
|
|
54
62
|
need(!stopped&&row.from_key===current,'batch_history_invalid');
|
|
55
63
|
if(row.phase==='batch_start'){need(index===0,'batch_history_invalid');continue;}
|
|
56
64
|
need(index>0&&rows[0].phase==='batch_start','batch_history_invalid');
|
|
65
|
+
if(row.phase==='batch_task_committed'){
|
|
66
|
+
need(typeof row.task_commit==='string'&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(row.task_commit),'batch_history_invalid');continue;
|
|
67
|
+
}
|
|
57
68
|
if(row.phase==='batch_cancel'){stopped=true;continue;}
|
|
58
69
|
need(plans.has(row.to_key)&&!seen.has(row.to_key)&&row.to_key!==current,'batch_history_invalid');
|
|
59
70
|
hex(row.checkpoint);hex(row.package_digest);seen.add(current);current=row.to_key;
|
|
@@ -62,9 +73,9 @@ export function createCmAiBatch({configuration,executionFor,logHome}){
|
|
|
62
73
|
}
|
|
63
74
|
function record(phase,data){
|
|
64
75
|
const result=spawnSync('python3',[writer,'--workflow','cm-ai','--event','decision','--phase',phase,
|
|
65
|
-
'--runtime',
|
|
76
|
+
'--runtime',runtime,'--project-root',config.codeProject,'--specs-dir',config.specsDir,'--run-id',config.batchId,
|
|
66
77
|
'--detail',phase==='batch_handoff'?'Task QA and context completed; advance to next task':
|
|
67
|
-
phase==='batch_start'?'Approved task batch started':'
|
|
78
|
+
phase==='batch_start'?'Approved task batch started':phase==='batch_member_blocked'?'Preserve member WIP and reschedule serial generation 2':phase,
|
|
68
79
|
'--data-json',JSON.stringify({repository_id:config.repositoryId,plan_digest:planDigest,...data})],
|
|
69
80
|
{timeout:10000,maxBuffer:1024*1024,encoding:'utf8',env:{...process.env,CM_WORKFLOW_LOG_HOME:logHome}});
|
|
70
81
|
need(!result.error&&result.status===0&&result.signal===null,'batch_log_failed');
|
|
@@ -72,13 +83,231 @@ export function createCmAiBatch({configuration,executionFor,logHome}){
|
|
|
72
83
|
}
|
|
73
84
|
async function open(taskKey){
|
|
74
85
|
const definition=plans.get(taskKey),state=path.join(config.specsDir,'.reviews','.execution',definition.identity.runId,'state.json');
|
|
75
|
-
return openControlRun(definition,fs.existsSync(state)?'resume':'create',await executionForKey(taskKey)
|
|
86
|
+
return openControlRun(definition,fs.existsSync(state)?'resume':'create',await executionForKey(taskKey),
|
|
87
|
+
membership.has(taskKey)?{parallelSelection:{version:1,group:membership.get(taskKey).map(key=>plans.get(key).identity.taskId)}}:{});
|
|
88
|
+
}
|
|
89
|
+
function parallelProgress(rows){
|
|
90
|
+
const done=new Set(),ready=new Map(),merging=new Map(),blocked=new Map();let stopped=false,code=null;
|
|
91
|
+
for(const [index,row] of rows.entries()){
|
|
92
|
+
need(row.schema_version===1&&row.repository_id===config.repositoryId&&row.plan_digest===planDigest,'batch_plan_mismatch');
|
|
93
|
+
need(!stopped&&plans.has(row.from_key),'batch_history_invalid');
|
|
94
|
+
if(row.phase==='batch_start'){need(index===0,'batch_history_invalid');continue;}
|
|
95
|
+
need(index>0&&rows[0].phase==='batch_start','batch_history_invalid');
|
|
96
|
+
if(row.phase==='batch_task_committed'){
|
|
97
|
+
need(typeof row.task_commit==='string'&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(row.task_commit),'batch_history_invalid');continue;
|
|
98
|
+
}
|
|
99
|
+
if(row.phase==='batch_cancel'){stopped=true;code='cancelled';continue;}
|
|
100
|
+
if(['batch_merge_conflict','batch_merge_blocked'].includes(row.phase)){stopped=true;code=row.code;continue;}
|
|
101
|
+
if(row.phase==='batch_member_blocked'){
|
|
102
|
+
need(originalMembership.has(row.from_key)&&!done.has(row.from_key)&&!ready.has(row.from_key)
|
|
103
|
+
&&!blocked.has(row.from_key)&&row.generation===2,'batch_history_invalid');
|
|
104
|
+
const expected=location(row.from_key);
|
|
105
|
+
need(row.worktree===expected.worktree&&row.branch===expected.branch
|
|
106
|
+
&&typeof row.code==='string'&&row.code.length>0&&typeof row.reason==='string','batch_history_invalid');
|
|
107
|
+
blocked.set(row.from_key,row);continue;
|
|
108
|
+
}
|
|
109
|
+
if(row.phase==='batch_member_ready'){
|
|
110
|
+
need(originalMembership.has(row.from_key)&&!blocked.has(row.from_key)&&!ready.has(row.from_key),'batch_history_invalid');
|
|
111
|
+
hex(row.checkpoint);hex(row.package_digest);ready.set(row.from_key,row);continue;
|
|
112
|
+
}
|
|
113
|
+
if(row.phase==='batch_merge_started'){
|
|
114
|
+
need(ready.has(row.from_key)&&!merging.has(row.from_key),'batch_history_invalid');merging.set(row.from_key,row);continue;
|
|
115
|
+
}
|
|
116
|
+
need(!done.has(row.from_key),'batch_history_invalid');hex(row.checkpoint);hex(row.package_digest);
|
|
117
|
+
if(originalMembership.has(row.from_key)&&!blocked.has(row.from_key))need(ready.has(row.from_key)&&merging.has(row.from_key),'batch_history_invalid');
|
|
118
|
+
done.add(row.from_key);
|
|
119
|
+
need(row.to_key===[...plans.keys()].find(key=>!done.has(key)),'batch_history_invalid');
|
|
120
|
+
}
|
|
121
|
+
// The durable decision is authoritative for both the live driver and resume.
|
|
122
|
+
for(const key of blocked.keys())if(membership.has(key)){
|
|
123
|
+
const definition=originalPlans.get(key);
|
|
124
|
+
plans.set(key,validateRunDefinition({...definition,identity:{...definition.identity,
|
|
125
|
+
runId:`task-${digest({batchId:config.batchId,task:key,generation:2}).slice(0,48)}`}}));
|
|
126
|
+
membership.delete(key);executions.delete(key);
|
|
127
|
+
}
|
|
128
|
+
return {rows,current:[...plans.keys()].find(key=>!done.has(key)),stopped,code,done,ready,merging,blocked};
|
|
129
|
+
}
|
|
130
|
+
const location=key=>{const definition=plans.get(key);return {
|
|
131
|
+
worktree:path.resolve(config.codeProject,'..','.cm-worktrees',config.batchId.slice(0,8),definition.identity.taskId),
|
|
132
|
+
branch:`cm/${definition.feature.replace(/^\d+\./,'')}/${definition.identity.taskId}`};};
|
|
133
|
+
function verifyMerged(row){
|
|
134
|
+
const definition=plans.get(row.from_key),state=JSON.parse(fs.readFileSync(path.join(config.specsDir,'.reviews','.execution',definition.identity.runId,'state.json'),'utf8'));
|
|
135
|
+
const {revision,...body}=state;
|
|
136
|
+
need(revision===row.checkpoint&&digest(body)===revision,'batch_checkpoint_mismatch');
|
|
137
|
+
const binding={specsDir:config.specsDir,feature:definition.feature,identity:row.identity,packageDigest:row.package_digest};
|
|
138
|
+
need(findCmAiQaDecision(binding)?.status==='skipped'&&inspectRunClosure(log,definition.identity.runId).closed,'batch_qa_not_ready');
|
|
139
|
+
git(config.codeProject,['merge-base','--is-ancestor',row.merge_commit,'HEAD'],'batch_merge_history_changed');
|
|
140
|
+
}
|
|
141
|
+
function prepareGroup(group){
|
|
142
|
+
const state=progress(),remaining=group.filter(key=>membership.has(key)&&!state.done.has(key));
|
|
143
|
+
for(const key of remaining){
|
|
144
|
+
const {worktree,branch}=location(key);
|
|
145
|
+
if(!fs.existsSync(worktree)){
|
|
146
|
+
need(!state.ready.has(key),'batch_worktree_missing');
|
|
147
|
+
fs.mkdirSync(path.dirname(worktree),{recursive:true});
|
|
148
|
+
git(config.codeProject,['worktree','add','-b',branch,worktree,'HEAD'],'batch_worktree_failed');
|
|
149
|
+
}
|
|
150
|
+
need(git(worktree,['branch','--show-current'])===branch,'batch_worktree_mismatch');
|
|
151
|
+
const definition=plans.get(key);
|
|
152
|
+
plans.set(key,validateRunDefinition({...definition,codeProject:worktree,
|
|
153
|
+
...(definition.codeProjects?{codeProjects:definition.codeProjects.map(root=>path.join(worktree,path.relative(config.codeProject,root)))}:{})}));
|
|
154
|
+
}
|
|
155
|
+
// Include the main checkout as the second assignment after a partial merge.
|
|
156
|
+
const assignments=remaining.map(key=>`${plans.get(key).identity.taskId}=${location(key).worktree}`);
|
|
157
|
+
if(assignments.length===1)assignments.push(`T-batch-main=${config.codeProject}`);
|
|
158
|
+
if(assignments.length)checkParallelWrite({repo:config.codeProject,assignment:assignments});
|
|
159
|
+
}
|
|
160
|
+
function preserveBlockedMember(row){
|
|
161
|
+
const {worktree,branch}=location(row.from_key);
|
|
162
|
+
need(row.worktree===worktree&&row.branch===branch,'batch_worktree_mismatch');
|
|
163
|
+
git(config.codeProject,['rev-parse','--verify',`refs/heads/${branch}`],'batch_worktree_missing');
|
|
164
|
+
if(!fs.existsSync(worktree))return;
|
|
165
|
+
need(git(worktree,['branch','--show-current'])===branch,'batch_worktree_mismatch');
|
|
166
|
+
commitChanges(worktree,taskCommitArgs(plans.get(row.from_key).identity.taskId,taskDescription(config,plans.get(row.from_key)),row.code,row.reason));
|
|
167
|
+
git(config.codeProject,['worktree','remove',worktree]);
|
|
168
|
+
// Keep the branch: its WIP is evidence, not approved code to merge.
|
|
169
|
+
}
|
|
170
|
+
async function driveMember(key,request){
|
|
171
|
+
const run=await open(key);if(run.blocked)return {outcome:'blocked',code:run.blocked.reason};
|
|
172
|
+
members.set(key,run);
|
|
173
|
+
try{
|
|
174
|
+
let status=await run.host.handle({version:1,operation:'status',requestId:request.requestId,identity:plans.get(key).identity});
|
|
175
|
+
const call=async(operation,extra={})=>{
|
|
176
|
+
need(!cancelled,'cancelled');
|
|
177
|
+
status=await run.host.handle({version:1,operation,requestId:request.requestId,identity:status.identity,
|
|
178
|
+
...(['decision','complete','qa','context_refresh'].includes(operation)?{packageDigest:status.packageDigest}:{}),...extra});
|
|
179
|
+
return status;
|
|
180
|
+
};
|
|
181
|
+
for(let round=status.identity.attempt;round<=2;round++){
|
|
182
|
+
if(status.code===null&&['ready','changes_requested'].includes(status.state)
|
|
183
|
+
||status.state==='blocked'&&status.code==='developer_result_invalid')await call('start');
|
|
184
|
+
if(['reported','advanced'].includes(status.outcome)&&(status.code===null&&status.state==='awaiting_review'
|
|
185
|
+
||status.state==='pending_review'&&status.code==='review_transport_timeout'))await call('decision');
|
|
186
|
+
if(status.outcome==='advanced'&&status.code===null&&status.state==='changes_requested'&&status.identity.attempt===round+1)continue;
|
|
187
|
+
if(['reported','advanced'].includes(status.outcome)&&status.code===null&&status.state==='approved'){
|
|
188
|
+
const completion=completeTail.then(()=>call('complete'));
|
|
189
|
+
completeTail=completion.then(()=>{},()=>{});await completion;
|
|
190
|
+
}
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
if(status.state==='fixture_completed'&&status.code===null){
|
|
194
|
+
await call('qa');
|
|
195
|
+
if(status.code==='qa_skipped')await call('context_refresh',{testRunId:null});
|
|
196
|
+
}
|
|
197
|
+
if(status.outcome!=='refreshed'||status.pendingAction!=='start_next_task')return status;
|
|
198
|
+
need(inspectRunClosure(log,plans.get(key).identity.runId).closed,'batch_resources_open');
|
|
199
|
+
record('batch_member_ready',{from_key:key,checkpoint:run.checkpoint(),package_digest:status.packageDigest,
|
|
200
|
+
identity:status.identity,...location(key)});
|
|
201
|
+
return null;
|
|
202
|
+
}finally{members.delete(key);run.close();}
|
|
203
|
+
}
|
|
204
|
+
async function mergeMember(row){
|
|
205
|
+
const key=row.from_key,{worktree,branch}=location(key);
|
|
206
|
+
need(row.worktree===worktree&&row.branch===branch,'batch_worktree_mismatch');
|
|
207
|
+
// Reopen the unchanged member root to verify its actual completion and QA.
|
|
208
|
+
const run=await open(key);
|
|
209
|
+
try{
|
|
210
|
+
need(!run.blocked&&run.checkpoint()===row.checkpoint,'batch_checkpoint_mismatch');
|
|
211
|
+
const status=await run.host.handle({version:1,operation:'status',requestId:'batch-merge-status',identity:row.identity});
|
|
212
|
+
need(status.state==='fixture_completed'&&status.code===null&&status.packageDigest===row.package_digest,'batch_checkpoint_mismatch');
|
|
213
|
+
need(findCmAiQaDecision({specsDir:config.specsDir,feature:plans.get(key).feature,
|
|
214
|
+
identity:row.identity,packageDigest:row.package_digest})?.status==='skipped','batch_qa_not_ready');
|
|
215
|
+
}finally{run.close();}
|
|
216
|
+
let intent=progress().merging.get(key);
|
|
217
|
+
if(!intent){
|
|
218
|
+
git(worktree,['add','-A']);
|
|
219
|
+
if(git(worktree,['status','--porcelain']))git(worktree,['commit',...taskCommitArgs(plans.get(key).identity.taskId,taskDescription(config,plans.get(key)))]);
|
|
220
|
+
need(git(config.codeProject,['status','--porcelain'])==='','batch_main_dirty');
|
|
221
|
+
intent={from_key:key,expected_old:git(config.codeProject,['rev-parse','HEAD']),member_commit:git(worktree,['rev-parse','HEAD'])};
|
|
222
|
+
record('batch_merge_started',intent);
|
|
223
|
+
}
|
|
224
|
+
const current=git(config.codeProject,['rev-parse','HEAD']);
|
|
225
|
+
if(current===intent.expected_old){
|
|
226
|
+
const restore=unionAttributes(config.codeProject);
|
|
227
|
+
let result;
|
|
228
|
+
try{result=spawnSync('git',['-C',config.codeProject,'merge','--no-ff','--no-edit',intent.member_commit],gitOptions());}
|
|
229
|
+
finally{restore();}
|
|
230
|
+
if(result.error||result.status!==0){
|
|
231
|
+
const files=git(config.codeProject,['diff','--name-only','--diff-filter=U']).split('\n').filter(Boolean);
|
|
232
|
+
git(config.codeProject,['merge','--abort'],'batch_merge_abort_failed');
|
|
233
|
+
need(git(config.codeProject,['rev-parse','HEAD'])===intent.expected_old,'batch_merge_history_changed');
|
|
234
|
+
record('batch_merge_conflict',{from_key:key,code:'merge_conflict',files,expected_old:intent.expected_old});
|
|
235
|
+
return {outcome:'blocked',code:'merge_conflict',batchId:config.batchId,files};
|
|
236
|
+
}
|
|
237
|
+
}else{
|
|
238
|
+
// A crash may happen after Git commits but before the handoff log append.
|
|
239
|
+
const parents=git(config.codeProject,['show','-s','--format=%P','HEAD']).split(' ');
|
|
240
|
+
need(parents.length===2&&parents[0]===intent.expected_old&&parents[1]===intent.member_commit,'batch_merge_history_changed');
|
|
241
|
+
}
|
|
242
|
+
const merge_commit=git(config.codeProject,['rev-parse','HEAD']);
|
|
243
|
+
let post_merge_check='skipped';
|
|
244
|
+
if(checkCommands?.length){
|
|
245
|
+
const check=createHostCheck({cwd:config.codeProject,commands:checkCommands,timeoutMs:checkTimeoutMs});
|
|
246
|
+
const results=await check({identity:row.identity},{signal:new AbortController().signal});
|
|
247
|
+
post_merge_check=results.every(item=>item.outcome==='passed')?'passed':'failed';
|
|
248
|
+
if(post_merge_check==='failed'){
|
|
249
|
+
record('batch_merge_blocked',{from_key:key,code:'post_merge_check_failed',merge_commit,post_merge_check});
|
|
250
|
+
return {outcome:'blocked',code:'post_merge_check_failed',batchId:config.batchId};
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const done=progress().done;done.add(key);
|
|
254
|
+
const next=[...plans.keys()].find(key=>!done.has(key));need(next,'parallel_final_task_excluded');
|
|
255
|
+
record('batch_handoff',{from_key:key,to_key:next,checkpoint:row.checkpoint,package_digest:row.package_digest,
|
|
256
|
+
identity:row.identity,merge_commit,post_merge_check});
|
|
257
|
+
git(config.codeProject,['worktree','remove',worktree]);git(config.codeProject,['branch','-d',branch]);
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
async function parallelGroup(group,request){
|
|
261
|
+
const initial=progress();
|
|
262
|
+
if(request.operation==='status')return {outcome:'reported',state:'parallel',batchId:config.batchId,
|
|
263
|
+
ready:group.filter(key=>initial.ready.has(key)),merged:group.filter(key=>initial.done.has(key))};
|
|
264
|
+
if(!initial.rows.length)record('batch_start',{from_key:liveKey});
|
|
265
|
+
if(request.operation==='cancel'){record('batch_cancel',{from_key:liveKey});return {outcome:'cancelled',code:'cancelled',batchId:config.batchId};}
|
|
266
|
+
prepareGroup(group);
|
|
267
|
+
// Resolve every member's actual worktree preflight before any start dispatch.
|
|
268
|
+
for(const key of group.filter(key=>membership.has(key)&&!initial.done.has(key))){
|
|
269
|
+
try{await executionForKey(key);}catch(cause){
|
|
270
|
+
if(cause.code!=='review_preflight_failed')throw cause;
|
|
271
|
+
return {outcome:'blocked',state:'blocked',code:'review_preflight_failed',batchId:config.batchId,
|
|
272
|
+
currentTask:key,identity:plans.get(key).identity};
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
need(!cancelled,'cancelled');
|
|
276
|
+
const pending=group.filter(key=>membership.has(key)&&!initial.ready.has(key)&&!initial.done.has(key));
|
|
277
|
+
const results=await Promise.allSettled(pending.map(key=>driveMember(key,request)));
|
|
278
|
+
if(cancelled)return {outcome:'cancelled',code:'cancelled',batchId:config.batchId};
|
|
279
|
+
for(const row of progress().ready.values()){
|
|
280
|
+
if(!group.includes(row.from_key)||progress().done.has(row.from_key))continue;
|
|
281
|
+
const result=await mergeMember(row);if(result)return result;
|
|
282
|
+
}
|
|
283
|
+
let waiting=null,rejected=null;
|
|
284
|
+
for(const [index,result] of results.entries()){
|
|
285
|
+
if(result.status==='rejected'){rejected??=result.reason;continue;}
|
|
286
|
+
const status=result.value;if(!status)continue;
|
|
287
|
+
// Retryable validation, review transport and completed-task QA stay on
|
|
288
|
+
// their existing recovery path; a new run must not bypass those gates.
|
|
289
|
+
const terminal=['blocked','failed','unknown'].includes(status.state)
|
|
290
|
+
&&status.code!=='developer_result_invalid'
|
|
291
|
+
||status.state==='pending_review'&&status.code!==null&&status.code!=='review_transport_timeout';
|
|
292
|
+
if(!terminal){waiting??=status;continue;}
|
|
293
|
+
const key=pending[index];
|
|
294
|
+
record('batch_member_blocked',{from_key:key,code:status.code??status.state,
|
|
295
|
+
reason:status.blockedReason??status.reason??status.code??status.state,...location(key),generation:2});
|
|
296
|
+
}
|
|
297
|
+
// Log before Git mutation so a crash during WIP commit/removal is resumable.
|
|
298
|
+
for(const row of progress().blocked.values())preserveBlockedMember(row);
|
|
299
|
+
if(rejected)throw rejected;
|
|
300
|
+
if(waiting)return {...waiting,batchId:config.batchId};
|
|
301
|
+
return null;
|
|
76
302
|
}
|
|
77
303
|
return Object.freeze({async handle(raw){
|
|
78
304
|
const request=json(raw);shape(request,['operation','requestId']);id(request.requestId);
|
|
79
305
|
need(['advance','status','cancel'].includes(request.operation));
|
|
80
306
|
if(request.operation==='cancel'&&busy){
|
|
81
307
|
cancelled=true;
|
|
308
|
+
if(members.size){record('batch_cancel',{from_key:liveKey});
|
|
309
|
+
await Promise.all([...members].map(([key,run])=>run.host.handle({version:1,operation:'cancel',requestId:request.requestId,identity:plans.get(key).identity})));
|
|
310
|
+
return {outcome:'cancelled',code:'cancelled',batchId:config.batchId};}
|
|
82
311
|
if(active){
|
|
83
312
|
if(progress().rows.length===0)record('batch_start',{from_key:liveKey});
|
|
84
313
|
record('batch_cancel',{from_key:liveKey});
|
|
@@ -89,11 +318,19 @@ export function createCmAiBatch({configuration,executionFor,logHome}){
|
|
|
89
318
|
if(request.operation==='status'&&busy)return {outcome:'reported',batchId:config.batchId,currentTask:liveKey,state:'running'};
|
|
90
319
|
need(!busy,'batch_busy');busy=true;
|
|
91
320
|
try{
|
|
321
|
+
releaseLock=acquireBatchLock(config);
|
|
92
322
|
const initial=progress();liveKey=initial.current;
|
|
93
|
-
if(initial.stopped)return {outcome:'blocked',code:'cancelled',batchId:config.batchId};
|
|
323
|
+
if(initial.stopped)return {outcome:'blocked',code:initial.code??'cancelled',batchId:config.batchId};
|
|
324
|
+
if(request.operation==='advance'&&!initial.rows.length){
|
|
325
|
+
const dirty=git(config.codeProject,['status','--porcelain']);
|
|
326
|
+
if(dirty)return {outcome:'blocked',code:'batch_main_dirty',batchId:config.batchId,
|
|
327
|
+
reason:`batch_main_dirty\n${dirty}`,files:dirty.split('\n')};
|
|
328
|
+
}
|
|
329
|
+
if(request.operation==='advance')for(const row of initial.blocked?.values()??[])preserveBlockedMember(row);
|
|
94
330
|
// Validate durable checkpoints, not old live snapshots: later approved
|
|
95
331
|
// tasks may legitimately change the same code paths.
|
|
96
332
|
for(const row of initial.rows.filter(row=>row.phase==='batch_handoff')){
|
|
333
|
+
if(membership.has(row.from_key)){verifyMerged(row);continue;}
|
|
97
334
|
const previous=await open(row.from_key);
|
|
98
335
|
try{
|
|
99
336
|
need(!previous.blocked&&previous.checkpoint()===row.checkpoint,'batch_checkpoint_mismatch');
|
|
@@ -108,11 +345,14 @@ export function createCmAiBatch({configuration,executionFor,logHome}){
|
|
|
108
345
|
}
|
|
109
346
|
finally{previous.close();}
|
|
110
347
|
}
|
|
111
|
-
for(let count=0;count<plans.size;count++){
|
|
348
|
+
for(let count=0;count<plans.size+groups.length;count++){
|
|
349
|
+
if(membership.has(liveKey)){
|
|
350
|
+
const result=await parallelGroup(membership.get(liveKey),request);
|
|
351
|
+
if(result)return result;liveKey=progress().current;continue;
|
|
352
|
+
}
|
|
112
353
|
active=await open(liveKey);
|
|
113
354
|
if(active.blocked)return {outcome:'blocked',code:active.blocked.reason,batchId:config.batchId};
|
|
114
|
-
//
|
|
115
|
-
// a stale selection made before another batch process advanced.
|
|
355
|
+
// batch.lock serializes selection across processes; child locks remain run-local.
|
|
116
356
|
need(progress().current===liveKey&&!progress().stopped,'batch_history_changed');
|
|
117
357
|
if(progress().rows.length===0&&request.operation!=='status')record('batch_start',{from_key:liveKey});
|
|
118
358
|
if(cancelled||request.operation==='cancel'){
|
|
@@ -124,13 +364,107 @@ export function createCmAiBatch({configuration,executionFor,logHome}){
|
|
|
124
364
|
if(cancelled)return {outcome:'cancelled',code:'cancelled',batchId:config.batchId};
|
|
125
365
|
if(result.state==='run_done'||result.pendingAction==='start_next_task')
|
|
126
366
|
need(inspectRunClosure(log,plans.get(liveKey).identity.runId).closed,'batch_resources_open');
|
|
127
|
-
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
367
|
+
const finished=result.state==='run_done'&&['run_done','run_done_degraded'].includes(result.code);
|
|
368
|
+
const handoff=result.outcome==='refreshed'&&result.pendingAction==='start_next_task';
|
|
369
|
+
if(request.operation!=='advance'||(!finished&&!handoff))return {...result,batchId:config.batchId};
|
|
370
|
+
const next=handoff?`${result.nextTask.feature}/${result.nextTask.id}`:null;
|
|
371
|
+
if(handoff)need(plans.has(next),'batch_task_scope_required');
|
|
372
|
+
let task_commit=commitChanges(config.codeProject,taskCommitArgs(plans.get(liveKey).identity.taskId,taskDescription(config,plans.get(liveKey))));
|
|
373
|
+
if(task_commit)record('batch_task_committed',{from_key:liveKey,task_commit});
|
|
374
|
+
else task_commit=progress().rows.filter(row=>row.phase==='batch_task_committed'&&row.from_key===liveKey).at(-1)?.task_commit??null;
|
|
375
|
+
if(finished)return {...result,batchId:config.batchId,task_commit};
|
|
376
|
+
record('batch_handoff',{from_key:liveKey,to_key:next,checkpoint:active.checkpoint(),package_digest:result.packageDigest,task_commit});
|
|
131
377
|
active.close();active=null;liveKey=next;
|
|
132
378
|
}
|
|
133
379
|
need(false,'batch_limit');
|
|
134
|
-
}finally{active?.close();active=null;busy=false;}
|
|
380
|
+
}finally{active?.close();active=null;releaseLock?.();releaseLock=null;busy=false;}
|
|
135
381
|
}});
|
|
136
382
|
}
|
|
383
|
+
|
|
384
|
+
function gitOptions(){return {encoding:'utf8',timeout:60000,maxBuffer:4*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:'0'}};}
|
|
385
|
+
function git(cwd,args,code='batch_git_failed'){
|
|
386
|
+
const result=spawnSync('git',['-C',cwd,...args],gitOptions());
|
|
387
|
+
need(!result.error&&result.status===0&&result.signal===null,code);return result.stdout.trim();
|
|
388
|
+
}
|
|
389
|
+
function commitChanges(cwd,messageArgs){
|
|
390
|
+
if(!git(cwd,['status','--porcelain']))return null;
|
|
391
|
+
git(cwd,['add','-A']);git(cwd,['commit',...messageArgs]);
|
|
392
|
+
return git(cwd,['rev-parse','HEAD']);
|
|
393
|
+
}
|
|
394
|
+
// Keep the original description in the body; only the subject is summarized.
|
|
395
|
+
export function taskCommitArgs(taskId,description,blockedCode=null,blockedReason=null){
|
|
396
|
+
let summary=description.split(/[;。\r\n\u2028\u2029]/u,1)[0].trim()
|
|
397
|
+
.replace(/^~\d+min\s*/u,'').replace(/\s*~\d+min$/u,'').trim();
|
|
398
|
+
summary=summary.replace(/\s+/gu,' ');
|
|
399
|
+
let subject=blockedCode===null?`${taskId}: ${summary||taskId}`:`WIP ${taskId}: blocked (${blockedCode})`;
|
|
400
|
+
// Count ASCII as one column and non-ASCII conservatively as two.
|
|
401
|
+
const width=character=>character.codePointAt(0)<=0x7f?1:2;
|
|
402
|
+
const characters=Array.from(subject);
|
|
403
|
+
if(blockedCode===null&&characters.reduce((sum,character)=>sum+width(character),0)>72){
|
|
404
|
+
subject='';let columns=0;
|
|
405
|
+
for(const character of characters){
|
|
406
|
+
if(columns+width(character)>70)break;
|
|
407
|
+
subject+=character;columns+=width(character);
|
|
408
|
+
}
|
|
409
|
+
subject=subject.trimEnd()+'…';
|
|
410
|
+
}
|
|
411
|
+
return ['-m',subject,'-m',description+(blockedCode!==null&&blockedReason!==null?`\n\n${blockedReason}`:'')];
|
|
412
|
+
}
|
|
413
|
+
function taskDescription(config,definition){
|
|
414
|
+
const parsed=parseFeatureTaskText(fs.readFileSync(path.join(config.specsDir,definition.feature,'tasks.md'),'utf8'),{allowDependencyPunctuation:true});
|
|
415
|
+
need(!parsed.error,'parallel_task_invalid');return parsed.tasks.find(task=>task.id===definition.identity.taskId)?.description??definition.identity.taskId;
|
|
416
|
+
}
|
|
417
|
+
function validateGroups(config,plans){
|
|
418
|
+
const groups=config.parallel??[];need(Array.isArray(groups),'invalid_parallel_groups');const used=new Set();
|
|
419
|
+
for(const group of groups){
|
|
420
|
+
need(Array.isArray(group)&&group.length>=2&&group.length<=4,'invalid_parallel_group');
|
|
421
|
+
need(group.every(key=>plans.has(key)&&!used.has(key))&&new Set(group).size===group.length,'invalid_parallel_group');
|
|
422
|
+
const feature=plans.get(group[0]).feature;
|
|
423
|
+
need(group.every(key=>plans.get(key).feature===feature),'parallel_feature_mismatch');
|
|
424
|
+
const parsed=parseFeatureTaskText(fs.readFileSync(path.join(config.specsDir,feature,'tasks.md'),'utf8'),{allowDependencyPunctuation:true});
|
|
425
|
+
need(!parsed.error,'parallel_task_invalid');
|
|
426
|
+
const ids=new Set(group.map(key=>plans.get(key).identity.taskId));
|
|
427
|
+
need([...ids].every(id=>parsed.tasks.some(task=>task.id===id&&!task.dropped)),'parallel_task_invalid');
|
|
428
|
+
need([...ids].every(id=>(parsed.dependencies.get(id)??[]).every(dep=>!ids.has(dep))),'parallel_dependency_conflict');
|
|
429
|
+
const ordered=parsed.tasks.filter(task=>!task.dropped),last=ordered.at(-1);
|
|
430
|
+
need(last&&!ids.has(last.id)&&plans.has(`${feature}/${last.id}`),'parallel_final_task_excluded');
|
|
431
|
+
const paths=new Set();
|
|
432
|
+
for(const key of group)for(const file of plans.get(key).scope){
|
|
433
|
+
need(!paths.has(file),'parallel_scope_overlap');paths.add(file);
|
|
434
|
+
}
|
|
435
|
+
for(const key of group)used.add(key);
|
|
436
|
+
}
|
|
437
|
+
return groups;
|
|
438
|
+
}
|
|
439
|
+
function acquireBatchLock(config){
|
|
440
|
+
const directory=path.join(config.specsDir,'.reviews','.execution');fs.mkdirSync(directory,{recursive:true,mode:0o700});
|
|
441
|
+
need(fs.realpathSync(directory)===directory,'batch_lock_invalid');
|
|
442
|
+
const target=path.join(directory,'batch.lock');
|
|
443
|
+
for(let attempt=0;attempt<3;attempt++){
|
|
444
|
+
let fd;
|
|
445
|
+
try{fd=fs.openSync(target,'wx',0o600);}catch(error){
|
|
446
|
+
if(error.code!=='EEXIST')throw error;
|
|
447
|
+
const stat=fs.lstatSync(target);need(stat.isFile()&&!stat.isSymbolicLink(),'batch_lock_invalid');
|
|
448
|
+
const owner=JSON.parse(fs.readFileSync(target,'utf8'));
|
|
449
|
+
need(Number.isSafeInteger(owner.pid)&&owner.pid>0,'batch_lock_invalid');
|
|
450
|
+
let alive=true;try{process.kill(owner.pid,0);}catch(error){if(error.code==='ESRCH')alive=false;}
|
|
451
|
+
need(!alive,'batch_locked');
|
|
452
|
+
const current=fs.lstatSync(target);need(current.ino===stat.ino&¤t.dev===stat.dev,'batch_locked');fs.unlinkSync(target);continue;
|
|
453
|
+
}
|
|
454
|
+
const stat=fs.fstatSync(fd);
|
|
455
|
+
try{fs.writeFileSync(fd,JSON.stringify({batchId:config.batchId,pid:process.pid,at:new Date().toISOString()}));fs.fsyncSync(fd);}
|
|
456
|
+
finally{fs.closeSync(fd);}
|
|
457
|
+
return ()=>{const current=fs.lstatSync(target);need(current.ino===stat.ino&¤t.dev===stat.dev,'batch_lock_changed');fs.unlinkSync(target);};
|
|
458
|
+
}
|
|
459
|
+
need(false,'batch_locked');
|
|
460
|
+
}
|
|
461
|
+
function unionAttributes(repo){
|
|
462
|
+
const target=git(repo,['rev-parse','--path-format=absolute','--git-path','info/attributes']);
|
|
463
|
+
const exists=fs.existsSync(target);
|
|
464
|
+
if(exists)need(fs.lstatSync(target).isFile()&&!fs.lstatSync(target).isSymbolicLink(),'batch_attributes_invalid');
|
|
465
|
+
const before=exists?fs.readFileSync(target):null;
|
|
466
|
+
const after=Buffer.concat([before??Buffer.alloc(0),Buffer.from('\nAGENTS.md merge=union\n')]);
|
|
467
|
+
fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,after);
|
|
468
|
+
return ()=>{need(fs.readFileSync(target).equals(after),'batch_attributes_changed');
|
|
469
|
+
if(before===null)fs.unlinkSync(target);else fs.writeFileSync(target,before);};
|
|
470
|
+
}
|