@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
@@ -7,12 +7,11 @@ export function createCmAiHost(options) {
7
7
  need(arguments.length===1,'invalid_input');
8
8
  shape(options,['runner','entry']);
9
9
  const keys=Object.keys(options.entry);shape(options.entry,keys);
10
- const {hostDecisionProvider,qaDecisionProvider,qaExecutor,documentationProvider,...data}=options.entry;
10
+ const {qaDecisionProvider,qaExecutor,documentationProvider,...data}=options.entry;
11
11
  const entryOptions=json(data);
12
12
  need(!Object.hasOwn(entryOptions,'runner'),'invalid_input');
13
13
  const runner=createTaskRunner(options.runner);
14
14
  const entry=createCmAiConversationEntry({...entryOptions,runner,
15
- ...(hostDecisionProvider===undefined?{}:{hostDecisionProvider}),
16
15
  ...(qaExecutor===undefined?{}:{qaExecutor}),
17
16
  ...(documentationProvider===undefined?{}:{documentationProvider}),
18
17
  ...(qaDecisionProvider===undefined?{}:{qaDecisionProvider})});
@@ -1,5 +1,3 @@
1
- import {REVIEW_NEVER_STARTED_MANUAL_STEP,MAX_REVIEW_NOT_DISPATCHED_RETRIES as REDISPATCHES,MAX_REVIEW_NOT_DISPATCHED_EXTENSIONS as EXTENSIONS,
2
- MAX_REVIEW_DENIAL_CONFIRMATIONS as DENIALS} from './review-dispatch-limits.mjs';
3
1
  // Presentation only. Native pendingAction decides the available path; guidance
4
2
  // never grants permission, changes retryability, or writes execution history.
5
3
  const deliveryMessages={
@@ -28,18 +26,40 @@ const documentationMessages={
28
26
  const explain=(summary,nextStep,operation=null,prerequisites=[])=>Object.freeze({
29
27
  summary,nextStep,recoveryOperation:operation,prerequisites:Object.freeze(prerequisites),authorizationGranted:false,
30
28
  });
31
- export function operatorGuidance(result,{executionActive=false}={}){
29
+ // Rendering context is private and ephemeral; it never enters results or journals.
30
+ const guidanceContext=new WeakMap();
31
+ export function operatorGuidance(result,options={}){
32
+ const guidance=renderOperatorGuidance(result,options);
33
+ if(guidance)guidanceContext.set(guidance,{executionActive:options.executionActive===true,protocol:options.protocol??'legacy'});
34
+ return guidance;
35
+ }
36
+ export function projectOperatorGuidance(result,options={}){
37
+ if(!result?.guidance)return result;
38
+ const context=guidanceContext.get(result.guidance);
39
+ if(!context)return result;
40
+ const guidance=operatorGuidance(result,{...context,...options});
41
+ return guidance?{...result,guidance}:result;
42
+ }
43
+ const fixedTarget='先只读 status,展示并核对 controlTarget 与恢复动作,按当前对话的具体决定完整固定为 expectedControl;发送 version:2 和单行 reason;snapshot_changed 时停止,不自动刷新目标重试';
44
+ function renderOperatorGuidance(result,{executionActive=false,protocol='legacy',surface='single'}={}){
45
+ const v2=protocol==='v2',batch=surface==='batch';
46
+ const resume=batch?'从原批次入口发送 advance':'恢复原运行并发送 advance';
47
+ const permission=flag=>v2?fixedTarget:`显式 ${flag},并提供单行 reason`;
48
+ const supersede=v2?'当前 v2 没有作废旧证据并新建运行的出口;保留原运行、文件与证据,核对 reason 后交由维护者处理,不改走旧入口。'
49
+ :'修好后按 reason 用 --supersede-reviewed-evidence 新建运行重做。';
50
+ const supersedePrerequisites=v2?['原运行记录与现有文件保留,不改写','不改变协议、身份或恢复预算']
51
+ :['原运行记录保留,不改写','本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift'];
32
52
  if(result?.workflow!=='cm-ai'||!result.state||!result.identity)return null;
33
53
  const {state,code,pendingAction:action,outcome}=result;
34
54
  if(outcome==='rejected'||outcome==='denied')return explain('本次操作被拒绝,运行状态没有因此获得新的执行权限。',
35
55
  '先核对 code 与 reason,修正请求或取得所需授权;不要据此重复开发或审查。');
36
56
  if(executionActive)return explain('原运行仍有操作在执行。','等待原操作结果;可读取状态,不重复派发。');
37
57
  if(code==='spec_drift')return explain('已批准规格发生变化,后续执行被阻止。',
38
- action==='spec_rebind'?'先核对重新批准的规格;符合原任务内容未变的条件时,在原运行显式换绑规格。'
58
+ action==='spec_rebind'?(v2?'先核对重新批准的规格;符合原条件时,只读 status 并展示 launchControlTarget,将完整固定副本写入文件,以原策略和配置带 --expected-control FILE、--rebind-spec-material 与单行 --spec-rebind-reason 恢复;snapshot_changed 时停止,不自动刷新。':'先核对重新批准的规格;符合原任务内容未变的条件时,在原运行显式换绑规格。')
39
59
  :'先核对规格变更与原任务绑定;当前没有可直接继续的恢复动作。',null,['保留原运行身份与历史','不得绕过规格审批']);
40
60
  if(action==='bootstrap_review_recover')return explain('项目规则交付已记录,但规则审查包尚未恢复。',
41
61
  '核对当前规则文件、handoff 和原证据;恢复原运行后发送 bootstrap_review_recover。此路径不重新派发开发。',
42
- 'bootstrap_review_recover',['使用原配置与 runId,以 --mode resume 启动','显式 --allow-bootstrap-review-recovery,并提供单行 reason','由原宿主重新核对恢复条件']);
62
+ 'bootstrap_review_recover',['使用原配置与 runId,以 --mode resume 启动',permission('--allow-bootstrap-review-recovery'),'由原宿主重新核对恢复条件']);
43
63
  if(state==='unknown'){
44
64
  if(action==='abandon_effect'||action==='abandon_review'){
45
65
  const review=action==='abandon_review';
@@ -49,67 +69,46 @@ export function operatorGuidance(result,{executionActive=false}={}){
49
69
  ?'先确认旧宿主及相关子进程已退出、会话已停止修改文档(宿主按存档核对文档路径以外的文件与此刻的文档);再发送 abandon_effect 登记中断,运行转为 documentation_sync_interrupted,之后只重发文档同步、不重新开发,计入文档同步重发的 2 次上限。盘上改动保留并经检查与独立审查;登记中断不代表成功。'
50
70
  :'先确认旧宿主及相关子进程已退出、会话已停止写入(provider 开发由宿主按存档记下的进程身份核对);再发送 abandon_effect 登记中断,运行从这一步的可重试阻断继续:开发重发本轮、未登记的审查重新派发、未写提交意图的完成重新复查。盘上改动保留并经检查与独立审查;登记中断不代表成功。',
51
71
  action,['保留原配置、runId 和失败历史,以 --mode resume 启动',
52
- review?'显式 --allow-abandon-review,并提供单行 reason':'显式 --allow-abandon-effect,并提供单行 reason',
72
+ review?permission('--allow-abandon-review'):permission('--allow-abandon-effect'),
53
73
  '由原宿主核对可放弃条件;不得直接重跑或改写完成记录']);
54
74
  }
55
75
  // V5 (A33/A36): a no-verdict review end the host cannot prove safe to redispatch.
56
76
  if(['review_process_unverified','review_observation_invalid','review_boundary_unverified','review_abandon_budget_exhausted'].includes(result.reviewAbandonRefusal))
57
77
  return explain('独立审查没有结论,且宿主不能证明再派一次是安全的(reason 写明原因)。',
58
- '按 reason 手工核对旧审查进程与原审查证据;本运行不再重派审查,确认后用 --supersede-reviewed-evidence 新建运行重做。',
59
- null,['原运行记录保留,不改写','本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift']);
78
+ `按 reason 手工核对旧审查进程与原审查证据;本运行不再重派审查。${supersede}`,
79
+ null,supersedePrerequisites);
60
80
  return explain('执行结果尚未确认,不能判断这一步成功或失败。',
61
81
  '只读核对原运行记录、进程及实际文件;当前没有已确认的直接重试入口,不新建运行绕过历史。');
62
82
  }
63
- // A review round that never started a reviewer (nothing ran, nothing to prove stopped).
64
- if(action==='abandon_review'&&result.reviewDispatchConfirmRequired===true&&code==='permission_denied')
65
- return explain('本轮独立审查的授权没有取得(被拒绝,或授权已失效),审查没有登记、没有派发、审查进程从未启动,不会有任何写入;宿主不会自动重试。',
66
- '先查清是谁拒绝、为什么;确认现在可以授权后,用 --allow-abandon-review 恢复原运行并发送 abandon_review(单行 reason 写明依据)登记确认,再按原方式重新取得本轮独立审查授权,然后 advance。',
67
- 'abandon_review',['保留原配置、runId 与历史,以 --mode resume 启动','显式 --allow-abandon-review,并提供单行 reason',`每轮最多确认 ${DENIALS} 次,用满为 review_permission_denied_limit;每次重派前仍须新的审查授权`]);
68
- if(action==='abandon_review'&&result.reviewDispatchConfirmRequired===true&&code==='review_not_dispatched_limit')
69
- return explain(`本轮独立审查已登记 ${REDISPATCHES+1} 次,每次都在派发前作废(授权过期或派发时钟倒退),审查进程从未启动、没有写入;自动重派已用满。`,
70
- `先查清宿主从授权到派发为何超过授权有效期(60 秒内)或本机时钟为何倒退,并修好;然后用 --allow-abandon-review 恢复原运行并发送 abandon_review(单行 reason 写明修好了什么)登记确认,再按原方式取得新的审查授权后 advance。本轮因此再多重派 ${REDISPATCHES} 次。`,
71
- 'abandon_review',['保留原配置、runId 与历史,以 --mode resume 启动','显式 --allow-abandon-review,并提供单行 reason',`每轮只能确认 ${EXTENSIONS} 次;再用满为 review_not_dispatched_limit,之后没有这个出口`]);
72
- if(code==='review_not_dispatched_limit')return explain(`本轮独立审查已在派发前作废 ${REDISPATCHES*(1+EXTENSIONS)+1} 次、已确认延长 ${EXTENSIONS} 次,不再提供继续重派的操作;审查进程从未启动,也没有写入。`,
73
- `先查清宿主从授权到派发为何超过授权有效期(60 秒内)或本机时钟为何倒退。${REVIEW_NEVER_STARTED_MANUAL_STEP}`,
74
- null,['原运行记录保留,不改写','本运行留在盘上的改动需另存或还原,不要加 --accept-superseded-code-drift']);
75
- if(state==='pending_review'&&action==='resume'&&['grant_expired','clock_invalid'].includes(code))return explain('本轮独立审查已登记,但派发前授权过期或派发时钟倒退,审查进程从未启动、没有结论。',
76
- '恢复原运行,按原方式重新取得本轮独立审查的新的审查授权,再发送 advance;派发要在授权后 60 秒内完成。',
77
- 'advance',['保留原配置、runId 与历史,以 --mode resume 启动','不算审查轮次,不占调用与 effect 名额',`每轮最多重派 ${REDISPATCHES} 次,用满为 review_not_dispatched_limit,再确认 ${EXTENSIONS} 次后才能多重派 ${REDISPATCHES} 次`]);
78
- if(code==='review_permission_denied_limit')return explain(`本轮独立审查的授权已被拒绝 ${DENIALS+1} 次、已确认重新授权 ${DENIALS} 次,不再提供重新授权的操作;审查从未启动,也没有写入。`,
79
- `先查清授权为何一直被拒绝(宿主是否配了审查权限、授权是否在 60 秒内用完)。${REVIEW_NEVER_STARTED_MANUAL_STEP}`,
80
- null,['原运行记录保留,不改写','本运行留在盘上的改动需另存或还原,不要加 --accept-superseded-code-drift']);
81
- if(state==='pending_review'&&action==='resume'&&code==='permission_denied_confirmed')return explain('审查授权被拒绝的情况已由操作员确认,本轮可以重新申请授权;审查从未启动。',
82
- '恢复原运行,按原方式重新取得本轮独立审查的新的审查授权(旧授权不复用),再发送 advance;仍被拒绝时需要再确认一次。',
83
- 'advance',['保留原配置、runId 与历史,以 --mode resume 启动','本轮独立审查授权须是新取得的','不算审查轮次,不占调用与 effect 名额']);
84
83
  if(state==='blocked'&&action==='abandon_review')return explain('本轮独立审查第二次没有结论,本轮还剩 1 次无结论重派,但宿主不能证明原审查进程已停止。',
85
- '先确认原审查进程(含子进程)已退出;再恢复原运行并发送 abandon_review 登记确认,之后 advance 重新取得授权并重派。不算审查轮次。',
86
- 'abandon_review',['保留原配置、runId 与历史,以 --mode resume 启动','显式 --allow-abandon-review,并提供单行 reason','用满 2 次后为 review_redispatch_limit']);
84
+ '先确认原审查进程(含子进程)已退出;再恢复原运行并发送 abandon_review 登记确认,之后 advance 重派。不算审查轮次。',
85
+ 'abandon_review',['保留原配置、runId 与历史,以 --mode resume 启动',permission('--allow-abandon-review'),'用满 2 次后为 review_redispatch_limit']);
87
86
  // Q16/Q17: the final task's documentation_sync failed after develop answered.
88
87
  // R3: whatever the failure, the host cannot see whether the session still writes.
89
88
  if(action==='develop_redo'&&Object.hasOwn(documentationMessages,code))return explain(`${documentationMessages[code][0]}宿主无法证明会话已停止修改文档。`,
90
89
  `先确认会话已停止修改文档,${documentationMessages[code][1]}再恢复原运行并发送 develop_redo 写入确认,之后 advance 只重发文档同步。盘上的开发与文档改动保留,经检查和独立审查。`,
91
- 'develop_redo',['保留原配置、runId 与历史,以 --mode resume 启动','显式 --allow-develop-redo,并提供单行 reason','只重发文档同步,不重发开发;每运行最多 2 次']);
90
+ 'develop_redo',['保留原配置、runId 与历史,以 --mode resume 启动',permission('--allow-develop-redo'),'只重发文档同步,不重发开发;每运行最多 2 次']);
92
91
  if(state==='blocked'&&action==='resume'&&Object.hasOwn(documentationMessages,code)){
93
92
  const [summary,repair]=documentationMessages[code];
94
- return explain(summary,`${repair}然后恢复原运行并发送 advance,只重发文档同步,复用已记录的开发应答,不重新开发。`,
93
+ return explain(summary,`${repair}然后${resume},只重发文档同步,复用已记录的开发应答,不重新开发。`,
95
94
  'advance',['保留原配置、runId 与历史,以 --mode resume 启动','文档路径以外的文件须与文档同步开始时一致、文档须与确认停写时一致,否则拒绝','不占调用与 effect 名额;每运行最多 2 次,用满为 documentation_sync_retry_limit']);
96
95
  }
97
96
  if(code==='documentation_sync_retry_limit')return explain('文档同步重发已在本运行用满 2 次,不再重发。',
98
- '先查清会话为何一直不应答、答复 blocked 或越界写文件;修好后按 reason 用 --supersede-reviewed-evidence 新建运行重做。',
99
- null,['原运行记录保留,不改写','本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift']);
97
+ `先查清会话为何一直不应答、答复 blocked 或越界写文件;${supersede}`,
98
+ null,supersedePrerequisites);
100
99
  if(action==='develop_redo')return explain('开发应答没有拿到(超时后代码已改动、会话断开或只回了 failed),会话可能仍在写文件。',
101
100
  '先确认会话已停止修改代码;再恢复原运行并发送 develop_redo 写入确认,之后 advance 重发本轮开发。盘上改动保留,经检查和独立审查。',
102
- 'develop_redo',['保留原配置、runId 与历史,以 --mode resume 启动','显式 --allow-develop-redo,并提供单行 reason','不占调用与 effect 名额;每运行最多 2 次']);
101
+ 'develop_redo',['保留原配置、runId 与历史,以 --mode resume 启动',permission('--allow-develop-redo'),'不占调用与 effect 名额;每运行最多 2 次']);
103
102
  if(state==='blocked'&&action==='resume'&&code==='develop_answer_missing')return explain('已确认会话停写,本轮开发等待重发。',
104
- '恢复原运行并发送 advance,用新 effect id 重发本轮开发;盘上改动保留,经检查和独立审查。',
103
+ `${resume},用新 effect id 重发本轮开发;盘上改动保留,经检查和独立审查。`,
105
104
  'advance',['保留原配置、runId 与历史,以 --mode resume 启动','确认原宿主已关闭,且本轮开发有原合同要求的授权']);
