@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
@@ -9,9 +9,12 @@ export function recordEffectAbandonment({specsDir,codeProject,feature,identity,r
9
9
  const data={node:p.effectKind==='complete'?'N5':p.effectKind==='review'?'N4':'N3',feature,task:identity.taskId,
10
10
  effect_id:p.effectId,effect_kind:p.effectKind,intent_digest:p.intentDigest,
11
11
  record_digest:record.digest,reason:p.reason};
12
- const args=[writer,'--workflow','cm-ai','--event','effect_abandoned','--runtime',runtime,
12
+ // effect-interrupted (V8) retires the step and the run continues from its block.
13
+ const interrupted=p.type==='effect-interrupted';
14
+ const args=[writer,'--workflow','cm-ai','--event',interrupted?'effect_interrupted':'effect_abandoned','--runtime',runtime,
13
15
  '--project-root',codeProject,'--specs-dir',specsDir,'--run-id',identity.runId,
14
- '--at',p.at,'--detail','显式放弃中断且无检查点的任务 effect','--data-json',JSON.stringify(data)];
16
+ '--at',p.at,'--detail',interrupted?'中断且无检查点的任务 effect 已登记,运行从这一步的可重试阻断继续'
17
+ :'显式放弃中断且无检查点的任务 effect','--data-json',JSON.stringify(data)];
15
18
  const result=spawnSync('python3',args,{timeout:10000,maxBuffer:1024*1024,
16
19
  ...(logHome?{env:{...process.env,CM_WORKFLOW_LOG_HOME:logHome}}:{})});
17
20
  need(!result.error&&result.status===0,'effect_abandon_log_failed');
@@ -51,7 +51,12 @@ const failureCodes=new Set(['invalid_input','limit_exceeded','call_timeout','can
51
51
  'unregistered_receipt','invalid_receipt','receipt_identity','receipt_package_mismatch','review_not_approved',
52
52
  'checks_not_passed','async_commit','commit_unknown','unsupported_path','unsupported_file','read_failed',
53
53
  'snapshot_changed','spec_drift','invalid_baseline','out_of_scope','empty_changes','invalid_package','package_mismatch',
54
- 'handoff_exists','verification_precheck_failed','completion_checks_changed','bootstrap_review_mismatch']);
54
+ 'handoff_exists','verification_precheck_failed','completion_checks_changed','bootstrap_review_mismatch',
55
+ // A lost or malformed session answer keeps its own code instead of collapsing
56
+ // into execution_error, so the answer-gap projections can tell it apart.
57
+ 'host_disconnected','host_request_timeout','verification_precheck_invalid',
58
+ // Raised only by the host's own role routing, before any session request.
59
+ 'role_log_failed','invalid_workflow_config']);
55
60
  // An unlisted code becomes execution_error, which on its own is not actionable.
56
61
  // The EEXIST that blocked every retry of a task in #81 stayed invisible in the
57
62
  // log, the state and stderr until a temporary print was added by hand. Emit one
@@ -30,6 +30,22 @@ function fixCallsResolved(records,configuration){
30
30
  return true;
31
31
  }
32
32
  const codeBinding=codeProject=>path.join(codeProject,'.cm-external-models-v1.json');
33
+ // The two refusals below are shared with callers that must tell, read-only, whether
34
+ // a new run on the same code root would pass this guard (cm-ai-batch-run.mjs hints).
35
+ // A strict (external-model or execution-policy) prior run: unknown external work
36
+ // belongs to the code root, even across tasks/features.
37
+ export function strictPriorAttemptResolved(config,history,records){
38
+ return !(config.externalModels||config.executionPolicy)||!history.pending&&history.state.state!=='unknown'
39
+ &&history.state.reviewInvocation?.result?.reconciliationRequired!==true
40
+ &&!history.state.calls.some(call=>call.requestedModel!=='current-session'
41
+ &&!['succeeded','not_dispatched'].includes(call.terminal)
42
+ &&!records.some(row=>row.payload.type==='review-invocation-reconciled'&&row.payload.invocationId===call.invocationId));
43
+ }
44
+ // A prior run of the same task on the same code root.
45
+ export function sameTaskPriorAttemptResolved(history){
46
+ return !history.pending&&!['unknown','ready','awaiting_review','pending_review','changes_requested','approved'].includes(history.state.state)
47
+ &&history.state.reviewInvocation?.result?.reconciliationRequired!==true;
48
+ }
33
49
  export const externalRunGuardExists=(specsDir,codeProject)=>fs.existsSync(path.join(specsDir,'.cm-external-models-v1'))||fs.existsSync(codeBinding(codeProject));
