@aibyzero/cm-workflow 0.16.8 → 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 (157) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +19 -0
  3. package/README.md +14 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/installation.md +1 -1
  7. package/docs/js-workflow-control.md +25 -1
  8. package/docs/next-steps.md +8 -2
  9. package/docs/user-guide.md +105 -5
  10. package/package.json +2 -1
  11. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  12. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -20
  13. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +69 -22
  14. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  15. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  16. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  17. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  18. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  19. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  20. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  21. package/runtime/js/cm-ai/host-check.mjs +4 -1
  22. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  23. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  24. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  25. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  26. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  27. package/runtime/js/cm-ai/host-session.mjs +1 -1
  28. package/runtime/js/cm-ai/host-tool-bridge.mjs +40 -3
  29. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  30. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  31. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  32. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  33. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  34. package/runtime/js/cm-ai/review-package.mjs +10 -1
  35. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  36. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  37. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  38. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  39. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  40. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  41. package/runtime/js/cm-fix/execution.mjs +176 -48
  42. package/runtime/js/cm-fix/host.mjs +2 -1
  43. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  44. package/runtime/js/cm-fix/progress.mjs +13 -3
  45. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  46. package/runtime/js/cm-fix/repair.mjs +11 -3
  47. package/runtime/js/cm-fix/test-author.mjs +10 -3
  48. package/runtime/js/cm-idea/session.mjs +67 -4
  49. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  50. package/runtime/js/cm-prd/session.mjs +43 -0
  51. package/runtime/js/cm-refactor/records.mjs +98 -8
  52. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  53. package/runtime/js/cm-test/host.mjs +10 -3
  54. package/runtime/js/cm-test/session.mjs +45 -6
  55. package/runtime/js/notify-safe-read.mjs +49 -0
  56. package/runtime/js/notify-send.mjs +312 -0
  57. package/runtime/js/notify.mjs +137 -33
  58. package/runtime/js/policy-binding-compat.mjs +54 -0
  59. package/scripts/ci-test-shards.mjs +67 -0
  60. package/scripts/ci-test-shards.test.mjs +64 -0
  61. package/scripts/ci-test-weights.json +222 -0
  62. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  63. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  64. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  65. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  66. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  67. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  68. package/scripts/cm-ai-batch-drive.mjs +55 -10
  69. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  70. package/scripts/cm-ai-batch-host.mjs +132 -13
  71. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  72. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  73. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  74. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  75. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  76. package/scripts/cm-ai-batch-run.mjs +184 -22
  77. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  78. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  79. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  80. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  81. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  82. package/scripts/cm-ai-drive.mjs +64 -22
  83. package/scripts/cm-ai-drive.test.mjs +29 -2
  84. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  85. package/scripts/cm-ai-host-fixture.mjs +268 -0
  86. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  87. package/scripts/cm-ai-host.mjs +27 -15
  88. package/scripts/cm-ai-host.test.mjs +17 -759
  89. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  90. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  91. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  92. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  93. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  94. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +56 -10
  95. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  96. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  97. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  98. package/scripts/cm-ai-run.mjs +15 -6
  99. package/scripts/cm-ai-supersede.test.mjs +486 -41
  100. package/scripts/cm-check-drive-files.mjs +8 -0
  101. package/scripts/cm-check-drive.test.mjs +2 -5
  102. package/scripts/cm-check-runtime.sh +4 -2
  103. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  104. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  105. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  106. package/scripts/cm-claude-worker.test.mjs +18 -2
  107. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  108. package/scripts/cm-fix-abandon.test.mjs +163 -10
  109. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  110. package/scripts/cm-fix-drive.mjs +25 -7
  111. package/scripts/cm-fix-host.mjs +8 -7
  112. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  113. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  114. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  115. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  116. package/scripts/cm-host-documentation.test.mjs +49 -0
  117. package/scripts/cm-host-qa-executor.test.mjs +22 -10
  118. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  119. package/scripts/cm-idea-drive.mjs +49 -11
  120. package/scripts/cm-idea-drive.test.mjs +66 -0
  121. package/scripts/cm-idea-host.mjs +106 -16
  122. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  123. package/scripts/cm-init-drive.mjs +41 -7
  124. package/scripts/cm-init-host.mjs +61 -12
  125. package/scripts/cm-log-event.mjs +21 -10
  126. package/scripts/cm-notify-command.test.mjs +900 -0
  127. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  128. package/scripts/cm-notify.mjs +469 -0
  129. package/scripts/cm-notify.test.mjs +221 -4
  130. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  131. package/scripts/cm-prd-drive.mjs +18 -5
  132. package/scripts/cm-prd-drive.test.mjs +15 -0
  133. package/scripts/cm-prd-host.mjs +37 -4
  134. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  135. package/scripts/cm-prd-review-gate.mjs +56 -0
  136. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  137. package/scripts/cm-refactor-drive.mjs +52 -8
  138. package/scripts/cm-refactor-drive.test.mjs +44 -0
  139. package/scripts/cm-refactor-host.test.mjs +10 -6
  140. package/scripts/cm-release-smoke.sh +2 -0
  141. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  142. package/scripts/cm-test-drive.mjs +21 -5
  143. package/scripts/fixtures/claude-review-process.mjs +1 -1
  144. package/scripts/policy-binding-compat.test.mjs +99 -0
  145. package/scripts/scan-public-safety.py +4 -0
  146. package/scripts/validate-public-repo.py +4 -0
  147. package/skills/cm-ai/references/js-host-qa-recovery.md +27 -1
  148. package/skills/cm-ai/references/js-host-recovery.md +120 -8
  149. package/skills/cm-ai/references/js-host.md +14 -7
  150. package/skills/cm-check/SKILL.md +3 -3
  151. package/skills/cm-fix/references/js-host.md +44 -5
  152. package/skills/cm-idea/references/js-host.md +27 -2
  153. package/skills/cm-init/references/js-host.md +16 -3
  154. package/skills/cm-notify/SKILL.md +34 -0
  155. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  156. package/skills/cm-refactor/references/js-host.md +17 -0
  157. package/skills/cm-test/references/js-host.md +14 -1
@@ -5,32 +5,134 @@ import {readBatchExternalModels,freezeBatchExternalModels,batchModelsFile} from
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import {fileURLToPath} from 'node:url';
8
- import {createCmAiBatch,batchTaskRunId} from './cm-ai-batch-run.mjs';
8
+ import {createCmAiBatch,batchTaskRunId,BATCH_MEMBER_ACTIONS} from './cm-ai-batch-run.mjs';
9
+ import {validEnvironmentFailureReason} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
9
10
  import {assertCreatableScope} from './cm-ai-run.mjs';
10
- import {createConversationExecution,readConversationReviewConfiguration,readConversationProtection,runReviewPreflight} from './cm-ai-host.mjs';
11
+ import {createConversationExecution,readConversationReviewConfiguration,readConversationReviewConfigurationValue,readConversationProtection,runReviewPreflight} from './cm-ai-host.mjs';
11
12
  import {loadConfig,resolveProtectedRuntimes} from './cm-workflow-config.mjs';
12
13
  import {preflightMatches} from '../runtime/js/cm-ai/worker-codex.mjs';
13
14
  import {claudePreflightMatches} from '../runtime/js/cm-ai/worker-claude.mjs';
14
- import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
15
+ import {createHostToolBridge,HOST_ANSWER_BACKSTOP_MS} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
15
16
  import {serveCmAiHost,parseHostInputLimit,inputLimitReason} from '../runtime/js/cm-ai/host-session.mjs';
16
17
  import {validateHostWorkflowConfiguration,featureHasBrowserCases,readBrowserCapability} from '../runtime/js/cm-ai/host-workflow-capabilities.mjs';
17
18
  import {digest,json,need,shape} from '../runtime/js/cm-ai/effect-contract.mjs';
18
19
  import {identifyApprovedBootstrapFeature} from '../runtime/js/cm-ai/bootstrap-feature.mjs';
19
20
 