106
105
  if(state==='blocked'&&action==='resume'&&code==='develop_out_of_scope')return explain('开发交付已落盘,但改动超出了任务 scope(reason 列出路径),尚未进入审查。',
107
- '核对这些路径:会话越界写的就还原,你自己的改动就移出代码根,确需改动先走规格变更扩大 scope;然后恢复原运行并发送 advance,只重跑检查、验证预检与审查包,不重新开发。',
106
+ `核对这些路径:会话越界写的就还原,你自己的改动就移出代码根,确需改动先走规格变更扩大 scope;然后${resume},只重跑检查、验证预检与审查包,不重新开发。`,
108
107
  'advance',['保留原配置、runId 与历史,以 --mode resume 启动','不占开发调用与 effect 名额;每运行最多 2 次','不擅自删除用户改动']);
109
108
  if(state==='blocked'&&action==='resume'&&['check_answer_missing','check_answer_invalid'].includes(code))
110
109
  return explain(code==='check_answer_invalid'?'开发交付已落盘,但之后的检查或验证预检答复格式不合格。'
111
110
  :'开发交付已落盘,但之后的检查或验证预检没有拿到应答(超时、断开或迟到)。',
112
- '先确认上一次检查命令已停止;然后恢复原运行并发送 advance,只重跑检查、验证预检与审查包,不重新开发。',
111
+ `先确认上一次检查命令已停止;然后${resume},只重跑检查、验证预检与审查包,不重新开发。`,
113
112
  'advance',['保留原配置、runId 与历史,以 --mode resume 启动','不占开发调用与 effect 名额;每运行最多 2 次','不会自动完成任务或消耗新的独立审查轮次']);
