@aibyzero/cm-workflow 0.16.9 → 0.17.1

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 (165) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +18 -1
  4. package/CONTRIBUTING.md +47 -0
  5. package/README.md +16 -1
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +29 -13
  8. package/docs/cm-control-policy-v2.md +331 -0
  9. package/docs/execution-optimizations.md +1 -1
  10. package/docs/external-models.md +3 -3
  11. package/docs/fixes/20261013-claude-preinit-ui-invalidate.md +48 -0
  12. package/docs/human-correction.md +5 -5
  13. package/docs/installation.md +1 -1
  14. package/docs/js-workflow-control.md +104 -85
  15. package/docs/next-steps.md +11 -0
  16. package/docs/untested-branches.md +2 -3
  17. package/docs/user-guide.md +3 -3
  18. package/package.json +1 -1
  19. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -8
  20. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +13 -69
  21. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +10 -5
  22. package/runtime/js/cm-ai/control-policy.mjs +112 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  24. package/runtime/js/cm-ai/drive-core.mjs +124 -25
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +32 -126
  26. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  27. package/runtime/js/cm-ai/host-check.mjs +3 -1
  28. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -20
  29. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  30. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  31. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  32. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  33. package/runtime/js/cm-ai/host-session.mjs +41 -8
  34. package/runtime/js/cm-ai/host-stage-observer.mjs +26 -0
  35. package/runtime/js/cm-ai/host-tool-bridge.mjs +25 -9
  36. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  37. package/runtime/js/cm-ai/host.mjs +1 -2
  38. package/runtime/js/cm-ai/operator-guidance.mjs +57 -54
  39. package/runtime/js/cm-ai/review-package.mjs +16 -4
  40. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  41. package/runtime/js/cm-ai/task-runner.mjs +41 -101
  42. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  43. package/runtime/js/cm-prd/review-host.mjs +1 -1
  44. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  45. package/runtime/js/cm-prd/summary.mjs +27 -12
  46. package/runtime/js/cm-refactor/workflow.mjs +1 -1
  47. package/runtime/js/notify-send.mjs +15 -14
  48. package/runtime/js/notify.mjs +27 -4
  49. package/runtime/js/policy-binding-compat.mjs +2 -1
  50. package/runtime/review.md +61 -7
  51. package/runtime/task-gates.md +107 -9
  52. package/scripts/cm-ai-abandon-effect-position.test.mjs +1 -8
  53. package/scripts/cm-ai-answer-gap-driver.test.mjs +12 -12
  54. package/scripts/cm-ai-answer-gap-fixture.mjs +1 -8
  55. package/scripts/cm-ai-batch-drive.mjs +50 -31
  56. package/scripts/cm-ai-batch-drive.test.mjs +62 -19
  57. package/scripts/cm-ai-batch-host.mjs +39 -20
  58. package/scripts/cm-ai-batch-host.test.mjs +83 -47
  59. package/scripts/cm-ai-batch-run-fixture.mjs +6 -53
  60. package/scripts/cm-ai-batch-run-member-stops.test.mjs +0 -12
  61. package/scripts/cm-ai-batch-run.mjs +46 -14
  62. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  63. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  64. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  65. package/scripts/cm-ai-control-policy.test.mjs +192 -0
  66. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  67. package/scripts/cm-ai-develop-answer-invalid.test.mjs +1 -8
  68. package/scripts/cm-ai-develop-call-timeout.test.mjs +1 -8
  69. package/scripts/cm-ai-develop-driver-gaps.test.mjs +33 -20
  70. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  71. package/scripts/cm-ai-documentation-sync-gap.test.mjs +3 -3
  72. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +57 -27
  73. package/scripts/cm-ai-drive.mjs +96 -54
  74. package/scripts/cm-ai-drive.test.mjs +46 -87
  75. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  76. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  77. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  78. package/scripts/cm-ai-host-cli-workflow.test.mjs +6 -10
  79. package/scripts/cm-ai-host-fixture.mjs +47 -16
  80. package/scripts/cm-ai-host-protected.test.mjs +35 -33
  81. package/scripts/cm-ai-host.mjs +103 -93
  82. package/scripts/cm-ai-host.test.mjs +34 -18
  83. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  84. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  85. package/scripts/cm-ai-light-modules.test.mjs +4 -7
  86. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  87. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  88. package/scripts/cm-ai-operator-guidance.test.mjs +56 -0
  89. package/scripts/cm-ai-progress.test.mjs +10 -8
  90. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  91. package/scripts/cm-ai-protected-scope.test.mjs +1 -2
  92. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  93. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  94. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -3
  95. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  96. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  97. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +3 -4
  98. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  99. package/scripts/cm-ai-review-failure.test.mjs +13 -19
  100. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  101. package/scripts/cm-ai-review-timeout.test.mjs +35 -128
  102. package/scripts/cm-ai-run.mjs +78 -24
  103. package/scripts/cm-ai-run.test.mjs +11 -38
  104. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  105. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  106. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  107. package/scripts/cm-ai-supersede.test.mjs +3 -10
  108. package/scripts/cm-blocked-reason.test.mjs +2 -3
  109. package/scripts/cm-capability-gate.test.mjs +33 -1
  110. package/scripts/cm-check-drive-files.mjs +1 -1
  111. package/scripts/cm-check-host.test.mjs +1 -1
  112. package/scripts/cm-check-runtime.sh +1 -1
  113. package/scripts/cm-claude-probe.test.mjs +26 -0
  114. package/scripts/cm-claude-review-stream.test.mjs +36 -0
  115. package/scripts/cm-claude-worker.test.mjs +21 -3
  116. package/scripts/cm-controlled-correction.test.mjs +469 -0
  117. package/scripts/cm-drive-liveness.test.mjs +83 -0
  118. package/scripts/cm-external-batch-host.test.mjs +38 -17
  119. package/scripts/cm-external-model-host.test.mjs +1 -1
  120. package/scripts/cm-external-model-recovery.test.mjs +3 -9
  121. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  122. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  123. package/scripts/cm-fix-review-recovery.test.mjs +1 -1
  124. package/scripts/cm-host-diagnostic.test.mjs +33 -0
  125. package/scripts/cm-host-liveness.test.mjs +150 -0
  126. package/scripts/cm-host-qa-executor.test.mjs +1 -2
  127. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  128. package/scripts/cm-host-review-authority.test.mjs +0 -31
  129. package/scripts/cm-host-stage-observer.test.mjs +41 -0
  130. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  131. package/scripts/cm-notify-command.test.mjs +54 -18
  132. package/scripts/cm-notify-read-drift.test.mjs +69 -4
  133. package/scripts/cm-notify.mjs +16 -4
  134. package/scripts/cm-notify.test.mjs +135 -29
  135. package/scripts/cm-patrol.test.mjs +3 -2
  136. package/scripts/cm-prd-drive.test.mjs +1 -1
  137. package/scripts/cm-prd-self-check-revision.test.mjs +15 -0
  138. package/scripts/cm-prd-session-recovery.test.mjs +5 -3
  139. package/scripts/cm-prd-summary.test.mjs +31 -0
  140. package/scripts/cm-release-smoke.sh +2 -14
  141. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  142. package/scripts/cm-task-gate.mjs +368 -34
  143. package/scripts/cm-task-gate.py +2 -0
  144. package/scripts/cm-task-gate.test.mjs +252 -4
  145. package/scripts/cm-test-suite.mjs +109 -0
  146. package/scripts/cm-test-suite.test.mjs +162 -0
  147. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  148. package/scripts/fixtures/host-diagnostic.mjs +33 -0
  149. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  150. package/scripts/policy-binding-compat.test.mjs +4 -0
  151. package/skills/cm-ai/SKILL.md +8 -6
  152. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  153. package/skills/cm-ai/references/N4-review.md +11 -21
  154. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  155. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  156. package/skills/cm-ai/references/js-host-modes.md +35 -14
  157. package/skills/cm-ai/references/js-host-qa-recovery.md +60 -12
  158. package/skills/cm-ai/references/js-host-recovery.md +95 -47
  159. package/skills/cm-ai/references/js-host.md +98 -29
  160. package/skills/cm-fix/SKILL.md +12 -0
  161. package/skills/cm-init/references/js-host.md +1 -1
  162. package/skills/cm-prd/references/js-host.md +1 -1
  163. package/skills/cm-refactor/SKILL.md +12 -0
  164. package/runtime/js/cm-ai/review-dispatch-limits.mjs +0 -18
  165. package/scripts/cm-ai-review-dispatch-exit.test.mjs +0 -475