34
50
  export function acquireExternalRunGuard(definition,{strictOnly=false}={}){
35
51
  const {specsDir,codeProject,identity,feature}=definition;
@@ -79,16 +95,11 @@ export function acquireExternalRunGuard(definition,{strictOnly=false}={}){
79
95
  if(config.root!==codeProject)continue;
80
96
  const history=readRunnerHistory(snapshot.records,config,init.version);
81
97
  // Unknown external work belongs to the code root, even across tasks/features.
82
- if(config.externalModels||config.executionPolicy)need(!history.pending&&history.state.state!=='unknown'
83
- &&history.state.reviewInvocation?.result?.reconciliationRequired!==true
84
- &&!history.state.calls.some(call=>call.requestedModel!=='current-session'
85
- &&!['succeeded','not_dispatched'].includes(call.terminal)
86
- &&!snapshot.records.some(row=>row.payload.type==='review-invocation-reconciled'&&row.payload.invocationId===call.invocationId)),'external_prior_attempt_unresolved');
98
+ need(strictPriorAttemptResolved(config,history,snapshot.records),'external_prior_attempt_unresolved');
87
99
  need(!oldWriterOpen(execution,entry.name),'external_prior_writer_active');
88
100
  if(config.identity.taskId!==identity.taskId
89
101
  ||config.completion?.owner?.tasksPath!==path.join(specsDir,feature,'tasks.md'))continue;
90
- need(!history.pending&&!['unknown','ready','awaiting_review','pending_review','changes_requested','approved'].includes(history.state.state)
91
- &&history.state.reviewInvocation?.result?.reconciliationRequired!==true,'external_prior_attempt_unresolved');
102
+ need(sameTaskPriorAttemptResolved(history),'external_prior_attempt_unresolved');
92
103
  need(!oldWriterOpen(execution,entry.name),'external_prior_writer_active');
93
104
  }
94
105
  return lease;
@@ -14,12 +14,13 @@ export function reportHostCheckProgress(event){
14
14
  `检查结束 ${event.id}: ${event.outcome} (exit ${event.exitCode??'unavailable'})`;
15
15
  try{process.stderr.write(`[check] ${message}\n`);}catch{/* display is not a check verdict */}
16
16
  }
17
- export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,outputIncludes=null,onOutput=null,onProgress=null,reuseDeclared=false}){
17
+ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,outputIncludes=null,onOutput=null,onProgress=null,reuseDeclared=false,onSpawn=null}){
18
18
  need(typeof reuseDeclared==='boolean','invalid_check_config');
19
19
  need(path.isAbsolute(cwd)&&fs.realpathSync(cwd)===cwd&&fs.statSync(cwd).isDirectory());
20
20
  validCallTimeout(timeoutMs);
21
21
  need(onOutput===null||typeof onOutput==='function');
22
22
  need(onProgress===null||typeof onProgress==='function');
23
+ need(onSpawn===null||typeof onSpawn==='function');
23
24
  const notify=event=>{
24
25
  try{
25
26
  const returned=onProgress?.(Object.freeze(event));
@@ -63,6 +64,8 @@ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,out
63
64
  shell:false,detached:true,stdio:['ignore','pipe','pipe']});
64
65
  }
65
66
  catch{resolve({outcome:'unavailable',exitCode:null,evidence:'host check: spawn_failed'});return;}
67
+ // Observers cannot change results or prevent cleanup.
68
+ if(onSpawn&&Number.isInteger(child.pid)&&child.pid>0)try{onSpawn(Object.freeze({id:item.id,pid:child.pid}));}catch{}
66
69
  let failure=null,cleanup,bytes=0;
67
70
  const counts=new Map();
