@aibyzero/cm-workflow 0.16.7 → 0.16.9

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.
Files changed (182) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +39 -3
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/compat/claude-commands/cm-notify.md +3 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +61 -4
  10. package/docs/next-steps.md +8 -2
  11. package/docs/user-guide.md +204 -0
  12. package/package.json +2 -1
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
  17. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  18. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  19. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  20. package/runtime/js/cm-ai/drive-core.mjs +26 -4
  21. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  22. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  23. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  24. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  25. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  26. package/runtime/js/cm-ai/host-check.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  28. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  29. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  30. package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
  31. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  32. package/runtime/js/cm-ai/host-session.mjs +47 -7
  33. package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
  34. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  35. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  36. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  37. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  38. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  39. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  40. package/runtime/js/cm-ai/review-package.mjs +10 -1
  41. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  42. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  43. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  44. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  45. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  46. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  47. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  48. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  49. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  50. package/runtime/js/cm-fix/execution.mjs +356 -187
  51. package/runtime/js/cm-fix/host.mjs +2 -1
  52. package/runtime/js/cm-fix/investigation.mjs +25 -9
  53. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  54. package/runtime/js/cm-fix/progress.mjs +15 -3
  55. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  56. package/runtime/js/cm-fix/repair.mjs +11 -3
  57. package/runtime/js/cm-fix/test-author.mjs +10 -3
  58. package/runtime/js/cm-idea/session.mjs +67 -4
  59. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  60. package/runtime/js/cm-prd/session.mjs +43 -0
  61. package/runtime/js/cm-refactor/records.mjs +98 -8
  62. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  63. package/runtime/js/cm-test/host.mjs +10 -3
  64. package/runtime/js/cm-test/session.mjs +45 -6
  65. package/runtime/js/notify-run.mjs +26 -0
  66. package/runtime/js/notify-safe-read.mjs +49 -0
  67. package/runtime/js/notify-send.mjs +312 -0
  68. package/runtime/js/notify.mjs +492 -0
  69. package/runtime/js/policy-binding-compat.mjs +54 -0
  70. package/runtime/model-efficiency.md +17 -0
  71. package/scripts/ci-test-shards.mjs +67 -0
  72. package/scripts/ci-test-shards.test.mjs +64 -0
  73. package/scripts/ci-test-weights.json +222 -0
  74. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  75. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  76. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  77. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  78. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  79. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  80. package/scripts/cm-ai-batch-drive.mjs +55 -10
  81. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  82. package/scripts/cm-ai-batch-host.mjs +132 -13
  83. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  84. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  85. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  86. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  87. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  88. package/scripts/cm-ai-batch-run.mjs +189 -22
  89. package/scripts/cm-ai-batch-run.test.mjs +22 -334
  90. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  91. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  92. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  93. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  94. package/scripts/cm-ai-drive.mjs +68 -23
  95. package/scripts/cm-ai-drive.test.mjs +37 -2
  96. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  97. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  98. package/scripts/cm-ai-host-fixture.mjs +268 -0
  99. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  100. package/scripts/cm-ai-host.mjs +28 -16
  101. package/scripts/cm-ai-host.test.mjs +17 -759
  102. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  103. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  104. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  105. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  106. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  107. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  108. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
  109. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  110. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  111. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  112. package/scripts/cm-ai-run.mjs +15 -6
  113. package/scripts/cm-ai-supersede.test.mjs +486 -41
  114. package/scripts/cm-check-drive-files.mjs +8 -0
  115. package/scripts/cm-check-drive.test.mjs +2 -5
  116. package/scripts/cm-check-runtime.sh +4 -2
  117. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  118. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  119. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  120. package/scripts/cm-claude-worker.test.mjs +18 -2
  121. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  122. package/scripts/cm-fix-abandon.test.mjs +249 -10
  123. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  124. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  125. package/scripts/cm-fix-drive.mjs +34 -8
  126. package/scripts/cm-fix-host.mjs +8 -7
  127. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  128. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  129. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  130. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  131. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  132. package/scripts/cm-host-documentation.test.mjs +49 -0
  133. package/scripts/cm-host-qa-executor.test.mjs +143 -10
  134. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  135. package/scripts/cm-idea-drive.mjs +49 -11
  136. package/scripts/cm-idea-drive.test.mjs +66 -0
  137. package/scripts/cm-idea-host.mjs +106 -16
  138. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  139. package/scripts/cm-init-drive.mjs +41 -7
  140. package/scripts/cm-init-host.mjs +61 -12
  141. package/scripts/cm-log-event.mjs +49 -12
  142. package/scripts/cm-notify-command.test.mjs +900 -0
  143. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  144. package/scripts/cm-notify.mjs +469 -0
  145. package/scripts/cm-notify.test.mjs +685 -0
  146. package/scripts/cm-patrol.mjs +83 -0
  147. package/scripts/cm-patrol.test.mjs +161 -0
  148. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  149. package/scripts/cm-prd-drive.mjs +18 -5
  150. package/scripts/cm-prd-drive.test.mjs +15 -0
  151. package/scripts/cm-prd-host.mjs +37 -4
  152. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  153. package/scripts/cm-prd-review-gate.mjs +56 -0
  154. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  155. package/scripts/cm-refactor-drive.mjs +52 -8
  156. package/scripts/cm-refactor-drive.test.mjs +44 -0
  157. package/scripts/cm-refactor-host.test.mjs +10 -6
  158. package/scripts/cm-release-smoke.sh +2 -0
  159. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  160. package/scripts/cm-test-drive.mjs +21 -5
  161. package/scripts/cm-token-report.mjs +497 -0
  162. package/scripts/cm-token-report.test.mjs +346 -0
  163. package/scripts/fixtures/claude-review-process.mjs +1 -1
  164. package/scripts/policy-binding-compat.test.mjs +99 -0
  165. package/scripts/scan-public-safety.py +4 -0
  166. package/scripts/validate-public-repo.py +4 -0
  167. package/skills/cm-ai/SKILL.md +7 -3
  168. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  169. package/skills/cm-ai/references/js-host-modes.md +90 -0
  170. package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
  171. package/skills/cm-ai/references/js-host-recovery.md +311 -0
  172. package/skills/cm-ai/references/js-host.md +76 -331
  173. package/skills/cm-check/SKILL.md +3 -3
  174. package/skills/cm-fix/SKILL.md +2 -0
  175. package/skills/cm-fix/references/js-host.md +56 -10
  176. package/skills/cm-idea/references/js-host.md +27 -2
  177. package/skills/cm-init/references/js-host.md +16 -3
  178. package/skills/cm-notify/SKILL.md +34 -0
  179. package/skills/cm-prd/SKILL.md +2 -0
  180. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  181. package/skills/cm-refactor/references/js-host.md +17 -0
  182. package/skills/cm-test/references/js-host.md +14 -1