114
113
  if(state==='blocked'&&action==='complete'&&code==='complete_commit_interrupted')return explain('宿主在写入任务完成提交意图后退出,tasks.md 可能已勾选也可能未勾选。',
115
114
  '恢复原运行并发送 complete;宿主只按存档里的提交计划核对并收尾,不重新复查、不重新开发。tasks.md 或证据被改动时会拒绝并保留现场。',
@@ -119,25 +118,26 @@ export function operatorGuidance(result,{executionActive=false}={}){
119
118
  'complete',['原 run 与已审交接、范围和包绑定不变','task-commit-intent 尚未写入;每运行最多 2 次']);
120
119
  if(state==='blocked'&&action==='resume'&&Object.hasOwn(deliveryMessages,code)){
121
120
  const [summary,repair]=deliveryMessages[code];
122
- return explain(summary,`${repair};然后恢复原运行并发送 advance,重做本轮交付和检查。`,
121
+ return explain(summary,`${repair};然后${resume},重做本轮交付和检查。`,
123
122
  'advance',['保留原配置、runId 与历史,以 --mode resume 启动','确认原宿主已关闭,且本轮开发有原合同要求的授权','不会自动完成任务或消耗新的独立审查轮次']);
124
123
  }
125
124
  if(state==='pending_review'&&action==='resume')return explain('本轮独立审查未取得可接受的结论。',
126
- '核对 code 与原审查证据;恢复原运行后,取得本轮绑定的独立审查授权,再发送 advance。',
125
+ `核对 code 与原审查证据;取得本轮绑定的独立审查授权,再${resume}。`,
127
126
  'advance',['原 run、配置和审查包绑定不变','原宿主仍须核对重派次数、进程和独立审查权限']);
128
127
  if(state==='blocked'&&action==='complete')return explain('完成前复核受阻,已有审查结论不能直接当作任务完成。',
129
128
  '核对 reason 中的检查或文件变化;满足原完成条件后,在原运行发送 complete,不重新开发。',
130
129
  'complete',['原 run 与已审交接、范围和包绑定不变','使用当前 packageDigest;由宿主重新核对完成条件']);
131
130
  if(code==='review_redispatch_limit')return explain('本轮独立审查已无结论重派 2 次,不再重派;这不计为审查轮次。',
132
- '先查清审查进程为何一直没有结论(登录、额度、网络或审查答复格式);修好后按 reason 用 --supersede-reviewed-evidence 新建运行重做。',
133
- null,['原运行记录保留,不改写','本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift']);
131
+ `先查清审查进程为何一直没有结论(登录、额度、网络或审查答复格式);${supersede}`,
132
+ null,supersedePrerequisites);
134
133
  if(['check_answer_retry_limit','complete_recheck_limit','develop_redo_limit'].includes(code))
135
134
  return explain('这一步的自动恢复已在本运行用满 2 次,不再重做。',
136
- '先查清会话为何一直不应答或答复不合格(或宿主环境为何失败);修好后按 reason 用 --supersede-reviewed-evidence 新建运行重做。',
137
- null,['原运行记录保留,不改写','本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift']);
135
+ `先查清会话为何一直不应答或答复不合格(或宿主环境为何失败);${supersede}`,
136
+ null,supersedePrerequisites);
138
137
  // Q06/Q07/Q11: a QA call that stopped as a whole.
