@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
@@ -18,7 +18,9 @@ import {approvedTaskGrammar} from '../runtime/js/spec-task-line.mjs';
18
18
  import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
19
19
  import {inspectRunClosure as inspectClosure} from './cm-log-event.mjs';
20
20
  import {releaseVerifiedQaResources} from '../runtime/js/cm-ai/qa-resource-release.mjs';
21
- import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
21
+ import {readRunnerHistory,projectedRunnerStatus} from '../runtime/js/cm-ai/durable-runner-state.mjs';
22
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
23
+ import {readControlPolicy,controlTarget,readControlTarget} from '../runtime/js/cm-ai/control-policy.mjs';
22
24
  import {strictPriorAttemptResolved,sameTaskPriorAttemptResolved} from '../runtime/js/cm-ai/external-run-guard.mjs';
23
25
 
24
26
  const writer=fileURLToPath(new URL('./cm-log-event.py',import.meta.url));
@@ -29,16 +31,17 @@ export const batchTaskRunId=(batchId,taskKey)=>`task-${digest({batchId,task:task
29
31
  // never advertise it for them. Name the exits that do exist instead. An idle
30
32
  // cancel of a parallel group does not end its member runs, so a parallel
31
33
  // member cannot be superseded afterwards and only the spec revert applies.
32
- export function batchMemberResult(result,{parallel=false,taskKey=null}={}){
34
+ export function batchMemberResult(result,{parallel=false,taskKey=null,protocol='legacy'}={}){
33
35
  const decorate=value=>{
34
- const guidance=batchOperatorGuidance(value,{taskKey});
36
+ const guidance=batchOperatorGuidance(value,{taskKey,protocol});
35
37
  return guidance?Object.freeze({...value,guidance}):value;
36
38
  };
37
39
  if(result?.pendingAction!=='spec_rebind')return decorate(result);
38
40
  const files=/变更文件:([^;]+)/.exec(result.reason??'')?.[1]??'规格文件';
39
41
  const revert=`规格已重新批准(变更:${files},只动了其他任务),但批次成员不能换绑。出口:还原这些规格改动并重新批准后继续本批次`;
40
42
  return decorate(Object.freeze({...result,pendingAction:'none',
41
- reason:parallel?`${revert}。并行组成员没有单独重做的出口。`
43
+ reason:protocol==='v2'?`${revert}。v2 不支持作废旧证据后新建运行;保留原记录,不改走旧入口。`
44
+ :parallel?`${revert}。并行组成员没有单独重做的出口。`
42
45
  :`${revert};或取消本批次,还原该任务已改动的代码后,用单任务宿主 cm-ai-host.mjs 以 --supersede-reviewed-evidence --supersede-reason 原因 新建运行重做该任务。`}));
43
46
  }
44
47
  // Q24: single-task recovery operations a batch forwards to the member run it is
@@ -89,7 +92,8 @@ export function memberSupersedeAdmitted(specsDir,runId,history){
89
92
  export function createCmAiBatch({configuration,executionFor,logHome,runtime='codex',checkCommands=null,checkTimeoutMs=60000,
90
93
  rerunUnknownQa=false,rerunBlockedQa=false,qaEnvironmentFailure=null,holdRevisions=[],bootstrapKeys=[],memberActions={}}){
91
94
  const config=json(configuration);
92
- shape(config,['version','repositoryId','batchId','specsDir','codeProject','tasks',...['externalModels','executionPolicy','codeProjects','parallel'].filter(name=>Object.hasOwn(config,name))]);
95
+ shape(config,['version','repositoryId','batchId','specsDir','codeProject','tasks',...['externalModels','executionPolicy','codeProjects','parallel','controlPolicy'].filter(name=>Object.hasOwn(config,name))]);
96
+ const controlPolicy=config.controlPolicy?readControlPolicy(config.controlPolicy):null;
93
97
  need(config.version===1);id(config.repositoryId);id(config.batchId);need(config.batchId.length>=8);
94
98
  need(typeof executionFor==='function'&&typeof logHome==='string'&&path.isAbsolute(logHome));
95
99
  need(Array.isArray(config.tasks)&&config.tasks.length>0&&config.tasks.length<=256);
@@ -135,6 +139,16 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
135
139
  const groups=validateGroups(config,plans),membership=new Map(groups.flatMap(group=>group.map(key=>[key,group])));
136
140
  const originalMembership=new Map(membership),originalPlans=new Map(plans);
137
141
  const first=plans.keys().next().value,planDigest=digest(config),log=path.join(config.specsDir,'运行日志.jsonl');
142
+ const batchControlTarget=async(taskKey,state=progress())=>{
143
+ const definition=plans.get(taskKey);need(definition,'batch_member_action_unavailable');
144
+ if(membership.has(taskKey))bindWorktree(taskKey);
145
+ const run=await open(taskKey);need(run.controlHost,'fingerprint_mismatch');
146
+ try{
147
+ const observed=await run.controlHost.handle({version:2,operation:'status',requestId:'control-preview',identity:definition.identity});
148
+ return {version:2,batchId:config.batchId,taskKey,member:observed.controlTarget,
149
+ batchDigest:digest({planDigest,rows:state.rows})};
150
+ }finally{run.close();}
151
+ };
138
152
  // Q26: before any closure check, close cleanup_failed QA command resources whose
139
153
  // journaled process group the host proves gone (qa-resource-release.mjs).
140
154
  let stillOpen=[];
@@ -211,7 +225,9 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
211
225
  const run=await openControlRun(definition,mode,execution,{...recovery,...permission,...(held.has(taskKey)?{holdRevision:true}:{}),
212
226
  ...(membership.has(taskKey)?{parallelSelection:{version:1,group:membership.get(taskKey).map(key=>plans.get(key).identity.taskId)}}:{})});
213
227
  if(!run.host)return run;
214
- return {...run,host:{...run.host,handle:async request=>batchMemberResult(await run.host.handle(request),{parallel:membership.has(taskKey),taskKey})}};
228
+ const decorate=host=>({...host,handle:async request=>batchMemberResult(await host.handle(request),
229
+ {parallel:membership.has(taskKey),taskKey,protocol:controlPolicy?'v2':'legacy'})});
230
+ return {...run,host:decorate(run.host),...(run.controlHost?{controlHost:decorate(run.controlHost)}:{})};
215
231
  }
216
232
  function parallelProgress(rows){
217
233
  const done=new Set(),ready=new Map(),merging=new Map(),blocked=new Map();let stopped=false,code=null;
@@ -475,7 +491,8 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
475
491
  :!['blocked','cancelled','unknown','fixture_completed'].includes(history.state.state)?`supersede 不接受原始状态 ${raw}`
476
492
  :`外部运行守卫会拒绝在这个代码根上新建运行(原严格运行仍为 ${raw} 或有未对账的调用),原调用对账也不可用`;
477
493
  const exit=`只读核对 ${key} 原运行的记录、进程与 worktree(${location(key).worktree});`
478
- +(supersedable?`确认旧宿主与该成员的会话或子进程已停止写入后,取消本批次,还原该任务已改动的代码,用单任务宿主 cm-ai-host.mjs(不加 --external-models、--execution-optimizations)以该 worktree 为代码根、--supersede-reviewed-evidence --supersede-reason 原因 新建运行重做该任务`
494
+ +(controlPolicy?'v2 不支持作废旧证据后新建运行;保留原批次、运行与 worktree,核对原调用与 reason 后交由维护者处理,不改走旧入口'
495
+ :supersedable?`确认旧宿主与该成员的会话或子进程已停止写入后,取消本批次,还原该任务已改动的代码,用单任务宿主 cm-ai-host.mjs(不加 --external-models、--execution-optimizations)以该 worktree 为代码根、--supersede-reviewed-evidence --supersede-reason 原因 新建运行重做该任务`
479
496
  :`批次与单任务宿主目前都没有能处理它的操作:${why}${original}。保留批次、原运行和 worktree,不要取消批次或手改存档,把 rawState 与本 reason 交给维护者处理`);
480
497
  return Object.freeze({outcome:'blocked',state:'blocked',code:'batch_parallel_member_unresolved',batchId:config.batchId,
481
498
  currentTask:key,identity:status.identity,memberState:status.state,memberCode:status.code??null,pendingAction:status.pendingAction??null,
@@ -495,7 +512,9 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
495
512
  }
496
513
  function parallelRecoveryRequired(key,status){
497
514
  const action=status.pendingAction,grant=BATCH_MEMBER_ACTIONS[action];
498
- const exit=action==='reconcile_review'
515
+ const exit=controlPolicy
516
+ ?`从原批次入口只读 status,展示并核对完整批次 controlTarget,按当前对话的具体决定固定为 expectedControl;发送 version:2 的批次操作 ${action}(taskKey ${key}、${action==='reconcile_review'?'原调用 invocationId':'单行 reason'});snapshot_changed 时停止,不自动刷新目标重试`
517
+ :action==='reconcile_review'
499
518
  ?`从批次入口发送 reconcile_review(taskKey ${key}、原调用 invocationId)对账原调用回执`
500
519
  :`关闭批次宿主,带 ${grant.flag} ${key} 用同一批次配置重新启动,发送批次操作 ${action}(taskKey ${key}、单行 reason)`;
501
520
  return Object.freeze({outcome:'blocked',state:'blocked',code:'batch_parallel_member_recovery_required',batchId:config.batchId,
@@ -521,7 +540,7 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
521
540
  ?membership.get(state.current).filter(key=>membership.has(key)&&!state.ready?.has(key)&&!state.done?.has(key)):[state.current];
522
541
  if(!stopped.includes(taskKey))return refuse('batch_member_action_not_current',
523
542
  `批次当前停在 ${stopped.join('、')};恢复操作只转给当前停住的成员,不跨成员`);
524
- if(!actionGrants.get(request.operation).has(taskKey))return refuse('batch_member_action_authorization_required',
543
+ if(!controlPolicy&&!actionGrants.get(request.operation).has(taskKey))return refuse('batch_member_action_authorization_required',
525
544
  `${request.operation} 需要批次宿主启动参数 ${flag} ${taskKey};关闭批次宿主,带上该参数用同一批次配置重新启动后再发送`);
526
545
  if(membership.has(taskKey))bindWorktree(taskKey);
527
546
  const definition=plans.get(taskKey);
@@ -530,15 +549,19 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
530
549
  const run=await open(taskKey,{[option]:true});
531
550
  if(run.blocked)return {outcome:'blocked',code:run.blocked.reason,batchId:config.batchId};
532
551
  try{
533
- const result=await run.host.handle({version:1,operation:request.operation,requestId:request.requestId,
534
- identity:definition.identity,reason:request.reason});
552
+ const result=controlPolicy?await run.controlHost.handle({version:2,operation:request.operation,requestId:request.requestId,
553
+ identity:request.expectedControl.member.identity,reason:request.reason,expectedControl:request.expectedControl.member})
554
+ :await run.host.handle({version:1,operation:request.operation,requestId:request.requestId,
555
+ identity:definition.identity,reason:request.reason});
535
556
  actionGrants.get(request.operation).delete(taskKey);
536
557
  return {...result,batchId:config.batchId,taskKey};
537
558
  }finally{run.close();}
538
559
  }
539
- return Object.freeze({async handle(raw){
560
+ return Object.freeze({controlTarget:()=>batchControlTarget(progress().current),async handle(raw){
540
561
  const request=json(raw);shape(request,['operation','requestId',...(request.operation==='reconcile_review'?['taskKey','invocationId']:[]),
541
- ...(Object.hasOwn(BATCH_MEMBER_ACTIONS,request.operation??'')?['taskKey','reason']:[])]);id(request.requestId);
562
+ ...(Object.hasOwn(BATCH_MEMBER_ACTIONS,request.operation??'')?['taskKey','reason']:[]),
563
+ ...(controlPolicy?['version',...((IN_RUN_ACTIONS.has(request.operation??''))?['expectedControl']:[])]:[])]);id(request.requestId);
564
+ if(controlPolicy)need(request.version===2,'fingerprint_mismatch');
542
565
  need(['advance','status','cancel','reconcile_review',...Object.keys(BATCH_MEMBER_ACTIONS)].includes(request.operation));
543
566
  if(request.operation==='cancel'&&busy){
544
567
  cancelled=true;
@@ -557,6 +580,13 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
557
580
  try{
558
581
  releaseLock=acquireBatchLock(config);
559
582
  const initial=progress();liveKey=initial.current;
583
+ if(controlPolicy&&IN_RUN_ACTIONS.has(request.operation)){
584
+ const expected=json(request.expectedControl);shape(expected,['version','batchId','taskKey','member','batchDigest']);
585
+ readControlTarget(expected.member);hex(expected.batchDigest);
586
+ if(membership.has(request.taskKey))bindWorktree(request.taskKey);
587
+ need(expected.version===2&&expected.batchId===config.batchId&&expected.taskKey===request.taskKey
588
+ &&expected.batchDigest===digest({planDigest,rows:initial.rows}),'snapshot_changed');
589
+ }
560
590
  const {externalModels:ignoredModels,executionPolicy:ignoredPolicy,...policyBatch}=config;
561
591
  const policy=readBatchExecutionPolicy({batch:policyBatch,started:initial.rows.length>0,enabled:!!config.executionPolicy});
562
592
  need(digest(policy)===digest(config.executionPolicy??null),'execution_policy_batch_binding');
@@ -569,7 +599,9 @@ export function createCmAiBatch({configuration,executionFor,logHome,runtime='cod
569
599
  const definition=plans.get(request.taskKey);
570
600
  need(fs.existsSync(path.join(config.specsDir,'.reviews','.execution',definition.identity.runId,'state.json')),'review_reconciliation_unavailable');
571
601
  const run=await open(request.taskKey);
572
- try{return await run.host.handle({version:1,operation:'reconcile_review',requestId:request.requestId,identity:definition.identity,invocationId:request.invocationId});}
602
+ try{return controlPolicy?await run.controlHost.handle({version:2,operation:'reconcile_review',requestId:request.requestId,
603
+ identity:request.expectedControl.member.identity,invocationId:request.invocationId,expectedControl:request.expectedControl.member})
604
+ :await run.host.handle({version:1,operation:'reconcile_review',requestId:request.requestId,identity:definition.identity,invocationId:request.invocationId});}
573
605
  finally{run.close();}
574
606
  }
575
607
  if(initial.stopped)return {outcome:'blocked',code:initial.code??'cancelled',batchId:config.batchId};
@@ -85,13 +85,7 @@ function open(f,taskId,mode='create',overrides={}){
85
85
  return {status:'succeeded',value:{verdict:revise?'changes_requested':'approved',packageDigest:request.payload.reviewPackage.packageDigest,
86
86
  examinedPaths:reviewPaths(request.payload.reviewPackage),findings:revise?[{id:'F1',severity:'P2',path:'AGENTS.md',
87
87
  message:'Reverify instruction applicability',evidence:'Synthetic revision fixture'}]:[],summary:'Synthetic independent review'}};}}],
88
- reviewInvocation:{developerThreadId:'scaffold-author',excludedThreadIds:['main'],authorize:(request,{authorizationAt})=>{
89
- const body={version:1,kind:'cm-review-dispatch-grant',grantId:'grant-'+request.identity.attempt,adapterId:'codex-review-adapter',
90
- invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,reviewerId:'reviewer',
91
- logicalContextId:request.contextId,packageDigest:request.payload.reviewPackage.packageDigest,hostContextId:'main',
92
- decisionId:'decision-'+request.identity.attempt,decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
93
- return {...body,grantDigest:digest(body)};
94
- }},
88
+ reviewInvocation:{developerThreadId:'scaffold-author',excludedThreadIds:['main']},
95
89
  check:createHostCheck({cwd:f.codeProject,timeoutMs:1000,commands:[{id:'syntax',command:[process.execPath,'--check','app.mjs']}]}),
96
90
  taskCompletion:{reviewsDir:path.join(f.specsDir,'.reviews'),handoffs:[1,2].map(a=>path.join(f.specsDir,'.reviews',`bootstrap-${taskId}-a${a}-handoff.json`))},
97
91
  persistence:{store,mode,version:3}});
@@ -43,7 +43,7 @@ function prepareCli(f){
43
43
  for(const [name,value] of Object.entries(files))fs.writeFileSync(path.join(f.root,name+'.json'),JSON.stringify(value));
44
44
  return {cli,env,args:['serve','--config',config,'--mode','create','--host-context','bootstrap-current-host','--allow-development',
45
45
  '--protected-conversation-config',path.join(f.root,'protection.json'),'--bootstrap-config',path.join(f.root,'bootstrap.json'),
46
- '--allow-bootstrap-write','--review-config',path.join(f.root,'review.json'),'--allow-review-attempt','1',
46
+ '--allow-bootstrap-write','--review-config',path.join(f.root,'review.json'),
47
47
  '--workflow-config',path.join(f.root,'workflow.json'),'--allow-qa']};
48
48
  }
49
49
 
@@ -67,8 +67,7 @@ function runCli(f,config,mode,operation){
67
67
  if(['init_generate','init_verify'].includes(row.kind)){assert(mode==='create'||f.resumeInit);
68
68
  response=reply(f,row.kind,row.payload);
69
69
  if(row.kind==='init_verify'&&f.failVerify>0){f.failVerify--;response.checks.commands={status:'failed',evidence:'npm test exited 1'};}}
70
- else if(row.kind==='qa_assess')response={scores:{scope:5,risk:5,accumulation:5,boundary:5},
71
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}};
70
+ else if(row.kind==='qa_assess')response={confirmed:true};
72
71
  else if(row.kind==='documentation_inspect'){
73
72
  const {syncId,identity,packageDigest,contextDigest}=row.payload;
74
73
  response={syncId,identity,packageDigest,contextDigest,status:'completed',reason:'Fixture instructions inspected; no documentation paths configured',
@@ -0,0 +1,219 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {openControlRun,controlLaunchTarget} from './cm-ai-run.mjs';
9
+ import {readLaunchControlFile} from './cm-ai-host.mjs';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
11
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
12
+ import {createHostQaExecutor} from '../runtime/js/cm-ai/host-qa-executor.mjs';
13
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
14
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
15
+
16
+ const policy={version:2,development:'conversation',bootstrap:'disabled',qa:'run',qaFix:'disabled'};
17
+ const cli=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
18
+ function fixture(t,{legacy=false}={}){
19
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-control-launch-')));
20
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
21
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),feature='1.work';
22
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
23
+ fs.writeFileSync(path.join(codeProject,'a.mjs'),'export const a=1;\n');
24
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'fixture');
25
+ for(const file of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,file),'# fixture\n');
26
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: implement a\n- [ ] T-002: implement b\n');
27
+ const approve=()=>fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
28
+ approve();
29
+ const identity={repositoryId:'launch-fixture',runId:'launch-run-0001',taskId:'T-001',attempt:1};
30
+ const definition={version:1,specsDir,codeProject,feature,identity,scope:['a.mjs'],requirements:['requirements.md']};
31
+ const execution={configuration:{kind:'synthetic-launch-v1',hostContextId:'main',...(legacy?{}:{controlPolicy:policy})},
32
+ timeoutMs:1000,excludedContexts:['main'],developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:()=>{throw new Error('must not execute');}},
33
+ reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
34
+ contexts:['review-1','review-2'],run:()=>{throw new Error('must not review');}}],
35
+ reviewInvocation:{developerThreadId:'author',excludedThreadIds:['main']},
36
+ check:createHostCheck({cwd:codeProject,commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]})};
37
+ const qa={commands:[],environment:{kind:'web',carrier:'browser',target:'fixture',scope:'local'}};
38
+ execution.qaLogHome=path.join(root,'logs');
39
+ execution.qaDecisionProvider={timeoutMs:1000,decide:()=>{throw new Error('must not assess');}};
40
+ const configure=qa=>{
41
+ execution.configuration.workflow={qa,documentationPaths:[],applicableAgentFiles:[]};
42
+ execution.qaExecutor=createHostQaExecutor({codeProject,specsDir,feature,requirements:['requirements.md'],runtime:'codex',
43
+ ...qa,timeoutMs:60000,logHome:execution.qaLogHome});
44
+ };configure(qa);
45
+ const storeIdentity={repositoryId:identity.repositoryId,runId:identity.runId};
46
+ const snapshot=()=>readExecutionSnapshot({specsRoot:specsDir,identity:storeIdentity});
47
+ const stateFile=path.join(specsDir,'.reviews','.execution',identity.runId,'state.json');
48
+ return {root,codeProject,specsDir,feature,identity,definition,execution,qa,configure,approve,snapshot,stateFile};
49
+ }
50
+ async function initialize(f){const run=await openControlRun(f.definition,'create',f.execution);run.close();return controlLaunchTarget(f.snapshot());}
51
+
52
+ test('v2 startup recovery refuses every missing target before durable records change',async t=>{
53
+ const f=fixture(t);await initialize(f);const before=fs.readFileSync(f.stateFile);
54
+ for(const options of [{specRebindReason:'same task'}, {rerunUnknownQa:true}, {rerunBlockedQa:true},
55
+ {qaConfigRevision:{previousWorkflow:f.execution.configuration.workflow,reason:'explicit revision'}}]){
56
+ await assert.rejects(openControlRun(f.definition,'resume',f.execution,options),{code:'invalid_input'});
57
+ assert.deepEqual(fs.readFileSync(f.stateFile),before);
58
+ }
59
+ });
60
+
61
+ test('writer-held replay rejects stale revision, state, code and package instead of refreshing preview',async t=>{
62
+ const f=fixture(t),target=await initialize(f),before=fs.readFileSync(f.stateFile);
63
+ for(const drift of [{revision:'0'.repeat(64)},{state:'fixture_completed'},{code:'qa_result_blocked'},{packageDigest:'1'.repeat(64)}]){
64
+ await assert.rejects(openControlRun(f.definition,'resume',f.execution,{specRebindReason:'same task',expectedControl:{...target,...drift}}),
65
+ {code:'snapshot_changed'});
66
+ assert.deepEqual(fs.readFileSync(f.stateFile),before);
67
+ }
68
+ assert.deepEqual(controlLaunchTarget(f.snapshot()),target);
69
+ });
70
+
71
+ test('valid launch preview permits specification rebind and preserves its concrete reason',async t=>{
72
+ const f=fixture(t),target=await initialize(f);
73
+ fs.writeFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'- [ ] T-001: implement a\n- [ ] T-002: implement b with another output\n');f.approve();
74
+ const reason='Only T-002 changed; keep the original T-001 contract.';
75
+ const run=await openControlRun(f.definition,'resume',f.execution,{specRebindReason:reason,expectedControl:target});run.close();
76
+ const rows=f.snapshot().records.filter(row=>row.payload.type==='specification-rebound');
77
+ assert.equal(rows.length,1);assert.equal(rows[0].payload.record.reason,reason);
78
+ await assert.rejects(openControlRun(f.definition,'resume',f.execution,{specRebindReason:reason,expectedControl:target}),{code:'snapshot_changed'});
79
+ });
80
+
81
+ test('QA configuration revision verifies the old preview before append and retains the reason',async t=>{
82
+ const f=fixture(t),target=await initialize(f),previousWorkflow=structuredClone(f.execution.configuration.workflow),before=fs.readFileSync(f.stateFile);
83
+ f.configure({...f.qa,commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs'],caseIds:[]}]});
84
+ const reason='Add the originally omitted syntax check.';
85
+ const options={qaConfigRevision:{previousWorkflow,reason}};
86
+ await assert.rejects(openControlRun(f.definition,'resume',f.execution,{...options,expectedControl:{...target,revision:'0'.repeat(64)}}),{code:'snapshot_changed'});
87
+ assert.deepEqual(fs.readFileSync(f.stateFile),before);
88
+ const run=await openControlRun(f.definition,'resume',f.execution,{...options,expectedControl:target});run.close();
89
+ const revision=f.snapshot().records.find(row=>row.payload.type==='qa-config-revised');
90
+ assert.equal(revision.payload.record.reason,reason);assert.equal(revision.payload.record.qaRound,0);
91
+ });
92
+
93
+ test('QA rerun flags accept a valid explicit target without manufacturing a QA outcome',async t=>{
94
+ const f=fixture(t),target=await initialize(f),before=fs.readFileSync(f.stateFile);
95
+ for(const options of [{rerunUnknownQa:true},{rerunBlockedQa:true,qaEnvironmentFailure:'Observed fixture environment failure.'}]){
96
+ const run=await openControlRun(f.definition,'resume',f.execution,{...options,expectedControl:target});run.close();
97
+ assert.deepEqual(fs.readFileSync(f.stateFile),before);
98
+ }
99
+ });
100
+
101
+ test('v1 recovery retains its original no-target and fingerprint behavior',async t=>{
102
+ const f=fixture(t,{legacy:true});await initialize(f);
103
+ fs.writeFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'- [ ] T-001: implement a\n- [ ] T-002: another unchanged dependency\n');f.approve();
104
+ const run=await openControlRun(f.definition,'resume',f.execution,{specRebindReason:'Legacy explicit reason.'});run.close();
105
+ assert.equal(f.snapshot().records.find(row=>row.payload.type==='specification-rebound').payload.record.reason,'Legacy explicit reason.');
106
+ });
107
+
108
+ test('target file rejects unknown fields, malformed targets, symlinks and hardlinks',async t=>{
109
+ const f=fixture(t),target=await initialize(f),file=path.join(f.root,'target.json');
110
+ fs.writeFileSync(file,JSON.stringify(target));assert.deepEqual(readLaunchControlFile(file),target);
111
+ fs.writeFileSync(file,JSON.stringify({...target,extra:true}));assert.throws(()=>readLaunchControlFile(file));
112
+ fs.writeFileSync(file,JSON.stringify({...target,revision:'invalid'}));assert.throws(()=>readLaunchControlFile(file));
113
+ fs.writeFileSync(file,JSON.stringify(target).replace('"version":2','"version":1,"version":2'));
114
+ assert.throws(()=>readLaunchControlFile(file),{code:'duplicate_model_json_key'});
115
+ fs.writeFileSync(file,JSON.stringify(target));const alias=path.join(f.root,'alias');fs.linkSync(file,alias);
116
+ assert.throws(()=>readLaunchControlFile(file),{code:'invalid_input'});fs.unlinkSync(alias);
117
+ fs.renameSync(file,alias);fs.symlinkSync(alias,file);assert.throws(()=>readLaunchControlFile(file),{code:'invalid_input'});
118
+ });
119
+
120
+ test('real v2 CLI publishes a launch target, refuses a stale target and rebinds with the saved target',t=>{
121
+ const f=fixture(t),config=path.join(f.root,'run.json'),control=path.join(f.root,'control.json'),
122
+ review=path.join(f.root,'review.json'),workflow=path.join(f.root,'workflow.json'),targetFile=path.join(f.root,'target.json');
123
+ fs.writeFileSync(config,JSON.stringify(f.definition));fs.writeFileSync(control,JSON.stringify(policy));
124
+ fs.writeFileSync(workflow,JSON.stringify(f.execution.configuration.workflow));
125
+ fs.writeFileSync(review,JSON.stringify({model:'fixture',preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',
126
+ config_fingerprint:configFingerprint({cwd:f.codeProject,model:'fixture'})}}));
127
+ const serve=(mode,extra=[])=>{
128
+ const result=spawnSync(process.execPath,[cli,'serve','--config',config,'--mode',mode,'--host-context','main',
129
+ '--control-config',control,'--review-config',review,'--workflow-config',workflow,...extra],
130
+ {encoding:'utf8',timeout:20000,input:JSON.stringify({version:2,requestId:'status',operation:'status',identity:f.identity})+'\n',
131
+ env:{...process.env,CM_WORKFLOW_HOME:path.join(f.root,'home'),CM_WORKFLOW_LOG_HOME:path.join(f.root,'logs')}});
132
+ return {...result,rows:result.stdout.trim().split('\n').filter(Boolean).map(JSON.parse)};
133
+ };
134
+ const created=serve('create');assert.equal(created.status,0,created.stderr);
135
+ const original=created.rows.find(row=>row.requestId==='status').result;
136
+ assert.deepEqual(original.launchControlTarget,controlLaunchTarget(f.snapshot()));
137
+ fs.writeFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'- [ ] T-001: implement a\n- [ ] T-002: add another output\n');f.approve();
138
+ const preview=serve('resume');assert.equal(preview.status,0,preview.stderr);
139
+ const current=preview.rows.find(row=>row.requestId==='status').result;
140
+ assert.equal(current.controlTarget.code,'spec_drift');
141
+ assert.deepEqual(current.launchControlTarget,original.launchControlTarget,'live spec drift does not refresh the durable launch preview');
142
+ const before=fs.readFileSync(f.stateFile),reason='Only another task changed; preserve T-001.';
143
+ const extra=['--rebind-spec-material','--spec-rebind-reason',reason,'--expected-control',targetFile];
144
+ fs.writeFileSync(targetFile,JSON.stringify({...original.launchControlTarget,revision:'0'.repeat(64)}));
145
+ const refused=serve('resume',extra);assert.equal(refused.status,1);assert.match(refused.stderr,/snapshot_changed/);
146
+ assert.match(refused.stderr,/launchControlTarget/);assert.deepEqual(fs.readFileSync(f.stateFile),before);
147
+ fs.writeFileSync(targetFile,JSON.stringify(original.launchControlTarget));
148
+ const recovered=serve('resume',extra);assert.equal(recovered.status,0,recovered.stderr);
149
+ assert.equal(recovered.rows.find(row=>row.requestId==='status').result.code,null);
150
+ assert.equal(f.snapshot().records.find(row=>row.payload.type==='specification-rebound').payload.record.reason,reason);
151
+ });
152
+
153
+ test('v2 argv requires target for startup recovery and refuses external allow flags or create supersession',t=>{
154
+ const f=fixture(t),config=path.join(f.root,'run.json'),control=path.join(f.root,'control.json');
155
+ fs.writeFileSync(config,JSON.stringify(f.definition));fs.writeFileSync(control,JSON.stringify(policy));
156
+ const args=['serve','--config',config,'--mode','resume','--host-context','main','--control-config',control];
157
+ for(const extra of [['--rebind-spec-material','--spec-rebind-reason','fixture'],['--rerun-blocked-qa'],
158
+ ['--revise-qa-config','previous.json','--qa-config-revision-reason','fixture']]){
159
+ const result=spawnSync(process.execPath,[cli,...args,...extra],{encoding:'utf8'});
160
+ assert.equal(result.status,1);assert.match(result.stderr,/invalid_input/);
161
+ }
162
+ for(const flag of ['--allow-qa','--allow-unknown']){
163
+ const result=spawnSync(process.execPath,[cli,...args,flag],{encoding:'utf8'});
164
+ assert.equal(result.status,1);assert.match(result.stderr,/invalid_arguments/);
165
+ }
166
+ const create=[...args];create[4]='create';
167
+ const result=spawnSync(process.execPath,[cli,...create,'--supersede-reviewed-evidence','--supersede-reason','fixture'],{encoding:'utf8'});
168
+ assert.equal(result.status,1);assert.match(result.stderr,/supersede_unavailable/);
169
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution')),false);
170
+ });
171
+
172
+ test('v2 manual QA Fix loads status with a simple owner without unused review or authoring adapters',t=>{
173
+ const f=fixture(t),config=path.join(f.root,'run.json'),control=path.join(f.root,'control.json'),
174
+ review=path.join(f.root,'review.json'),workflow=path.join(f.root,'workflow.json'),fix=path.join(f.root,'fix.json');
175
+ fs.writeFileSync(config,JSON.stringify(f.definition));fs.writeFileSync(control,JSON.stringify({...policy,qaFix:'manual'}));
176
+ fs.writeFileSync(workflow,JSON.stringify(f.execution.configuration.workflow));
177
+ fs.writeFileSync(review,JSON.stringify({model:'fixture',preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',
178
+ config_fingerprint:configFingerprint({cwd:f.codeProject,model:'fixture'})}}));
179
+ fs.writeFileSync(fix,JSON.stringify({specsRoot:f.specsDir,identity:{...f.identity,runId:'simple-child'},configuration:{
180
+ hostContextId:'main',runtime:'codex',reproduction:{cwd:f.codeProject},
181
+ qaSource:{identity:f.identity,feature:f.feature,packageDigest:'a'.repeat(64),testRunId:'fixture-qa'}}}));
182
+ const args=[cli,'serve','--config',config,'--mode','create','--host-context','main','--control-config',control,
183
+ '--review-config',review,'--workflow-config',workflow,'--qa-fix-owner-config',fix];
184
+ const input=[{version:2,requestId:'status',operation:'status',identity:f.identity},
185
+ {version:2,requestId:'fix_status',operation:'fix_status',identity:f.identity,packageDigest:'a'.repeat(64),testRunId:'fixture-qa'}]
186
+ .map(JSON.stringify).join('\n')+'\n';
187
+ const result=spawnSync(process.execPath,args,{input,encoding:'utf8',timeout:20000,
188
+ env:{...process.env,CM_WORKFLOW_HOME:path.join(f.root,'home'),CM_WORKFLOW_LOG_HOME:path.join(f.root,'logs')}});
189
+ assert.equal(result.status,0,result.stderr);
190
+ const rows=result.stdout.trim().split('\n').map(JSON.parse);
191
+ assert.equal(rows[0].type,'host_ready');assert.equal(rows.find(row=>row.requestId==='status').result.state,'ready');
192
+ assert.ok(rows.find(row=>row.requestId==='fix_status'),'fix_status reaches the original owner; this ready fixture has no matching QA failure');
193
+ assert.doesNotMatch(result.stderr,/test_author_configuration_required|repair_configuration_required|review_configuration_required/);
194
+ const missingReview=spawnSync(process.execPath,args.filter((value,index)=>value!=='--review-config'&&args[index-1]!=='--review-config'),
195
+ {encoding:'utf8'});
196
+ assert.equal(missingReview.status,1);assert.match(missingReview.stderr,/review_configuration_required/);assert.match(missingReview.stderr,/--review-config/);
197
+ assert.doesNotMatch(missingReview.stderr,/allow-review-attempt/);
198
+ });
199
+
200
+ test('resume with missing stored evidence preserves the owner refusal for v1 and v2',async t=>{
201
+ for(const legacy of [false,true])for(const depth of [0,2,3]){
202
+ const f=fixture(t,{legacy});let dir=f.specsDir;
203
+ for(const part of ['.reviews','.execution',f.identity.runId].slice(0,depth)){
204
+ dir=path.join(dir,part);fs.mkdirSync(dir,{mode:0o700});
205
+ }
206
+ await assert.rejects(openControlRun(f.definition,'resume',f.execution),{code:depth===3?'store_layout_legacy':'store_missing'});
207
+ assert.equal(fs.existsSync(f.stateFile),false);
208
+ assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution',f.identity.runId,'writer.sqlite')),false);
209
+ }
210
+ });
211
+
212
+ test('missing state in an existing writer layout is left for the owner without replacement',async t=>{
213
+ for(const legacy of [false,true]){
214
+ const f=fixture(t,{legacy});await initialize(f);fs.unlinkSync(f.stateFile);
215
+ await assert.rejects(openControlRun(f.definition,'resume',f.execution),{code:'ENOENT'});
216
+ assert.equal(fs.existsSync(f.stateFile),false);
217
+ assert.equal(fs.statSync(path.join(path.dirname(f.stateFile),'writer.sqlite')).isFile(),true);
218
+ }
219
+ });
@@ -0,0 +1,192 @@
1
+ import test from 'node:test';
2
+ import {operatorGuidance,guidanceText} from '../runtime/js/cm-ai/operator-guidance.mjs';
3
+ import assert from 'node:assert/strict';
4
+ import fs from 'node:fs';
5
+ import {spawnSync} from 'node:child_process';
6
+ import {createCmAiBatch,batchTaskRunId} from './cm-ai-batch-run.mjs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import {buildManifest} from './cm-spec-manifest.mjs';
10
+ import {openControlRun} from './cm-ai-run.mjs';
11
+ import {createConversationExecution} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
12
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
13
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
14
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
15
+ import {readControlPolicy,readControlPolicyFile,assertControlEntry,controlTarget,withControlPolicyHost}
16
+ from '../runtime/js/cm-ai/control-policy.mjs';
17
+
18
+ const policy={version:2,development:'conversation',bootstrap:'disabled',qa:'disabled',qaFix:'disabled'};
19
+ const identity={repositoryId:'control-fixture',runId:'control-fixture-run',taskId:'T-001',attempt:1};
20
+ const snapshot=(revision=digest('a'))=>({revision,records:[{payload:{type:'init',config:{controlPolicy:policy}}}]});
21
+ const status={identity,state:'unknown',code:'execution_error',packageDigest:digest('package')};
22
+ const wire=(operation,extra={})=>({version:2,operation,requestId:'control-request',identity,...extra});
23
+ function temp(t){const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-control-policy-')));
24
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));return root;}
25
+
26
+ test('control choices are strict and cannot turn data presence into execution permission',()=>{
27
+ assert.deepEqual(readControlPolicy(policy),policy);
28
+ for(const value of [{...policy,allow:true},{...policy,version:1},{...policy,development:'auto'},
29
+ {...policy,qaFix:'auto'},{...policy,qa:'skip'},{...policy,bootstrap:'yes'}])assert.throws(()=>readControlPolicy(value));
30
+ assert.deepEqual(readControlPolicy({...policy,qa:'run',qaFix:'manual'}).qaFix,'manual');
31
+ });
32
+ test('policy file rejects duplicate keys, invalid UTF8 and symbolic links',t=>{
33
+ const root=temp(t),file=path.join(root,'control.json');
34
+ fs.writeFileSync(file,JSON.stringify(policy));assert.deepEqual(readControlPolicyFile(file),policy);
35
+ fs.writeFileSync(file,JSON.stringify(policy).replace('"version":2','"version":1,"version":2'));
36
+ assert.throws(()=>readControlPolicyFile(file),{code:'duplicate_model_json_key'});
37
+ fs.writeFileSync(file,Buffer.from([0xff]));assert.throws(()=>readControlPolicyFile(file),{code:'invalid_input'});
38
+ const link=path.join(root,'link.json');fs.symlinkSync(file,link);
39
+ assert.throws(()=>readControlPolicyFile(link),{code:'invalid_input'});
40
+ });
41
+ test('legacy and current entries cannot silently cross or change bound choices',()=>{
42
+ const legacy={records:[{payload:{type:'init',config:{version:3}}}]};
43
+ assert.doesNotThrow(()=>assertControlEntry(legacy,null));assert.doesNotThrow(()=>assertControlEntry(snapshot(),policy));
44
+ assert.throws(()=>assertControlEntry(legacy,policy),{code:'fingerprint_mismatch'});
45
+ assert.throws(()=>assertControlEntry(snapshot(),null),{code:'fingerprint_mismatch'});
46
+ assert.throws(()=>assertControlEntry(snapshot(),{...policy,bootstrap:'write'}),{code:'fingerprint_mismatch'});
47
+ });
48
+ test('only an exact current preview can invoke recovery; repeated/stale previews never mutate',async()=>{
49
+ let current=snapshot(),mutations=0;
50
+ const host=withControlPolicyHost({async handle(request){
51
+ if(request.operation==='status')return status;
52
+ mutations++;current=snapshot(digest(String(mutations)));return {outcome:'blocked',code:'develop_interrupted'};
53
+ }},{identity,snapshot:()=>current});
54
+ assert.equal((await host.handle(wire('abandon_effect'))).code,'invalid_input');
55
+ const preview=(await host.handle(wire('status'))).controlTarget;
56
+ assert.equal((await host.handle(wire('abandon_effect',{expectedControl:preview}))).code,'develop_interrupted');
57
+ assert.equal((await host.handle(wire('abandon_effect',{expectedControl:preview}))).code,'snapshot_changed');
58
+ assert.equal((await host.handle(wire('abandon_effect',{expectedControl:{...preview,identity:{...identity,attempt:2}}}))).code,'snapshot_changed');
59
+ assert.equal(mutations,1);
60
+ assert.equal((await host.handle({...wire('advance'),version:1})).code,'fingerprint_mismatch');
61
+ assert.equal((await host.handle(wire('advance',{expectedControl:preview}))).code,'invalid_input');
62
+ });
63
+ test('ordinary flow is automatic; recovery cannot queue behind an in-flight mutation',async()=>{
64
+ let release;const finished=new Promise(resolve=>release=resolve);
65
+ const host=withControlPolicyHost({async handle(request){return request.operation==='status'?status:finished;}},
66
+ {identity,snapshot});
67
+ const running=host.handle(wire('advance'));
68
+ assert.equal((await host.handle(wire('abandon_effect',{expectedControl:controlTarget(status,snapshot())}))).code,'host_busy');
69
+ const busyStatus=await host.handle(wire('status'));assert.equal(busyStatus.controlTarget,undefined);
70
+ release(status);assert.deepEqual(await running,status);
71
+ assert.ok((await host.handle(wire('status'))).controlTarget);
72
+ });
73
+ test('QA-fix recovery binds the child preview as well as parent state',async()=>{
74
+ const child={runId:'qa-child',revision:digest('child'),stage:'unknown'};let forwarded;
75
+ const host=withControlPolicyHost({async handle(request){
76
+ if(request.operation==='status')return status;
77
+ if(request.operation==='fix_status')return {code:'qa_fix_incomplete',childControlTarget:child};
78
+ forwarded=request;return {code:'fix_step_interrupted'};
79
+ }},{identity,snapshot});
80
+ const target=(await host.handle(wire('fix_status'))).controlTarget;
81
+ assert.deepEqual(target.child,child);
82
+ const recovery={fixOperation:'abandon_step',reason:'Synthetic interrupted child'};
83
+ assert.equal((await host.handle(wire('fix_action',{...recovery,expectedControl:controlTarget(status,snapshot())}))).code,'invalid_input');
84
+ await host.handle(wire('fix_action',{...recovery,expectedControl:target}));
85
+ assert.deepEqual(forwarded.expectedFixControl,child);assert.equal(forwarded.expectedControl,undefined);
86
+ });
87
+
88
+ test('real owned journals keep legacy bytes and reject cross-entry resumes before writes',async t=>{
89
+ const root=temp(t),codeProject=path.join(root,'code'),specsDir=path.join(root,'specs');
90
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,'1.work'),{recursive:true});
91
+ fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
92
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,'1.work',name),'# Fixture\n');
93
+ fs.writeFileSync(path.join(specsDir,'1.work/tasks.md'),'- [ ] T-001: fixture\n');
94
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.work'],specFiles:buildManifest(specsDir)}));
95
+ const definition={version:1,specsDir,codeProject,feature:'1.work',identity,scope:['target.mjs'],requirements:[]};
96
+ const review={model:'fixture',disabledSkills:[],preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',
97
+ config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture'})}};
98
+ const execution=control=>createConversationExecution(definition,'control-fixture-host',{call(){assert.fail('no provider dispatch');}},
99
+ review,null,null,false,'codex',control?{controlPolicy:policy}:{});
100
+ let run=await openControlRun(definition,'create',execution(false));assert.equal(run.blocked,undefined,JSON.stringify(run.blocked));run.close();
101
+ const file=path.join(specsDir,'.reviews/.execution',identity.runId,'state.json'),before=fs.readFileSync(file);
102
+ await assert.rejects(openControlRun(definition,'resume',execution(true)),{code:'fingerprint_mismatch'});
103
+ assert.deepEqual(fs.readFileSync(file),before);
104
+ run=await openControlRun(definition,'resume',execution(false));
105
+ assert.equal((await run.host.handle({...wire('status'),version:1})).state,'ready');run.close();
106
+ assert.deepEqual(fs.readFileSync(file),before);
107
+ definition.identity={...identity,runId:'control-current-run'};
108
+ run=await openControlRun(definition,'create',execution(true));
109
+ const saved=readExecutionSnapshot({specsRoot:specsDir,identity:{repositoryId:identity.repositoryId,runId:definition.identity.runId}});
110
+ assert.deepEqual(saved.records[0].payload.config.controlPolicy,policy);run.close();
111
+ const newFile=path.join(specsDir,'.reviews/.execution',definition.identity.runId,'state.json'),newBytes=fs.readFileSync(newFile);
112
+ await assert.rejects(openControlRun(definition,'resume',execution(false)),{code:'fingerprint_mismatch'});
113
+ assert.deepEqual(fs.readFileSync(newFile),newBytes);
114
+ });
115
+
116
+
117
+ test('reused error codes do not swallow failures from the underlying host',async()=>{
118
+ for(const operation of ['advance','abandon_effect'])for(const code of ['invalid_input','snapshot_changed','fingerprint_mismatch']){
119
+ const failure=Object.assign(new Error('Underlying host failure'),{code});
120
+ const host=withControlPolicyHost({async handle(request){
121
+ if(request.operation==='status'&&operation==='advance')return status;
122
+ throw failure;
123
+ }},{identity,snapshot});
124
+ await assert.rejects(host.handle(wire(operation,operation==='abandon_effect'
125
+ ?{expectedControl:controlTarget(status,snapshot())}:{})),error=>error===failure);
126
+ }
127
+ });
128
+
129
+
130
+ test('v2 wrapper re-renders recovery guidance without reads, mutations or journal changes',async()=>{
131
+ let reads=0;const current=snapshot(),before=JSON.stringify(current);
132
+ const native={workflow:'cm-ai',...status,pendingAction:'abandon_effect',outcome:'reported'};
133
+ native.guidance=operatorGuidance(native);const nativeBefore=JSON.stringify(native);
134
+ const requests=[];
135
+ const host=withControlPolicyHost({async handle(request){requests.push(request);return native;}},
136
+ {identity,snapshot:()=>{reads++;return current;}});
137
+ for(const operation of ['status','advance']){
138
+ const output=await host.handle(wire(operation));
139
+ assert.doesNotMatch(guidanceText(output),/--allow-/);assert.match(guidanceText(output),/expectedControl/);
140
+ const {guidance,controlTarget:target,...unchanged}=output;
141
+ const {guidance:original,...expected}=native;assert.deepEqual(unchanged,expected);
142
+ }
143
+ assert.equal(reads,1,'guidance does not read state');assert.equal(requests.length,2,'guidance does not dispatch');
144
+ assert.equal(JSON.stringify(current),before);assert.equal(JSON.stringify(native),nativeBefore);
145
+ });
146
+
147
+ test('v2 wrapper preserves an active-operation suppression',async()=>{
148
+ const native={workflow:'cm-ai',...status,pendingAction:'abandon_effect',outcome:'reported'};
149
+ native.guidance=operatorGuidance(native,{executionActive:true});
150
+ const host=withControlPolicyHost({async handle(){return native;}},{identity,snapshot});
151
+ const output=await host.handle(wire('status'));
152
+ assert.equal(output.guidance.recoveryOperation,null);assert.match(guidanceText(output),/不重复派发/);
153
+ });
154
+
155
+
156
+ test('real v2 batch status and recovery render the batch target and leave status history unchanged',async t=>{
157
+ const root=temp(t),codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),logHome=path.join(root,'logs');
158
+ const feature='1.work',taskKey=`${feature}/T-001`,batchId='guidance-batch';
159
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
160
+ // A clean disposable Git root without a commit; explicit scope remains authoritative.
161
+ const initialized=spawnSync('git',['init','-q',codeProject],{encoding:'utf8'});assert.equal(initialized.status,0);
162
+ fs.writeFileSync(path.join(codeProject,'.git/info/exclude'),'*\n');
163
+ fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
164
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
165
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: fixture\n');
166
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
167
+ let calls=0;
168
+ const configuration={version:1,repositoryId:identity.repositoryId,batchId,specsDir,codeProject,controlPolicy:policy,
169
+ tasks:[{feature,taskId:'T-001',scope:['target.mjs'],requirements:[]}]};
170
+ const batch=createCmAiBatch({configuration,logHome,executionFor:async definition=>createConversationExecution(
171
+ definition,'control-fixture-host',{async call(operation){
172
+ calls++;assert.equal(operation,'develop');fs.writeFileSync(path.join(codeProject,'target.mjs'),'// preserved edit\n');
173
+ throw Object.assign(new Error('Synthetic disconnect'),{code:'host_disconnected'});
174
+ }},{model:'fixture',disabledSkills:[],preflight:{passed:true,cli_model:'fixture',prompt_transport:'stdin',
175
+ config_fingerprint:configFingerprint({cwd:codeProject,model:'fixture'})}},null,null,false,'codex',{controlPolicy:policy,qaLogHome:logHome})});
176
+ const advance=await batch.handle({version:2,operation:'advance',requestId:'batch-advance'});
177
+ assert.equal(advance.pendingAction,'develop_redo',JSON.stringify(advance));
178
+ assert.match(guidanceText(advance),/完整批次 controlTarget/);assert.doesNotMatch(guidanceText(advance),/--allow-/);
179
+ const journal=path.join(specsDir,'.reviews/.execution',batchTaskRunId(batchId,taskKey),'state.json');
180
+ const before=fs.readFileSync(journal),log=path.join(specsDir,'运行日志.jsonl'),beforeLog=fs.readFileSync(log);
181
+ const reported=await batch.handle({version:2,operation:'status',requestId:'batch-status'});
182
+ assert.match(guidanceText(reported),/batchId、taskKey、member、batchDigest/);
183
+ assert.deepEqual(fs.readFileSync(journal),before);assert.deepEqual(fs.readFileSync(log),beforeLog);assert.equal(calls,1);
184
+ const expectedControl=await batch.controlTarget();
185
+ assert.deepEqual(fs.readFileSync(journal),before);assert.deepEqual(fs.readFileSync(log),beforeLog);
186
+ const recovered=await batch.handle({version:2,operation:'develop_redo',requestId:'batch-redo',taskKey,
187
+ reason:'Synthetic stopped conversation',expectedControl});
188
+ assert.equal(recovered.code,'develop_answer_missing',JSON.stringify(recovered));
189
+ assert.match(guidanceText(recovered),/原批次入口/);assert.doesNotMatch(guidanceText(recovered),/--allow-|恢复原运行/);
190
+ assert.equal(calls,1,'recovery only records confirmation');
191
+ assert.equal(fs.readFileSync(path.join(codeProject,'target.mjs'),'utf8'),'// preserved edit\n');
192
+ });