@@ -16,7 +16,10 @@ import {checkParallelWrite} from './cm-task-gate.mjs';
16
16
  import {parseFeatureTaskText} from '../runtime/js/cm-ai/cm-ai-admission.mjs';
17
17
  import {approvedTaskGrammar} from '../runtime/js/spec-task-line.mjs';
18
18
  import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
19
- import {inspectRunClosure} from './cm-log-event.mjs';
19
+ import {inspectRunClosure as inspectClosure} from './cm-log-event.mjs';
20
+ import {releaseVerifiedQaResources} from '../runtime/js/cm-ai/qa-resource-release.mjs';
21
+ import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
22
+ import {strictPriorAttemptResolved,sameTaskPriorAttemptResolved} from '../runtime/js/cm-ai/external-run-guard.mjs';
20
23
 
21
24
  const writer=fileURLToPath(new URL('./cm-log-event.py',import.meta.url));
22
25
  const key=task=>`${task.feature}/${task.taskId}`;
@@ -26,9 +29,9 @@ export const batchTaskRunId=(batchId,taskKey)=>`task-${digest({batchId,task:task
26
29
  // never advertise it for them. Name the exits that do exist instead. An idle
27
30
  // cancel of a parallel group does not end its member runs, so a parallel
28
31
  // member cannot be superseded afterwards and only the spec revert applies.
29
- export function batchMemberResult(result,{parallel=false}={}){
32
+ export function batchMemberResult(result,{parallel=false,taskKey=null}={}){
30
33
  const decorate=value=>{
31
- const guidance=batchOperatorGuidance(value);
34
+ const guidance=batchOperatorGuidance(value,{taskKey});
32
35
  return guidance?Object.freeze({...value,guidance}):value;
33
36
  };
34
37
  if(result?.pendingAction!=='spec_rebind')return decorate(result);
@@ -38,8 +41,53 @@ export function batchMemberResult(result,{parallel=false}={}){
38
41
  reason:parallel?`${revert}。并行组成员没有单独重做的出口。`
39
42
  :`${revert};或取消本批次,还原该任务已改动的代码后,用单任务宿主 cm-ai-host.mjs 以 --supersede-reviewed-evidence --supersede-reason 原因 新建运行重做该任务。`}));
40
43
  }
44
+ // Q24: single-task recovery operations a batch forwards to the member run it is
45
+ // stopped on, through the same cm-ai entry. option is the openControlRun one-shot
46
+ // permission; flag is the batch host launch flag that grants it for one member.
47
+ export const BATCH_MEMBER_ACTIONS=Object.freeze({
48
+ develop_redo:Object.freeze({option:'allowDevelopRedo',flag:'--allow-develop-redo'}),
49
+ abandon_effect:Object.freeze({option:'allowAbandonEffect',flag:'--allow-abandon-effect'}),
50
+ abandon_review:Object.freeze({option:'allowAbandonReview',flag:'--allow-abandon-review'}),
51
+ bootstrap_review_recover:Object.freeze({option:'allowBootstrapReviewRecovery',flag:'--allow-bootstrap-review-recovery'})});
52
+ // Pending actions a member resolves inside its own run from the batch entry.
53
+ const IN_RUN_ACTIONS=new Set([...Object.keys(BATCH_MEMBER_ACTIONS),'reconcile_review']);
54
+ // A batch may reschedule a parallel member serially (a second generation: new runId,
55
+ // attempt 1) only from a checkpointed blocked terminal: the old call returned, so it
56
+ // ended and its writer stopped. The decision reads the member's RAW persisted journal
57
+ // (history from readRunnerHistory), never the host's projected status alone: a
58
+ // projection such as blocked/develop_redo_limit can sit over a raw unknown whose last
59
+ // call nobody proved stopped. Anything unresolved (raw unknown, a pending effect, an
60
+ // open review, a pending reconcile, an operator confirmation still due) stays in its
61
+ // original run. Shared by every batch kind that reschedules.
62
+ export function memberRescheduleAllowed(status,history){
63
+ const raw=history?.state;
64
+ return status?.state==='blocked'&&raw?.state==='blocked'&&history.pending==null
65
+ &&!IN_RUN_ACTIONS.has(status.pendingAction)&&status.pendingAction!=='reconcile'
66
+ &&status.developRedoRequired!==true&&status.reviewRedispatchStopRequired!==true;
67
+ }
68
+ // The member's raw journal replay, or null when it cannot be read or replayed.
69
+ export function memberRunHistory(specsDir,runId){
70
+ try{
71
+ const state=JSON.parse(fs.readFileSync(path.join(specsDir,'.reviews','.execution',runId,'state.json'),'utf8'));
72
+ const records=state.records;return readRunnerHistory(records,records[0].payload.config,records[0].payload.version);
73
+ }catch{return null;}
74
+ }
75
+ // Whether an ordinary single-task supersede on the member's own worktree would be
76
+ // admitted, by the same entry conditions: reviewed-evidence-supersede takes only a raw
77
+ // blocked, cancelled, unknown or fixture_completed run with no pending effect; the
78
+ // external run guard such a launch takes (strictOnly, when a strict binding exists on
79
+ // the root) skips a non-strict prior run but refuses a strict one that is unknown or
80
+ // holds an unreconciled call, and a same-task prior run still in flight.
81
+ export function memberSupersedeAdmitted(specsDir,runId,history){
82
+ if(!history?.state||history.pending||!['blocked','cancelled','unknown','fixture_completed'].includes(history.state.state))return false;
83
+ let records;
84
+ try{records=JSON.parse(fs.readFileSync(path.join(specsDir,'.reviews','.execution',runId,'state.json'),'utf8')).records;}catch{return false;}
85
+ const runConfig=records[0]?.payload?.config;if(!runConfig)return false;
86
+ if(!(runConfig.externalModels||runConfig.executionPolicy))return true;
87
+ return strictPriorAttemptResolved(runConfig,history,records)&&sameTaskPriorAttemptResolved(history);
88
+ }
41
89
  export function createCmAiBatch({configuration,executionFor,logHome,runtime='codex',checkCommands=null,checkTimeoutMs=60000,
42
- rerunUnknownQa=false,rerunBlockedQa=false,holdRevisions=[],bootstrapKeys=[]}){
90
+ rerunUnknownQa=false,rerunBlockedQa=false,qaEnvironmentFailure=null,holdRevisions=[],bootstrapKeys=[],memberActions={}}){
43
91
  const config=json(configuration);
44
92
  shape(config,['version','repositoryId','batchId','specsDir','codeProject','tasks',...['externalModels','executionPolicy','codeProjects','parallel'].filter(name=>Object.hasOwn(config,name))]);
45
93
  need(config.version===1);id(config.repositoryId);id(config.batchId);need(config.batchId.length>=8);
@@ -79,9 +127,30 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
79
127
  // Tasks whose second-round answer is not written yet stop after a changes_requested review.
80
128
  need(Array.isArray(holdRevisions)&&holdRevisions.every(item=>plans.has(item)),'invalid_input');
81
129
  const held=new Set(holdRevisions);
130
+ need(qaEnvironmentFailure===null||(rerunUnknownQa||rerunBlockedQa)&&typeof qaEnvironmentFailure==='string','qa_recovery_authorization_required');
131
+ need(memberActions!==null&&typeof memberActions==='object'&&Object.keys(memberActions).every(name=>Object.hasOwn(BATCH_MEMBER_ACTIONS,name)
132
+ &&Array.isArray(memberActions[name])&&memberActions[name].every(item=>plans.has(item))),'invalid_input');
133
+ // One-shot per launch and member, like the single-task flags.
134
+ const actionGrants=new Map(Object.keys(BATCH_MEMBER_ACTIONS).map(name=>[name,new Set(memberActions[name]??[])]));
82
135
  const groups=validateGroups(config,plans),membership=new Map(groups.flatMap(group=>group.map(key=>[key,group])));
83
136
  const originalMembership=new Map(membership),originalPlans=new Map(plans);
84
137
  const first=plans.keys().next().value,planDigest=digest(config),log=path.join(config.specsDir,'运行日志.jsonl');
138
+ // Q26: before any closure check, close cleanup_failed QA command resources whose
139
+ // journaled process group the host proves gone (qa-resource-release.mjs).
140
+ let stillOpen=[];
141
+ const inspectRunClosure=(file,runId)=>{
142
+ const plan=[...plans.values()].find(item=>item.identity.runId===runId);stillOpen=[];
143
+ if(plan)try{stillOpen=releaseVerifiedQaResources({specsDir:config.specsDir,codeProject:plan.codeProject,runId,runtime,logHome}).open;}
144
+ catch(error){if(error?.code==='qa_resource_release_failed')throw error;}
145
+ return inspectClosure(file,runId);
146
+ };
147
+ // R4: an open closure names what is still open and the exit, not a bare code.
148
+ const requireClosed=runId=>{
149
+ if(inspectRunClosure(log,runId).closed)return;
150
+ const listed=stillOpen.map(row=>`${row.resourceId}(${row.phase},${row.verdict==='alive'?'进程组仍在':row.verdict==='unrecorded'?'没有记录进程身份':'无法核实'})`);
151
+ throw Object.assign(new Error('batch_resources_open'),{code:'batch_resources_open',
152
+ reason:`成员运行 ${runId} 的 QA 资源或测试轮次尚未闭合${listed.length?`:${listed.join('、')}`:''}。宿主只在 cleanup_failed 记录了进程组且核实已退出时自动补记 released;先确认这些 QA 命令进程已退出,再从批次入口 advance。`});
153
+ };
85
154
  let active=null,busy=false,cancelled=false,liveKey=first;
86
155
  const executions=new Map(),members=new Map();
87
156
  let releaseLock=null,completeTail=Promise.resolve();
@@ -129,18 +198,20 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
129
198
  need(!result.error&&result.status===0&&result.signal===null,'batch_log_failed');
130
199
  const receipt=JSON.parse(result.stdout);need(receipt.run_id===config.batchId,'batch_log_failed');
131
200
  }
132
- async function open(taskKey){
201
+ async function open(taskKey,permission={}){
133
202
  const definition=plans.get(taskKey),state=path.join(config.specsDir,'.reviews','.execution',definition.identity.runId,'state.json');
134
203
  const mode=fs.existsSync(state)?'resume':'create',execution=await executionForKey(taskKey);
135
204
  // QA recovery is rejected outright for a created run or one without a QA
136
205
  // executor. Passing it to every task would take down the unrelated ones, so
137
206
  // only the tasks the flag can legally apply to receive it.
138
207
  const recovery=mode==='resume'&&execution?.qaExecutor&&(rerunUnknownQa||rerunBlockedQa)
139
- ? {rerunUnknownQa,rerunBlockedQa} : {};
140
- const run=await openControlRun(definition,mode,execution,{...recovery,...(held.has(taskKey)?{holdRevision:true}:{}),
208
+ ? {rerunUnknownQa,rerunBlockedQa,...(qaEnvironmentFailure===null?{}:{qaEnvironmentFailure})} : {};
209
+ // Q24: a forwarded recovery operation opens the member with exactly its one permission.
210
+ need(mode==='resume'||!Object.keys(permission).length,'batch_member_action_unavailable');
211
+ const run=await openControlRun(definition,mode,execution,{...recovery,...permission,...(held.has(taskKey)?{holdRevision:true}:{}),
141
212
  ...(membership.has(taskKey)?{parallelSelection:{version:1,group:membership.get(taskKey).map(key=>plans.get(key).identity.taskId)}}:{})});
142
213
  if(!run.host)return run;
143
- return {...run,host:{...run.host,handle:async request=>batchMemberResult(await run.host.handle(request),{parallel:membership.has(taskKey)})}};
214
+ return {...run,host:{...run.host,handle:async request=>batchMemberResult(await run.host.handle(request),{parallel:membership.has(taskKey),taskKey})}};
144
215
  }
145
216
  function parallelProgress(rows){
146
217
  const done=new Set(),ready=new Map(),merging=new Map(),blocked=new Map();let stopped=false,code=null;
@@ -204,6 +275,11 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
204
275
  }
205
276
  function prepareGroup(group){
206
277
  const state=progress(),remaining=group.filter(key=>membership.has(key)&&!state.done.has(key));
278
+ // A member may only create files (js-host.md 3.1): every scope path of a member
279
+ // about to get its worktree must be absent from HEAD. Checked for the whole group
280
+ // before any worktree exists; started members are not rechecked.
281
+ for(const key of remaining)if(!fs.existsSync(location(key).worktree))for(const file of plans.get(key).scope)
282
+ need(spawnSync('git',['-C',config.codeProject,'cat-file','-e',`HEAD:${file}`],gitOptions()).status!==0,'parallel_scope_existing_file');
207
283
  for(const key of remaining){
208
284
  const {worktree,branch}=location(key);
209
285
  if(!fs.existsSync(worktree)){
@@ -260,7 +336,7 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
260
336
  if(status.code==='qa_skipped')await call('context_refresh',{testRunId:null});
261
337
  }
262
338
  if(status.outcome!=='refreshed'||status.pendingAction!=='start_next_task')return status;
263
- need(inspectRunClosure(log,plans.get(key).identity.runId).closed,'batch_resources_open');
339
+ requireClosed(plans.get(key).identity.runId);
264
340
  record('batch_member_ready',{from_key:key,checkpoint:run.checkpoint(),package_digest:status.packageDigest,
265
341
  identity:status.identity,...location(key)});
266
342
  return null;
@@ -345,7 +421,7 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
345
421
  if(!group.includes(row.from_key)||progress().done.has(row.from_key))continue;
346
422
  const result=await mergeMember(row);if(result)return result;
347
423
  }
348
- let waiting=null,rejected=null;
424
+ let waiting=null,rejected=null,recoverable=null,unresolved=null;const rescheduled=[];
349
425
  for(const [index,result] of results.entries()){
350
426
  if(result.status==='rejected'){rejected??=result.reason;continue;}
351
427
  const status=result.value;if(!status)continue;
@@ -354,20 +430,116 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
354
430
  const terminal=['blocked','failed','unknown'].includes(status.state)
355
431
  &&!developmentRetryable(status)&&!completionRetryable(status)
356
432
  ||status.state==='pending_review'&&status.code!==null&&!reviewRetryable(status);
357
- if(!terminal||config.externalModels||config.executionPolicy){waiting??=status;continue;}
433
+ if(!terminal){waiting??=status;continue;}
358
434
  const key=pending[index];
435
+ // Q25: a member that can still be resolved in its own run (original-invocation
436
+ // receipts, interrupted effect, a redo awaiting stop confirmation) keeps its
437
+ // worktree and stops with the batch operation named; an unconfirmed one stays
438
+ // in its run with an explicit stop; only a raw checkpointed blocked terminal is
439
+ // rescheduled serially. Ordinary batches follow the same rules (they used to
440
+ // reschedule every terminal, unknown included, and develop gen 2 at once).
441
+ if(IN_RUN_ACTIONS.has(status.pendingAction)){recoverable??={key,status};continue;}
442
+ const history=memberRunHistory(config.specsDir,plans.get(key).identity.runId);
443
+ if(!memberRescheduleAllowed(status,history)){
444
+ unresolved??={key,status,history,raw:history?.state?`${history.state.state}/${history.state.code??history.state.state}`:'unreadable'};continue;}
445
+ rescheduled.push(key);
359
446
  record('batch_member_blocked',{from_key:key,code:status.code??status.state,
360
447
  reason:status.blockedReason??status.reason??status.code??status.state,...location(key),generation:2});
361
448
  }
362
449
  // Log before Git mutation so a crash during WIP commit/removal is resumable.
363
450
  for(const row of progress().blocked.values())preserveBlockedMember(row);
364
451
  if(rejected)throw rejected;
452
+ if(recoverable)return parallelRecoveryRequired(recoverable.key,recoverable.status);
453
+ if(unresolved)return parallelMemberUnresolved(unresolved.key,unresolved.status,unresolved.raw,unresolved.history);
454
+ // The second generation is a new run: stop here so the next advance (and its
455
+ // driver) prepares that run's answers before anything is dispatched to it.
456
+ if(rescheduled.length)return parallelMemberRescheduled(rescheduled);
365
457
  if(waiting)return {...waiting,batchId:config.batchId};
366
458
  return null;
367
459
  }
460
+ const stopGuidance=(summary,nextStep,prerequisites)=>Object.freeze({summary,nextStep,recoveryOperation:null,
461
+ prerequisites:Object.freeze(prerequisites),authorizationGranted:false});
462
+ // reconcile_review exists only for external-model or execution-policy runs.
463
+ const batchKind=strict=>strict?'外部模型或执行策略批次':'批次';
464
+ // Name only exits whose entry conditions accept this member. Recoverable pendingActions
465
+ // (develop_redo, abandon_*, an available reconcile_review) never reach here
466
+ // (parallelRecoveryRequired); original-call reconciliation that is not available now
467
+ // cannot become available later, so it is not offered. Supersede is offered only when
468
+ // memberSupersedeAdmitted says the supersede check and the external run guard pass.
469
+ function parallelMemberUnresolved(key,status,raw,history){
470
+ const strict=Boolean(config.externalModels||config.executionPolicy),runId=plans.get(key).identity.runId;
471
+ const supersedable=memberSupersedeAdmitted(config.specsDir,runId,history);
472
+ const original=status.reviewReconciliation?`(原调用 invocationId ${status.reviewReconciliation.invocationId}${status.reviewReconciliation.providerThreadId?`、providerThreadId ${status.reviewReconciliation.providerThreadId}`:''})`:'';
473
+ const why=!history?.state?'原运行存档无法读取'
474
+ :history.pending?`原运行仍有在途 ${history.pending.kind} effect`
475
+ :!['blocked','cancelled','unknown','fixture_completed'].includes(history.state.state)?`supersede 不接受原始状态 ${raw}`
476
+ :`外部运行守卫会拒绝在这个代码根上新建运行(原严格运行仍为 ${raw} 或有未对账的调用),原调用对账也不可用`;
477
+ const exit=`只读核对 ${key} 原运行的记录、进程与 worktree(${location(key).worktree});`
478
+ +(supersedable?`确认旧宿主与该成员的会话或子进程已停止写入后,取消本批次,还原该任务已改动的代码,用单任务宿主 cm-ai-host.mjs(不加 --external-models、--execution-optimizations)以该 worktree 为代码根、--supersede-reviewed-evidence --supersede-reason 原因 新建运行重做该任务`
479
+ :`批次与单任务宿主目前都没有能处理它的操作:${why}${original}。保留批次、原运行和 worktree,不要取消批次或手改存档,把 rawState 与本 reason 交给维护者处理`);
480
+ return Object.freeze({outcome:'blocked',state:'blocked',code:'batch_parallel_member_unresolved',batchId:config.batchId,
481
+ currentTask:key,identity:status.identity,memberState:status.state,memberCode:status.code??null,pendingAction:status.pendingAction??null,
482
+ rawState:raw,
483
+ reason:`${batchKind(strict)}的并行成员 ${key} 停在 ${status.state}/${status.code??status.state}(原始存档状态 ${raw}),结果尚未确认、写入方未证明已停或审查尚未终结,不改排串行(改排会换 runId、从 attempt 1 重派,绕过原调用对账与写入方停止证明)。出口:${exit}。`,
484
+ guidance:stopGuidance('并行成员结果未确认,批次不会自动改排或重派。',`${exit}。`,
485
+ ['不新建第二代运行,不删除该成员 worktree','先确认旧宿主与该成员的会话或子进程已停止写入'])});
486
+ }
487
+ function parallelMemberRescheduled(keys){
488
+ const list=keys.join('、');
489
+ return Object.freeze({outcome:'blocked',state:'blocked',code:'batch_member_rescheduled',batchId:config.batchId,
490
+ currentTask:keys[0],rescheduled:Object.freeze([...keys]),
491
+ reason:`并行成员 ${list} 已在 blocked/failed 终态存档,已改排为串行第二代(新运行、从 attempt 1 开始,WIP 留在原分支)。本次 advance 到此为止,不在同一次里开发第二代;下一次 advance 先预检第二代的开发答案再开发。`,
492
+ guidance:stopGuidance('并行成员已改排为串行第二代,等待下一次 advance。',
493
+ `按 WIP 分支与 reason 准备 ${list} 第二代的开发答案(answers/<feature>/<task>/develop.json,从第 1 轮开始),再从批次入口 advance。`,
494
+ ['第二代是新运行,旧运行记录与 WIP 分支保留','开发与审查仍需原合同授权'])});
495
+ }
496
+ function parallelRecoveryRequired(key,status){
497
+ const action=status.pendingAction,grant=BATCH_MEMBER_ACTIONS[action];
498
+ const exit=action==='reconcile_review'
499
+ ?`从批次入口发送 reconcile_review(taskKey ${key}、原调用 invocationId)对账原调用回执`
500
+ :`关闭批次宿主,带 ${grant.flag} ${key} 用同一批次配置重新启动,发送批次操作 ${action}(taskKey ${key}、单行 reason)`;
501
+ return Object.freeze({outcome:'blocked',state:'blocked',code:'batch_parallel_member_recovery_required',batchId:config.batchId,
502
+ currentTask:key,identity:status.identity,memberState:status.state,memberCode:status.code??null,pendingAction:action,
503
+ reason:`${batchKind(Boolean(config.externalModels||config.executionPolicy))}的并行成员 ${key} 停在 ${status.state}/${status.code??status.state},可在它自己的运行里恢复,所以不改排串行(改排会丢掉原调用回执或中断记录)。出口:${exit};之后 advance 继续本批次。`,
504
+ guidance:Object.freeze({summary:'并行成员停在可在原运行内恢复的状态,批次不会自动改排。',nextStep:`${exit};之后 advance 继续本批次。`,
505
+ recoveryOperation:action,prerequisites:Object.freeze(['先确认旧宿主与该成员的会话或子进程已停止写入','恢复只转给该成员运行,不跨成员']),authorizationGranted:false})});
506
+ }
507
+ // Q24: forward one recovery operation to the member the batch is stopped on.
508
+ function bindWorktree(taskKey){
509
+ const {worktree,branch}=location(taskKey);
510
+ need(fs.existsSync(worktree),'batch_member_action_unavailable');
511
+ need(batchGit(worktree,['branch','--show-current'])===branch,'batch_worktree_mismatch');
512
+ const definition=plans.get(taskKey);
513
+ plans.set(taskKey,validateRunDefinition({...definition,codeProject:worktree,
514
+ ...(definition.codeProjects?{codeProjects:definition.codeProjects.map(root=>path.join(worktree,path.relative(config.codeProject,root)))}:{})}));
515
+ }
516
+ async function memberAction(request,state){
517
+ const {option,flag}=BATCH_MEMBER_ACTIONS[request.operation],taskKey=request.taskKey;
518
+ const refuse=(code,reason)=>Object.freeze({outcome:'rejected',code,batchId:config.batchId,taskKey,operation:request.operation,reason});
519
+ if(!plans.has(taskKey))return refuse('batch_member_action_unavailable',`taskKey ${taskKey} 不是本批次的任务`);
520
+ const stopped=membership.has(state.current)
521
+ ?membership.get(state.current).filter(key=>membership.has(key)&&!state.ready?.has(key)&&!state.done?.has(key)):[state.current];
522
+ if(!stopped.includes(taskKey))return refuse('batch_member_action_not_current',
523
+ `批次当前停在 ${stopped.join('、')};恢复操作只转给当前停住的成员,不跨成员`);
524
+ if(!actionGrants.get(request.operation).has(taskKey))return refuse('batch_member_action_authorization_required',
525
+ `${request.operation} 需要批次宿主启动参数 ${flag} ${taskKey};关闭批次宿主,带上该参数用同一批次配置重新启动后再发送`);
526
+ if(membership.has(taskKey))bindWorktree(taskKey);
527
+ const definition=plans.get(taskKey);
528
+ if(!fs.existsSync(path.join(config.specsDir,'.reviews','.execution',definition.identity.runId,'state.json')))
529
+ return refuse('batch_member_action_unavailable',`${taskKey} 还没有运行存档,没有可恢复的步骤`);
530
+ const run=await open(taskKey,{[option]:true});
531
+ if(run.blocked)return {outcome:'blocked',code:run.blocked.reason,batchId:config.batchId};
532
+ try{
533
+ const result=await run.host.handle({version:1,operation:request.operation,requestId:request.requestId,
534
+ identity:definition.identity,reason:request.reason});
535
+ actionGrants.get(request.operation).delete(taskKey);
536
+ return {...result,batchId:config.batchId,taskKey};
537
+ }finally{run.close();}
538
+ }
368
539
  return Object.freeze({async handle(raw){
369
- const request=json(raw);shape(request,['operation','requestId',...(request.operation==='reconcile_review'?['taskKey','invocationId']:[])]);id(request.requestId);
370
- need(['advance','status','cancel','reconcile_review'].includes(request.operation));
540
+ const request=json(raw);shape(request,['operation','requestId',...(request.operation==='reconcile_review'?['taskKey','invocationId']:[]),
541
+ ...(Object.hasOwn(BATCH_MEMBER_ACTIONS,request.operation??'')?['taskKey','reason']:[])]);id(request.requestId);
542
+ need(['advance','status','cancel','reconcile_review',...Object.keys(BATCH_MEMBER_ACTIONS)].includes(request.operation));
371
543
  if(request.operation==='cancel'&&busy){
372
544
  cancelled=true;
373
545
  if(members.size){record('batch_cancel',{from_key:liveKey});
@@ -392,12 +564,7 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
392
564
  if(request.operation==='reconcile_review'){
393
565
  need((config.externalModels||config.executionPolicy)&&plans.has(request.taskKey),'review_reconciliation_unavailable');id(request.invocationId);
394
566
  if(membership.has(request.taskKey)){
395
- const {worktree,branch}=location(request.taskKey);
396
- need(fs.existsSync(worktree),'review_reconciliation_unavailable');
397
- need(batchGit(worktree,['branch','--show-current'])===branch,'batch_worktree_mismatch');
398
- const definition=plans.get(request.taskKey);
399
- plans.set(request.taskKey,validateRunDefinition({...definition,codeProject:worktree,
400
- ...(definition.codeProjects?{codeProjects:definition.codeProjects.map(root=>path.join(worktree,path.relative(config.codeProject,root)))}:{})}));
567
+ need(fs.existsSync(location(request.taskKey).worktree),'review_reconciliation_unavailable');bindWorktree(request.taskKey);
401
568
  }
402
569
  const definition=plans.get(request.taskKey);
403
570
  need(fs.existsSync(path.join(config.specsDir,'.reviews','.execution',definition.identity.runId,'state.json')),'review_reconciliation_unavailable');
@@ -406,6 +573,7 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
406
573
  finally{run.close();}
407
574
  }
408
575
  if(initial.stopped)return {outcome:'blocked',code:initial.code??'cancelled',batchId:config.batchId};
576
+ if(Object.hasOwn(BATCH_MEMBER_ACTIONS,request.operation))return await memberAction(request,initial);
409
577
  if(request.operation==='advance'&&!initial.rows.length){
410
578
  const dirty=batchGit(config.codeProject,['status','--porcelain']);
411
579
  if(dirty)return {outcome:'blocked',code:'batch_main_dirty',batchId:config.batchId,
@@ -426,7 +594,7 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
426
594
  const binding={specsDir:config.specsDir,feature:definition.feature,identity:status.identity,packageDigest:status.packageDigest};
427
595
  const qa=findCmAiQaDecision(binding);
428
596
  need(qa?.status==='skipped'||(qa?.status==='triggered'&&latestCmAiQaRun(binding)?.status==='passed'),'batch_qa_not_ready');
429
- need(inspectRunClosure(log,definition.identity.runId).closed,'batch_resources_open');
597
+ requireClosed(definition.identity.runId);
430
598
  }
431
599
  finally{previous.close();}
432
600
  }
@@ -447,8 +615,7 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
447
615
  const result=await active.host.handle({version:1,operation:request.operation,requestId:request.requestId,
448
616
  identity:plans.get(liveKey).identity});
449
617
  if(cancelled)return {outcome:'cancelled',code:'cancelled',batchId:config.batchId};
450
- if(result.state==='run_done'||result.pendingAction==='start_next_task')
451
- need(inspectRunClosure(log,plans.get(liveKey).identity.runId).closed,'batch_resources_open');
618
+ if(result.state==='run_done'||result.pendingAction==='start_next_task')requireClosed(plans.get(liveKey).identity.runId);
452
619
  const finished=result.state==='run_done'&&['run_done','run_done_degraded'].includes(result.code);
453
620
  const handoff=result.outcome==='refreshed'&&result.pendingAction==='start_next_task';
454
621
  if(request.operation!=='advance'||(!finished&&!handoff))return {...result,batchId:config.batchId};