139
138
  if(state==='fixture_completed'&&code==='qa_execution_unknown')return explain('本轮 QA 没有正常结束(整轮超时、宿主中途退出、答复格式不合格,或浏览器请求超时后设备可能仍被会话占用)。',
140
- '先确认上一轮的会话、浏览器或模拟器已停止、设备已空闲;再用原配置 --mode resume 加 --rerun-unknown-qa 重跑本轮。宿主拒绝时按拒绝码处理:含原始 FAIL、未解决的 [需确认] 或无法归因的旧记录的轮次不能替代,改用 --supersede-reviewed-evidence 新建运行。',
139
+ v2?(batch?'先确认上一轮会话与设备已空闲;批次 v2 没有启动型 QA 重跑出口,保留批次与 QA 证据并核对 reason,不新建运行绕过。':'先确认上一轮的会话、浏览器或模拟器已停止、设备已空闲;只读 status,展示并核对 launchControlTarget 后完整固定到文件。以原策略与配置 --mode resume、--expected-control FILE 和 --rerun-unknown-qa 启动;snapshot_changed 时停止,不自动刷新目标。宿主拒绝时保留原运行与 QA 证据,不改走旧入口。')
140
+ :'先确认上一轮的会话、浏览器或模拟器已停止、设备已空闲;再用原配置 --mode resume 加 --rerun-unknown-qa 重跑本轮。宿主拒绝时按拒绝码处理:含原始 FAIL、未解决的 [需确认] 或无法归因的旧记录的轮次不能替代,改用 --supersede-reviewed-evidence 新建运行。',
141
141
  null,['保留原运行与 QA 日志,只追加不改写','因宿主或应答原因替代的轮次不占三轮预算']);
142
142
  // Q15: the read-only documentation check answered blocked.