20
- const usage='cm-ai-batch-host.mjs serve --config PATH --host-context ID --allow-development --review-config PATH (required for a new batch; later launches pass the same file) [--execution-optimizations] [--external-models [--external-models-config PATH]] [--runtime codex|claude] [--input-limit BYTES] [--allow-review FEATURE/TASK:1|2]... [--allow-qa] [--rerun-unknown-qa | --rerun-blocked-qa] [--verification-precheck] [--browser-qa available|unavailable] [--protected-conversation-config PATH | --protected-config PATH] [--allow-provider-development FEATURE/TASK:1|2]... [--hold-revision FEATURE/TASK]...';
21
+ const usage='cm-ai-batch-host.mjs serve --config PATH --host-context ID --allow-development --review-config PATH (required for a new batch; later launches pass the same file) [--execution-optimizations] [--external-models [--external-models-config PATH]] [--runtime codex|claude] [--input-limit BYTES] [--allow-review FEATURE/TASK:1|2]... [--allow-qa] [--rerun-unknown-qa | --rerun-blocked-qa [--qa-environment-failure REASON]] [--allow-develop-redo FEATURE/TASK]... [--allow-abandon-effect FEATURE/TASK]... [--allow-abandon-review FEATURE/TASK]... [--allow-bootstrap-review-recovery FEATURE/TASK]... [--verification-precheck] [--browser-qa available|unavailable] [--protected-conversation-config PATH | --protected-config PATH] [--allow-provider-development FEATURE/TASK:1|2]... [--hold-revision FEATURE/TASK]...';
21
22
  const safeCode=error=>typeof error?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(error.code)?error.code:'batch_host_failed';
23
+ // Operator-facing reasons the batch owner writes itself (R4); others stay redacted.
24
+ const REASONED=new Set(['batch_resources_open','legacy_preflight_cache_invalid']);
25
+ const boundedReason=error=>REASONED.has(error?.code)&&typeof error.reason==='string'&&error.reason.length<=8192&&!/[\r\n\0]/.test(error.reason)?error.reason:null;
26
+ const actionFlags=new Map(Object.entries(BATCH_MEMBER_ACTIONS).map(([name,{flag}])=>[flag,name]));
27
+ // Single-task recovery inputs a batch cannot take: each member's fingerprint binds
28
+ // the whole batch workflow map, and a member cannot be rebound alone.
29
+ const UNSUPPORTED={'--revise-qa-config':'batch_qa_revision_unavailable','--qa-config-revision-reason':'batch_qa_revision_unavailable',
30
+ '--rebind-spec-material':'batch_spec_rebind_unavailable','--spec-rebind-reason':'batch_spec_rebind_unavailable'};
31
+ const UNSUPPORTED_REASON={batch_qa_revision_unavailable:'批次不能修订单个成员的 QA 配置:每个成员的运行指纹绑定整批 workflows,改一个成员会让其他成员都无法恢复,单任务宿主也打不开批次成员运行。出口:QA 环境问题用 --rerun-blocked-qa(必要时加 --qa-environment-failure 原因);确需改 QA 命令,取消本批次后用单任务宿主 cm-ai-host.mjs 以 --supersede-reviewed-evidence --supersede-reason 原因 新建运行重做该任务',
32
+ batch_spec_rebind_unavailable:'批次成员不能换绑规格。出口:还原这些规格改动并重新批准后继续本批次;或取消本批次,还原该任务已改动的代码后,用单任务宿主 cm-ai-host.mjs 以 --supersede-reviewed-evidence --supersede-reason 原因 新建运行重做该任务'};
22
33
 
23
34
  export async function serveHostTransport(options,rawInputLimit,serve=serveCmAiHost){
24
35
  return serve({...options,inputLimit:parseHostInputLimit(rawInputLimit)});
25
36
  }
26
37
 