@@ -61,15 +61,22 @@ export function deliberatelyUnanswered(message){
61
61
  if(!deliberateStop){deliberateStop=true;process.on('exit',()=>{process.exitCode=2;});}
62
62
  return Object.assign(new Error(message),{code:'confirm_reask_decision_required'});
63
63
  }
64
- export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor,beforeRequest=null}){
65
- const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe']});
64
+ // Transport-only budgets: no field is added to a run or its configuration hash.
65
+ // The long fallback covers hosts that cannot advertise individual phase budgets.
66
+ export const DRIVE_LIVENESS_DEFAULTS=Object.freeze({startupMs:60000,operationMs:21600000,
67
+ heartbeatMs:30000,graceMs:30000,closeMs:5000,killMs:1000,pollMs:250});
68
+ export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor,beforeRequest=null,liveness={}}){
69
+ const budget={...DRIVE_LIVENESS_DEFAULTS,...liveness};
70
+ for(const value of Object.values(budget))if(!Number.isSafeInteger(value)||value<1)throw Error('driver_liveness_invalid');
71
+ const ownGroup=process.platform!=='win32';
72
+ const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe'],detached:ownGroup,
73
+ env:{...process.env,CM_HOST_HEARTBEAT:'1'}});
66
74
  const control=new AbortController();
67
75
  child.stderr.on('data',chunk=>process.stderr.write(chunk));
68
- // After a rejected reply the session is ended; later rows get no answer.
69
- const send=value=>{if(!child.stdin.writableEnded)child.stdin.write(JSON.stringify(value)+'\n');};
70
76
  let done=false,refused=false,rejected=null,unanswered=false,finalRow=null,noticed=false,failureCode=null;
71
- // Optional stuck/done notice (runtime/js/notify.mjs): decided once when the
72
- // host is gone. It is loaded lazily and can never change exit code or output.
77
+ let sessionId=null,ready=false,heartbeat=false,lastBeat=0,waitingFor='drive',stopping=false,closed=false;
78
+ let deadline=Date.now()+budget.startupMs,phase='startup',closeDeadline=null,killTimer=null,forceTimer=null;
79
+ // Optional notices never change the result or make watchdog failures successful.
73
80
  const notice=failure=>{
74
81
  if(noticed)return;noticed=true;
75
82
  if(rejected!==null)failure='host_response_rejected';else if(!failure&&unanswered&&!finalRow)failure='host_request_unanswered';
@@ -78,51 +85,143 @@ export function driveHost({host,args,cwd,operation,request={},answers,paths,answ
78
85
  return fields?notify(fields):null;
79
86
  }).catch(()=>{});
80
87
  };
