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