68
71
  const collect=line=>{
@@ -182,13 +182,18 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
182
182
  const authority=review?createHostReviewAuthority({hostContextId,reviewerId:'reviewer',adapterId,
183
183
  decide:async binding=>allowedAttempts.includes(binding.identity.attempt)?{status:'approved'}:null}):null;
184
184
  // Reread role declarations at each boundary; never switch a bound invocation.
185
- const dispatchSpawn=(role,identity,signal)=>{
185
+ // onWorker (provider development, task-runner.mjs) journals the worker's
186
+ // identity right before and right after the spawn; a journal failure kills
187
+ // the new process group like a refused role route does.
188
+ const dispatchSpawn=(role,identity,signal,onWorker=null)=>{
186
189
  const configuration=loadConfig({projectRoot:definition.codeProject});
187
190
  need(digest(resolveProtectedRuntimes(configuration,runtime))===digest({coderRuntime,reviewerRuntime}),'runtime_selection_mismatch');
188
191
  return (cli,args,options)=>{
192
+ onWorker?.({phase:'spawning'});
189
193
  const child=spawn(cli,args,options);
190
194
  if(Number.isInteger(child.pid)){
191
- try{resolveHostRole({definition,identity,role,signal,runtime,configuration,
195
+ try{onWorker?.({phase:'started',pid:child.pid});
196
+ resolveHostRole({definition,identity,role,signal,runtime,configuration,
192
197
  dispatchedRuntime:role==='coder'?coderRuntime:reviewerRuntime});}
193
198
  catch(error){child.on('error',()=>{});child.stdin?.on('error',()=>{});
194
199
  try{options.detached?process.kill(-child.pid,'SIGKILL'):child.kill('SIGKILL');}catch{}throw error;}
@@ -246,7 +251,7 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
246
251
  ...(developerLog?{onUsageClaim:()=>developerLog.claimed(),onUsage:value=>{developerUsage=value;}}:{}),
247
252
  cwd:definition.codeProject,model:provider.model,...(externalModels?{effort:provider.effort}:{}),timeoutMs:protection.timeoutMs,
248
253
  ...(coderRuntime==='codex'?{specsRoot:definition.specsDir}:{}),
249
- spawnProcess:dispatchSpawn('coder',bound.identity,control.signal)}):null;
254
+ spawnProcess:dispatchSpawn('coder',bound.identity,control.signal,typeof control.onWorker==='function'?control.onWorker:null)}):null;
250
255
  const worker=async({prompt})=>{
251
256
  if(provider&&coderRuntime==='codex'){
252
257
  if(documentationPaths.length)prompt='Synchronize approved documentation inside this invocation: '+JSON.stringify(documentationPaths)+'\n'+prompt;
@@ -297,8 +302,10 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
297
302
  if(protection&&response.value.outcome!=='blocked'){
298
303
  if(bound.payload.specification)verifySpecificationMaterial({specificationRoot:definition.specsDir,
299
304
  specification:bound.payload.specification,identity:bound.identity});
305
+ // The applying sandbox subprocess is journaled like the worker (V9).
300
306
  try{await projectExecution.commit({scope:bound.payload.scope,
301
- edits,expected,identity:bound.identity,signal:control.signal});}
307
+ edits,expected,identity:bound.identity,signal:control.signal,
308
+ ...(typeof control.onWorker==='function'?{onApply:event=>control.onWorker(event)}:{})});}
302
309
  catch(error){
303
310
  // This code is emitted by the pre-write expected-hash check.
304
311
  // Sandbox execution/partial-write failures stay ambiguous.
@@ -2,7 +2,7 @@
2
2
  // checks/Learning/handoff/review. This adapter grants no additional file scope.
3
3
  import {isFinalCmAiTask} from './cm-ai-admission.mjs';
4
4
  import {captureReviewBaseline} from './review-package.mjs';
5
- import {digest,json,shape,need,terminalFor} from './effect-contract.mjs';
5
+ import {digest,json,shape,need,terminalFor,boundedReason} from './effect-contract.mjs';
6
6
 
7
7
  export function validateDocumentationPaths(raw,scope){
8
8
  const paths=json(raw);
@@ -16,27 +16,68 @@ export function validateDocumentationPaths(raw,scope){
16
16
  return paths;
17
17
  }
18
18
 
19
+ // Q16/Q17: a code-root snapshot split into the documentation paths (each
20
+ // path's sha256, null when absent) and one digest of everything else. The
21
+ // task runner supplies the snapshot (control.documentationSnapshot): its fixed
22
+ // task-snapshot rules (full develop scope, the ignore policy bound at create),
23
+ // so a develop-scope file Git ignores is still part of "everything else". The
24
+ // runner records the split when the sync starts and compares a later one with
25
+ // it before it re-asks only documentation_sync.
26
+ export function splitDocumentationState(files,paths){
27
+ const others=files.filter(file=>!paths.includes(file.path));
28
+ return {files,documents:paths.map(file=>({path:file,
29
+ sha256:files.find(item=>item.path===file)?.sha256??null})),othersDigest:digest(others)};
30
+ }
31
+ // Without a runner snapshot (no journal: nothing is recorded or retried), the
32
+ // adapter keeps its own scope-only capture for the out-of-scope check.
33
+ export function captureDocumentationState({root,specsRoot,identity,paths,requirements,specification=null}){
34
+ const baseline=captureReviewBaseline({root,specsRoot,identity,scope:paths,requirements,
35
+ ...(specification?{specification}:{})});
36
+ return splitDocumentationState(baseline.files,paths);
37
+ }
38
+ // Paths outside the documentation paths that differ between two captures.
39
+ export function documentationOutOfScopePaths(before,after,paths){
40
+ const index=files=>new Map(files.filter(file=>!paths.includes(file.path)).map(file=>[file.path,digest(file)]));
41
+ const a=index(before),b=index(after);
42
+ return [...new Set([...a.keys(),...b.keys()])].filter(file=>a.get(file)!==b.get(file)).sort();
43
+ }
44
+ const fail=(code,message=code)=>Object.assign(new Error(message),{code});
45
+
19
46
  export function withHostDocumentation({developer,documentationSync,specsDir,codeProject,feature,scope,parallelSelection=null,featureSelection}){
20
47
  shape(documentationSync,['paths','run']);need(typeof documentationSync.run==='function');
21
48
  const paths=validateDocumentationPaths(documentationSync.paths,scope),run=documentationSync.run;
22
49
  need(paths.length>0);
23
50
  return {...developer,run:async(request,control)=>{
24
- const response=terminalFor(await developer.run(request,control),request);
51
+ // A documentation-only redo (task-runner: documentation-sync-retry) reuses
52
+ // the developer answer journaled when the failed sync started; the
53
+ // developer is never asked again.
54
+ const redo=control.documentationRedo;
55
+ if(redo!==undefined)shape(redo,['result','effectiveModel']);
56
+ const response=terminalFor(redo!==undefined?{version:1,invocationId:request.invocationId,contextId:request.contextId,
57
+ provider:request.provider,effectiveModel:redo.effectiveModel,status:'succeeded',accepted:true,result:redo.result}
58
+ :await developer.run(request,control),request);
25
59
  if(response.status!=='succeeded')return response;
26
60
  need(!control.signal.aborted,'cancelled');
27
- if(!isFinalCmAiTask({specsDir,codeProject,feature,taskId:request.identity.taskId,parallelSelection,featureSelection}))return response;
28
- const baseline=captureReviewBaseline({root:codeProject,specsRoot:specsDir,identity:request.identity,
29
- scope:paths,requirements:request.payload.requirements.map(file=>file.path),
30
- ...(request.payload.specification?{specification:{specsRoot:specsDir,feature}}:{})});
61
+ if(!isFinalCmAiTask({specsDir,codeProject,feature,taskId:request.identity.taskId,parallelSelection,featureSelection})){
62
+ need(redo===undefined,'documentation_redo_mismatch');return response;
63
+ }
64
+ const capture=()=>typeof control.documentationSnapshot==='function'?control.documentationSnapshot(paths):captureDocumentationState({root:codeProject,specsRoot:specsDir,identity:request.identity,paths,
65
+ requirements:request.payload.requirements.map(file=>file.path),
66
+ specification:request.payload.specification?{specsRoot:specsDir,feature}:null});
67
+ const before=capture();
68
+ // The runner journals the developer answer and this start before the sync
69
+ // is asked, so a lost sync can be re-asked alone.
70
+ if(typeof control.onDocumentationSync==='function')control.onDocumentationSync({result:response.result,
71
+ effectiveModel:response.effectiveModel,documents:before.documents,othersDigest:before.othersDigest});
31
72
  const result=json(await run(json({identity:request.identity,invocationId:request.invocationId,
32
73
  specsDir,codeProject,feature,paths}),control.signal));
33
- need(!control.signal.aborted,'cancelled');shape(result,['status']);
74
+ need(!control.signal.aborted,'cancelled');
75
+ try{shape(result,['status']);need(['completed','blocked'].includes(result.status));}
76
+ catch{throw fail('documentation_sync_answer_invalid');}
34
77
  need(result.status==='completed','documentation_sync_blocked');
35
- const after=captureReviewBaseline({root:codeProject,specsRoot:specsDir,identity:request.identity,
36
- scope:paths,requirements:request.payload.requirements.map(file=>file.path),
37
- ...(request.payload.specification?{specification:{specsRoot:specsDir,feature}}:{})});
38
- need(digest(baseline.files.filter(file=>!paths.includes(file.path)))===
39
- digest(after.files.filter(file=>!paths.includes(file.path))),'out_of_scope');
78
+ const after=capture();
79
+ if(after.othersDigest!==before.othersDigest)throw fail('out_of_scope',
80
+ boundedReason('out_of_scope: ',documentationOutOfScopePaths(before.files,after.files,paths),''));
40
81
  return response;
41
82
  }};
42
83
  }
@@ -35,7 +35,7 @@ export function createProjectExecution({definition,protection,executionPolicy=nu
35
35
  return Object.freeze({
36
36
  expected(scope){recheck();return Object.fromEntries(groups(scope).flatMap(group=>
37
37
  Object.entries(group.paths.length?captureProtectedEdits(group.codeProject,group.paths):{}).map(([file,hash])=>[full(group,file),hash])));},
38
- async commit({scope,edits,expected,identity,signal}){
38
+ async commit({scope,edits,expected,identity,signal,onApply=null}){
39
39
  recheck();need(Array.isArray(edits),'protected_edit_invalid');
40
40
  for(const edit of edits)need(scope.includes(edit.path),'out_of_scope');
41
41
  // Precheck all roots before the first root writes; no claim of atomicity.
@@ -47,7 +47,7 @@ export function createProjectExecution({definition,protection,executionPolicy=nu
47
47
  .map(edit=>({...edit,path:group.prefix?edit.path.slice(group.prefix.length+1):edit.path}));
48
48
  if(!local.length)continue;
49
49
  await commitProtectedEdits({cwd:group.codeProject,specsRoot:data.specsDir,scope:group.paths,edits:local,
50
- expected:Object.fromEntries(group.paths.map(file=>[file,expected[full(group,file)]])),identity,signal,timeoutMs:config.timeoutMs});
50
+ expected:Object.fromEntries(group.paths.map(file=>[file,expected[full(group,file)]])),identity,signal,timeoutMs:config.timeoutMs,onApply});
51
51
  }
52
52
  },
53
53
  async check(request,control){
@@ -15,6 +15,24 @@ import {captureReviewBaseline} from './review-package.mjs';
15
15
  import {writeCmAiQaStatus} from './cm-ai-run-finalizer.mjs';
16
16
  import {digest,freeze,hex,id,json,need,shape,text,validCallTimeout,validIdentity} from './effect-contract.mjs';
17
17
  import {isQaEnvironmentCarrier,QA_ENVIRONMENT_SCOPES} from './qa-environment.mjs';
18
+ export const QA_DEVICE_UNVERIFIED_REASON='qa_device_unverified: 浏览器用例的宿主请求超时没有拿到应答,会话可能仍在操作设备(浏览器、模拟器或真机),'
19
+ +'宿主无法核实设备已释放,本次 QA 停在这里,不再派发后面的浏览器用例。先确认该会话已停止、设备已空闲,'
20
+ +'再用 --rerun-unknown-qa 重跑本轮(因宿主原因替代的轮次不占三轮预算)。';
21
+ import {readProcessStartTime} from './worker-process-identity.mjs';
22
+
23
+ // Q12: the whole-round deadline scales with the plan: every command may use the
24
+ // command timeout, every logic case one request window and every browser case
25
+ // two (its one evidence correction), plus a minute of margin. Never below the
26
+ // historical 30 minutes and never above a day. Not part of any fingerprint.
27
+ export function qaRoundDeadlineMs({timeoutMs,requestTimeoutMs=null,configuration=null}){
28
+ const plan=configuration?.plan;
29
+ if(!Number.isSafeInteger(timeoutMs)||timeoutMs<=0)return 1800000;
30
+ if(!plan||!Array.isArray(plan.cases)||!Array.isArray(plan.commands)||!Array.isArray(plan.modes))return timeoutMs;
31
+ const request=Number.isSafeInteger(requestTimeoutMs)&&requestTimeoutMs>0?requestTimeoutMs:timeoutMs;
32
+ const commands=plan.modes.includes('commands')?plan.commands.length:0;
33
+ const logic=plan.cases.filter(item=>item.kind==='logic').length,browser=plan.cases.filter(item=>item.kind==='browser').length;
34
+ return Math.min(Math.max(timeoutMs,commands*timeoutMs+logic*request+browser*2*request+60000),24*3600000);
35
+ }
18
36
 
19
37
  const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
20
38
  const order={ 'cm-default':['logic','commands','browser'],
@@ -225,18 +243,24 @@ export function createHostQaExecutor(options) {
225
243
  else if(!plan.commands.length)rows.push({id:'commands-unavailable',kind:'commands',verdict:'BLOCKED',evidence:['No declared project test command',...dropped]});
226
244
  for(const command of plan.commands){
227
245
  notCancelled();
246
+ // Q13: the command's process group identity, so a cleanup_failed row can
247
+ // later be released once the host proves that group gone.
248
+ let spawned=null;
228
249
  const check=createHostCheck({cwd:roots?command.codeProject:configuration.codeProject,commands:[{id:command.id,command:command.command}],
229
- timeoutMs:configuration.timeoutMs,specsRoot:configuration.specsRoot??null,onProgress:reportHostCheckProgress});
250
+ timeoutMs:configuration.timeoutMs,specsRoot:configuration.specsRoot??null,onProgress:reportHostCheckProgress,
251
+ onSpawn:({pid})=>{spawned={pid,process_start_time:readProcessStartTime(pid)};}});
252
+ const failedCleanup=()=>({...resource,...(spawned?spawned:{})});
230
253
  const resource={resource_id:`qa-command-${digest({testRunId:binding.testRunId,command:command.id}).slice(0,48)}`,
231
254
  resource_kind:'qa_command'};
232
255
  logStep(configuration,binding,'resource','acquired',{...resource,cleanup_required:true},'QA command resource acquired');
233
256
  let observed;
234
257
  try{
235
258
  [observed]=await check({identity:binding.identity},{signal});
236
- logStep(configuration,binding,'resource',observed.evidence==='host check: cleanup_failed'?'cleanup_failed':'released',
237
- resource,'QA command resource finished');
259
+ const failed=observed.evidence==='host check: cleanup_failed';
260
+ logStep(configuration,binding,'resource',failed?'cleanup_failed':'released',
261
+ failed?failedCleanup():resource,'QA command resource finished');
238
262
  }catch(error){
239
- logStep(configuration,binding,'resource','cleanup_failed',resource,'QA command cleanup not confirmed');throw error;
263
+ logStep(configuration,binding,'resource','cleanup_failed',failedCleanup(),'QA command cleanup not confirmed');throw error;
240
264
  }
241
265
  notCancelled();
242
266
  commandResults.set(command.id,observed);
@@ -312,12 +336,33 @@ export function createHostQaExecutor(options) {
312
336
  ...(answered&&observed.verdict==='BLOCKED'?{hostDeclaredBlocked:true}:{})});
313
337
  // The durable log row, appended now through the writer, is the record
314
338
  // that the session itself answered BLOCKED; the report only mirrors it.
339
+ // Why the host itself judged this case BLOCKED (Q06/Q11 read it after a
340
+ // call stopped as a whole); never for a session-declared or timed-out case.
341
+ // A missing capability and an unresolved [需确认] come first: neither is a
342
+ // host fault a rerun can fix, whatever the cleanup or evidence looked like.
343
+ const blockedReason=verdict!=='BLOCKED'||answered&&observed.verdict==='BLOCKED'||hostRequestTimeout&&!answered?null
344
+ :browser===null?'unavailable':item.expected.some(value=>value.includes('[需确认]'))?'needs_confirmation'
345
+ :evidenceProblem!==null?'evidence':digest(observed.environment)!==digest(environment)?'environment'
346
+ :observed.cleanup==='failed'||(item.cleanup.length>0&&observed.cleanup!=='completed')?'cleanup':'unclassified';
315
347
  logStep(configuration,binding,'test_run',verdict==='BLOCKED'?'case_blocked':'case_complete',
316
348
  {case_id:item.id,result:verdict,...(answered&&observed.verdict==='BLOCKED'?{host_declared_blocked:true}:{}),
349
+ ...(blockedReason?{blocked_reason:blockedReason}:{}),
350
+ // The session's own verdict before any host downgrade: a FAIL the host
351
+ // turned BLOCKED (evidence, environment, cleanup) is never a host fault.
352
+ ...(answered?{answered_verdict:observed.verdict}:{}),
317
353
  // Whether this BLOCKED is a host request that timed out without an
318
354
  // answer; --rerun-unknown-qa reads it after a whole-call timeout.
319
355
  ...(verdict==='BLOCKED'?{host_request_timeout:hostRequestTimeout&&!answered}:{})},
320
356
  'QA browser case finished');
357
+ // Q07: an unanswered browser request may leave the session driving the
358
+ // device. Never dispatch the next browser case on top of it: stop this
359
+ // call (no complete row), so the round waits for the operator to confirm
360
+ // the device is free and rerun it with --rerun-unknown-qa.
361
+ if(hostRequestTimeout&&!answered){
362
+ const remaining=plan.cases.filter(candidate=>candidate.kind==='browser');
363
+ if(remaining.indexOf(item)<remaining.length-1)throw Object.assign(new Error(QA_DEVICE_UNVERIFIED_REASON),
364
+ {code:'qa_device_unverified',reason:QA_DEVICE_UNVERIFIED_REASON});
365
+ }
321
366
  }
322
367
  }
323
368
  }
@@ -8,8 +8,24 @@ import {createFixHost} from '../cm-fix/host.mjs';
8
8
  import {bindQaFixDefinition} from './qa-fix-definition.mjs';
9
9
  import {digest,id,json,need,shape,validIdentity,hex} from './effect-contract.mjs';
10
10
 
11
- export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHostContextId,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={},externalModels=null,executionPolicy=null}){
11
+ // Q23: the child's recovery operations, each with the original cm-fix flag the
12
+ // shared dispatcher (cm-fix/host.mjs) checks and the parent flag that grants it.
13
+ // The dispatcher stays the only validator; this table only names the missing flag.
14
+ const QA_FIX_ACTION_FLAGS=Object.freeze({rediagnose:'--allow-rediagnosis',rerun_blocked_step:'--allow-rerun-blocked-step',
15
+ recover_final_review:'--allow-final-review-recovery',abandon_step:'--allow-abandon',abandon_review:'--allow-abandon-review',
16
+ revision_test_check:'--allow-regression'});
17
+ const QA_FIX_REASONED=['abandon_step','abandon_review','rediagnose','rerun_blocked_step'];
18
+ export const QA_FIX_ACTIONS=Object.freeze(['red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback',
19
+ 'handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression',
20
+ 'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review','reconcile_review',
21
+ ...Object.keys(QA_FIX_ACTION_FLAGS)]);
22
+ const parentFlag=flag=>flag.replace(/^--allow-/,'--allow-qa-fix-');
23
+ const actionRefusal=(fixOperation,code,reason)=>Object.freeze({outcome:'rejected',code,fixOperation,reason,
24
+ guidance:Object.freeze({summary:'QA 修复子流程的这次操作被拒绝,子运行没有因此改变。',nextStep:reason,
25
+ recoveryOperation:null,prerequisites:Object.freeze([]),authorizationGranted:false})});
26
+ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHostContextId,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={},externalModels=null,executionPolicy=null,recoveryInvocationId=null}){
12
27
  id(hostContextId);id(parentHostContextId);
28
+ if(recoveryInvocationId!==null)id(recoveryInvocationId);
13
29
  need((fix===null)!==(template===null),'invalid_fix_config');
14
30
  let definition=null;
15
31
  let fixedTemplate=template===null?null:json(template,64*1024);
@@ -59,8 +75,13 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
59
75
  if(!['fix_status','fix_advance','fix_action','fix_run'].includes(request.operation)){
60
76
  busy=true;try{return await current.host.handle(request);}finally{busy=false;}
61
77
  }
78
+ // recover_final_review binds the child's final review package; packageDigest
79
+ // here is the parent QA package, so the child digest is reviewPackageDigest.
62
80
  const value=json(request);shape(value,['version','requestId','operation','identity','packageDigest','testRunId',
63
- ...(request.operation==='fix_action'?['fixOperation',...(request.fixOperation==='reconcile_review'?['invocationId']:[]),...(['abandon_step','abandon_review'].includes(request.fixOperation)&&Object.hasOwn(request,'reason')?['reason']:[])]:[])]);
81
+ ...(request.operation==='fix_action'?['fixOperation',...(request.fixOperation==='reconcile_review'?['invocationId']:[]),
82
+ ...(QA_FIX_REASONED.includes(request.fixOperation)&&Object.hasOwn(request,'reason')?['reason']:[]),
83
+ ...(request.fixOperation==='prepare_revision'&&Object.hasOwn(request,'tests')?['tests']:[]),
84
+ ...(request.fixOperation==='recover_final_review'?['invocationId','reviewPackageDigest','previousInvocationStopped','reason']:[])]:[])]);
64
85
  need(value.version===1,'invalid_input');id(value.requestId);validIdentity(value.identity);hex(value.packageDigest);id(value.testRunId);
65
86
  if(fixedTemplate)definition=bindQaFixDefinition({template:fixedTemplate,identity:value.identity,
66
87
  packageDigest:value.packageDigest,testRunId:value.testRunId});
@@ -70,10 +91,13 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
70
91
  const running=value.operation==='fix_run';
71
92
  const advancing=value.operation==='fix_advance'||running;
72
93
  const acting=value.operation==='fix_action';
73
- if(acting)need(['red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback',
74
- 'handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression',
75
- 'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review','reconcile_review','abandon_step','abandon_review'].includes(value.fixOperation),'fix_operation_unavailable');
94
+ if(acting)need(QA_FIX_ACTIONS.includes(value.fixOperation),'fix_operation_unavailable');
76
95
  need(!(advancing||acting)||allowStart,'qa_fix_start_authorization_required');
96
+ // Refuse a recovery action whose flag this launch lacks before the parent is
97
+ // closed, naming the parent flag; the cm-fix dispatcher still re-checks it.
98
+ const actionFlag=acting?QA_FIX_ACTION_FLAGS[value.fixOperation]:undefined;
99
+ if(actionFlag&&!permissions.includes(actionFlag))return actionRefusal(value.fixOperation,'qa_fix_action_authorization_required',
100
+ `fix_action ${value.fixOperation} 需要父宿主启动参数 ${parentFlag(actionFlag)}(等同单独 cm-fix-host 的 ${actionFlag});关闭父宿主,带上该参数以 --mode resume 重开后再发 fix_action。`);
77
101
  busy=true;let child=null,released=false,result;
78
102
  try{
79
103
  const status=await current.host.handle({version:1,operation:'status',requestId:value.requestId,identity:value.identity});
@@ -89,10 +113,21 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
89
113
  let actionResult;
90
114
  if(advancing||acting){
91
115
  const host=createFixHost({owner:child,config:{...definition.configuration,specsRoot:definition.specsRoot,identity:definition.identity},
92
- runtime:definition.configuration.runtime??'codex',permissions:[...permissions,'--allow-reproduction'],...fixAuthorities});
93
- actionResult=running?await host.run(value.requestId)
94
- :await host.handle({requestId:value.requestId,operation:advancing?'advance':value.fixOperation,
95
- ...(value.fixOperation==='reconcile_review'?{invocationId:value.invocationId}:{}),...(['abandon_step','abandon_review'].includes(value.fixOperation)?{reason:value.reason}:{})});
116
+ runtime:definition.configuration.runtime??'codex',permissions:[...permissions,'--allow-reproduction'],...fixAuthorities,recoveryInvocationId});
117
+ const action=advancing?{operation:'advance'}:{operation:value.fixOperation,
118
+ ...(value.fixOperation==='reconcile_review'?{invocationId:value.invocationId}:{}),
119
+ ...(QA_FIX_REASONED.includes(value.fixOperation)?{reason:value.reason}:{}),
120
+ ...(value.fixOperation==='prepare_revision'&&Object.hasOwn(value,'tests')?{tests:value.tests}:{}),
121
+ ...(value.fixOperation==='recover_final_review'?{invocationId:value.invocationId,packageDigest:value.reviewPackageDigest,
122
+ previousInvocationStopped:value.previousInvocationStopped,reason:value.reason}:{})};
123
+ try{actionResult=running?await host.run(value.requestId):await host.handle({requestId:value.requestId,...action});}
124
+ catch(error){
125
+ // A refused recovery action is the original cm-fix refusal, reported with
126
+ // its code instead of an opaque host failure; the parent still reopens.
127
+ if(!(acting&&actionFlag&&typeof error?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(error.code)))throw error;
128
+ return actionRefusal(value.fixOperation,error.code,
129
+ `cm-fix 拒绝了 ${value.fixOperation}(${error.code}):子运行当前阶段不满足该操作的条件或参数不匹配;先用 fix_status 核对 fixStage 与 progress,再按 skills/cm-fix/references/js-host.md 的条件重发。`);
130
+ }
96
131
  }
97
132
  // Original observation/escalation finish intentionally closes its owner. Preserve
98
133
  // that successful incomplete exit without reading a closed store.
@@ -15,7 +15,7 @@ export function parseHostInputLimit(raw){
15
15
  &&value>=LIMIT&&value<=4*1024*1024,'invalid_arguments');
16
16
  return value;
17
17
  }
18
- const operationNames=new Set(['repair_review_response','reconcile_review','rediagnose','replace_inputs','read_batch','recover_final_review','abandon_step','abandon_review','abandon_effect','bootstrap_review_recover','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
18
+ const operationNames=new Set(['repair_review_response','reconcile_review','rediagnose','replace_inputs','read_batch','recover_final_review','abandon_step','abandon_review','rerun_blocked_step','abandon_effect','bootstrap_review_recover','develop_redo','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
19
19
  'context_refresh','finish','completion_evidence','run_finalize','review_findings','review_disposition','save_draft','save_design','correct_findings','prepare_summary','publish_summary','inspect_correction','resume_correction','cancel','resume','prepare_judge_revision','cause_review_package','cause_review','red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression','publish_dossier','walkthrough']);
20
20
 
21
21
  // Which contract codes may reach the peer is a deliberate boundary: the host
@@ -15,12 +15,43 @@ function waitNotice(kind,callId){
15
15
  return ()=>{cancelled=true;cancel?.();};
16
16
  }
17
17
 
18
- export function createHostToolBridge({responseLimit=64*1024}={}){
18
+ // Every call has a deadline (R0). A call without its own timeoutMs waits at most
19
+ // the host answer limit: CM_HOST_ANSWER_TIMEOUT_MINUTES (integer 1-60, default 30).
20
+ // It is read when the host starts and is never journaled, so it changes no run
21
+ // fingerprint and a resumed run may use another value. Hosts whose calls already
22
+ // run under their own budget (cm-ai, cm-ai batch, cm-fix: at most 60 minutes)
23
+ // pass HOST_ANSWER_BACKSTOP_MS, which never fires before that budget.
24
+ export const HOST_ANSWER_TIMEOUT_DEFAULT_MS=30*60000;
25
+ export const HOST_ANSWER_TIMEOUT_MAX_MS=60*60000;
26
+ export const HOST_ANSWER_BACKSTOP_MS=HOST_ANSWER_TIMEOUT_MAX_MS+60000;
27
+ export function hostAnswerTimeoutMs(env=process.env){
28
+ const raw=env.CM_HOST_ANSWER_TIMEOUT_MINUTES;
29
+ if(raw===undefined||raw==='')return HOST_ANSWER_TIMEOUT_DEFAULT_MS;
30
+ need(/^[1-9][0-9]?$/.test(raw)&&Number(raw)<=60,'host_answer_timeout_invalid');
31
+ return Number(raw)*60000;
32
+ }
33
+ // Every kind a workflow host may ask the session. A kind missing here makes
34
+ // that step throw host_operation_invalid on every attempt (O20: the second-round
35
+ // refactor judge revision, refactor_revise_tests, was missing).
36
+ export const HOST_CALL_KINDS=Object.freeze(['develop','check','verification_precheck','check_runtime','check_semantic','qa_assess','qa_logic','qa_browser','change_impact','test_cases','refactor_analyze','refactor_confirm','refactor_apply','refactor_review','refactor_batch','refactor_prepare_tests','refactor_revise_tests','refactor_retrospective','refactor_recover','documentation_sync','documentation_inspect','fix_diagnose','fix_learning','fix_test_author','fix_repair','fix_retrospective','init_analyze','init_generate','init_verify','init_confirm','init_review','init_write','idea_interview','idea_confirm_save','prd_analyze','prd_materials','prd_generate','prd_self_check','prd_review','prd_correct','prd_summary']);
37
+ // Answers that first run the project's own commands (test suites, builds,
38
+ // devices) normally take tens of minutes; they always get the 60-minute maximum.
39
+ const COMMAND_KINDS=new Set(['check','verification_precheck','init_verify','check_runtime','qa_logic','qa_browser']);
40
+ // A late answer (its call already stopped by the deadline or a cancel) is refused
41
+ // with one diagnostic line; it never reaches the step that stopped waiting.
42
+ const LATE_CALLS=32;
43
+ const lateDiagnostic=fields=>{try{process.stderr.write(JSON.stringify({diagnostic:'host_response_late',...fields})+'\n');}catch{}};
44
+
45
+ export function createHostToolBridge({responseLimit=64*1024,answerTimeoutMs=hostAnswerTimeoutMs()}={}){
19
46
  need(Number.isSafeInteger(responseLimit)&&responseLimit>=64*1024&&responseLimit<=4*1024*1024,'host_response_limit_invalid');
47
+ need(Number.isSafeInteger(answerTimeoutMs)&&answerTimeoutMs>=1000&&answerTimeoutMs<=HOST_ANSWER_BACKSTOP_MS,'host_answer_timeout_invalid');
20
48
  const sessionId=randomUUID();let send=null,pending=null,closed=false;
49
+ const stopped=new Map();
21
50
  const stop=(code,call=pending)=>{
22
51
  if(!call||pending!==call)return;pending=null;clearTimeout(call.timer);call.notice?.();
23
52
  call.signal.removeEventListener('abort',call.abort);
53
+ if(code!=='host_disconnected'){stopped.set(call.request.callId,{kind:call.request.kind,stoppedBy:code});
54
+ if(stopped.size>LATE_CALLS)stopped.delete(stopped.keys().next().value);}
24
55
  call.reject(Object.assign(new Error(code),{code}));
25
56
  };
26
57
  return Object.freeze({
@@ -30,8 +61,7 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
30
61
  },
31
62
  call(kind,payload,signal,{timeoutMs=null}={}){
32
63
  need(send!==null&&!closed,'host_bridge_unavailable');need(pending===null,'host_bridge_busy');
33
- need(['develop','check','verification_precheck','check_runtime','check_semantic','qa_assess','qa_logic','qa_browser','change_impact','test_cases','refactor_analyze','refactor_confirm','refactor_apply','refactor_review','refactor_batch','refactor_prepare_tests','refactor_retrospective','refactor_recover','documentation_sync','documentation_inspect','fix_diagnose','fix_learning','fix_test_author','fix_repair','fix_retrospective','init_analyze','init_generate','init_verify','init_confirm','init_review','init_write','idea_interview','idea_confirm_save','prd_analyze','prd_materials','prd_generate','prd_self_check','prd_review','prd_correct','prd_summary']
34
- .includes(kind),'host_operation_invalid');need(!signal.aborted,'cancelled');
64
+ need(HOST_CALL_KINDS.includes(kind),'host_operation_invalid');need(!signal.aborted,'cancelled');
35
65
  const data=json({kind,payload},12*1024*1024);
36
66
  const request={type:'host_request',sessionId,callId:randomUUID(),requestDigest:digest(data),...data};
37
67
  need(timeoutMs===null||Number.isSafeInteger(timeoutMs)&&timeoutMs>0&&timeoutMs<=3600000,'host_request_timeout_invalid');
@@ -42,6 +72,9 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
42
72
  };
43
73
  const call={request,signal,abort,resolve,reject,timer:null,notice:waitNotice(kind,request.callId)};pending=call;
44
74
  if(timeoutMs!==null)call.timer=setTimeout(()=>stop('host_request_timeout',call),timeoutMs);
75
+ // The default deadline never keeps an otherwise finished process alive.
76
+ else {call.timer=setTimeout(()=>stop('host_request_timeout',call),
77
+ COMMAND_KINDS.has(kind)?Math.max(answerTimeoutMs,HOST_ANSWER_TIMEOUT_MAX_MS):answerTimeoutMs);call.timer.unref?.();}
45
78
  signal.addEventListener('abort',abort,{once:true});
46
79
  if(signal.aborted){abort();return;}
47
80
  Promise.resolve().then(()=>{
@@ -57,6 +90,10 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
57
90
  closed=true;stop('host_disconnected');return {accepted:true,closing:true};
58
91
  }
59
92
  reply=json(raw,responseLimit);shape(reply,['type','sessionId','callId','requestDigest','result']);
93
+ const late=reply.type==='host_result'&&reply.sessionId===sessionId&&pending?.request.callId!==reply.callId
94
+ ?stopped.get(reply.callId):undefined;
95
+ if(late){lateDiagnostic({kind:late.kind,callId:reply.callId,stoppedBy:late.stoppedBy});
96
+ return {accepted:false,code:'host_response_late'};}
60
97
  need(reply.type==='host_result'&&pending!==null&&!closed,'host_response_mismatch');
61
98
  for(const key of ['sessionId','callId','requestDigest'])need(reply[key]===pending.request[key],'host_response_mismatch');
62
99
  }catch(error){return {accepted:false,code:error?.code==='limit_exceeded'?'host_response_too_large':'host_response_mismatch'};}