81
- readline.createInterface({input:child.stdout}).on('line',async line=>{
88
+ const signalOwnHost=(signal,cleanup=false)=>{
89
+ if((closed&&!cleanup)||!child.pid)return;
90
+ try{if(ownGroup)process.kill(-child.pid,signal);else child.kill(signal);}catch{}
91
+ };
92
+ const fail=(code,reason,message)=>{
93
+ if(stopping||closed)return;
94
+ stopping=true;failureCode=reason;control.abort();process.exitCode=code;
95
+ stderr(`${reason}:${message};未写入成功或取消结果;清理仅覆盖本驾驶员创建的进程组,脱离该组的后代须另行核对,恢复前请核对原运行`);
96
+ // Only the process/group created here is eligible for cleanup. Never inspect
97
+ // or signal PIDs received from a host message or another run's heartbeat.
98
+ signalOwnHost('SIGTERM');
99
+ killTimer=setTimeout(()=>{
100
+ signalOwnHost('SIGKILL',true);
101
+ if(closed)return;
102
+ forceTimer=setTimeout(()=>{child.stdin.destroy();child.stdout.destroy();child.stderr.destroy();child.unref();clearInterval(watchdog);notice(failureCode);},budget.killMs);
103
+ forceTimer.unref();
104
+ },budget.killMs);
105
+ // Keep cleanup alive after the host exits: same-group workers can ignore
106
+ // SIGTERM and use stdio:ignore, so child.close does not prove group exit.
107
+ };
108
+ const send=value=>{
109
+ if(stopping||closed)return;
110
+ if(child.stdin.destroyed||child.stdin.writableEnded){fail(74,'host_pipe_closed','宿主输入管道没有可写端');return;}
111
+ try{child.stdin.write(JSON.stringify(value)+'\n',error=>{if(error)fail(74,'host_pipe_closed','宿主输入管道已关闭,无法发送请求');});}
112
+ catch{fail(74,'host_pipe_closed','宿主输入管道已关闭,无法发送请求');}
113
+ };
114
+ const closeHost=force=>{
115
+ if(stopping||closed)return;
116
+ closeDeadline=Date.now()+budget.closeMs;
117
+ if(force)stderr('显式 force 关闭无法继续应答的宿主;在途步骤可能进入 unknown,请核对原运行');
118
+ send({type:'host_close',sessionId,...(force?{force:true}:{})});
119
+ if(force&&!heartbeat){
120
+ stderr('旧宿主未声明关闭握手能力:已显式请求 force,随后结束输入以兼容旧宿主;在途步骤可能进入 unknown');
121
+ child.stdin.end();
122
+ }
123
+ };
124
+ const phaseDeadlines=new Map();
125
+ const phaseBudget=inFlight=>{
126
+ const candidates=[];
127
+ for(const [prefix,value,id] of [['call',inFlight?.call,inFlight?.call?.callId],
128
+ ['native',inFlight?.nativeStage,inFlight?.nativeStage?.id]]){
129
+ if(typeof id!=='string'||!Number.isSafeInteger(value?.deadlineMs))continue;
130
+ const key=`${prefix}:${id}`;
131
+ // Keep the first announced deadline, including while a nested phase is
132
+ // active. A heartbeat or return to its enclosing phase cannot extend it.
133
+ if(!phaseDeadlines.has(key))phaseDeadlines.set(key,value.deadlineMs+budget.graceMs);
134
+ candidates.push({key,deadline:phaseDeadlines.get(key)});
135
+ }
136
+ if(candidates.length){phase=candidates.map(item=>item.key).join('|');deadline=Math.min(...candidates.map(item=>item.deadline));}
137
+ else if(phase!=='operation'){phase='operation';deadline=Date.now()+budget.operationMs;}
138
+ };
139
+ const watchdog=setInterval(()=>{
140
+ if(stopping||closed)return;
141
+ const now=Date.now();
142
+ if(closeDeadline!==null){if(now>closeDeadline)fail(failureCode==='host_exited'?71:75,failureCode==='host_exited'?'host_exited':'host_close_timeout','宿主或其继承管道未在关闭期限内退出');return;}
143
+ if(ready&&heartbeat&&now-lastBeat>budget.heartbeatMs){fail(72,'host_heartbeat_timeout','宿主心跳超时,进程可能已卡死');return;}
144
+ if(now>deadline)fail(ready?73:70,ready?'host_stage_timeout':'host_start_timeout',ready?'当前阶段超过已声明期限或有界后备期限':'宿主未在启动期限内发出 host_ready');
145
+ },budget.pollMs);
146
+ child.stdin.on('error',()=>fail(74,'host_pipe_closed','宿主输入管道已关闭,无法继续写入'));
147
+ child.stdin.on('close',()=>{if(!done&&!refused&&!unanswered&&rejected===null&&!stopping&&!closed&&failureCode!=='host_exited')fail(74,'host_pipe_closed','宿主输入管道提前关闭');});
148
+ const lines=readline.createInterface({input:child.stdout});
149
+ lines.on('line',async line=>{
82
150
  let row;try{row=JSON.parse(line);}catch{process.stdout.write(line+'\n');return;}
151
+ if(stopping||closed||done)return;
152
+ if(row.type==='host_heartbeat'){
153
+ if(ready&&heartbeat&&row.sessionId===sessionId){lastBeat=Date.now();phaseBudget(row.inFlight);}
154
+ return;
155
+ }
83
156
  if(row.type==='host_ready'){
157
+ if(ready)return;
158
+ ready=true;sessionId=row.sessionId;heartbeat=Boolean(row.heartbeat);lastBeat=Date.now();
159
+ phase='operation';deadline=Date.now()+budget.operationMs;
84
160
  if(beforeRequest){
85
161
  let refusal;
86
162
  try{refusal=await beforeRequest();}catch(error){refusal=`发送操作前的准备失败:${error.message}`;}
87
- if(refusal){refused=true;failureCode='driver_refused';stderr(refusal);process.exitCode=2;send({type:'host_close',sessionId:row.sessionId});child.stdin.end();return;}
163
+ if(stopping||closed)return;
164
+ if(refusal){refused=true;failureCode='driver_refused';stderr(refusal);process.exitCode=2;closeHost(false);return;}
88
165
  }
89
166
  send({requestId:'drive',operation,...request});return;
90
167
  }
91
168
  if(row.type==='host_request'){
169
+ if(done||unanswered||rejected!==null)return;
92
170
  let result;
93
171
  try{result=await answerFor(row,answers,paths,{signal:control.signal});}catch(error){stderr(`应答 ${row.kind} 失败:${error.message}`);result=null;}
94
- if(control.signal.aborted)return;
172
+ if(control.signal.aborted||stopping||closed)return;
95
173
  if(result===null){
96
- unanswered=true;
97
- stderr(`宿主问了预检没覆盖的问题 ${row.kind},无法应答;这一步会留在 unknown`);
98
- send({type:'host_close',sessionId:row.sessionId});return;
174
+ unanswered=true;process.exitCode=deliberateStop?2:1;
175
+ stderr(`宿主问了预检没覆盖的问题 ${row.kind},无法应答`);
176
+ closeHost(true);return;
99
177
  }
100
178
  stderr(`应答 ${row.kind}`);
101
179
  send({type:'host_result',sessionId:row.sessionId,callId:row.callId,requestDigest:row.requestDigest,result});
102
180
  return;
103
181
  }
104
182
  if(row.type==='host_response'){
183
+ if(row.code==='host_close_busy'){
184
+ stderr('host_close_busy:宿主仍有在途工作;继续等待原请求结果');closeDeadline=null;return;
185
+ }
186
+ if(row.accepted===true&&row.closing===true){child.stdin.end();return;}
105
187
  if(row.accepted===false&&rejected===null){
106
- rejected=typeof row.code==='string'?row.code:'host_response_rejected';
107
- control.abort();
108
- stderr(`宿主拒收了应答:${rejected};${rejectedReplyHint(rejected)}。驾驶员不再等待,已结束会话;宿主会把这一步记为 unknown`);
109
- child.stdin.end();
188
+ rejected=typeof row.code==='string'?row.code:'host_response_rejected';control.abort();process.exitCode=1;
189
+ stderr(`宿主拒收了应答:${rejected};${rejectedReplyHint(rejected)}`);
190
+ closeHost(true);
110
191
  }
111
192
  return;
112
193
  }
113
- if(row.requestId==='drive'){
114
- done=true;finalRow=row;
115
- control.abort();
194
+ if(row.requestId===waitingFor||row.requestId==='drive'){
195
+ if(row.error?.code==='host_busy'){
196
+ const inFlight=row.error.inFlight;
197
+ if(typeof inFlight?.requestId==='string')waitingFor=inFlight.requestId;
198
+ phaseBudget(inFlight);stderr(`host_busy:上一步仍在执行,继续等待 ${waitingFor} 的结果`);return;
199
+ }
200
+ done=true;finalRow=row;control.abort();
116
201
  process.stdout.write(JSON.stringify(row,null,2)+'\n');
117
202
  const guidance=guidanceText(row.result);if(guidance)stderr(guidance);
118
203
  if(row.result?.stage)stderr(`stage = ${row.result.stage}`);
119
204
  if(row.error)stderr(`宿主拒绝:${row.error.code}(真实原因和位置在上面 [host] 那行 diagnostic 里)`);
120
- process.exitCode=hostResponseFailed(row)||rejected!==null?1:0;
121
- child.stdin.end();
205
+ process.exitCode=deliberateStop||refused?2:hostResponseFailed(row)||rejected!==null||unanswered?1:0;
206
+ // Normal EOF follows a final result. The explicit force compatibility
207
+ // path for a legacy host is separately logged by closeHost above.
208
+ closeDeadline=Date.now()+budget.closeMs;child.stdin.end();
209
+ }
210
+ });
211
+ child.on('error',()=>fail(71,'host_start_failed','宿主进程无法启动'));
212
+ child.on('exit',(code,signal)=>{
213
+ control.abort();
214
+ if(!done&&!refused&&!stopping&&!unanswered&&rejected===null){
215
+ failureCode='host_exited';stderr(`host_exited:宿主在给出结果前退出了,exit ${code},signal ${signal??'none'}`);process.exitCode=71;closeDeadline=Date.now()+budget.closeMs;
122
216
  }
123
217
  });
124
- child.on('error',error=>{control.abort();stderr(`宿主启动失败:${error.message}`);process.exitCode=1;notice('host_start_failed');});
125
- child.on('exit',code=>{control.abort();if(!done&&!refused){stderr(`宿主在给出结果前退出了,exit ${code}`);process.exitCode=1;}});
126
- // 'close' waits for the host's stdout, so a final row still in flight is seen.
127
- child.on('close',()=>notice(failureCode??(done?null:'host_exited')));
218
+ // close drains stdout so a buffered final result can still determine outcome.
219
+ child.on('close',()=>{
220
+ // stdout has drained now; absence of a final result is definitive. Clean
221
+ // this spawn's process group even if ignored stdio let its leader close.
222
+ if(!done&&!refused&&!unanswered&&rejected===null&&!stopping)fail(71,'host_exited','宿主未返回结果,清理其在途进程组');
223
+ closed=true;control.abort();clearInterval(watchdog);
224
+ if(!stopping)clearTimeout(killTimer);
225
+ clearTimeout(forceTimer);lines.close();notice(failureCode??(done?null:'host_exited'));
226
+ });
128
227
  }
@@ -1,4 +1,5 @@
1
1
  import {readExecutionPolicy} from './execution-policy.mjs';
2
+ import {readControlPolicy} from './control-policy.mjs';
2
3
  import {readExternalModels} from './external-models.mjs';
3
4
  import {beforeFirstQaRound,qaRevisionFollows,readQaConfigRevision} from './qa-config-revision.mjs';
4
5
  import {readCloseoutPolicy} from './knowledge-closeout.mjs';
@@ -21,10 +22,6 @@ import {identifyApprovedBootstrapFeature} from './bootstrap-feature.mjs';
21
22
  import {readSpecificationRebind} from './specification-material.mjs';
22
23
  import {protectedScopePaths} from './developer-adapter.mjs';
23
24
  import {validWorkerPid,validStartTime} from './worker-process-identity.mjs';
24
- import {MAX_REVIEW_NOT_DISPATCHED_RETRIES,MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS,REVIEW_NOT_DISPATCHED_LIMIT_CODE,MAX_REVIEW_DENIAL_CONFIRMATIONS,
25
- REVIEW_DENIAL_LIMIT_CODE,REVIEW_NEVER_STARTED_MANUAL_STEP} from './review-dispatch-limits.mjs';
26
- export {MAX_REVIEW_NOT_DISPATCHED_RETRIES,MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS,REVIEW_NOT_DISPATCHED_LIMIT_CODE,MAX_REVIEW_DENIAL_CONFIRMATIONS,
27
- REVIEW_DENIAL_LIMIT_CODE,REVIEW_NEVER_STARTED_MANUAL_STEP};
28
25
 
29
26
  const LIMIT=16*1024*1024;
30
27
  // The developer adapter refuses a protected scope on every dispatch, before any
@@ -41,8 +38,7 @@ const uuid=s=>need(typeof s==='string' && /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}
41
38
  const states=['ready','awaiting_review','approved','changes_requested','fixture_completed','blocked','unknown','cancelled','pending_review'];
42
39
  export const stageAllowed=(kind,state,code=null,reviewVerdict=null)=>
43
40
  kind==='develop'&&state==='blocked'&&['developer_result_invalid','verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed','bootstrap_instruction_conflict','develop_call_timeout','develop_answer_invalid',...RECHECK_CODES,DEVELOP_REDO_CODE,DISPATCH_RETRY_CODE,DEVELOP_INTERRUPTED_CODE,...DOCUMENTATION_SYNC_CODES].includes(code)
44
- ||kind==='review'&&state==='pending_review'&&(REVIEW_RETRY_CODES.includes(code)||REVIEW_NOT_DISPATCHED_CODES.includes(code)
45
- ||code===REVIEW_DENIAL_CONFIRMED_CODE)
41
+ ||kind==='review'&&state==='pending_review'&&REVIEW_RETRY_CODES.includes(code)
46
42
  ||kind==='complete'&&state==='blocked'&&(['completion_checks_changed','completion_package_changed',COMPLETE_RECHECK_CODE].includes(code)
47
43
  ||code==='review_package_changed'&&reviewVerdict==='approved')
48
44
  ||kind==='develop'&&state==='blocked'&&code==='review_package_changed'&&reviewVerdict==='changes_requested'
@@ -61,72 +57,6 @@ export const reviewerFailure=result=>result?.outcome==='failed'&&result.reconcil
61
57
  export const reviewRetryCode=result=>reviewTransportTimeout(result)?'review_transport_timeout'
62
58
  :reviewerFailure(result)?(result.inspection.category==='verdict'?'review_verdict_invalid':'review_provider_failed'):null;
63
59
  export const REVIEW_RETRY_CODES=Object.freeze(['review_transport_timeout','review_abandoned','review_provider_failed','review_verdict_invalid']);
64
- // A review registered but never handed to the reviewer: the dispatch grant had
65
- // expired, or the dispatch clock ran backwards (task-runner, outcome not_dispatched,
66
- // call started:false). No reviewer process ran and no verdict exists, so nothing has
67
- // to be proven stopped: the round may dispatch again under a fresh grant (new effect
68
- // id, same review round). Such an effect holds no call or effect slot. Only the
69
- // runner's not_dispatched halt yields pending_review with these codes.
70
- export const REVIEW_NOT_DISPATCHED_CODES=Object.freeze(['grant_expired','clock_invalid']);
71
- const notDispatchedEffect=entry=>entry.effect.kind==='review'&&entry.result.state==='pending_review'
72
- &&REVIEW_NOT_DISPATCHED_CODES.includes(entry.result.code)&&entry.result.reviewInvocation?.result?.outcome==='not_dispatched';
73
- // Bounded on its own (it holds no call or effect slot): at most two such redispatches
74
- // per review round, like the no-result ones. The count is the round's not-dispatched
75
- // effects in the checkpointed cache, so live and replay read the same number; once the
76
- // round's latest end is the third, no review effect is admitted (live and replay) and
77
- // status shows the explicit limit block. The limit has one audited exit: the operator's
78
- // confirmation (abandon_review + reason, journaled as review-dispatch-confirmed) grants
79
- // MAX_REVIEW_NOT_DISPATCHED_RETRIES more, at most MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS
80
- // per round, so the retry cap (R2) is never defeated, only extended on the record.
81
- export const reviewNotDispatchedCount=(cache,attempt)=>cache.filter(entry=>entry.effect.identity.attempt===attempt&&notDispatchedEffect(entry)).length;
82
- export const reviewNotDispatchedExhausted=(s,extended=0)=>s.state==='pending_review'&&REVIEW_NOT_DISPATCHED_CODES.includes(s.code)
83
- &&reviewNotDispatchedCount(s.cache,s.attempt)>MAX_REVIEW_NOT_DISPATCHED_RETRIES*(1+extended);
84
- export const reviewNotDispatchedExtendable=(s,confirmed)=>reviewNotDispatchedExhausted(s,confirmed.extended)
85
- &&confirmed.extended<MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS
86
- &&s.cache.at(-1)!==undefined&&notDispatchedEffect(s.cache.at(-1))&&s.cache.at(-1).effect.identity.attempt===s.attempt;
87
- export const reviewNotDispatchedLimitReason=(code,extended=0)=>`${REVIEW_NOT_DISPATCHED_LIMIT_CODE}: 本轮独立审查已登记 ${MAX_REVIEW_NOT_DISPATCHED_RETRIES*(1+extended)+1} 次,每次都在派发前作废(最近一次 pending_review/${code}:授权过期或派发时钟倒退),审查进程从未启动、没有写入。`
88
- +(extended<MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS
89
- ?'本运行不再自动重派。先查清宿主从授权到派发为何超过授权有效期(60 秒内)或本机时钟为何倒退,并修好;'
90
- +`然后用 --mode resume 加 --allow-abandon-review 启动并发送 abandon_review(单行 reason 写明修好了什么)登记确认,本轮再多重派 ${MAX_REVIEW_NOT_DISPATCHED_RETRIES} 次(每轮只能确认 ${MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS} 次,用满后不再有这个出口)。`
91
- :`已确认延长 ${extended} 次(用满),不再提供继续重派的操作。先查清宿主从授权到派发为何超过授权有效期(60 秒内)或本机时钟为何倒退。${REVIEW_NEVER_STARTED_MANUAL_STEP}`);
92
- // A review whose authorization was refused before any registration (the runner's
93
- // permission_denied halt): no call, no grant, no reviewer, so nothing can be writing.
94
- // It is a decision, not a timing failure: only an explicit operator confirmation
95
- // (abandon_review, journaled as review-dispatch-confirmed with its reason) lets the same
96
- // round ask for a fresh authorization, once per denial, at most
97
- // MAX_REVIEW_DENIAL_CONFIRMATIONS per round; a host or a standing approval never does.
98
- export const REVIEW_DENIED_CODE='permission_denied';
99
- export const REVIEW_DENIAL_CONFIRMED_CODE='permission_denied_confirmed';
100
- export const REVIEW_DISPATCH_CONFIRM_REQUIRED_CODE='review_dispatch_confirmation_required';
101
- const deniedEffect=entry=>entry.effect.kind==='review'&&entry.result.state==='pending_review'&&entry.result.code===REVIEW_DENIED_CODE;
102
- export const reviewDenialUnconfirmed=s=>s.state==='pending_review'&&s.code===REVIEW_DENIED_CODE;
103
- export const reviewDenialExhausted=(s,confirmed)=>reviewDenialUnconfirmed(s)&&confirmed.denied>=MAX_REVIEW_DENIAL_CONFIRMATIONS;
104
- export const reviewDenialConfirmable=(s,confirmed)=>reviewDenialUnconfirmed(s)&&confirmed.denied<MAX_REVIEW_DENIAL_CONFIRMATIONS
105
- &&deniedEffect(s.cache.at(-1)??{effect:{},result:{}})&&s.cache.at(-1).effect.identity.attempt===s.attempt;
106
- // Confirmations of a review round, read the same way live (journal payloads) and in
107
- // replay (the running tally in answerGaps.reviewDispatchConfirmed).
108
- export const noReviewDispatchConfirmations=()=>({denied:0,extended:0});
109
- export const countReviewDispatchConfirmations=(payloads,attempt)=>{
110
- const count=noReviewDispatchConfirmations();
111
- for(const p of payloads)if(p.type==='review-dispatch-confirmed'&&p.attempt===attempt)
112
- count[p.code===REVIEW_DENIED_CODE?'denied':'extended']++;
113
- return count;
114
- };
115
- export const reviewDenialConfirmReason=confirmed=>`${REVIEW_DENIED_CODE}: 本轮独立审查的授权没有取得(被拒绝,或授权已超过有效期),审查没有登记、没有派发、审查进程从未启动,不会有任何写入。`
116
- +'宿主不会自动重试,也不会因为留着的审查授权而重派:先查清是谁拒绝、为什么,确认现在可以授权后,用 --mode resume 加 --allow-abandon-review 启动并发送 abandon_review(单行 reason 写明依据)登记确认,'
117
- +`再按原方式重新取得本轮审查授权后 advance。每轮最多这样确认 ${MAX_REVIEW_DENIAL_CONFIRMATIONS} 次(本轮已确认 ${confirmed.denied} 次),之后为 ${REVIEW_DENIAL_LIMIT_CODE}。`;
118
- export const reviewDenialLimitReason=()=>`${REVIEW_DENIAL_LIMIT_CODE}: 本轮独立审查的授权已被拒绝 ${MAX_REVIEW_DENIAL_CONFIRMATIONS+1} 次,已确认重新授权 ${MAX_REVIEW_DENIAL_CONFIRMATIONS} 次(用满),审查进程从未启动,也没有写入。`
119
- +`本运行不再提供重新授权的操作。先查清授权为何一直被拒绝(宿主是否配了审查权限、授权是否在 60 秒内用完)。${REVIEW_NEVER_STARTED_MANUAL_STEP}`;
120
- // Status-only overlay for a review round that ended without ever starting a reviewer,
121
- // read by the live runner and by replay (projectedRunnerStatus) alike; never journaled.
122
- export function reviewNeverStartedStatus(s,confirmed){
123
- if(reviewDenialExhausted(s,confirmed))return {state:'blocked',code:REVIEW_DENIAL_LIMIT_CODE,reason:reviewDenialLimitReason()};
124
- if(reviewDenialUnconfirmed(s))return {reviewDispatchConfirmRequired:true,reason:reviewDenialConfirmReason(confirmed)};
125
- if(reviewNotDispatchedExhausted(s,confirmed.extended))
126
- return {state:'blocked',code:REVIEW_NOT_DISPATCHED_LIMIT_CODE,reason:reviewNotDispatchedLimitReason(s.code,confirmed.extended),
127
- ...(confirmed.extended<MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS?{reviewDispatchConfirmRequired:true}:{})};
128
- return null;
129
- }
130
60
  const timeoutEffect=entry=>entry.effect.kind==='review'&&reviewRetryCode(entry.result.reviewInvocation?.result)!==null
131
61
  &&entry.result.code===reviewRetryCode(entry.result.reviewInvocation.result);
132
62
  export const reviewRetrySpent=(cache,calls,attempt,contextId)=>cache.some(entry=>entry.effect.identity.attempt===attempt&&timeoutEffect(entry))
@@ -152,8 +82,8 @@ const spentRetryBlock=s=>{
152
82
  return s.state==='blocked'&&REVIEW_RETRY_CODES.includes(s.code)&&entry?.effect.kind==='review'
153
83
  &&s.reviewInvocation?.result?.observation?.result?.code!=='process_cleanup_unknown'
154
84
  &&entry.effect.identity.attempt===s.attempt&&timeoutEffect(entry)&&entry.result.state==='blocked'&&entry.result.code===s.code
155
- &&s.reviewInvocation?.registration?.grant?.invocationId!=null
156
- &&entry.result.reviewInvocation?.registration?.grant?.invocationId===s.reviewInvocation.registration.grant.invocationId;
85
+ &&s.reviewInvocation?.registration?.binding?.invocationId!=null
86
+ &&entry.result.reviewInvocation?.registration?.binding?.invocationId===s.reviewInvocation.registration.binding.invocationId;
157
87
  };
158
88
  export const reviewRedispatchable=(s,contextId,records=0)=>spentRetryBlock(s)
159
89
  &&reviewRedispatchCount(s.cache,s.calls,s.attempt,contextId,records)<MAX_REVIEW_REDISPATCHES;
@@ -165,7 +95,7 @@ export const reviewRedispatchLimitReason=code=>`${REVIEW_REDISPATCH_LIMIT_CODE}:
165
95
  +'修好后用 --supersede-reviewed-evidence 新建运行重做;本运行记录保留不改写。';
166
96
  export const reviewRedispatchStopReason=code=>`review_redispatch_stop_required: 本轮独立审查第二次没有结论(blocked/${code}),本轮还剩 1 次无结论重派。`
167
97
  +'宿主只中止了原调用、没有等到审查进程退出,不能证明它已停止:先确认原审查进程(含子进程)已退出,'
168
- +'再用 --allow-abandon-review 发送 abandon_review(单行 reason)登记确认,之后 advance 重新取得授权并重派;不算审查轮次。';
98
+ +'再用 --allow-abandon-review 发送 abandon_review(单行 reason)登记确认,之后 advance 重派;不算审查轮次。';
169
99
  export const reviewTimeoutTransition=(result,cache,attempt,calls=[],contextId=null)=>{
170
100
  const code=reviewRetryCode(result);
171
101
  return code===null?null:{state:reviewRetrySpent(cache,calls,attempt,contextId)?'blocked':'pending_review',code};
@@ -532,12 +462,12 @@ const INTERRUPTIBLE_TRAILERS={develop:['control','develop-worker','documentation
532
462
  export const developRedoSource=entry=>developAnswerMissingEffect(entry)||providerStuckCause(entry)!==null;
533
463
  export const countedCalls=(calls,cache)=>calls.filter(call=>!invalidDeveloperCall(call)&&call.terminal!=='abandoned').length
534
464
  -cache.filter(timeoutEffect).length-cache.filter(developTimeoutEffect).length-cache.filter(developAnswerInvalidEffect).length
535
- -cache.filter(developRedoSource).length-cache.filter(developDispatchFailedEffect).length-cache.filter(notDispatchedEffect).length
465
+ -cache.filter(developRedoSource).length-cache.filter(developDispatchFailedEffect).length
536
466
  -cache.filter(documentationSyncSource).length;
537
467
  // A review effect whose journaled result the operator abandoned (below) no
538
468
  // longer holds one of the six effect slots; its retry does.
539
469
  const abandonedResult=(entry,calls)=>entry.effect.kind==='review'&&entry.result.state==='unknown'
540
- &&calls.some(call=>call.terminal==='abandoned'&&call.invocationId===entry.result.reviewInvocation?.registration?.grant?.invocationId);
470
+ &&calls.some(call=>call.terminal==='abandoned'&&call.invocationId===entry.result.reviewInvocation?.registration?.binding?.invocationId);
541
471
  // Completion holds no effect slot. It makes no provider call, it is admitted
542
472
  // only from an approved review (stageAllowed), and every outcome but a
543
473
  // completion re-check block ends the run; those blocks have their own bound,
@@ -550,7 +480,7 @@ export const completionBlockCount=cache=>cache.filter(completionBlock).length;
550
480
  export const completedEffectCount=(cache,calls=[])=>cache.filter(entry=>!(entry.effect.kind==='develop'
551
481
  &&entry.result.state==='blocked'&&['developer_result_invalid','check_output_out_of_scope'].includes(entry.result.code))
552
482
  &&!timeoutEffect(entry)&&!developTimeoutEffect(entry)&&!developAnswerInvalidEffect(entry)&&!developRecheckSource(entry)
553
- &&!developRedoSource(entry)&&!developDispatchFailedEffect(entry)&&!notDispatchedEffect(entry)&&!deniedEffect(entry)&&!documentationSyncSource(entry)
483
+ &&!developRedoSource(entry)&&!developDispatchFailedEffect(entry)&&!documentationSyncSource(entry)
554
484
  &&!abandonedResult(entry,calls)&&entry.effect.kind!=='complete').length;
555
485
  // The six-effect cap counts develop and review effects only; completion (above),
556
486
  // QA, documentation and finalization hold no slot.
@@ -607,7 +537,7 @@ export function abandonableReviewResult(s,contextId,records=0){
607
537
  const entry=s.cache.at(-1),result=s.reviewInvocation?.result;
608
538
  return s.state==='unknown'&&entry?.effect.kind==='review'&&entry.effect.identity.attempt===s.attempt
609
539
  &&entry.result.state==='unknown'&&abandonableReviewOutcome(result)
610
- &&entry.result.reviewInvocation?.registration?.grant?.invocationId===s.reviewInvocation.registration?.grant?.invocationId
540
+ &&entry.result.reviewInvocation?.registration?.binding?.invocationId===s.reviewInvocation.registration?.binding?.invocationId
611
541
  &&reviewRedispatchCount(s.cache,s.calls,s.attempt,contextId,records)<MAX_REVIEW_REDISPATCHES;
612
542
  }
613
543
  // R4: why a no-verdict review end cannot be abandoned, with its real exit.
@@ -686,7 +616,7 @@ export function runnerStatus(s,config) {
686
616
  export function controlledState(state,event,outstanding,version=1) {
687
617
  const s=structuredClone(state);
688
618
  const unresolvedReview=version===3&&s.reviewInvocation?.result?.reconciliationRequired===true
689
- &&s.reviewInvocation.registration?.grant?.identity?.attempt===s.attempt;
619
+ &&s.reviewInvocation.registration?.binding?.identity?.attempt===s.attempt;
690
620
  if(event==='workflow-error') {s.workflowError='workflow_error';if(!outstanding && s.state!=='fixture_completed'
691
621
  && !(s.state==='unknown'&&(version>=2&&s.taskCommit||unresolvedReview))){s.state='blocked';s.code='workflow_error';if(Object.hasOwn(s,'reason'))s.reason=null;}}
692
622
  else if(event==='late-cancel'){s.cancelAfterCommit=true;s.cancellationRequested=true;}
@@ -775,15 +705,19 @@ export function validateReviewDispatchGrant(raw,expected) {
775
705
  need(digest(grantBody(grant))===grant.grantDigest,'runner_grant');return grant;
776
706
  }
777
707
  function readRegistration(p,before,effect,config,session,carried=null) {
778
- shape(p,['version','protocol','type','effectId','reviewerId','adapterId','requestDigest','authorizationAt','registeredAt','grant']);
708
+ need(!Object.hasOwn(p,'grant')&&!Object.hasOwn(p,'authorizationAt'),'runner_invocation');
709
+ shape(p,['version','protocol','type','effectId','reviewerId','adapterId','requestDigest','registeredAt','binding']);
779
710
  need(p.effectId===effect.id,'runner_invocation');
780
- const request=reviewRequest(before,config,session,carried),reviewer=config.reviewers[0];
781
- need(p.reviewerId===reviewer.id&&p.adapterId===reviewer.adapterId&&p.requestDigest===request.requestDigest,'runner_grant');
782
- const grant=validateReviewDispatchGrant(p.grant,{request,reviewerId:reviewer.id,adapterId:reviewer.adapterId,
783
- packageDigest:before.reviewPackage.packageDigest,hostContextIds:[config.reviewInvocation.developerThreadId,...config.reviewInvocation.excludedThreadIds],
784
- authorizationAt:p.authorizationAt,registeredAt:p.registeredAt});
711
+ const request=reviewRequest(before,config,session,carried),reviewer=config.reviewers[0],binding=json(p.binding);
712
+ shape(binding,['adapterId','invocationId','requestDigest','identity','reviewerId','logicalContextId','packageDigest','hostContextId']);
713
+ id(binding.hostContextId);need(Number.isSafeInteger(p.registeredAt),'runner_invocation');
714
+ need([config.reviewInvocation.developerThreadId,...config.reviewInvocation.excludedThreadIds].includes(binding.hostContextId),'runner_invocation');
715
+ same(binding,{adapterId:reviewer.adapterId,invocationId:request.invocationId,requestDigest:request.requestDigest,
716
+ identity:request.identity,reviewerId:reviewer.id,logicalContextId:request.contextId,
717
+ packageDigest:before.reviewPackage.packageDigest,hostContextId:binding.hostContextId});
718
+ need(p.reviewerId===reviewer.id&&p.adapterId===reviewer.adapterId&&p.requestDigest===request.requestDigest,'runner_invocation');
785
719
  return {request,record:json({reviewerId:p.reviewerId,adapterId:p.adapterId,requestDigest:p.requestDigest,
786
- authorizationAt:p.authorizationAt,registeredAt:p.registeredAt,grant})};
720
+ registeredAt:p.registeredAt,binding})};
787
721
  }
788
722
  function readStarted(p,registration,effect,config) {
789
723
  shape(p,['version','protocol','type','effectId','invocationId','providerThreadId']);
@@ -796,9 +730,7 @@ function readInvocationResult(p,registration,started,effect,config) {
796
730
  const common=['version','protocol','type','effectId','invocationId','dispatchAt','outcome','observation','inspection','reconciliationRequired'];
797
731
  need(p.effectId===effect.id&&p.invocationId===registration.request.invocationId,'runner_invocation');
798
732
  need(typeof p.reconciliationRequired==='boolean','runner_invocation');
799
- if(p.outcome==='not_dispatched')need(p.dispatchAt===null||Number.isSafeInteger(p.dispatchAt),'runner_invocation');
800
- else need(Number.isSafeInteger(p.dispatchAt)&&registration.record.registeredAt<=p.dispatchAt
801
- &&p.dispatchAt<registration.record.grant.expiresAt,'runner_invocation');
733
+ need(Number.isSafeInteger(p.dispatchAt)&&registration.record.registeredAt===p.dispatchAt,'runner_invocation');
802
734
  const expectation={request:registration.request,developerThreadId:config.reviewInvocation.developerThreadId,
803
735
  excludedThreadIds:config.reviewInvocation.excludedThreadIds};
804
736
  let inspected=null;
@@ -833,11 +765,6 @@ function readInvocationResult(p,registration,started,effect,config) {
833
765
  const failure=inspectProviderReviewFailure(JSON.stringify(observation),JSON.stringify(expectation));
834
766
  need(failure!==null,'runner_invocation');same(p.inspection,failure);
835
767
  need(failure.providerThreadId===started,'runner_invocation');
836
- } else if(p.outcome==='not_dispatched') {
837
- shape(p,[...common,'reason']);need(['grant_expired','clock_invalid'].includes(p.reason)
838
- &&p.observation===null&&p.inspection===null&&p.reconciliationRequired===true&&started===null,'runner_invocation');
839
- need(p.reason==='grant_expired'?Number.isSafeInteger(p.dispatchAt)&&p.dispatchAt>=registration.record.grant.expiresAt:
840
- p.dispatchAt===null||p.dispatchAt<registration.record.registeredAt,'runner_invocation');
841
768
  } else need(false,'runner_invocation');
842
769
  return json(Object.fromEntries(Object.entries(p).filter(([key])=>!['version','protocol','type','effectId','invocationId'].includes(key))),512*1024);
843
770
  }
@@ -845,11 +772,11 @@ function invocationCall(call,registration,started,result,before) {
845
772
  shape(call,['invocationId','contextId','provider','requestedModel','effectiveModel','channel','started','terminal','requestDigest','resultDigest','providerThreadId']);
846
773
  const request=registration.request;need(call.invocationId===request.invocationId&&call.contextId===request.contextId
847
774
  &&call.provider===request.provider&&call.requestedModel===request.requestedModel&&call.effectiveModel==='unknown'
848
- &&call.channel==='host-authorized'&&call.requestDigest===request.requestDigest
775
+ &&call.channel==='host-review'&&call.requestDigest===request.requestDigest
849
776
  &&call.providerThreadId===started,'runner_call');
850
777
  const expectedTerminal=result.outcome==='observed'?'succeeded':result.outcome==='cancelled'?'cancelled':
851
- result.outcome==='not_dispatched'?'not_dispatched':reviewTransportTimeout(result)||reviewerFailure(result)?'failed':'unknown';
852
- need(call.started===(result.outcome!=='not_dispatched')&&call.terminal===expectedTerminal
778
+ reviewTransportTimeout(result)||reviewerFailure(result)?'failed':'unknown';
779
+ need(call.started===true&&call.terminal===expectedTerminal
853
780
  &&call.resultDigest===digest(result.outcome==='observed'?result.inspection.review:result)
854
781
  &&before.sequence+1===Number(request.invocationId.split('.').at(-1)),'runner_call');
855
782
  }
@@ -1009,9 +936,8 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
1009
936
  need(!invocation?.result&&added.length===0&&s.sequence===before.sequence,'runner_invocation');
1010
937
  same(s.reviewInvocation,before.reviewInvocation);same(s.receipt,before.receipt);same(s.receipts,before.receipts);same(s.priorReview,before.priorReview);
1011
938
  if(controls.cancelled===true){expectedState='cancelled';expectedCode='cancelled';}
1012
- else if(s.code==='permission_denied')expectedState='pending_review';
1013
939
  else if(Object.hasOwn(original,'specification')&&s.code==='spec_drift')expectedState='blocked';
1014
- else {need(['authorization_invalid','clock_invalid'].includes(s.code),'runner_invocation');expectedState='unknown';}
940
+ else {need(s.code==='clock_invalid','runner_invocation');expectedState='unknown';}
1015
941
  expectedCode??=s.code;
1016
942
  } else {
1017
943
  need(invocation.result&&added.length===1,'runner_invocation');
@@ -1036,7 +962,6 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
1036
962
  }
1037
963
  }
1038
964
  else if(invocation.result.outcome==='cancelled'){need(controls.cancelled===true,'runner_control');expectedState='cancelled';expectedCode='cancelled';}
1039
- else if(invocation.result.outcome==='not_dispatched'){expectedState='pending_review';expectedCode=invocation.result.reason;}
1040
965
  else {const retry=reviewTimeoutTransition(invocation.result,before.cache,before.attempt,before.calls,
1041
966
  config.reviewers[0].contexts[before.attempt-1]);
1042
967
  expectedState=retry?.state??'unknown';expectedCode=retry?.code??invocation.result.reason??invocation.result.inspection?.code??'reconciliation_required';}
@@ -1160,7 +1085,8 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
1160
1085
  function completionConfig(config,version){
1161
1086
  shape(config,['root','identity','scope','requirements','excludedContexts','timeoutMs','developer','reviewers','completion',
1162
1087
  ...(version===3?['reviewInvocation']:[]),...(Object.hasOwn(config,'taskLearning')?['taskLearning']:[]),
1163
- ...['bootstrap','codeProjectPaths','knowledgeCloseout','externalModels','executionPolicy'].filter(key=>Object.hasOwn(config,key))]);
1088
+ ...['bootstrap','codeProjectPaths','knowledgeCloseout','externalModels','executionPolicy','controlPolicy'].filter(key=>Object.hasOwn(config,key))]);
1089
+ if(Object.hasOwn(config,'controlPolicy')){same(config.controlPolicy,readControlPolicy(config.controlPolicy));need(version===3,'runner_version');}
1164
1090
  if(Object.hasOwn(config,'knowledgeCloseout'))readCloseoutPolicy(config.knowledgeCloseout);
1165
1091
  if(Object.hasOwn(config,'executionPolicy')){same(config.executionPolicy,readExecutionPolicy(config.executionPolicy));need(version===3,'execution_policy_runner_version');}
1166
1092
  if(Object.hasOwn(config,'externalModels')){same(config.externalModels,readExternalModels(config.externalModels));need(version===3,'external_model_runner_version');}
@@ -1252,8 +1178,7 @@ export function readRunnerHistory(raw,config,version=1) {
1252
1178
  let original,session,state,pending=null,beforeIntent=null,controlCount=0,controls={},completeIntentDigest=null,transaction=null;
1253
1179
  let invocation={registration:null,started:null,result:null};let registrationRecord=null,startedRecord=null,resultRecord=null,lastReview=null;
1254
1180
  const acceptedFixes=[],joinedHosts=[],reviewerThreads=[];let qaAttachment=null,qaRevision=null,joinedForInvocation=false,supersession=null;
1255
- const answerGaps={developRecheck:0,completeRecheck:0,developRedo:0,developDispatch:0,documentationSync:0,reviewRedispatch:{1:0,2:0},
1256
- reviewDispatchConfirmed:{1:noReviewDispatchConfirmations(),2:noReviewDispatchConfirmations()}};
1181
+ const answerGaps={developRecheck:0,completeRecheck:0,developRedo:0,developDispatch:0,documentationSync:0,reviewRedispatch:{1:0,2:0}};
1257
1182
  // Q16: documentation-sync-started records by digest, and the pending develop's.
1258
1183
  const documentationRecords=new Map();let pendingDocumentation=null,documentationStop=null;
1259
1184
  // V8/V9: interrupted intents (their ids are never reused) and the provider
@@ -1368,7 +1293,6 @@ export function readRunnerHistory(raw,config,version=1) {
1368
1293
  if(Object.hasOwn(e,'learningInput')){need(e.kind==='develop'&&Object.hasOwn(config,'taskLearning'),'runner_learning');
1369
1294
  validTaskLearningInput(e.learningInput,e.identity,config.taskLearning.feature);}
1370
1295
  same(e.identity,{...config.identity,attempt:state.attempt});need(e.version===1 && stageAllowed(e.kind,state.state,state.code,state.priorReview?.verdict),'runner_stage');
1371
- need(!(e.kind==='review'&&reviewNotDispatchedExhausted(state,answerGaps.reviewDispatchConfirmed[state.attempt].extended)),'runner_stage');
1372
1296
  need(effectSlotFree(e.kind,state.cache,state.calls) && !state.cache.some(c=>c.effect.id===e.id),'runner_cache');
1373
1297
  pending=e;beforeIntent=structuredClone(state);controls={};completeIntentDigest=e.kind==='complete'?r.digest:null;pendingDocumentation=null;documentationStop=null;
1374
1298
  invocation={registration:null,started:null,result:null};registrationRecord=null;startedRecord=null;resultRecord=null;
@@ -1553,25 +1477,9 @@ export function readRunnerHistory(raw,config,version=1) {
1553
1477
  need(r.kind==='result'&&pending===null&&p.attempt===state.attempt
1554
1478
  &&reviewRedispatchable(state,contextId,answerGaps.reviewRedispatch[state.attempt])
1555
1479
  &&p.code===state.code&&p.effectId===state.cache.at(-1).effect.id
1556
- &&p.invocationId===state.reviewInvocation.registration.grant.invocationId,'runner_review_redispatch');
1480
+ &&p.invocationId===state.reviewInvocation.registration.binding.invocationId,'runner_review_redispatch');
1557
1481
  answerGaps.reviewRedispatch[state.attempt]++;
1558
1482
  state.state='pending_review';lastReview=null;
1559
- } else if(version===3&&p.type==='review-dispatch-confirmed') {
1560
- // The operator's confirmation (abandon_review + reason) for a review that never
1561
- // started: a refused authorization (once per denial) or the spent not-dispatched
1562
- // redispatch bound (once per round). Nothing ran, so there is no process to prove
1563
- // stopped (unlike review-redispatch). Re-derived from the journal.
1564
- shape(p,[...common,'effectId','attempt','code','reason','at']);
1565
- need(typeof p.reason==='string'&&p.reason.trim().length>0&&Buffer.byteLength(p.reason,'utf8')<=500
1566
- &&!/[\r\n\0]/.test(p.reason),'runner_review_dispatch_confirm');
1567
- need(typeof p.at==='string'&&Number.isFinite(Date.parse(p.at))&&new Date(p.at).toISOString()===p.at,'runner_review_dispatch_confirm');
1568
- const confirmed=answerGaps.reviewDispatchConfirmed[state.attempt];
1569
- need(r.kind==='result'&&pending===null&&p.attempt===state.attempt&&p.code===state.code
1570
- &&p.effectId===state.cache.at(-1)?.effect.id
1571
- &&(reviewDenialConfirmable(state,confirmed)||reviewNotDispatchedExtendable(state,confirmed)),'runner_review_dispatch_confirm');
1572
- if(p.code===REVIEW_DENIED_CODE){confirmed.denied++;state.code=REVIEW_DENIAL_CONFIRMED_CODE;}
1573
- else confirmed.extended++;
1574
- lastReview=null;
1575
1483
  } else if(version===3&&p.type==='completion-retry-limit') {
1576
1484
  // Terminal: written instead of a complete intent once the re-check bound
1577
1485
  // is spent. Every field is recomputed from the replayed state.
@@ -1592,7 +1500,7 @@ export function readRunnerHistory(raw,config,version=1) {
1592
1500
  &&!/[\r\n\0]/.test(p.reason),'runner_abandon');
1593
1501
  need(typeof p.at==='string'&&Number.isFinite(Date.parse(p.at))&&new Date(p.at).toISOString()===p.at,'runner_abandon');
1594
1502
  const call=state.calls.find(item=>item.invocationId===p.invocationId);
1595
- need(call?.terminal==='unknown'&&call.channel==='host-authorized','runner_abandon');
1503
+ need(call?.terminal==='unknown'&&call.channel==='host-review','runner_abandon');
1596
1504
  // The invocation keeps its slot and its result digest; only its terminal
1597
1505
  // records the operator's exit, which also marks the attempt's retry spent.
1598
1506
  call.terminal='abandoned';
@@ -1621,7 +1529,7 @@ export function readRunnerHistory(raw,config,version=1) {
1621
1529
  need(roundRedispatches()<MAX_REVIEW_REDISPATCHES,'runner_abandon_budget');
1622
1530
  const request=invocation.registration.request;
1623
1531
  state.calls.push({invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
1624
- requestedModel:request.requestedModel,effectiveModel:'unknown',channel:'host-authorized',
1532
+ requestedModel:request.requestedModel,effectiveModel:'unknown',channel:'host-review',
1625
1533
  started:startedRecord!==null,terminal:'abandoned',requestDigest:request.requestDigest,
1626
1534
  resultDigest:r.digest,providerThreadId:invocation.started});
1627
1535
  state.sequence++;
@@ -1883,8 +1791,6 @@ export function projectedRunnerStatus(history,config){
1883
1791
  if(reviewRedispatchable(s,contextId,records))return {...s,reviewRedispatchStopRequired:true,reason:reviewRedispatchStopReason(s.code)};
1884
1792
  if(reviewRedispatchExhausted(s,contextId,records))return {...s,code:REVIEW_REDISPATCH_LIMIT_CODE,reason:reviewRedispatchLimitReason(s.code)};
1885
1793
  }
1886
- const never=reviewNeverStartedStatus(s,gaps.reviewDispatchConfirmed?.[s.attempt]??noReviewDispatchConfirmations());
1887
- if(never!==null)return {...s,...never};
1888
1794
  if(s.state!=='unknown')return s;
1889
1795
  const recheck=developRecheckCode(s,config,gaps.developRecheck??0);
1890
1796
  if(recheck!==null)return project(recheck);
@@ -12,10 +12,10 @@ export function checkCompletion({receipt,registered,execution,reviewPackage,iden
12
12
  for(const field of ['packageDigest','baseIdentity','artifactDigest','requirementsDigest','checksDigest'])
13
13
  need(r[field]===reviewPackage[field],'receipt_package_mismatch');
14
14
  const executionKeys=['invocationId','contextId','provider','requestedModel','effectiveModel','channel','started','terminal','requestDigest','resultDigest'];
15
- const hostAuthorized=r.execution?.channel==='host-authorized';
16
- shape(r.execution,[...executionKeys,...(hostAuthorized?['providerThreadId']:[])]);
17
- need(['fixture','host-authorized'].includes(r.execution.channel),'execution_mismatch');
18
- if(hostAuthorized)id(r.execution.providerThreadId);
15
+ const observedReview=['host-review','host-authorized'].includes(r.execution?.channel);
16
+ shape(r.execution,[...executionKeys,...(observedReview?['providerThreadId']:[])]);
17
+ need(['fixture','host-review','host-authorized'].includes(r.execution.channel),'execution_mismatch');
18
+ if(observedReview)id(r.execution.providerThreadId);
19
19
  need(r.id===r.execution.invocationId && r.execution.started===true && r.execution.terminal==='succeeded'
20
20
  && digest(r.execution)===digest(json(execution)),'execution_mismatch');
21
21
  const result=reviewResult(r.result,reviewPackage);
@@ -1,6 +1,7 @@
1
1
  // Runs host-configured, already-authorized project checks. Commands may execute
2
2
  // project code; specsRoot opts into Codex's native sandbox for that subprocess.
3
3
  // Without specsRoot this preserves the existing direct host-check behavior.
4
+ import {beginHostStage} from './host-stage-observer.mjs';
4
5
  import fs from 'node:fs';
5
6
  import path from 'node:path';
6
7
  import {spawn} from 'node:child_process';
@@ -55,6 +56,7 @@ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,out
55
56
  ...(signature?{signatureMatched:original.signatureMatched}:{})});continue;
56
57
  }
57
58
  notify({phase:'start',id:item.id});
59
+ const endStage=beginHostStage('check',timeoutMs);
58
60
  const result=await new Promise(resolve=>{
59
61
  let child;
60
62
  try{
@@ -126,7 +128,7 @@ export function createHostCheck({cwd,commands,timeoutMs=60000,specsRoot=null,out
126
128
  evidence:prefix+(summary.length?` (${summary.join(', ')})`:'')});
127
129
  }
128
130
  });
129
- });
131
+ }).finally(endStage);
130
132
  notify({phase:'complete',id:item.id,outcome:result.outcome,exitCode:result.exitCode});
131
133
  need(!signal.aborted,'cancelled');
132
134
  results.push({id:item.id,command:item.command,...result,...(signature?{signatureMatched}:{})});