143
143
  if(state==='fixture_completed'&&code==='documentation_sync_blocked')return explain('文档核对判定文档尚未同步(reason 写明缺什么)。',
@@ -174,20 +174,23 @@ const BATCH_RECOVERY={
174
174
  };
175
175
  // A member result is not a batch control surface. Keep unsupported single-run
176
176
  // recovery operations out of batch instructions without changing pendingAction.
177
- export function batchOperatorGuidance(result,{taskKey=null}={}){
178
- const g=result?.guidance;if(!g)return null;
177
+ export function batchOperatorGuidance(result,{taskKey=null,protocol='legacy'}={}){
178
+ const context=guidanceContext.get(result?.guidance);
179
+ const g=context?operatorGuidance(result,{...context,protocol,surface:'batch'}):result?.guidance;
180
+ if(!g)return null;
179
181
  if(Object.hasOwn(BATCH_RECOVERY,g.recoveryOperation)){
180
- const [flag,confirm]=BATCH_RECOVERY[g.recoveryOperation],target=taskKey??'FEATURE/TASK';
182
+ const [flag,defaultConfirm]=BATCH_RECOVERY[g.recoveryOperation],target=taskKey??'FEATURE/TASK';
183
+ const confirm=g.recoveryOperation==='develop_redo'&&Object.hasOwn(documentationMessages,result.code)
184
+ ?'先确认会话已停止修改文档':defaultConfirm;
185
+ if(protocol==='v2')return explain(g.summary,
186
+ `${confirm};用原策略与配置从批次入口只读 status,展示并核对完整批次 controlTarget(batchId、taskKey、member、batchDigest),按当前对话的具体决定固定为 expectedControl;发送 version:2 的批次操作 ${g.recoveryOperation}(taskKey ${target}、单行 reason),之后 advance 继续本批次。`,
187
+ g.recoveryOperation,['保留原批次、成员身份与历史;不跨成员','snapshot_changed 时停止,不自动刷新目标重试;批次 cancel 后不能再恢复']);
181
188
  return explain(g.summary,`${confirm};关闭批次宿主,带 ${flag} ${target} 用同一批次配置重新启动,发送批次操作 ${g.recoveryOperation}(taskKey ${target}、单行 reason),之后 advance 继续本批次。`,
182
189
  g.recoveryOperation,['保持原批次配置;批次只用这一项权限打开该成员运行,不跨成员','授权用一次即失效;批次 cancel 后不能再恢复']);
183
190
  }
184
191
  if(result.code==='spec_drift')return explain(g.summary,
185
192
  '批次成员不能换绑规格;先按 reason 核对原批次可用出口,不直接重派。');
186
- if(g.recoveryOperation==='advance')return explain(g.summary,
187
- g.nextStep.replace('然后恢复原运行并发送 advance,重做本轮交付和检查。','然后从原批次入口发送 advance,重做本轮交付和检查。')
188
- .replace('然后恢复原运行并发送 advance,只重跑','然后从原批次入口发送 advance,只重跑')
189
- .replace('恢复原运行并发送 advance,用新 effect id','从原批次入口发送 advance,用新 effect id')
190
- .replace('恢复原运行后,取得本轮绑定的独立审查授权,再发送 advance。','沿原批次续接,取得本轮绑定的独立审查授权,再发送 advance。'),
193
+ if(g.recoveryOperation==='advance')return explain(g.summary,g.nextStep,
191
194
  'advance',['保持原批次配置、身份和 PLAN;成员运行由批次宿主选择恢复','先确认原批次宿主已关闭;开发与审查仍需原合同授权']);
192
195
  if(g.recoveryOperation==='complete')return explain(g.summary,
193
196
  '核对 reason 中的检查或文件变化;满足原完成条件后,从原批次入口发送 advance,由成员宿主继续完成复核。',
@@ -316,7 +316,7 @@ export function reviewSpecsPath(root,specsRoot) {
316
316
  need(root!==specsRoot&&!root.startsWith(specsRoot+path.sep),'overlapping_roots');
317
317
  return specsRoot.startsWith(root+path.sep)?filePath(path.relative(root,specsRoot).split(path.sep).join('/')):null;
318
318
  }
319
- function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selected=null,policy=null) {
319
+ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selected=null,policy=null,inventoryOnly=false) {
320
320
  if(specsPath!==null){
321
321
  const target=path.join(root,specsPath);
322
322
  need(fs.realpathSync(target)===target&&fs.lstatSync(target).isDirectory(),'unsupported_path');
@@ -324,9 +324,9 @@ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selecte
324
324
  const files=[],seen=new Set(); let total=0,materialBytes=0,materialCount=0,visitedSpecs=false;
325
325
  function add(p,s){
326
326
  if(!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw diagnostic('unsupported_file',p);
327
- const includeContent=selected===null||materialPath(p,selected);
328
- const countLimit=selected===null?FILE_COUNT:INVENTORY_COUNT;
329
- const byteLimit=selected===null?SNAPSHOT_LIMIT:INVENTORY_LIMIT;
327
+ const includeContent=!inventoryOnly&&(selected===null||materialPath(p,selected));
328
+ const countLimit=selected===null&&!inventoryOnly?FILE_COUNT:INVENTORY_COUNT;
329
+ const byteLimit=selected===null&&!inventoryOnly?SNAPSHOT_LIMIT:INVENTORY_LIMIT;
330
330
  if(files.length>=countLimit)throw diagnostic('limit_exceeded',p,`file count > ${countLimit}`);
331
331
  if(total+s.size>byteLimit)throw diagnostic('limit_exceeded',p,`inventory bytes > ${byteLimit}`);
332
332
  if(includeContent&&materialCount>=FILE_COUNT)
@@ -354,7 +354,14 @@ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selecte
354
354
  try { names=fs.readdirSync(path.join(root,rel)).sort(); } catch { fail('read_failed'); }
355
355
  for(const name of names) {
356
356
  const p=rel ? rel+'/'+name : name;
357
+ // Compatibility evidence is outside the code inventory: only the code
358
+ // root's own .reviews and the specs subtree. A nested directory that
359
+ // merely shares the name is ordinary code and stays in the inventory.
360
+ // Existing JS snapshots retain their historical selection and record shape.
357
361
  let s; try { s=fs.lstatSync(path.join(root,p)); } catch { fail('read_failed'); }
362
+ if(inventoryOnly&&p==='.reviews'&&p!==specsPath){
363
+ need(s.isDirectory()&&!s.isSymbolicLink(),'unsupported_path');continue;
364
+ }
358
365
  // Linked worktrees use a regular .git pointer file instead of a directory.
359
366
  // Treat both as Git metadata, never read/follow the pointer or traverse it.
360
367
  // Scope and requirement paths still cannot select any .git entry.
@@ -924,3 +931,8 @@ export function readReviewBaseline(raw) {
924
931
  export function readReviewPackage(raw) {
925
932
  const value=plain(raw);validPackage(value);return freeze(value);
926
933
  }
934
+
935
+ // Reuse the same bounded scanner and two-sided stable policy for compatibility
936
+ // inventories; the default snapshot mode above is unchanged for JS callers.
937
+ export {snapshot,rootPath,stableIgnorePolicy,stablePublicPolicy,stableSnapshotPolicy,
938
+ comparableFiles,validateStablePolicy,filePath,INVENTORY_COUNT,INVENTORY_LIMIT};
@@ -64,7 +64,7 @@ export function fixReviewedAt(specsRoot,evidence){
64
64
  // Journals without a registered V3 review have no order and never qualify.
65
65
  export function approvedReviewAt(state){
66
66
  const registration=state?.reviewInvocation?.registration;
67
- return registration&&registration.grant?.packageDigest===state.reviewPackage?.packageDigest
67
+ return registration&&registration.binding?.packageDigest===state.reviewPackage?.packageDigest
68
68
  &&Number.isSafeInteger(registration.registeredAt)?registration.registeredAt:null;
69
69
  }
70
70
 
@@ -1,3 +1,4 @@
1
+ import {beginHostStage} from './host-stage-observer.mjs';
1
2
  import {readExecutionPolicy} from './execution-policy.mjs';
2
3
  import {readExternalModels} from './external-models.mjs';
3
4
  import {beforeFirstQaRound,readQaConfigRevision} from './qa-config-revision.mjs';
@@ -17,10 +18,9 @@ import { digest,need,shape,id,text,json,freeze,arrayItems,validIdentity,validTas
17
18
  import { reviewResult,reviewReceipt,boundReviewText,reviewPaths } from './review-runner.mjs';
18
19
  import { checkCompletion } from './gate-bridge.mjs';
19
20
  import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRunnerRecord,
20
- MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,effectSlotFree,reviewTimeoutTransition,validateReviewDispatchGrant,validateTaskLearningReviewPackage,
21
+ MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,effectSlotFree,reviewTimeoutTransition,validateTaskLearningReviewPackage,
21
22
  reviewRetrySpent,abandonableReviewResult,developBudget,developBudgetExhausted,
22
- MAX_REVIEW_REDISPATCHES,REVIEW_RETRY_CODES,reviewNotDispatchedExhausted,REVIEW_NOT_DISPATCHED_LIMIT_CODE,reviewNeverStartedStatus,reviewNotDispatchedLimitReason,reviewNotDispatchedExtendable,reviewDenialUnconfirmed,reviewDenialExhausted,reviewDenialConfirmable,reviewDenialLimitReason,
23
- REVIEW_DENIAL_LIMIT_CODE,REVIEW_DISPATCH_CONFIRM_REQUIRED_CODE,countReviewDispatchConfirmations,reviewRedispatchCount,reviewRedispatchable,reviewRedispatchExhausted,REVIEW_REDISPATCH_LIMIT_CODE,reviewRedispatchLimitReason,reviewRedispatchStopReason,reviewAbandonRefusal,
23
+ MAX_REVIEW_REDISPATCHES,REVIEW_RETRY_CODES,reviewRedispatchCount,reviewRedispatchable,reviewRedispatchExhausted,REVIEW_REDISPATCH_LIMIT_CODE,reviewRedispatchLimitReason,reviewRedispatchStopReason,reviewAbandonRefusal,
24
24
  completionBlockCount,completionRetriesExhausted,supersededReviewPayload,bootstrapReviewRecoverable,protectedDevelopScope,protectedScopeBlockReason,
25
25
  developTimeoutBasis,developTimeoutEffect,developTimeoutState,DEVELOP_CALL_TIMEOUT_REASON,
26
26
  developAnswerInvalidEffect,developAnswerRetryable,developAnswerInvalidReason,
@@ -31,6 +31,7 @@ import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRu
31
31
  pendingDevelopStart,redoDevelopStart,workerGoneBinding,EFFECT_INTERRUPT_LIMIT_CODE,effectInterruptLimitReason,developRedoSource,COMMIT_INTERRUPTED_CODE,COMMIT_INTERRUPTED_REASON,
32
32
  DOCUMENTATION_SYNC_CODES,documentationSyncSource,documentationSyncRetryCode,documentationSyncStopReason } from './durable-runner-state.mjs';
33
33
  import {splitDocumentationState} from './host-documentation.mjs';
34
+ import {readControlPolicy} from './control-policy.mjs';
34
35
  import {readProcessStartTime,inspectWorkerGroup} from './worker-process-identity.mjs';
35
36
  import {recoverRunnerCommitImage} from './task-commit.mjs';
36
37
  import {commitRunnerFixture} from './task-commit.mjs';
@@ -156,6 +157,7 @@ export function createTaskRunner(options) {
156
157
  if(options && Object.hasOwn(options,'knowledgeCloseout'))optionKeys.push('knowledgeCloseout');
157
158
  if(options && Object.hasOwn(options,'executionPolicy'))optionKeys.push('executionPolicy');
158
159
  if(options && Object.hasOwn(options,'externalModels'))optionKeys.push('externalModels');
160
+ if(options && Object.hasOwn(options,'controlPolicy'))optionKeys.push('controlPolicy');
159
161
  if(invocationMode)optionKeys.push('reviewInvocation');
160
162
  shape(options,optionKeys);
161
163
  need(options.providerDevelopment===undefined||typeof options.providerDevelopment==='boolean','invalid_input');
@@ -192,10 +194,10 @@ export function createTaskRunner(options) {
192
194
  if(invocationMode)id(r.adapterId);
193
195
  return {...v,...(invocationMode?{adapterId:r.adapterId}:{}),run};
194
196
  });
195
- let invocationConfig=null,authorize=null,liveHostContextId=null,reviewTimeoutMs=null;
197
+ let invocationConfig=null,liveHostContextId=null,reviewTimeoutMs=null;
196
198
  if(invocationMode){
197
199
  need(reviewers.length===1&&['codex','claude'].includes(reviewers[0].provider)&&reviewers[0].allowed&&reviewers[0].available,'runner_invocation');
198
- shape(options.reviewInvocation,['developerThreadId','excludedThreadIds','authorize',
200
+ shape(options.reviewInvocation,['developerThreadId','excludedThreadIds',
199
201
  ...['hostContextId','timeoutMs'].filter(key=>Object.hasOwn(options.reviewInvocation,key))]);
200
202
  liveHostContextId=options.reviewInvocation.hostContextId??null;
201
203
  // Transient like hostContextId, never journaled: the host sizes the review
@@ -206,7 +208,6 @@ export function createTaskRunner(options) {
206
208
  }
207
209
  if(liveHostContextId!==null){id(liveHostContextId);
208
210
  need(![developer.contextId,...reviewers.flatMap(r=>r.contexts)].includes(liveHostContextId),'not_independent');}
209
- authorize=options.reviewInvocation.authorize;need(typeof authorize==='function','runner_invocation');
210
211
  invocationConfig=json({developerThreadId:options.reviewInvocation.developerThreadId,
211
212
  excludedThreadIds:options.reviewInvocation.excludedThreadIds});
212
213
  id(invocationConfig.developerThreadId);need(Array.isArray(invocationConfig.excludedThreadIds)
@@ -219,7 +220,8 @@ export function createTaskRunner(options) {
219
220
  ...(Object.hasOwn(options,'taskLearning')?{taskLearning:json(options.taskLearning)}:{}),
220
221
  ...(Object.hasOwn(options,'knowledgeCloseout')?{knowledgeCloseout:readCloseoutPolicy(options.knowledgeCloseout)}:{}),
221
222
  ...(Object.hasOwn(options,'executionPolicy')?{executionPolicy:readExecutionPolicy(options.executionPolicy)}:{}),
222
- ...(Object.hasOwn(options,'externalModels')?{externalModels:readExternalModels(options.externalModels)}:{})});
223
+ ...(Object.hasOwn(options,'externalModels')?{externalModels:readExternalModels(options.externalModels)}:{}),
224
+ ...(Object.hasOwn(options,'controlPolicy')?{controlPolicy:readControlPolicy(options.controlPolicy)}:{})});
223
225
  const taskLearning=metadata.taskLearning??null;
224
226
  if(taskLearning!==null){need(taskMode,'runner_learning');
225
227
  shape(taskLearning,['feature',...(Object.hasOwn(taskLearning,'hostHandoff')?['hostHandoff']:[])]);
@@ -353,13 +355,10 @@ export function createTaskRunner(options) {
353
355
  function reviewRedispatchRecords(){
354
356
  return journal?.filter(row=>row.payload.type==='review-redispatch'&&row.payload.attempt===attempt).length??0;
355
357
  }
356
- // The review effect ids of the current round: the entry derives the next redispatch id from
357
- // them, never from reviewInvocation (a refused authorization leaves it at the previous round's
358
- // value), so an id can never repeat one the cache holds.
358
+ // The entry derives each redispatch id from the current round's durable effects,
359
+ // so an id cannot repeat one the cache already holds.
359
360
  const reviewEffectIds=()=>[...cache.values()].filter(entry=>entry.effect.kind==='review'
360
361
  &&entry.effect.identity.attempt===attempt).map(entry=>entry.effect.id);
361
- // Confirmations of this round (abandon_review on a review that never started).
362
- const reviewDispatchConfirmations=()=>countReviewDispatchConfirmations((journal??[]).map(row=>row.payload),attempt);
363
362
  // A spent retryable review block this round may still redispatch (advance).
364
363
  const reviewRedispatchLive=()=>Boolean(!(metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned
365
364
  &&!restored?.pending&&reviewRedispatchable({state,code,attempt,cache:[...cache.values()],calls,reviewInvocation},
@@ -615,12 +614,6 @@ export function createTaskRunner(options) {
615
614
  current=freeze({...current,reviewRedispatchStopRequired:true,reason:reviewRedispatchStopReason(current.code)});
616
615
  else if(current.state==='blocked'&&reviewRedispatchSpent())
617
616
  current=freeze({...current,code:REVIEW_REDISPATCH_LIMIT_CODE,reason:reviewRedispatchLimitReason(current.code)});
618
- // A round whose review never started: a refused authorization (explicit confirmation
619
- // needed) or registrations voided before dispatch three times. Shared with replay.
620
- if(!busy&&current.state==='pending_review'){
621
- const never=reviewNeverStartedStatus({state,code,attempt,cache:[...cache.values()]},reviewDispatchConfirmations());
622
- if(never!==null)current=freeze({...current,...never});
623
- }
624
617
  // Status only; never part of a cached result or checkpoint.
625
618
  if(current.state==='unknown'&&reviewResultAbandonable())current=freeze({...current,abandonableReviewResult:true});
626
619
  else if(current.state==='unknown'&&!(metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned&&!restored?.pending){
@@ -631,8 +624,8 @@ export function createTaskRunner(options) {
631
624
  &&readRunnerHistory(journal,metadata,3).reviewReconciliation!==null;
632
625
  if((metadata.externalModels||metadata.executionPolicy)&&!busy&&!poisoned&&invocationMode&&store&&reviewInvocation?.registration
633
626
  &&(available||current.state==='unknown'&&reviewInvocation.result?.reconciliationRequired!==false)){
634
- const grant=reviewInvocation.registration.grant;
635
- current=freeze({...current,reviewReconciliation:{invocationId:grant.invocationId,requestDigest:grant.requestDigest,
627
+ const binding=reviewInvocation.registration.binding;
628
+ current=freeze({...current,reviewReconciliation:{invocationId:binding.invocationId,requestDigest:binding.requestDigest,
636
629
  provider:reviewers[0].provider,providerThreadId:reviewInvocation.started,available},
637
630
  reason:available?'原调用的终态与本地清理收据已保存;使用 reconcile_review 接纳证据,此操作不派发模型。'
638
631
  :'缺少原调用的可信终态或本地清理证据。保留本 run、attempt、journal 和快照;按 invocationId / providerThreadId 向原宿主或 provider 核对结果及终止状态,并确认本地后代已退出。当前适配器没有远端状态查询入口,人工说明、PID 消失或重启均不能解锁;不要删 journal、换 runId 或重派。'});
@@ -848,6 +841,7 @@ export function createTaskRunner(options) {
848
841
  function active(){need(!poisoned,'store_failure');need(state!=='cancelled','cancelled');}
849
842
  async function bounded(fn,request,extraControl=null) {
850
843
  active();let timer,abort;
844
+ const endStage=beginHostStage(request?.role==='developer'?'develop':request?.role==='reviewer'?'review':'check',config.timeoutMs);
851
845
  try {
852
846
  const boxed=await Promise.race([
853
847
  new Promise((resolve,reject)=>{
@@ -873,7 +867,7 @@ export function createTaskRunner(options) {
873
867
  })
874
868
  ]);
875
869
  return boxed.value;
876
- } finally {clearTimeout(timer);controller.signal.removeEventListener('abort',abort);}
870
+ } finally {endStage();clearTimeout(timer);controller.signal.removeEventListener('abort',abort);}
877
871
  }
878
872
  async function invoke(adapter,role,contextId,payload,extraControl=null) {
879
873
  const request=requestFor({invocationId:`${session}.${++sequence}`,identity:{...config.identity,attempt},
@@ -919,60 +913,26 @@ export function createTaskRunner(options) {
919
913
  const nextSequence=sequence+1,request=requestFor({invocationId:`${session}.${nextSequence}`,
920
914
  identity:{...config.identity,attempt},role:'reviewer',provider:adapter.provider,
921
915
  requestedModel:adapter.requestedModel,contextId,payload});
922
- let authorizationAt;
923
- try{authorizationAt=safeTime();}catch{halt('unknown','clock_invalid');return;}
924
- let grant;
925
- try{
926
- const returned=authorize(request,Object.freeze({authorizationAt}));
927
- if(types.isPromise(returned)){
928
- observePromise(returned,ignorePromiseResult,ignorePromiseResult);
929
- if(state==='cancelled'||controller.signal.aborted)return;
930
- need(false,'authorization_invalid');
931
- }
932
- if(state==='cancelled'||controller.signal.aborted)return;
933
- grant=json(returned);
934
- if(digest(grant)===digest({status:'denied',code:'permission_denied'})){
935
- halt('pending_review','permission_denied');return;
936
- }
937
- }catch(error){
938
- if(state==='cancelled'||controller.signal.aborted)return;
939
- halt('unknown',failureCode(error)==='clock_invalid'?'clock_invalid':'authorization_invalid');return;
940
- }
941
- if(state==='cancelled'||controller.signal.aborted)return;
942
916
  let registeredAt;
943
917
  try{registeredAt=safeTime();}catch{halt('unknown','clock_invalid');return;}
944
- if(registeredAt<authorizationAt){halt('unknown','clock_invalid');return;}
945
- try{grant=validateReviewDispatchGrant(grant,{request,reviewerId:adapter.id,adapterId:adapter.adapterId,
946
- packageDigest:reviewPackage.packageDigest,hostContextIds:[invocationConfig.developerThreadId,...liveInvocation().excludedThreadIds],
947
- authorizationAt,registeredAt});}
948
- catch{halt('unknown','authorization_invalid');return;}
949
- const registrationFields={effectId,reviewerId:adapter.id,adapterId:adapter.adapterId,requestDigest:request.requestDigest,
950
- authorizationAt,registeredAt,grant};
951
- // Validate first, then journal the signer immediately before registration.
952
- // Durable host lists and prior joiners already have replayable authority.
953
- if(![invocationConfig.developerThreadId,...invocationConfig.excludedThreadIds,...joinedHosts].includes(grant.hostContextId)){
918
+ if(state==='cancelled'||controller.signal.aborted)return;
919
+ const hostContextId=liveHostContextId??invocationConfig.developerThreadId;
920
+ const binding=json({adapterId:adapter.adapterId,invocationId:request.invocationId,requestDigest:request.requestDigest,
921
+ identity:request.identity,reviewerId:adapter.id,logicalContextId:request.contextId,
922
+ packageDigest:reviewPackage.packageDigest,hostContextId});
923
+ if(![invocationConfig.developerThreadId,...invocationConfig.excludedThreadIds,...joinedHosts].includes(hostContextId)){
954
924
  need(joinedHosts.length<MAX_AI_JOINED_HOSTS,'host_limit');
955
- persist('host-joined',{hostContextId:grant.hostContextId});joinedHosts.push(grant.hostContextId);
925
+ persist('host-joined',{hostContextId});joinedHosts.push(hostContextId);
956
926
  }
957
- persist('review-invocation-registered',registrationFields);
958
- sequence=nextSequence;
959
927
  const registration=json({reviewerId:adapter.id,adapterId:adapter.adapterId,requestDigest:request.requestDigest,
960
- authorizationAt,registeredAt,grant});
928
+ registeredAt,binding});
929
+ persist('review-invocation-registered',{effectId,...registration});
930
+ sequence=nextSequence;
961
931
  const call={invocationId:request.invocationId,contextId,provider:request.provider,requestedModel:adapter.requestedModel,
962
- effectiveModel:'unknown',channel:'host-authorized',started:false,terminal:'running',requestDigest:request.requestDigest,
932
+ effectiveModel:'unknown',channel:'host-review',started:false,terminal:'running',requestDigest:request.requestDigest,
963
933
  resultDigest:null,providerThreadId:null};
964
934
  calls.push(call);
965
- let dispatchAt=null,notDispatched=null;
966
- try{dispatchAt=safeTime();if(dispatchAt<registeredAt)notDispatched='clock_invalid';
967
- else if(dispatchAt>=grant.expiresAt)notDispatched='grant_expired';}
968
- catch{notDispatched='clock_invalid';}
969
- if(notDispatched){
970
- const fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'not_dispatched',observation:null,inspection:null,
971
- reconciliationRequired:true,reason:notDispatched};
972
- persist('review-invocation-result',fields);const result=resultView(fields);
973
- Object.assign(call,{terminal:'not_dispatched',resultDigest:digest(result)});
974
- reviewInvocation=json({registration,started:null,result});halt('pending_review',notDispatched);return;
975
- }
935
+ const dispatchAt=registeredAt;
976
936
  call.started=true;
977
937
  const expectation={request,developerThreadId:invocationConfig.developerThreadId,
978
938
  excludedThreadIds:reviewExclusions(liveInvocation(),calls,developer.contextId)};
@@ -1023,6 +983,7 @@ export function createTaskRunner(options) {
1023
983
  }
1024
984
  };
1025
985
  let timer,timedOut=false,cancelReject;
986
+ const endReviewStage=beginHostStage('review',reviewTimeoutMs??config.timeoutMs);
1026
987
  try{
1027
988
  let raw;
1028
989
  try{
@@ -1132,7 +1093,7 @@ export function createTaskRunner(options) {
1132
1093
  else if(retry)halt(retry.state,retry.code);
1133
1094
  else halt('unknown',inspection.code??'reconciliation_required');
1134
1095
  }finally{
1135
- captureOpen=false;
1096
+ endReviewStage();captureOpen=false;
1136
1097
  if((metadata.externalModels||metadata.executionPolicy)&&(state==='unknown'||state==='pending_review'&&code==='review_transport_timeout')
1137
1098
  &&started!==null&&!invalid&&!receiptConflict&&capturedReceipt)
1138
1099
  pendingReconciliation={effectId,invocationId:request.invocationId,receipt:capturedReceipt};
@@ -1481,14 +1442,9 @@ export function createTaskRunner(options) {
1481
1442
  timeoutBasis=developTimeoutRetryBasis();need(timeoutBasis!==null,'develop_timeout_root_changed');
1482
1443
  if(state==='blocked')timeoutBasis=null;
1483
1444
  }
1484
- // A refused authorization is a decision: a review is admitted again only after the
1485
- // operator's journaled confirmation (abandon_review), bounded per round.
1486
- if(v.kind==='review'&&reviewDenialUnconfirmed({state,code}))
1487
- need(false,reviewDenialExhausted({state,code},reviewDispatchConfirmations())?REVIEW_DENIAL_LIMIT_CODE:REVIEW_DISPATCH_CONFIRM_REQUIRED_CODE);
1488
1445
  answerRetry=v.kind==='develop'&&state==='blocked'&&code==='failed'&&answerRetryable();
1489
1446
  need(timeoutBasis!==null||answerRetry||recheck!==null||completeSource!==null||dispatchBasis!==null
1490
1447
  ||stageAllowed(v.kind,state,code,priorReview?.verdict),'stage_mismatch');need(effectSlotFree(v.kind,[...cache.values()],calls),'limit_exceeded');
1491
- need(!(v.kind==='review'&&reviewNotDispatchedExhausted({state,code,attempt,cache:[...cache.values()]},reviewDispatchConfirmations().extended)),REVIEW_NOT_DISPATCHED_LIMIT_CODE);
1492
1448
  if(Object.hasOwn(original,'specification'))verifySpecificationMaterial(original);
1493
1449
  if(v.kind==='develop'&&bootstrap!==null)bootstrap.assertWriteAuthorized();
1494
1450
  } catch(error){return Promise.resolve(freeze({outcome:'rejected',code:error.code??'invalid_input',
@@ -1730,29 +1686,6 @@ export function createTaskRunner(options) {
1730
1686
  };
1731
1687
  const abandonReview=raw=>{
1732
1688
  try{
1733
- // A review that never started (a refused authorization, or the spent not-dispatched
1734
- // redispatch bound): nothing ran, so no process needs proving stopped, even for
1735
- // external-model runs. Only this explicit, audited confirmation leaves those ends.
1736
- if(invocationMode&&store&&!busy&&!poisoned&&!restored?.pending&&state==='pending_review'){
1737
- const confirmed=reviewDispatchConfirmations(),ended={state,code,attempt,cache:[...cache.values()]};
1738
- const denied=reviewDenialUnconfirmed(ended),voided=reviewNotDispatchedExhausted(ended,confirmed.extended);
1739
- if(denied||voided){
1740
- if(denied&&reviewDenialExhausted(ended,confirmed))
1741
- throw Object.assign(new Error(REVIEW_DENIAL_LIMIT_CODE),{code:REVIEW_DENIAL_LIMIT_CODE,reason:reviewDenialLimitReason()});
1742
- if(voided&&!reviewNotDispatchedExtendable(ended,confirmed))
1743
- throw Object.assign(new Error(REVIEW_NOT_DISPATCHED_LIMIT_CODE),
1744
- {code:REVIEW_NOT_DISPATCHED_LIMIT_CODE,reason:reviewNotDispatchedLimitReason(code,confirmed.extended)});
1745
- need(denied?reviewDenialConfirmable(ended,confirmed):true,'review_abandon_unavailable');
1746
- const value=json(raw);shape(value,['allowed','reason']);
1747
- need(value.allowed===true,'review_abandon_authorization_required');
1748
- need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1749
- &&!/[\r\n\0]/.test(value.reason),'review_abandon_reason_required');
1750
- persist('review-dispatch-confirmed',{effectId:[...cache.values()].at(-1).effect.id,attempt,code,reason:value.reason,
1751
- at:new Date().toISOString()});
1752
- const recovered=readRunnerHistory(journal,metadata,3).state;
1753
- ({state,code}=recovered);reason=recovered.reason??null;publication=privateStatus();return status();
1754
- }
1755
- }
1756
1689
  need(!(metadata.externalModels||metadata.executionPolicy),'external_review_reconciliation_required');
1757
1690
  // V5 (A34): the operator confirms the spent block's reviewer stopped; this
1758
1691
  // journals the round's second no-result redispatch (no dispatch here).
@@ -1762,7 +1695,7 @@ export function createTaskRunner(options) {
1762
1695
  need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1763
1696
  &&!/[\r\n\0]/.test(value.reason),'review_abandon_reason_required');
1764
1697
  persist('review-redispatch',{effectId:[...cache.values()].at(-1).effect.id,
1765
- invocationId:reviewInvocation.registration.grant.invocationId,attempt,code,reason:value.reason,at:new Date().toISOString()});
1698
+ invocationId:reviewInvocation.registration.binding.invocationId,attempt,code,reason:value.reason,at:new Date().toISOString()});
1766
1699
  state='pending_review';publication=privateStatus();return status();
1767
1700
  }
1768
1701
  if(state==='blocked'&&reviewRedispatchSpent())throw Object.assign(new Error('review_abandon_budget_exhausted'),{code:'review_abandon_budget_exhausted'});
@@ -1804,7 +1737,7 @@ export function createTaskRunner(options) {
1804
1737
  need(reviewRedispatchCount(history.state.cache,history.state.calls,attempt,contextId,reviewRedispatchRecords())<MAX_REVIEW_REDISPATCHES,
1805
1738
  'review_abandon_budget_exhausted');
1806
1739
  const fields={effectId:history.pending.id,
1807
- invocationId:history.state.reviewInvocation.registration.grant.invocationId,
1740
+ invocationId:history.state.reviewInvocation.registration.binding.invocationId,
1808
1741
  registeredDigest:registration.digest,startedDigest:started?.digest??null,
1809
1742
  ...(withResult?{resultDigest:last.digest}:{}),
1810
1743
  reason:value.reason,at:new Date().toISOString()};
@@ -1828,7 +1761,7 @@ export function createTaskRunner(options) {
1828
1761
  const {request,effect,before,result,...binding}=proof;
1829
1762
  const call=calls.find(item=>item.invocationId===value.invocationId);
1830
1763
  need(['unknown','failed'].includes(call?.terminal),'review_reconciliation_unavailable');
1831
- // Same call, same grant and same effect. The journal retains the original
1764
+ // Same call, same binding and same effect. The journal retains the original
1832
1765
  // unknown and receipt; one atomic record contains the validated transition.
1833
1766
  Object.assign(call,{terminal:result.outcome==='observed'?'succeeded':'failed',
1834
1767
  resultDigest:digest(result.outcome==='observed'?result.inspection.review:result)});
@@ -2007,7 +1940,14 @@ export function createTaskRunner(options) {
2007
1940
  };
2008
1941
  // Interrupted intents keep their ids; the entry derives fresh ones from this count.
2009
1942
  const interruptions=kind=>parsedHistory?.interrupted?.filter(item=>item.kind===kind).length??0;
2010
- const api={reviseQa,supersedeEvidence,rebindSpecification,abandonReview,reconcileReview,abandonEffect,recoverBootstrapReview,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks,completionBlocks,reviewEffectIds,recheckLearningInput,redoDevelop,recoverCommit,interruptions};
1943
+ // Read-only projection of the baseline-derived reviewed change inventory.
1944
+ // Entry checks current status before/after the call; do not rebuild a baseline
1945
+ // from the author's handoff or change any completion/correction authority.
1946
+ const qaChangedFiles=packageDigest=>{
1947
+ need(state==='fixture_completed'&&reviewPackage?.packageDigest===packageDigest,'stale_qa');
1948
+ return freeze({paths:reviewPackage.changes.map(change=>change.path),source:'review_package'});
1949
+ };
1950
+ const api={qaChangedFiles,reviseQa,supersedeEvidence,rebindSpecification,abandonReview,reconcileReview,abandonEffect,recoverBootstrapReview,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks,completionBlocks,reviewEffectIds,recheckLearningInput,redoDevelop,recoverCommit,interruptions};
2011
1951
  if(bootstrap!==null)api.inspectBootstrapAdmission=()=>bootstrap.inspectAdmission(original);
2012
1952
  if(taskLearning!==null)api.attachLearningEvidence=attachLearningEvidence;
2013
1953
  // A terminal reviewer observation is durable even if the host died before
@@ -2015,7 +1955,7 @@ export function createTaskRunner(options) {
2015
1955
  if(restored?.pendingObservedReview){
2016
1956
  const observed=restored.pendingObservedReview,request=observed.request,result=observed.result;
2017
1957
  const call={invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
2018
- requestedModel:request.requestedModel,effectiveModel:'unknown',channel:'host-authorized',
1958
+ requestedModel:request.requestedModel,effectiveModel:'unknown',channel:'host-review',
2019
1959
  started:true,terminal:'succeeded',requestDigest:request.requestDigest,
2020
1960
  resultDigest:digest(result.inspection.review),providerThreadId:observed.started};
2021
1961
  sequence++;calls.push(call);