27
- async function memberReviewConfiguration(batch,definition,review,runtime,pair=null,allowPreflight=true){
38
+ // Before 53c385e an execution-policy batch (without external models) cached its member
39
+ // loopback preflights in .reviews/.execution/<batchId>/preflight-<task>.json. The
40
+ // external run guard refuses that non-run directory, so such a batch could never open
41
+ // a member again. A directory that is exactly that old cache (only 0600 single-link
42
+ // preflight files of this batch's parallel members, each still bound to the launch
43
+ // review model, disabled skills and the member worktree cwd) moves file by file to
44
+ // the current location; an identical file already there drops the old copy. Anything
45
+ // else is refused with the directory named and nothing moved, so it is checked by hand.
46
+ export function migrateLegacyPreflightCache(batch,review,runtime){
47
+ const legacy=path.join(batch.specsDir,'.reviews','.execution',batch.batchId);
48
+ let stat;try{stat=fs.lstatSync(legacy);}catch(error){if(error.code==='ENOENT')return {moved:[],dropped:[]};throw error;}
49
+ const refuse=detail=>{throw Object.assign(new Error('legacy_preflight_cache_invalid'),{code:'legacy_preflight_cache_invalid',
50
+ reason:`运行目录下的 ${legacy} 不是可识别的旧版并行成员预检缓存(${detail})。外部运行守卫会把它当作无法核实的运行,批次成员打不开;宿主没有移动或删除其中任何文件。`
51
+ +`下一步:只读核对该目录;确认只是旧版 preflight 缓存且没有进程在写后,把它移出 .reviews/.execution(例如移到 .reviews/external-preflight-legacy/),再用同一批次配置重新启动批次宿主并 advance,成员会重新做一次本地 loopback 预检`});};
52
+ if(!stat.isDirectory()||stat.isSymbolicLink()||(stat.mode&0o077)!==0||fs.realpathSync(legacy)!==legacy)refuse('不是权限 0700 的普通目录');
53
+ if(review===null)refuse('本次启动没有 --review-config,无法核对缓存绑定的审查模型');
54
+ const members=new Map((batch.parallel??[]).flat().map(key=>[`preflight-${key.slice(key.lastIndexOf('/')+1)}.json`,key.slice(key.lastIndexOf('/')+1)]));
55
+ // The target and its parent are checked before anything is moved or deleted,
56
+ // whether or not a file will be moved; a missing one is created 0700 (one level at
57
+ // a time) and checked again only right before the first move.
58
+ const parent=path.join(batch.specsDir,'.reviews','external-preflight'),target=path.join(parent,batch.batchId);
59
+ const targetDirectories=create=>{
60
+ for(const directory of [parent,target]){
61
+ if(create)try{fs.mkdirSync(directory,{mode:0o700});}catch(error){if(error.code!=='EEXIST')throw error;}
62
+ let info;try{info=fs.lstatSync(directory);}catch(error){if(error.code==='ENOENT'&&!create)return;throw error;}
63
+ if(!info.isDirectory()||info.isSymbolicLink()||(info.mode&0o077)!==0||fs.realpathSync(directory)!==directory)
64
+ refuse(`新位置 ${directory} 不是权限 0700 的普通目录`);
65
+ }
66
+ };
67
+ targetDirectories(false);
68
+ // One read per file through a no-follow fd bound to the path's dev+ino; only these
69
+ // exact bytes are validated and compared. links: 2 only for an interrupted move,
70
+ // where the old and new names are the same inode.
71
+ const pinned=(file,links=1)=>{
72
+ let before;try{before=fs.lstatSync(file);}catch(error){if(error.code==='ENOENT')return null;throw error;}
73
+ if(!before.isFile()||before.isSymbolicLink()||before.nlink!==links||(before.mode&0o077)!==0||before.size>64*1024)
74
+ refuse(`${file} 不是权限 0600、${links} 个链接的普通文件`);
75
+ let fd;try{fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);}catch{refuse(`${file} 无法按不跟随链接的方式打开`);}
76
+ try{
77
+ const info=fs.fstatSync(fd);
78
+ if(info.dev!==before.dev||info.ino!==before.ino||!info.isFile()||info.nlink!==links)refuse(`${file} 在核对时被替换`);
79
+ return {bytes:fs.readFileSync(fd),dev:info.dev,ino:info.ino};
80
+ }finally{fs.closeSync(fd);}
81
+ };
82
+ const same=(left,right)=>left!==null&&right!==null&&left.dev===right.dev&&left.ino===right.ino&&left.bytes.equals(right.bytes);
83
+ const plan=[];
84
+ for(const entry of fs.readdirSync(legacy,{withFileTypes:true})){
85
+ const taskId=members.get(entry.name);if(!taskId)refuse(`含有不属于本批次并行成员预检缓存的条目 ${entry.name}`);
86
+ const file=path.join(legacy,entry.name),destination=path.join(target,entry.name);
87
+ let interrupted=false;
88
+ try{const a=fs.lstatSync(file),b=fs.lstatSync(destination);interrupted=a.dev===b.dev&&a.ino===b.ino;}catch(error){if(error.code!=='ENOENT')throw error;}
89
+ const source=pinned(file,interrupted?2:1);
90
+ if(source===null)refuse(`${entry.name} 在核对时消失`);
91
+ const cwd=path.resolve(batch.codeProject,'..','.cm-worktrees',batch.batchId.slice(0,8),taskId);
92
+ const options={cwd,model:review.model,disabledSkills:review.disabledSkills,promptTransport:'stdin'};
93
+ let cached;try{cached=readConversationReviewConfigurationValue(JSON.parse(source.bytes.toString('utf8')),null);}
94
+ catch{refuse(`${entry.name} 不是预检缓存格式`);}
95
+ if(Object.hasOwn(cached,'timeoutMs')||cached.model!==review.model||digest(cached.disabledSkills)!==digest(review.disabledSkills)
96
+ ||!(runtime==='claude'?claudePreflightMatches:preflightMatches)(cached.preflight,options))
97
+ refuse(`${entry.name} 绑定的审查模型、禁用技能或成员 worktree 指纹与本次启动不一致`);
98
+ if(interrupted){plan.push({file,destination,source,action:'finish'});continue;}
99
+ const existing=pinned(destination);
100
+ if(existing!==null&&!existing.bytes.equals(source.bytes))refuse(`新位置 ${destination} 已有不同内容`);
101
+ plan.push({file,destination,source,existing,action:existing===null?'move':'drop'});
102
+ }
103
+ // Commit without overwriting: link (fails on an existing name), re-read the linked
104
+ // inode, then remove the old name. A duplicate is removed only after both sides are
105
+ // re-read unchanged. A stop at any point leaves either the old file, or the same inode
106
+ // under both names, which the next launch finishes ('finish').
107
+ const moved=[],dropped=[];
108
+ if(plan.some(item=>item.action==='move'))targetDirectories(true);
109
+ for(const item of plan){
110
+ const name=path.basename(item.file);
111
+ if(item.action==='move'){
112
+ try{fs.linkSync(item.file,item.destination);}
113
+ catch(error){if(error.code==='EEXIST')refuse(`新位置 ${item.destination} 在迁移时出现`);throw error;}
114
+ const linked=pinned(item.destination,2);
115
+ if(!same(linked,item.source)){fs.unlinkSync(item.destination);refuse(`${name} 在迁移时被改动`);}
116
+ }else if(item.action==='drop'){
117
+ if(!same(pinned(item.file),item.source)||!same(pinned(item.destination),item.existing))refuse(`${name} 或新位置的副本在迁移时被改动`);
118
+ }else if(!same(pinned(item.destination,2),item.source))refuse(`${name} 在迁移时被改动`);
119
+ fs.unlinkSync(item.file);
120
+ (item.action==='drop'?dropped:moved).push(name);
121
+ }
122
+ try{fs.rmdirSync(legacy);}catch(error){if(['ENOTEMPTY','EEXIST'].includes(error.code))refuse('迁移时目录里出现了新条目');throw error;}
123
+ return {moved,dropped};
124
+ }
125
+ // strict: an execution-policy batch. Its member runs take the external run guard,
126
+ // which refuses any non-run directory under .reviews/.execution, so the loopback
127
+ // cache lives beside the external-model one instead.
128
+ async function memberReviewConfiguration(batch,definition,review,runtime,pair=null,allowPreflight=true,strict=false){
129
+ if(strict&&!pair)migrateLegacyPreflightCache(batch,review,runtime);
28
130
  try{
29
131
  need(review!==null,'review_configuration_required');
30
132
  const options={cwd:definition.codeProject,model:review.model,...(pair?{effort:pair.effort}:{}),disabledSkills:review.disabledSkills,promptTransport:'stdin'};
31
133
  const matches=config=>config.model===review.model&&digest(config.disabledSkills)===digest(review.disabledSkills)
32
134
  &&(runtime==='claude'?claudePreflightMatches:preflightMatches)(config.preflight,options);
33
- const directory=path.join(batch.specsDir,'.reviews',...(pair?['external-preflight']:['.execution']),batch.batchId);
135
+ const directory=path.join(batch.specsDir,'.reviews',...(pair||strict?['external-preflight']:['.execution']),batch.batchId);
34
136
  fs.mkdirSync(directory,{recursive:true,mode:0o700});
35
137
  need(fs.realpathSync(directory)===directory,'invalid_preflight_cache');
36
138
  const file=path.join(directory,`preflight-${definition.identity.taskId}.json`);
@@ -54,7 +156,8 @@ async function memberReviewConfiguration(batch,definition,review,runtime,pair=nu
54
156
 
55
157
  export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
56
158
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Optional --execution-optimizations freezes policy v1 for new runs only; recovery retains the original policy and legacy runs reject retrofit. See docs/execution-optimizations.md.\n');
57
- if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\nOptional --input-limit BYTES sets the host input transport limit to an integer from 65536 to 4194304 (default 65536); it may change on resume.\nOptional --protected-conversation-config PATH uses the shared current-host scoped text proposals and native sandbox checks; {checkCommands,timeoutMs}. No extra model call, same Codex/Claude runtime and per-task Review permissions. Optional --protected-config PATH {model,checkCommands,timeoutMs} enables CLI development only for per-task --allow-provider-development FEATURE/TASK:1|2 grants; mutually exclusive with --protected-conversation-config. Optional bundle.bootstraps maps approved bootstrap task keys to {selection}; --allow-bootstrap-write grants only those fixed instruction/scaffold steps. Optional batch.codeProjects uses prefixed paths and checks with codeProject per command; one task remains one completion gate.\n--review-config PATH is required when no member run of the batch exists yet (like single-task create): it is bound into every member fingerprint and cannot be added on resume. It is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 900000). It is independent of --protected-conversation-config/--protected-config and wins over their timeoutMs for the reviewer. It is not part of the authorized configuration digest, so a resumed run may raise it after review_transport_timeout.\n--browser-qa available|unavailable declares interactive QA capability for applicable feature carriers including browser and ios-simulator; the flag name is retained for compatibility.\nOptional --rerun-unknown-qa / --rerun-blocked-qa carry the same single-task QA recovery into a batch and require --allow-qa; they are mutually exclusive. A batch has no --mode, so each task applies the flag only when it resumes an existing run and has a QA executor; a created run or a task without QA ignores it rather than failing the whole batch. Semantics, limits and the qaRound cap are the single-task ones, unchanged.\nOptional --verification-precheck sends the written verification of the task and the collected checks back as a verification_precheck request before any handoff or review package is built. It may only block: a requirement reported unsatisfied stops the task at blocked / verification_precheck_failed with pendingAction resume and spends no review round. Passing it is not an approval, writes no receipt and does not replace the independent review. A task with no written verification is unaffected.\nOptional --hold-revision FEATURE/TASK (repeatable, launch-only, never persisted) stops that task after a changes_requested review with code revision_answer_required, before any second-round develop intent; the next launch without it resumes the revision. It only narrows what this launch does.\nBatch entry requires a clean Git main checkout (including untracked files); batch_main_dirty lists dirty files before any task or worktree starts. Serial tasks are committed automatically before batch_handoff, with task_commit recording the SHA (null if unchanged). Terminal parallel members preserve WIP on their retained branches and fall back once to serial generation 2 after ready members merge.\n');return 0;}
159
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('成员恢复(Q24):--allow-develop-redo / --allow-abandon-effect / --allow-abandon-review / --allow-bootstrap-review-recovery FEATURE/TASK 各授权一次同名批次操作 {operation, requestId, taskKey, reason},只转给批次当前停住的那个成员运行(同一 cm-ai 入口、只带这一项权限,不跨成员),之后 advance 继续本批次;缺授权返回 batch_member_action_authorization_required,非当前成员返回 batch_member_action_not_current。批次 cancel 后永久停止不变。--qa-environment-failure REASON 随 --rerun-blocked-qa / --rerun-unknown-qa 使用。--revise-qa-config 与 --rebind-spec-material 不支持(batch_qa_revision_unavailable / batch_spec_rebind_unavailable,原因里写明出口)。并行成员停在可在原运行内恢复的状态时返回 batch_parallel_member_recovery_required;结果未确认时返回 batch_parallel_member_unresolved 并留在原运行;只有原始存档为已 checkpoint 的 blocked 才改排串行第二代,且先停在 batch_member_rescheduled,下一次 advance 才开发第二代(普通批次与外部模型、执行策略批次相同)。\n');
160
+ if(argv.length===1&&['--help','-h'].includes(argv[0])){output.write(usage+'\nOptional --input-limit BYTES sets the host input transport limit to an integer from 65536 to 4194304 (default 65536); it may change on resume.\nOptional --protected-conversation-config PATH uses the shared current-host scoped text proposals and native sandbox checks; {checkCommands,timeoutMs}. No extra model call, same Codex/Claude runtime and per-task Review permissions. Optional --protected-config PATH {model,checkCommands,timeoutMs} enables CLI development only for per-task --allow-provider-development FEATURE/TASK:1|2 grants; mutually exclusive with --protected-conversation-config. Optional bundle.bootstraps maps approved bootstrap task keys to {selection}; --allow-bootstrap-write grants only those fixed instruction/scaffold steps. Optional batch.codeProjects uses prefixed paths and checks with codeProject per command; one task remains one completion gate.\n--review-config PATH is required when no member run of the batch exists yet (like single-task create): it is bound into every member fingerprint and cannot be added on resume. It is {model,preflight[,disabledSkills][,timeoutMs]}; timeoutMs is the reviewer transport budget in milliseconds (integer 1-3600000, default 900000). It is independent of --protected-conversation-config/--protected-config and wins over their timeoutMs for the reviewer. It is not part of the authorized configuration digest, so a resumed run may raise it after review_transport_timeout.\n--browser-qa available|unavailable declares interactive QA capability for applicable feature carriers including browser and ios-simulator; the flag name is retained for compatibility.\nOptional --rerun-unknown-qa / --rerun-blocked-qa carry the same single-task QA recovery into a batch and require --allow-qa; they are mutually exclusive. A batch has no --mode, so each task applies the flag only when it resumes an existing run and has a QA executor; a created run or a task without QA ignores it rather than failing the whole batch. Semantics, limits and the qaRound cap are the single-task ones, unchanged.\nOptional --verification-precheck sends the written verification of the task and the collected checks back as a verification_precheck request before any handoff or review package is built. It may only block: a requirement reported unsatisfied stops the task at blocked / verification_precheck_failed with pendingAction resume and spends no review round. Passing it is not an approval, writes no receipt and does not replace the independent review. A task with no written verification is unaffected.\nOptional --hold-revision FEATURE/TASK (repeatable, launch-only, never persisted) stops that task after a changes_requested review with code revision_answer_required, before any second-round develop intent; the next launch without it resumes the revision. It only narrows what this launch does.\nBatch entry requires a clean Git main checkout (including untracked files); batch_main_dirty lists dirty files before any task or worktree starts. Serial tasks are committed automatically before batch_handoff, with task_commit recording the SHA (null if unchanged). A parallel member whose raw journal is a checkpointed blocked terminal preserves WIP on its retained branch and falls back once to serial generation 2 after ready members merge; that advance stops at batch_member_rescheduled and the next one develops generation 2. Unconfirmed members stay in their original run.\n');return 0;}
58
161
  let bridge;
59
162
  try{
60
163
  need(argv.length>=6&&argv[0]==='serve'&&argv[1]==='--config'&&argv[3]==='--host-context'
@@ -73,7 +176,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
73
176
  need(keys.length===Object.keys(workflows).length&&keys.every(key=>Object.hasOwn(workflows,key)),'workflow_task_mismatch');
74
177
  for(const key of keys)if(workflows[key]!==null)validateHostWorkflowConfiguration(workflows[key]);
75
178
  let review=null,allowQa=false,allowBootstrap=false,runtime=null,protection=null,providerConfig=null,browserQaFlag,inputLimitRaw;
76
- let rerunUnknownQa=false,rerunBlockedQa=false,verificationPrecheck=false;const approvals=new Set(),developments=new Map(),holds=new Set();
179
+ let rerunUnknownQa=false,rerunBlockedQa=false,verificationPrecheck=false,qaEnvironmentFailure=null;const approvals=new Set(),developments=new Map(),holds=new Set();
180
+ const memberActions=Object.fromEntries(Object.keys(BATCH_MEMBER_ACTIONS).map(name=>[name,[]]));
77
181
  let externalEnabled=false,externalFile,executionPolicyEnabled=false;
78
182
  for(let index=6;index<argv.length;index++){
79
183
  const name=argv[index];
@@ -82,6 +186,19 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
82
186
  else if(name==='--rerun-unknown-qa'){need(!rerunUnknownQa,'invalid_arguments');rerunUnknownQa=true;}
83
187
  else if(name==='--rerun-blocked-qa'){need(!rerunBlockedQa,'invalid_arguments');rerunBlockedQa=true;}
84
188
  else if(name==='--verification-precheck'){need(!verificationPrecheck,'invalid_arguments');verificationPrecheck=true;}
189
+ else if(name==='--qa-environment-failure'){
190
+ need(qaEnvironmentFailure===null&&validEnvironmentFailureReason(argv[index+1]),'invalid_arguments');qaEnvironmentFailure=argv[++index];
191
+ }
192
+ else if(actionFlags.has(name)){
193
+ // A recovery grant names one member; it is consumed by that member's first forwarded operation.
194
+ const target=argv[++index],granted=memberActions[actionFlags.get(name)];
195
+ if(!(typeof target==='string'&&keys.includes(target)&&!granted.includes(target)))
196
+ throw Object.assign(new Error('invalid_arguments'),{code:'invalid_arguments',reason:`${name} 需要一个本批次的 FEATURE/TASK,且同一任务只给一次`});
197
+ granted.push(target);
198
+ }
199
+ else if(Object.hasOwn(UNSUPPORTED,name)){
200
+ const code=UNSUPPORTED[name];throw Object.assign(new Error(code),{code,reason:UNSUPPORTED_REASON[code]});
201
+ }
85
202
  else if(name==='--browser-qa'){
86
203
  need(browserQaFlag===undefined&&typeof argv[index+1]==='string','invalid_arguments');browserQaFlag=argv[++index];
87
204
  }
@@ -147,6 +264,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
147
264
  // per-task resume check lives in createCmAiBatch rather than here.
148
265
  need(!(rerunUnknownQa&&rerunBlockedQa),'qa_recovery_authorization_required');
149
266
  need(!(rerunUnknownQa||rerunBlockedQa)||allowQa,'qa_recovery_authorization_required');
267
+ need(qaEnvironmentFailure===null||rerunUnknownQa||rerunBlockedQa,'qa_recovery_authorization_required');
150
268
  need(allowQa||!Object.values(workflows).some(item=>item?.qa!=null),'qa_authorization_required');
151
269
  // Same rule as single-task create: the reviewer binding is part of every
152
270
  // member's durable fingerprint and cannot be added on resume. A batch none
@@ -158,7 +276,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
158
276
  reason:'新批次必须带 --review-config:审查配置写进每个任务运行的指纹,恢复时不能再补。先用 cm-ai-host.mjs preflight 生成 review.json;'
159
277
  +'是否真正派发审查仍由 --allow-review 单独授权'});
160
278
  // Tool replies travel on the same input lines, so they share the one limit.
161
- bridge=createHostToolBridge({responseLimit:parseHostInputLimit(inputLimitRaw)});
279
+ bridge=createHostToolBridge({responseLimit:parseHostInputLimit(inputLimitRaw),answerTimeoutMs:HOST_ANSWER_BACKSTOP_MS});
162
280
  // The current conversation transport accepts one outstanding host call.
163
281
  // Queue those calls only; member runners and independent Review stay concurrent.
164
282
  let hostCallTail=Promise.resolve();
@@ -169,13 +287,13 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
169
287
  let reconciling=false;
170
288
  const driver=createCmAiBatch({configuration:{...batch,...(externalModels?{externalModels}:{}),...(executionPolicy?{executionPolicy}:{})},logHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
171
289
  runtime:runtime??'codex',checkCommands:(providerConfig??protection)?.checkCommands??null,checkTimeoutMs:(providerConfig??protection)?.timeoutMs??60000,
172
- rerunUnknownQa,rerunBlockedQa,holdRevisions:[...holds],bootstrapKeys:Object.keys(bootstraps??{}),
290
+ rerunUnknownQa,rerunBlockedQa,qaEnvironmentFailure,memberActions,holdRevisions:[...holds],bootstrapKeys:Object.keys(bootstraps??{}),
173
291
  executionFor:async(definition,{parallelMember=false}={})=>{
174
292
  await freezeBatchExecutionPolicy(batch,executionPolicy);
175
293
  freezeBatchExternalModels(batch,externalModels);
176
294
  const key=`${definition.feature}/${definition.identity.taskId}`;
177
295
  const attempts=[1,2].filter(attempt=>approvals.has(`${key}:${attempt}`));
178
- const memberReview=parallelMember?await memberReviewConfiguration(batch,definition,review,externalModels?routes.reviewerRuntime:runtime??'codex',externalModels?.providers[routes.reviewerRuntime]??null,!reconciling):review;
296
+ const memberReview=parallelMember?await memberReviewConfiguration(batch,definition,review,externalModels?routes.reviewerRuntime:runtime??'codex',externalModels?.providers[routes.reviewerRuntime]??null,!reconciling,Boolean(executionPolicy)):review;
179
297
  const execution=createConversationExecution(definition,argv[4],parallelMember?memberBridge:bridge,memberReview,attempts,workflows[key],allowQa,runtime??'codex',
180
298
  {parallelMember,...(executionPolicy?{executionPolicy}:{}),...(externalModels?{externalModels,...(providerConfig?{reviewerRuntime:routes.reviewerRuntime}:{})}:{}),...(verificationPrecheck?{verificationPrecheck:true}:{}),batchWorkflowsDigest:digest(executionPolicy?{workflows,bootstraps,externalModels,executionPolicy}:externalModels?{workflows,bootstraps,externalModels}:bootstraps?{workflows,bootstraps}:workflows),qaLogHome:path.join(batch.specsDir,'.reviews','host-log-mirror'),
181
299
  // A protected CLI config also protects unauthorized tasks: they stay on the
@@ -190,13 +308,14 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
190
308
  return execution;
191
309
  }});
192
310
  const host={async handle(request){
193
- try{reconciling=request.operation==='reconcile_review';return await driver.handle(request);}catch(cause){return {outcome:'blocked',code:safeCode(cause)};}
311
+ try{reconciling=request.operation==='reconcile_review';return await driver.handle(request);}
312
+ catch(cause){const reason=boundedReason(cause);return {outcome:'blocked',code:safeCode(cause),...(reason?{reason}:{})};}
194
313
  }};
195
314
  const rawMode=input.isTTY&&typeof input.setRawMode==='function';if(rawMode)input.setRawMode(true);
196
315
  try{await serveHostTransport({host,input,output,toolBridge:bridge},inputLimitRaw);}
197
316
  finally{if(rawMode)input.setRawMode(false);}
198
317
  return 0;
199
- }catch(cause){const code=safeCode(cause);error.write(JSON.stringify({error:{code,...(['browser_capability_required','browser_capability_unavailable','invalid_arguments','review_configuration_required','protected_scope'].includes(code)
318
+ }catch(cause){const code=safeCode(cause);error.write(JSON.stringify({error:{code,...(['browser_capability_required','browser_capability_unavailable','invalid_arguments','review_configuration_required','protected_scope',...Object.keys(UNSUPPORTED_REASON)].includes(code)
200
319
  &&typeof cause.reason==='string'?{reason:cause.reason}:{}),...(code==='request_too_large'?{reason:inputLimitReason(cause.limit)}:{})}})+'\n');return 1;}
201
320
  finally{bridge?.close();}
202
321
  }
@@ -63,9 +63,12 @@ function fixture(runtime='codex'){
63
63
  ...(runtime==='claude'?['--runtime','claude']:[])]};
64
64
  }
65
65
 
66
- function execute(f,approvals,{cancel=false}={}){
66
+ // operations are sent one after another (each after the previous reply); the
67
+ // session closes after the last. failDevelop: task ids whose next develop
68
+ // answer is a bare failure after the session wrote (develop_answer_missing).
69
+ function execute(f,approvals,{cancel=false,args=[],operations=[{operation:'advance',requestId:'advance'}],failDevelop=new Set()}={}){
67
70
  return new Promise((resolve,reject)=>{
68
- const child=spawn(process.execPath,[cli,...f.args,...approvals.flatMap(value=>['--allow-review',value])],
71
+ const child=spawn(process.execPath,[cli,...f.args,...args,...approvals.flatMap(value=>['--allow-review',value])],
69
72
  {env:f.env,stdio:['pipe','pipe','pipe']});
70
73
  let buffer='',stderr='',sessionId;const calls=[],rows=[];
71
74
  const timer=setTimeout(()=>{child.kill('SIGTERM');reject(Error('batch host timeout'));},Number(process.env.CM_TEST_FIXTURE_TIMEOUT_MS??60000));
@@ -93,6 +96,7 @@ function execute(f,approvals,{cancel=false}={}){
93
96
  assert.deepEqual(payload.request.payload.specification.sources,buildManifest(f.specsDir));
94
97
  const content=`export const value = ${40+n};\n`;
95
98
  if(!f.protected)fs.writeFileSync(path.join(cwd,`task${n}.mjs`),content);
99
+ if(failDevelop.delete(identity.taskId)){respond(row,{status:'failed',code:'session_error'});continue;}
96
100
  respond(row,{status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
97
101
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}},...(f.protected?{edits:
98
102
  payload.request.payload.scope.map(file=>({path:file,beforeSha256:payload.expected[file],
@@ -115,12 +119,17 @@ function execute(f,approvals,{cancel=false}={}){
115
119
  at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')});
116
120
  }else assert.fail(`Unexpected ${row.kind}`);
117
121
  }
118
- if(row.requestId==='advance'&&(row.result||row.error))send({type:'host_close',sessionId});
122
+ const index=operations.findIndex(item=>item.requestId===row.requestId);
123
+ if(index>=0&&(row.result||row.error)){
124
+ if(index+1<operations.length)send(operations[index+1]);else send({type:'host_close',sessionId});
125
+ }
119
126
  }catch(error){clearTimeout(timer);child.kill('SIGTERM');reject(error);}
120
127
  }
121
128
  });
122
- child.once('close',code=>{clearTimeout(timer);resolve({code,stderr,calls,rows,result:rows.find(row=>row.requestId==='advance')?.result});});
123
- send({operation:'advance',requestId:'advance'});
129
+ child.once('close',code=>{clearTimeout(timer);resolve({code,stderr,calls,rows,
130
+ results:Object.fromEntries(operations.map(item=>[item.requestId,rows.find(row=>row.requestId===item.requestId)?.result])),
131
+ result:rows.find(row=>row.requestId===operations.at(-1).requestId)?.result});});
132
+ send(operations[0]);
124
133
  });
125
134
  }
126
135
 
@@ -245,6 +254,198 @@ let input='';process.stdin.on('data',part=>input+=part);process.stdin.on('end',(
245
254
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
246
255
  });
247
256
 
257
+ // 53c385e moved the execution-policy member preflight cache out of .reviews/.execution.
258
+ // A batch that had already cached there (old layout) was refused by the external run
259
+ // guard on every later launch. The exact old cache now moves to the current location
260
+ // and is reused without a new loopback; anything else is refused with a reason.
261
+ function legacyParallelFixture(){
262
+ const f=fixture();f.parallel=true;
263
+ f.batch.tasks=[1,2,3].map(n=>({feature:'1.work',taskId:`T-00${n}`,scope:[`task${n}.mjs`],requirements:['requirements.md']}));
264
+ f.batch.parallel=[['1.work/T-001','1.work/T-002']];
265
+ fs.writeFileSync(path.join(f.specsDir,'1.work','tasks.md'),'- [ ] T-001: first\n- [ ] T-002: second\n- [ ] T-003: final\n\n- T-003 依赖 T-001, T-002\n');
266
+ fs.writeFileSync(path.join(f.specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(f.specsDir)}));
267
+ const original=JSON.parse(fs.readFileSync(f.config,'utf8')).workflows['1.work/T-001'];
268
+ fs.writeFileSync(f.config,JSON.stringify({batch:f.batch,workflows:Object.fromEntries(f.batch.tasks.map(task=>[`1.work/${task.taskId}`,original]))}));
269
+ f.legacy=path.join(f.specsDir,'.reviews','.execution',f.batch.batchId);
270
+ f.current=path.join(f.specsDir,'.reviews','external-preflight',f.batch.batchId);
271
+ f.worktree=taskId=>path.join(f.root,'.cm-worktrees',f.batch.batchId.slice(0,8),taskId);
272
+ return f;
273
+ }
274
+ const legacyReceipt=(f,taskId,extra={})=>JSON.stringify({model:'fixture',disabledSkills:[],preflight:{passed:true,cli_model:'fixture',
275
+ config_fingerprint:configFingerprint({cwd:f.worktree(taskId),model:'fixture',disabledSkills:[]}),prompt_transport:'stdin',
276
+ real_model_requests:0,listener_closed:true,...extra}})+'\n';
277
+ function writeLegacy(f,files){
278
+ fs.mkdirSync(f.legacy,{recursive:true,mode:0o700});fs.chmodSync(f.legacy,0o700);
279
+ for(const [name,bytes] of Object.entries(files))fs.writeFileSync(path.join(f.legacy,name),bytes,{mode:0o600});
280
+ }
281
+ test('execution-policy batch moves an exact old-layout member preflight cache out of the run directory and reuses it',async()=>{
282
+ const f=legacyParallelFixture();
283
+ try{
284
+ const log=path.join(f.root,'probe-cwds.jsonl'),fail=path.join(f.root,'fail-probe');
285
+ fs.writeFileSync(fail,'fail second member');
286
+ const processFixture=fileURLToPath(new URL('./fixtures/codex-review-process.mjs',import.meta.url));
287
+ fs.writeFileSync(path.join(f.root,'bin','codex'),`#!${process.execPath}
288
+ const fs=require('node:fs'),cp=require('node:child_process');
289
+ const args=process.argv.slice(2),cwd=args[args.indexOf('--cd')+1];
290
+ fs.appendFileSync(${JSON.stringify(log)},JSON.stringify(cwd)+'\\n');
291
+ if(cwd.endsWith('T-002')&&fs.existsSync(${JSON.stringify(fail)}))process.exit(1);
292
+ let input='';process.stdin.on('data',part=>input+=part);process.stdin.on('end',()=>{
293
+ const result=cp.spawnSync(process.execPath,[${JSON.stringify(processFixture)},...args],{input,encoding:'utf8'});
294
+ process.stdout.write(result.stdout??'');process.stderr.write(result.stderr??'');process.exit(result.status??1);
295
+ });
296
+ `,{mode:0o700});
297
+ const probes=()=>fs.readFileSync(log,'utf8').trim().split('\n').length;
298
+ const policy=['--execution-optimizations'];
299
+ // Stop before any member run exists (T-002's loopback fails): T-001 gets a real receipt.
300
+ const failed=await execute(f,['1.work/T-001:1','1.work/T-002:1'],{args:policy});
301
+ assert.equal(failed.result.code,'review_preflight_failed',JSON.stringify(failed));
302
+ fs.unlinkSync(fail);
303
+ const real=fs.readFileSync(path.join(f.current,'preflight-T-001.json'),'utf8');
304
+ // Old layout: the same receipts under .reviews/.execution/<batchId>, nothing at the new place.
305
+ const second=JSON.parse(real);second.preflight.config_fingerprint=configFingerprint({cwd:f.worktree('T-002'),model:'fixture',disabledSkills:[]});
306
+ const receipts={'preflight-T-001.json':real,'preflight-T-002.json':JSON.stringify(second)+'\n'};
307
+ assert.deepEqual(Object.keys(JSON.parse(receipts['preflight-T-002.json'])),Object.keys(JSON.parse(real)));
308
+ fs.rmSync(path.dirname(f.current),{recursive:true});writeLegacy(f,receipts);
309
+ const before=probes();
310
+ const resumed=await execute(f,[],{args:policy});
311
+ assert.equal(resumed.code,0,resumed.stderr);
312
+ assert.equal(resumed.result.code,'decision_required',JSON.stringify(resumed.result));
313
+ assert.equal(resumed.calls.filter(call=>call.endsWith(':develop')).length,2,JSON.stringify(resumed.calls));
314
+ assert.equal(probes(),before,'migrated receipts are reused without a new loopback');
315
+ assert(!fs.existsSync(f.legacy));
316
+ for(const [name,bytes] of Object.entries(receipts))assert.equal(fs.readFileSync(path.join(f.current,name),'utf8'),bytes);
317
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
318
+ });
319
+ test('old-layout preflight cache that is not the exact old shape or binding is refused with a reason and left untouched',async()=>{
320
+ const {migrateLegacyPreflightCache}=await import('./cm-ai-batch-host.mjs');
321
+ const review={model:'fixture',preflight:{},disabledSkills:[]};
322
+ const cases=[
323
+ ['an unrelated entry',f=>({'preflight-T-001.json':legacyReceipt(f,'T-001'),'state.json':'{}'}),/state\.json/],
324
+ ['a non-member task',f=>({'preflight-T-003.json':legacyReceipt(f,'T-003')}),/preflight-T-003\.json/],
325
+ ['a stale fingerprint',f=>({'preflight-T-001.json':legacyReceipt(f,'T-001',{config_fingerprint:'0'.repeat(64)})}),/指纹/],
326
+ ['another member cwd',f=>({'preflight-T-002.json':legacyReceipt(f,'T-001')}),/指纹/],
327
+ ['a reviewer budget',f=>({'preflight-T-001.json':JSON.stringify({...JSON.parse(legacyReceipt(f,'T-001')),timeoutMs:5})}),/不一致/],
328
+ ['not a cache',f=>({'preflight-T-001.json':'{"model":"fixture"}'}),/格式/],
329
+ ];
330
+ for(const [label,files,pattern] of cases){
331
+ const f=legacyParallelFixture();
332
+ try{
333
+ const content=files(f);writeLegacy(f,content);
334
+ assert.throws(()=>migrateLegacyPreflightCache(f.batch,review,'codex'),error=>error.code==='legacy_preflight_cache_invalid'
335
+ &&pattern.test(error.reason)&&/下一步/.test(error.reason)&&error.reason.includes(f.legacy),label);
336
+ assert.deepEqual(fs.readdirSync(f.legacy).sort(),Object.keys(content).sort(),label);
337
+ assert(!fs.existsSync(f.current),label);
338
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
339
+ }
340
+ const f=legacyParallelFixture();
341
+ try{
342
+ // Symlinked file, loose directory mode, and a differing file at the new place: refused.
343
+ writeLegacy(f,{});fs.symlinkSync(path.join(f.root,'review.json'),path.join(f.legacy,'preflight-T-001.json'));
344
+ assert.throws(()=>migrateLegacyPreflightCache(f.batch,review,'codex'),/legacy_preflight_cache_invalid/);
345
+ fs.unlinkSync(path.join(f.legacy,'preflight-T-001.json'));
346
+ writeLegacy(f,{'preflight-T-001.json':legacyReceipt(f,'T-001'),'preflight-T-002.json':legacyReceipt(f,'T-002')});
347
+ fs.chmodSync(f.legacy,0o755);
348
+ assert.throws(()=>migrateLegacyPreflightCache(f.batch,review,'codex'),/legacy_preflight_cache_invalid/);
349
+ fs.chmodSync(f.legacy,0o700);
350
+ fs.mkdirSync(f.current,{recursive:true,mode:0o700});
351
+ fs.writeFileSync(path.join(f.current,'preflight-T-002.json'),legacyReceipt(f,'T-002',{listener_closed:false}),{mode:0o600});
352
+ assert.throws(()=>migrateLegacyPreflightCache(f.batch,review,'codex'),error=>/已有不同内容/.test(error.reason));
353
+ assert.equal(fs.readdirSync(f.legacy).length,2);
354
+ assert.throws(()=>migrateLegacyPreflightCache(f.batch,null,'codex'),/legacy_preflight_cache_invalid/);
355
+ // An identical copy already at the new place drops the old one; the other one moves.
356
+ fs.writeFileSync(path.join(f.current,'preflight-T-002.json'),legacyReceipt(f,'T-002'));
357
+ assert.deepEqual(migrateLegacyPreflightCache(f.batch,review,'codex'),{moved:['preflight-T-001.json'],dropped:['preflight-T-002.json']});
358
+ assert(!fs.existsSync(f.legacy));
359
+ assert.equal(fs.readFileSync(path.join(f.current,'preflight-T-001.json'),'utf8'),legacyReceipt(f,'T-001'));
360
+ // Idempotent: nothing left to migrate.
361
+ assert.deepEqual(migrateLegacyPreflightCache(f.batch,review,'codex'),{moved:[],dropped:[]});
362
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
363
+ });
364
+ // Batch 4 review round 1: the migration commits without overwriting, validates the
365
+ // exact bytes it moves, re-checks both sides before dropping a duplicate and leaves
366
+ // a resumable state when it stops part way. fs is patched at the commit step only.
367
+ test('old-layout preflight migration never overwrites, re-checks what it commits and resumes an interrupted move',async()=>{
368
+ const {migrateLegacyPreflightCache}=await import('./cm-ai-batch-host.mjs');
369
+ const review={model:'fixture',preflight:{},disabledSkills:[]};
370
+ const {linkSync,unlinkSync}=fs;
371
+ const run=async(label,files,patch,check)=>{
372
+ const f=legacyParallelFixture();
373
+ try{
374
+ writeLegacy(f,files(f));
375
+ if(patch.existing){fs.mkdirSync(f.current,{recursive:true,mode:0o700});
376
+ for(const [name,bytes] of Object.entries(patch.existing(f)))fs.writeFileSync(path.join(f.current,name),bytes,{mode:0o600});}
377
+ if(patch.link)fs.linkSync=(...args)=>{patch.link(f,...args);return linkSync.apply(fs,args);};
378
+ if(patch.unlink)fs.unlinkSync=(...args)=>{patch.unlink(f,...args);return unlinkSync.apply(fs,args);};
379
+ let error=null;try{migrateLegacyPreflightCache(f.batch,review,'codex');}catch(cause){error=cause;}
380
+ finally{fs.linkSync=linkSync;fs.unlinkSync=unlinkSync;}
381
+ await check(f,error,label);
382
+ }finally{fs.linkSync=linkSync;fs.unlinkSync=unlinkSync;fs.rmSync(f.root,{recursive:true,force:true});}
383
+ };
384
+ const one=f=>({'preflight-T-001.json':legacyReceipt(f,'T-001')});
385
+ const refused=(error,pattern,label)=>assert(error?.code==='legacy_preflight_cache_invalid'&&pattern.test(error.reason),`${label}: ${error?.code} ${error?.reason}`);
386
+ // A different file appears at the target between planning and commit: not replaced.
387
+ await run('target appears',one,{link:(f,from,to)=>{if(!fs.existsSync(to))fs.writeFileSync(to,'other\n',{mode:0o600});}},(f,error,label)=>{
388
+ refused(error,/在迁移时出现/,label);
389
+ assert.equal(fs.readFileSync(path.join(f.current,'preflight-T-001.json'),'utf8'),'other\n');
390
+ assert.equal(fs.readFileSync(path.join(f.legacy,'preflight-T-001.json'),'utf8'),legacyReceipt(f,'T-001'));
391
+ });
392
+ // The source changes in place (same inode) after validation: the link is undone.
393
+ await run('source rewritten',one,{link:(f,from)=>fs.writeFileSync(from,legacyReceipt(f,'T-001',{listener_closed:false}))},(f,error,label)=>{
394
+ refused(error,/被改动/,label);
395
+ assert(!fs.existsSync(path.join(f.current,'preflight-T-001.json')));
396
+ assert(fs.existsSync(path.join(f.legacy,'preflight-T-001.json')));
397
+ });
398
+ // A duplicate's new copy changes after planning: the old copy is kept.
399
+ await run('duplicate changed',f=>({'preflight-T-001.json':legacyReceipt(f,'T-001'),'preflight-T-002.json':legacyReceipt(f,'T-002')}),
400
+ {existing:f=>({'preflight-T-002.json':legacyReceipt(f,'T-002')}),
401
+ link:f=>fs.writeFileSync(path.join(f.current,'preflight-T-002.json'),legacyReceipt(f,'T-002',{listener_closed:false}))},(f,error,label)=>{
402
+ refused(error,/被改动/,label);
403
+ assert(fs.existsSync(path.join(f.legacy,'preflight-T-002.json')));
404
+ });
405
+ // A stop after the link (both names on one inode) is finished by the next launch.
406
+ await run('interrupted move',one,{unlink:(f,file)=>{if(file.startsWith(f.legacy))throw Object.assign(new Error('crash'),{code:'synthetic_crash'});}},(f,error,label)=>{
407
+ assert.equal(error?.code,'synthetic_crash',label);
408
+ const a=fs.lstatSync(path.join(f.legacy,'preflight-T-001.json')),b=fs.lstatSync(path.join(f.current,'preflight-T-001.json'));
409
+ assert.deepEqual([a.ino,a.nlink],[b.ino,2]);
410
+ assert.deepEqual(migrateLegacyPreflightCache(f.batch,review,'codex'),{moved:['preflight-T-001.json'],dropped:[]});
411
+ assert(!fs.existsSync(f.legacy));
412
+ assert.equal(fs.lstatSync(path.join(f.current,'preflight-T-001.json')).nlink,1);
413
+ assert.equal(fs.readFileSync(path.join(f.current,'preflight-T-001.json'),'utf8'),legacyReceipt(f,'T-001'));
414
+ });
415
+ });
416
+ // Batch 4 review round 1: the target directory and its parent are checked before any
417
+ // delete or move, also when every old file is a duplicate (nothing to move).
418
+ test('old-layout preflight migration refuses a symlinked target even when every old file is a duplicate',async()=>{
419
+ const {migrateLegacyPreflightCache}=await import('./cm-ai-batch-host.mjs');
420
+ const review={model:'fixture',preflight:{},disabledSkills:[]};
421
+ for(const linked of ['target','parent']){
422
+ const f=legacyParallelFixture();
423
+ try{
424
+ const files={'preflight-T-001.json':legacyReceipt(f,'T-001'),'preflight-T-002.json':legacyReceipt(f,'T-002')};
425
+ writeLegacy(f,files);
426
+ // The real directory holds identical copies; the expected path only links to it.
427
+ const elsewhere=path.join(f.root,'elsewhere'),real=path.join(elsewhere,linked==='target'?'':f.batch.batchId);
428
+ fs.mkdirSync(real,{recursive:true,mode:0o700});fs.chmodSync(elsewhere,0o700);
429
+ for(const [name,bytes] of Object.entries(files))fs.writeFileSync(path.join(real,name),bytes,{mode:0o600});
430
+ if(linked==='target'){fs.mkdirSync(path.dirname(f.current),{recursive:true,mode:0o700});fs.symlinkSync(elsewhere,f.current);}
431
+ else fs.symlinkSync(elsewhere,path.dirname(f.current));
432
+ assert.throws(()=>migrateLegacyPreflightCache(f.batch,review,'codex'),
433
+ error=>error.code==='legacy_preflight_cache_invalid'&&/不是权限 0700 的普通目录/.test(error.reason),linked);
434
+ assert.deepEqual(fs.readdirSync(f.legacy).sort(),Object.keys(files).sort(),linked);
435
+ for(const [name,bytes] of Object.entries(files))assert.equal(fs.readFileSync(path.join(f.legacy,name),'utf8'),bytes);
436
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
437
+ }
438
+ // A target copy that breaks the file constraints (mode, links) is refused too.
439
+ const f=legacyParallelFixture();
440
+ try{
441
+ writeLegacy(f,{'preflight-T-001.json':legacyReceipt(f,'T-001')});
442
+ fs.mkdirSync(f.current,{recursive:true,mode:0o700});
443
+ fs.writeFileSync(path.join(f.current,'preflight-T-001.json'),legacyReceipt(f,'T-001'),{mode:0o644});
444
+ assert.throws(()=>migrateLegacyPreflightCache(f.batch,review,'codex'),/legacy_preflight_cache_invalid/);
445
+ assert(fs.existsSync(path.join(f.legacy,'preflight-T-001.json')));
446
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
447
+ });
448
+
248
449
  test('provider development grants select worktree runtimes and keep the serial task on protected conversation transport',async()=>{
249
450
  const f=fixture();
250
451
  try{
@@ -260,10 +461,10 @@ test('provider development grants select worktree runtimes and keep the serial t
260
461
  const workerModule=new URL('../runtime/js/cm-ai/codex-config.mjs',import.meta.url).href;
261
462
  fs.writeFileSync(stub,`
262
463
  import {configFingerprint} from ${JSON.stringify(workerModule)};
263
- export {readConversationReviewConfiguration,readConversationProtection} from ${JSON.stringify(hostModule)};
464
+ export {readConversationReviewConfiguration,readConversationReviewConfigurationValue,readConversationProtection} from ${JSON.stringify(hostModule)};
264
465
  export {parseHostInputLimit,inputLimitReason} from ${JSON.stringify(sessionModule)};
265
466
  export const calls=[];export let scheduler;
266
- export {batchTaskRunId} from ${JSON.stringify(new URL('./cm-ai-batch-run.mjs',import.meta.url).href)};
467
+ export {batchTaskRunId,BATCH_MEMBER_ACTIONS} from ${JSON.stringify(new URL('./cm-ai-batch-run.mjs',import.meta.url).href)};
267
468
  export function createConversationExecution(...args){calls.push(args);return {};}
268
469
  export async function runReviewPreflight(definition,{model}){return {model,disabledSkills:[],preflight:{passed:true,
269
470
  cli_model:model,prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd:definition.codeProject,model})}};}
@@ -306,3 +507,50 @@ export async function serveCmAiHost({host}){await host.handle({});}
306
507
  }
307
508
  }finally{fs.rmSync(f.root,{recursive:true,force:true});}
308
509
  });
510
+
511
+ // Q24 (real host): a serial member whose develop answer came back as a bare failure
512
+ // after the session wrote stops at develop_redo. The batch host used to accept only
513
+ // advance/status/cancel/reconcile_review, so the batch stayed stuck there. Now the
514
+ // batch host forwards develop_redo to that member's run (same cm-ai entry, one-shot
515
+ // per-member grant) and the next advance redoes the round and finishes the batch.
516
+ test('Q24 batch host recovers a serial member stopped at develop_redo and continues the batch',async()=>{
517
+ const f=fixture();
518
+ try{
519
+ const approvals=['1.work/T-001:1','1.work/T-002:1'];
520
+ const first=await execute(f,approvals,{failDevelop:new Set(['T-001'])});
521
+ assert.equal(first.code,0,first.stderr);
522
+ assert.deepEqual([first.result.state,first.result.code,first.result.pendingAction],['blocked','develop_answer_missing','develop_redo'],JSON.stringify(first.result));
523
+ assert.match(first.result.guidance.nextStep,/--allow-develop-redo 1\.work\/T-001/);assert.deepEqual(first.calls,['T-001:develop']);
524
+ const redo={operation:'develop_redo',requestId:'redo',taskKey:'1.work/T-001',reason:'会话已停止修改代码'};
525
+ // advance alone never redispatches; the operation needs its per-member grant.
526
+ const refused=await execute(f,approvals,{operations:[{operation:'advance',requestId:'advance'},redo]});
527
+ assert.equal(refused.results.advance.pendingAction,'develop_redo');
528
+ assert.deepEqual([refused.result.outcome,refused.result.code],['rejected','batch_member_action_authorization_required']);
529
+ assert.match(refused.result.reason,/--allow-develop-redo 1\.work\/T-001/);assert.deepEqual(refused.calls,[]);
530
+ const bad=spawnSync(process.execPath,[cli,...f.args,'--allow-develop-redo','1.work/T-999'],{env:f.env,encoding:'utf8',timeout:5000});
531
+ assert.equal(bad.status,1);assert.match(bad.stderr,/invalid_arguments/);assert.match(bad.stderr,/FEATURE\/TASK/);
532
+ for(const [flag,code] of [['--revise-qa-config','batch_qa_revision_unavailable'],['--rebind-spec-material','batch_spec_rebind_unavailable']]){
533
+ const unsupported=spawnSync(process.execPath,[cli,...f.args,flag,'x'],{env:f.env,encoding:'utf8',timeout:5000});
534
+ assert.equal(unsupported.status,1);assert.match(unsupported.stderr,new RegExp(code));assert.match(unsupported.stderr,/出口/);
535
+ }
536
+ const recovered=await execute(f,approvals,{args:['--allow-develop-redo','1.work/T-001'],
537
+ operations:[redo,{operation:'advance',requestId:'advance'}]});
538
+ assert.equal(recovered.code,0,recovered.stderr);
539
+ assert.deepEqual([recovered.results.redo.outcome,recovered.results.redo.pendingAction,recovered.results.redo.taskKey],
540
+ ['recorded','resume','1.work/T-001'],JSON.stringify(recovered.results.redo));
541
+ assert.equal(recovered.result.state,'run_done',JSON.stringify(recovered.result));
542
+ assert.deepEqual(recovered.calls.slice(0,2),['T-001:develop','T-001:check']);
543
+ assert(recovered.calls.includes('T-002:develop'));
544
+ assert.equal(fs.readFileSync(path.join(f.specsDir,'1.work','tasks.md'),'utf8').match(/\[x\]/g).length,2);
545
+ const {batchTaskRunId}=await import('./cm-ai-batch-run.mjs');
546
+ const records=JSON.parse(fs.readFileSync(path.join(f.specsDir,'.reviews','.execution',batchTaskRunId(f.batch.batchId,'1.work/T-001'),'state.json'),'utf8')).records;
547
+ assert.equal(records.filter(row=>row.payload.type==='develop-answer-redo').length,1);
548
+ // After cancel the batch stays stopped; a forwarded operation cannot reopen it.
549
+ const g=fixture();
550
+ try{
551
+ const stopped=await execute(g,[],{cancel:true});assert.equal(stopped.result.code,'cancelled');
552
+ const after=await execute(g,[],{args:['--allow-develop-redo','1.work/T-001'],operations:[redo]});
553
+ assert.deepEqual([after.result.outcome,after.result.code],['blocked','cancelled']);
554
+ }finally{fs.rmSync(g.root,{recursive:true,force:true});}
555
+ }finally{fs.rmSync(f.root,{recursive:true,force:true});}
556
+ });