@aibyzero/cm-workflow 0.16.8 → 0.16.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +19 -0
  3. package/README.md +14 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/installation.md +1 -1
  7. package/docs/js-workflow-control.md +25 -1
  8. package/docs/next-steps.md +8 -2
  9. package/docs/user-guide.md +105 -5
  10. package/package.json +2 -1
  11. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  12. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -20
  13. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +69 -22
  14. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  15. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  16. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  17. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  18. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  19. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  20. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  21. package/runtime/js/cm-ai/host-check.mjs +4 -1
  22. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  23. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  24. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  25. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  26. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  27. package/runtime/js/cm-ai/host-session.mjs +1 -1
  28. package/runtime/js/cm-ai/host-tool-bridge.mjs +40 -3
  29. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  30. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  31. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  32. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  33. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  34. package/runtime/js/cm-ai/review-package.mjs +10 -1
  35. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  36. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  37. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  38. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  39. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  40. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  41. package/runtime/js/cm-fix/execution.mjs +176 -48
  42. package/runtime/js/cm-fix/host.mjs +2 -1
  43. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  44. package/runtime/js/cm-fix/progress.mjs +13 -3
  45. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  46. package/runtime/js/cm-fix/repair.mjs +11 -3
  47. package/runtime/js/cm-fix/test-author.mjs +10 -3
  48. package/runtime/js/cm-idea/session.mjs +67 -4
  49. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  50. package/runtime/js/cm-prd/session.mjs +43 -0
  51. package/runtime/js/cm-refactor/records.mjs +98 -8
  52. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  53. package/runtime/js/cm-test/host.mjs +10 -3
  54. package/runtime/js/cm-test/session.mjs +45 -6
  55. package/runtime/js/notify-safe-read.mjs +49 -0
  56. package/runtime/js/notify-send.mjs +312 -0
  57. package/runtime/js/notify.mjs +137 -33
  58. package/runtime/js/policy-binding-compat.mjs +54 -0
  59. package/scripts/ci-test-shards.mjs +67 -0
  60. package/scripts/ci-test-shards.test.mjs +64 -0
  61. package/scripts/ci-test-weights.json +222 -0
  62. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  63. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  64. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  65. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  66. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  67. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  68. package/scripts/cm-ai-batch-drive.mjs +55 -10
  69. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  70. package/scripts/cm-ai-batch-host.mjs +132 -13
  71. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  72. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  73. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  74. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  75. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  76. package/scripts/cm-ai-batch-run.mjs +184 -22
  77. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  78. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  79. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  80. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  81. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  82. package/scripts/cm-ai-drive.mjs +64 -22
  83. package/scripts/cm-ai-drive.test.mjs +29 -2
  84. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  85. package/scripts/cm-ai-host-fixture.mjs +268 -0
  86. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  87. package/scripts/cm-ai-host.mjs +27 -15
  88. package/scripts/cm-ai-host.test.mjs +17 -759
  89. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  90. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  91. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  92. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  93. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  94. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +56 -10
  95. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  96. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  97. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  98. package/scripts/cm-ai-run.mjs +15 -6
  99. package/scripts/cm-ai-supersede.test.mjs +486 -41
  100. package/scripts/cm-check-drive-files.mjs +8 -0
  101. package/scripts/cm-check-drive.test.mjs +2 -5
  102. package/scripts/cm-check-runtime.sh +4 -2
  103. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  104. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  105. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  106. package/scripts/cm-claude-worker.test.mjs +18 -2
  107. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  108. package/scripts/cm-fix-abandon.test.mjs +163 -10
  109. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  110. package/scripts/cm-fix-drive.mjs +25 -7
  111. package/scripts/cm-fix-host.mjs +8 -7
  112. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  113. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  114. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  115. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  116. package/scripts/cm-host-documentation.test.mjs +49 -0
  117. package/scripts/cm-host-qa-executor.test.mjs +22 -10
  118. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  119. package/scripts/cm-idea-drive.mjs +49 -11
  120. package/scripts/cm-idea-drive.test.mjs +66 -0
  121. package/scripts/cm-idea-host.mjs +106 -16
  122. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  123. package/scripts/cm-init-drive.mjs +41 -7
  124. package/scripts/cm-init-host.mjs +61 -12
  125. package/scripts/cm-log-event.mjs +21 -10
  126. package/scripts/cm-notify-command.test.mjs +900 -0
  127. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  128. package/scripts/cm-notify.mjs +469 -0
  129. package/scripts/cm-notify.test.mjs +221 -4
  130. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  131. package/scripts/cm-prd-drive.mjs +18 -5
  132. package/scripts/cm-prd-drive.test.mjs +15 -0
  133. package/scripts/cm-prd-host.mjs +37 -4
  134. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  135. package/scripts/cm-prd-review-gate.mjs +56 -0
  136. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  137. package/scripts/cm-refactor-drive.mjs +52 -8
  138. package/scripts/cm-refactor-drive.test.mjs +44 -0
  139. package/scripts/cm-refactor-host.test.mjs +10 -6
  140. package/scripts/cm-release-smoke.sh +2 -0
  141. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  142. package/scripts/cm-test-drive.mjs +21 -5
  143. package/scripts/fixtures/claude-review-process.mjs +1 -1
  144. package/scripts/policy-binding-compat.test.mjs +99 -0
  145. package/scripts/scan-public-safety.py +4 -0
  146. package/scripts/validate-public-repo.py +4 -0
  147. package/skills/cm-ai/references/js-host-qa-recovery.md +27 -1
  148. package/skills/cm-ai/references/js-host-recovery.md +120 -8
  149. package/skills/cm-ai/references/js-host.md +14 -7
  150. package/skills/cm-check/SKILL.md +3 -3
  151. package/skills/cm-fix/references/js-host.md +44 -5
  152. package/skills/cm-idea/references/js-host.md +27 -2
  153. package/skills/cm-init/references/js-host.md +16 -3
  154. package/skills/cm-notify/SKILL.md +34 -0
  155. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  156. package/skills/cm-refactor/references/js-host.md +17 -0
  157. package/skills/cm-test/references/js-host.md +14 -1
@@ -21,14 +21,18 @@ import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
21
21
  import {need,shape,json,id,digest} from '../runtime/js/cm-ai/effect-contract.mjs';
22
22
  import {openPrdSession} from '../runtime/js/cm-prd/session.mjs';
23
23
  import {createPrdChange,assertPrdReviewsSettled} from '../runtime/js/cm-prd/change.mjs';
24
- import {publishPrdReview} from '../runtime/js/cm-prd/review-publication.mjs';
24
+ import {publishPrdReview,inspectPrdReviewResponse} from '../runtime/js/cm-prd/review-publication.mjs';
25
+ import {abandonPrdReviewAttempt} from './cm-prd-review-gate.mjs';
25
26
 
26
27
  const sessionFailureCodes=new Set(['prd_operation_recovery_required','prd_host_result_unknown','prd_nothing_to_resume',
27
28
  'prd_recovery_binding','prd_recovery_evidence_required','prd_replay_inputs_changed','cancelled','prd_turn_not_ready',
28
29
  'prd_review_recovery_required','prd_batch_inputs_replaced','prd_inputs_changed','prd_replacement_authorization_required',
29
30
  'prd_inputs_not_changed','prd_successor_not_fresh','prd_replacement_conflict','prd_replacement_not_ready',
30
31
  'execution_policy_required','execution_policy_legacy_run','prd_response_already_canonical',
31
- 'prd_predecessor_binding','prd_successor_inputs_changed']);
32
+ 'prd_predecessor_binding','prd_successor_inputs_changed',
33
+ 'prd_answer_discard_limit','prd_correction_recovery_required','prd_review_abandon_not_enabled','prd_review_result_publishable',
34
+ 'prd_review_abandon_unavailable','prd_review_abandon_limit','prd_review_abandon_reason_required','prd_review_abandon_binding',
35
+ 'prd_correction_recovery_conflict']);
32
36
 
33
37
  export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr}={}){
34
38
  let bridge,analysis,session,change=null,started=false,closed=false,record;
@@ -37,6 +41,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
37
41
  output.write('replace_inputs {requestId,operation,approved:true,reason,successorSpecs,successorSessionId} ends a changed-input batch with immutable history; read_batch/status remain available. Start the bound fresh specs root with --session SUCCESSOR_ID --predecessor ABSOLUTE_RECEIPT_PATH. No approvals transfer.\n');
38
42
  output.write('New and --change SELECTOR share this host. --session prd-ID resumes a durable local conversation; obtain runId from status. resume {requestId,operation,resolution:null|{callId,requestDigest,result,evidence}} consumes only the original host result, never re-dispatches an unknown call. decision {requestId,operation,proposalDigest,approved,allowUserCaseChanges} confirms an exact change proposal; save_draft archives and writes awaiting_review. prepare_revision {requestId,operation,reason} revises the saved current batch with original review history retained; no review counters reset.\n');
39
43
  output.write('resume also accepts resolution:{callId,requestDigest,abandon:true,evidence} with result absent: discard the entire pending operation and restore its before checkpoint, only if no call is prd_review. Explicit cancel is terminal: checkpoint cancelled and active cleared; resume cannot continue it. Session failures return {status:blocked,reason,recovery,completionAuthorized:false} (2026-09-17 dogfood: cancelled checkpoint retained active and hid recovery errors).\n');
44
+ output.write('resume resolution:{callId,requestDigest,discard:true,evidence} discards the last RECORDED answer the host then refused (not prd_review/prd_correct), keeps an append-only discardedAnswers record and asks that call again under the same pending operation; at most 2 per call kind in a session. resolution:{callId,requestDigest,abandonReview:true,evidence} needs --allow-review-write and --allow-review-abandon: only for a pending final_review whose prd_review result was lost or fails publication, it releases the gate claim into prd-<feature>-<stage>-dispatch-abandoned-N.json (at most 2 per feature and stage), records abandonedReviews and restores the before checkpoint; then send final_review again for a fresh independent review. A recorded result that would publish is never abandoned.\n');
40
45
  output.write('promote_design {requestId,operation,draftDigest,reason} moves an unreviewed full draft to design while preserving draft and self-check rounds. Saved drafts require complete exact original bytes with private permissions; partial/conflicting saves, prior review and exhausted rounds are rejected. Saved task revisions archive both versions before replacement; no approval is implied.\n');
41
46
  output.write('select_design_reviews {requestId,operation,draftDigest,risks:[{feature,signals,evidence}]} at design_ready freezes host-reported Step 9.5 risks for every feature. Only high-risk features may request design review; low-risk exact saved designs continue without it. Not approval; existing attempts cannot be downgraded.\n');
42
47
  output.write('plan_design {requestId,operation,text} generates requirements/design only. design_ready permits save_design with --allow-spec-write and original design review. After original design disposition, advance generates tasks from the exact current design, then original self-check/save_draft. No approval is implied.\n');
@@ -48,11 +53,13 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
48
53
  const reviewEnabled=argv.includes('--allow-review-write');
49
54
  const dispositionEnabled=argv.includes('--allow-disposition-write');
50
55
  const specWriteEnabled=argv.includes('--allow-spec-write');
56
+ const reviewAbandonEnabled=argv.includes('--allow-review-abandon');
57
+ need(argv.filter(x=>x==='--allow-review-abandon').length<=1&&(!reviewAbandonEnabled||reviewEnabled),'invalid_arguments');
51
58
  need(argv.filter(x=>x==='--allow-spec-write').length<=1,'invalid_arguments');
52
59
  need(argv.filter(x=>x==='--allow-disposition-write').length<=1,'invalid_arguments');
53
60
  need(argv.filter(x=>x==='--allow-review-write').length<=1,'invalid_arguments');
54
61
  need(argv.filter(x=>x==='--execution-optimizations').length<=1,'invalid_arguments');
55
- const args=argv.slice(1).filter(x=>!['--execution-optimizations','--allow-log-write','--allow-review-write','--allow-disposition-write','--allow-spec-write'].includes(x)),options={};
62
+ const args=argv.slice(1).filter(x=>!['--execution-optimizations','--allow-log-write','--allow-review-write','--allow-disposition-write','--allow-spec-write','--allow-review-abandon'].includes(x)),options={};
56
63
  for(let i=0;i<args.length;i+=2){
57
64
  need(['--skill-dir','--project','--specs','--runtime','--cases','--host-context','--change','--session','--predecessor'].includes(args[i])
58
65
  &&!Object.hasOwn(options,args[i])&&typeof args[i+1]==='string','invalid_arguments');
@@ -279,12 +286,38 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
279
286
  shape(request,['requestId','operation','resolution']);
280
287
  need(!reviewController.signal.aborted&&session.state.checkpoint?.analysis?.stage!=='cancelled'
281
288
  &&session.state.checkpoint?.change?.stage!=='cancelled','cancelled');
289
+ if(request.resolution?.discard===true){
290
+ const {operation:discardedOperation,kind,callId,evidence}=session.discardAnswer(request.resolution);
291
+ record({event:'decision',phase:'recovery',data:{operation:discardedOperation,kind,callId,evidence,outcome:'answer_discarded'}});
292
+ }else if(request.resolution?.abandonReview===true){
293
+ need(reviewAbandonEnabled,'prd_review_abandon_not_enabled');
294
+ const active=session.state.active,call=active?.calls.find(item=>item.callId===request.resolution.callId);
295
+ need(active?.request.operation==='final_review'&&call?.kind==='prd_review'
296
+ &&call.requestDigest===request.resolution.requestDigest,'prd_recovery_binding');
297
+ // A recorded result that would publish must be published (plain resume), never re-reviewed.
298
+ if(Object.hasOwn(call,'result')){
299
+ let publishable=true;
300
+ try{const response=session.reviewResponse(call),{packageDigest,...reviewPackage}=call.payload.package;
301
+ validatePrdReviewMode(active.request.mode,response);
302
+ inspectPrdReviewResponse({reviewPackage,packageDigest,authorContextId:call.payload.authorContextId,response});}
303
+ catch{publishable=false;}
304
+ need(!publishable,'prd_review_result_publishable');
305
+ }
306
+ const slug=active.request.feature.replace(/^\d+\./,''),prefix=path.join(admission.specs,'.reviews',`prd-${slug}-${active.request.stage}`);
307
+ const gate=abandonPrdReviewAttempt({stage:active.request.stage,feature:slug,evidence:`${prefix}-r1.md`,
308
+ receipt:`${prefix}-disposition.json`,call_id:call.callId,reason:request.resolution.evidence});
309
+ const {kind,callId,evidence}=session.abandonReview(request.resolution);
310
+ restore(session.state.checkpoint);replaying=false;reviewState=null;
311
+ record({event:'decision',phase:'recovery',data:{operation:'final_review',kind,callId,evidence,
312
+ outcome:'review_attempt_abandoned',abandoned:gate.abandoned}});
313
+ session.commit(checkpoint());return status();
314
+ }
282
315
  if(request.resolution?.abandon===true){
283
316
  const decision=session.abandon(request.resolution);
284
317
  restore(session.state.checkpoint);replaying=false;
285
318
  record({event:'decision',phase:'recovery',data:decision});return status();
286
319
  }
287
- if(request.resolution!==null)session.resolve(request.resolution);
320
+ if(request.resolution!==null&&request.resolution.discard!==true)session.resolve(request.resolution);
288
321
  const active=session.replay();
289
322
  replayCallIndex=0;
290
323
  need(active.calls.every(call=>Object.hasOwn(call,'result')),'prd_host_result_unknown');
@@ -167,7 +167,12 @@ for(const mode of ['saved','partial','drift','outside','completed-task','cancell
167
167
  assert.equal(fresh.status,0,fresh.stderr);assert.equal(JSON.parse(fresh.stdout).status,'correction_saved');
168
168
  assert.equal(calls,1);assert.match(fs.readFileSync(path.join(args.specs,design.path),'utf8'),/Clarified/);
169
169
  fs.appendFileSync(path.join(args.specs,design.path),'\nUser edit');
170
- assert.throws(()=>inspectPrdCorrectionRecovery(input),/recovery_conflict/);
170
+ // V6: inspection lists the conflicting file for a person; resuming refuses and writes nothing.
171
+ const conflict=inspectPrdCorrectionRecovery(input),row=conflict.states.find(item=>item.path===design.path);
172
+ assert.equal(conflict.status,'correction_recovery_conflict');assert.equal(row.status,'conflict');assert.ok(row.currentSha256&&row.correctedSha256);
173
+ const edited=fs.readFileSync(path.join(args.specs,design.path),'utf8');
174
+ assert.throws(()=>resumePrdCorrection({...input,writeEnabled:true},new AbortController().signal),/prd_correction_recovery_conflict/);
175
+ assert.equal(fs.readFileSync(path.join(args.specs,design.path),'utf8'),edited);
171
176
  }
172
177
  assert.equal(fs.existsSync(receipt),false);
173
178
  });
@@ -206,6 +206,62 @@ export function claimPrdReview(args){
206
206
  return {stage:args.stage,feature:args.feature,outcome:'dispatch_claimed',dispatch_record:file,
207
207
  package_sha256:args.package_sha256,providerAuthorized:false,completionAuthorized:false};
208
208
  }
209
+ // V5 (O05/O06): release one interrupted attempt so a fresh independent review
210
+ // can be claimed. Only while the claim has no r1 evidence (dispatch_unknown);
211
+ // the claim moves to an append-only abandoned record carrying the operator
212
+ // reason and the abandoned session call, and at most MAX_PRD_REVIEW_ABANDONS
213
+ // attempts per feature and stage are released. Repeating it for the same call
214
+ // after the claim already moved is a no-op, so a host that died between this
215
+ // and its session record can finish. JS host contract only; the CLI and its
216
+ // Python oracle keep their inspect/claim/record commands unchanged.
217
+ export const MAX_PRD_REVIEW_ABANDONS=2;
218
+ const abandonedFile=(evidence,index)=>evidence.replace(/-r1\.md$/,`-dispatch-abandoned-${index}.json`);
219
+ function releaseClaim(file,directory){
220
+ fs.unlinkSync(file);
221
+ if(process.platform!=='win32'){
222
+ const directoryFd=fs.openSync(directory,'r');try{fs.fsyncSync(directoryFd);}finally{fs.closeSync(directoryFd);}
223
+ }
224
+ }
225
+ export function abandonPrdReviewAttempt(args){
226
+ const {evidence}=paths(args),directory=path.dirname(evidence),file=dispatchFile(evidence);
227
+ need(typeof args.call_id==='string'&&/^[A-Za-z0-9-]{1,128}$/.test(args.call_id),'invalid call id','prd_review_abandon_binding');
228
+ need(typeof args.reason==='string'&&strip(args.reason).length>0&&args.reason.length<=2000&&!/[\r\n\0]/.test(args.reason),
229
+ 'abandon reason required','prd_review_abandon_reason_required');
230
+ const existing=[];
231
+ for(let index=1;index<=MAX_PRD_REVIEW_ABANDONS;index++){
232
+ const record=abandonedFile(evidence,index);if(!stat(record))break;
233
+ need(!link(record),'unsafe PRD abandon record','prd_review_dispatch_invalid',()=>({dispatch:reviewFile(record)}));
234
+ existing.push(parseJson(read(record,'prd_review_dispatch_invalid',{dispatch:reviewFile(record)}),'prd_review_dispatch_invalid',{dispatch:reviewFile(record)}));
235
+ }
236
+ const gate=inspectPrdReview(args);
237
+ if(gate.outcome==='dispatch_once'&&existing.some(item=>item.call_id===args.call_id))
238
+ return {stage:args.stage,feature:args.feature,outcome:'already_abandoned',abandoned:existing.length};
239
+ need(gate.outcome==='dispatch_unknown','only an unpublished claimed attempt can be abandoned','prd_review_abandon_unavailable',
240
+ ()=>({dispatch:reviewFile(file)}));
241
+ const dispatch=loadDispatch(file,args);
242
+ // Crash window: the abandoned record is durable but the claim was not yet
243
+ // removed. The same call and the same claim finish that release; no new
244
+ // record is appended and no slot is spent.
245
+ const pending=existing.findIndex(item=>item.call_id===args.call_id&&item.package_sha256===dispatch.package_sha256
246
+ &&item.dispatch_at===dispatch.at&&item.stage===args.stage&&item.feature===args.feature&&item.status==='abandoned');
247
+ if(pending!==-1){
248
+ releaseClaim(file,directory);
249
+ need(inspectPrdReview(args).outcome==='dispatch_once','PRD review claim was not released','prd_review_abandon_unavailable');
250
+ return {stage:args.stage,feature:args.feature,outcome:'release_completed',abandoned:pending+1,record:abandonedFile(evidence,pending+1),
251
+ providerAuthorized:false,completionAuthorized:false};
252
+ }
253
+ need(existing.length<MAX_PRD_REVIEW_ABANDONS,'PRD review abandon limit reached','prd_review_abandon_limit',
254
+ ()=>({dispatch:reviewFile(file)}));
255
+ const index=existing.length+1,record=abandonedFile(evidence,index);
256
+ const value={schema_version:1,stage:args.stage,feature:args.feature,package_sha256:dispatch.package_sha256,
257
+ dispatch_at:dispatch.at,status:'abandoned',call_id:args.call_id,reason:args.reason,at:new Date().toISOString()};
258
+ const fd=fs.openSync(record,'wx',0o600);
259
+ try{fs.writeFileSync(fd,JSON.stringify(value)+'\n');fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
260
+ releaseClaim(file,directory);
261
+ need(inspectPrdReview(args).outcome==='dispatch_once','PRD review claim was not released','prd_review_abandon_unavailable');
262
+ return {stage:args.stage,feature:args.feature,outcome:'abandoned',abandoned:index,record,
263
+ providerAuthorized:false,completionAuthorized:false};
264
+ }
209
265
  export function inspectPrdReview(args){
210
266
  const {evidence,receipt}=paths(args);
211
267
  const dispatch=loadDispatch(dispatchFile(evidence),args);
@@ -0,0 +1,206 @@
1
+ // External answer gaps, batch 3 (O18/O19): a refused or lost text-only answer is
2
+ // discarded by an append-only journal row and asked again; commands and writes
3
+ // never are. Main paths drive the real cm-refactor-host.mjs over JSONL.
4
+ import test from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import {spawn,spawnSync} from 'node:child_process';
9
+ import {once} from 'node:events';
10
+ import {createInterface} from 'node:readline';
11
+ import {fileURLToPath} from 'node:url';
12
+ import {createCmRefactorHost} from '../runtime/js/cm-refactor/host.mjs';
13
+ import {openRefactorRecords,effectDigest} from '../runtime/js/cm-refactor/records.mjs';
14
+ import {refactorDiscardable} from '../runtime/js/cm-refactor/workflow.mjs';
15
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
16
+ import {fixture,response,original,replacement} from './fixtures/cm-refactor.mjs';
17
+ const root=fileURLToPath(new URL('..',import.meta.url));
18
+ const journalFile=project=>path.join(project,'docs/refactors/extract/execution.jsonl');
19
+ const rows=project=>fs.readFileSync(journalFile(project),'utf8').trimEnd().split('\n').map(line=>JSON.parse(line));
20
+
21
+ // One real host process: sends each operation after the previous reply.
22
+ async function serve(t,config,temp,respond,operations){
23
+ const configPath=path.join(temp,'config.json');fs.writeFileSync(configPath,JSON.stringify(config));
24
+ const child=spawn(process.execPath,[path.join(root,'scripts/cm-refactor-host.mjs'),'serve','--config',configPath],{stdio:['pipe','pipe','pipe']});
25
+ t.after(()=>{if(child.exitCode===null)child.kill();});
26
+ const closed=once(child,'close'),lines=createInterface({input:child.stdout});let sessionId,stderr='',index=0;const results=[],asked=[];
27
+ const send=value=>child.stdin.write(JSON.stringify(value)+'\n');child.stderr.on('data',chunk=>{stderr+=chunk;});
28
+ const next=()=>{if(index<operations.length){const op=operations[index++];send({requestId:`r${index}`,...(typeof op==='function'?op(results):op)});}
29
+ else send({type:'host_close',sessionId});};
30
+ for await(const line of lines){const message=JSON.parse(line);
31
+ if(message.type==='host_ready'){sessionId=message.sessionId;next();}
32
+ else if(message.type==='host_request'){asked.push(message);const result=await respond(message,child);
33
+ if(result!==undefined)send({type:'host_result',sessionId,callId:message.callId,requestDigest:message.requestDigest,result});}
34
+ else if(message.requestId){results.push(message.result??message.error);next();}
35
+ }
36
+ const [code]=await closed;return {code,results,asked,stderr};
37
+ }
38
+
39
+ test('real host O18: a refused analysis replays the same refusal until it is discarded, then the run continues',{timeout:60000},async t=>{
40
+ const {config,temp,project}=fixture(t);let bad=1;
41
+ const respond=message=>message.kind==='refactor_analyze'&&bad-->0?{decision:'proceed'}:response(message.kind,message.payload);
42
+ let run=await serve(t,config,temp,respond,[{operation:'start'},{operation:'resume'}]);
43
+ assert.equal(run.code,0,run.stderr);
44
+ for(const result of run.results){assert.equal(result.stage,'blocked');assert.equal(result.reason,'refactor_analysis_invalid');}
45
+ const blocked=run.results[1];assert.equal(blocked.recovery.lastAnswer.kind,'refactor_analyze');assert.match(blocked.guidance.nextStep,/discard/);
46
+ assert.equal(run.asked.length,1);
47
+ const {key,requestDigest}=blocked.recovery.lastAnswer;
48
+ run=await serve(t,config,temp,respond,[{operation:'resume',discard:{key,requestDigest:'0'.repeat(64),evidence:'wrong binding'}},
49
+ {operation:'resume',discard:{key,requestDigest,evidence:'analysis reply had no reason or metric'}}]);
50
+ assert.equal(run.code,0,run.stderr);assert.equal(run.results[0].reason,'refactor_discard_binding');
51
+ assert.equal(run.results[1].stage,'awaiting_finish',JSON.stringify(run.results[1]));
52
+ assert.equal(run.asked.filter(item=>item.kind==='refactor_analyze').length,1);
53
+ const discard=rows(project).filter(row=>row.type==='discard');
54
+ assert.equal(discard.length,1);assert.equal(discard[0].reason,'answer_rejected');assert.equal(discard[0].kind,'refactor_analyze');
55
+ assert.equal(JSON.stringify(discard).includes('analysis reply had no reason'),false);
56
+ assert.equal(fs.readFileSync(path.join(project,'input.mjs'),'utf8'),replacement);
57
+ });
58
+
59
+ test('real host O19: an apply answer nobody can recover is discarded as answer_missing; the proposal is asked again',{timeout:60000},async t=>{
60
+ const {config,temp,project}=fixture(t);
61
+ let run=await serve(t,config,temp,(message,child)=>{
62
+ if(message.kind==='refactor_apply'){setImmediate(()=>child.kill('SIGKILL'));return undefined;}
63
+ return response(message.kind,message.payload);},[{operation:'start'}]);
64
+ assert.notEqual(run.code,0);assert.equal(fs.readFileSync(path.join(project,'input.mjs'),'utf8'),original);
65
+ run=await serve(t,config,temp,message=>{
66
+ if(message.kind==='refactor_recover')return {decision:'unknown',evidence:'the original session is gone'};
67
+ return response(message.kind,message.payload);},[{operation:'resume'}]);
68
+ const blocked=run.results[0];assert.equal(blocked.reason,'refactor_unknown_effect');
69
+ const unknown=blocked.recovery.unknown[0];assert.equal(unknown.callKind,'refactor_apply');assert.match(blocked.guidance.nextStep,/discard/);
70
+ run=await serve(t,config,temp,message=>response(message.kind,message.payload),
71
+ [{operation:'resume',discard:{key:unknown.key,requestDigest:unknown.requestDigest,evidence:'session lost the proposal'}}]);
72
+ assert.equal(run.results[0].stage,'awaiting_finish',JSON.stringify(run.results[0]));
73
+ assert.deepEqual(run.asked.map(item=>item.kind),['refactor_apply','refactor_review']);
74
+ assert.equal(rows(project).find(row=>row.type==='discard').reason,'answer_missing');
75
+ });
76
+
77
+ test('commands with unknown results are never discardable; guidance asks for the original receipt',{timeout:60000},async t=>{
78
+ const {config,project}=fixture(t),host=createCmRefactorHost(config,{call:async(kind,payload)=>response(kind,payload)});
79
+ assert.equal((await host.handle({operation:'start'})).stage,'awaiting_finish');
80
+ const lines=fs.readFileSync(journalFile(project),'utf8').trimEnd().split('\n'),index=lines.findIndex(line=>JSON.parse(line).type==='intent'&&JSON.parse(line).kind==='command');
81
+ // Crash prefix at the first judge command: no source write had happened yet.
82
+ fs.writeFileSync(journalFile(project),lines.slice(0,index+1).join('\n')+'\n');fs.writeFileSync(path.join(project,'input.mjs'),original);
83
+ const reopened=createCmRefactorHost(config,{call:async kind=>{assert.equal(kind,'refactor_recover');return {decision:'unknown',evidence:'not known'};}});
84
+ const blocked=await reopened.handle({operation:'resume'});
85
+ assert.equal(blocked.reason,'refactor_unknown_effect');assert.match(blocked.guidance.nextStep,/cleanupConfirmed/);
86
+ const command=blocked.recovery.unknown[0];assert.equal(command.kind,'command');
87
+ const refused=await reopened.handle({operation:'resume',discard:{key:command.key,requestDigest:command.requestDigest,evidence:'try'}});
88
+ assert.equal(refused.reason,'refactor_discard_binding');assert.equal(rows(project).some(row=>row.type==='discard'),false);
89
+ });
90
+
91
+ // Forged rows keep a valid hash chain; replay must still refuse them.
92
+ function appendRow(project,body){
93
+ const list=rows(project),row={...body,previous:list.at(-1).hash};
94
+ fs.appendFileSync(journalFile(project),JSON.stringify({...row,hash:digest(row)})+'\n');
95
+ }
96
+ test('replay refuses forged, duplicated and over-limit discard rows; an old journal replays unchanged',{timeout:60000},async t=>{
97
+ const {config,project}=fixture(t);let bad=1;
98
+ const host=createCmRefactorHost(config,{call:async(kind,payload)=>kind==='refactor_analyze'&&bad-->0?{decision:'proceed'}:response(kind,payload)});
99
+ const blocked=await host.handle({operation:'start'});const last=blocked.recovery.lastAnswer;
100
+ const base=fs.readFileSync(journalFile(project),'utf8');
101
+ const open=()=>openRefactorRecords(path.dirname(journalFile(project)),{discardable:refactorDiscardable});
102
+ const good={type:'discard',key:last.key,kind:'refactor_analyze',reason:'answer_rejected',attempt:1,requestDigest:last.requestDigest,resultDigest:last.resultDigest,
103
+ evidence:{sha256:digest('x'),length:1},released:null,at:'2026-10-09T00:00:00.000Z'};
104
+ const forged={wrongResult:{...good,resultDigest:'0'.repeat(64)},wrongReason:{...good,reason:'answer_missing',resultDigest:null},
105
+ notReaskable:{...good,kind:'refactor_recover'},rawEvidence:{...good,evidence:'x'},wrongAttempt:{...good,attempt:2},
106
+ wrongIdentity:{...good,requestDigest:'0'.repeat(64)},
107
+ noRelease:Object.fromEntries(Object.entries(good).filter(([name])=>name!=='released'))};
108
+ for(const [name,row] of Object.entries(forged)){
109
+ fs.writeFileSync(journalFile(project),base);appendRow(project,row);
110
+ assert.throws(open,/refactor_journal_invalid/,name);
111
+ }
112
+ // Duplicate: the same answer discarded twice (the second has no effect left to discard).
113
+ fs.writeFileSync(journalFile(project),base);appendRow(project,good);assert.doesNotThrow(open);
114
+ appendRow(project,good);assert.throws(open,/refactor_journal_invalid/);
115
+ // Over limit: three discards of one kind, each with its own re-asked answer.
116
+ fs.writeFileSync(journalFile(project),base);
117
+ const intent=rows(project).find(row=>row.type==='intent'&&row.key===last.key);
118
+ for(let n=0;n<3;n++){
119
+ if(n)for(const type of ['intent','result'])
120
+ appendRow(project,type==='intent'?{type,key:last.key,kind:'host',input:intent.input,attempt:n+1}:{type,key:last.key,result:{value:{decision:'proceed'},durationMs:n}});
121
+ const current=rows(project).filter(row=>row.type==='result'&&row.key===last.key).at(-1);
122
+ appendRow(project,{...good,attempt:n+1,requestDigest:effectDigest({input:intent.input,attempt:n+1}),resultDigest:digest(current.result)});
123
+ if(n<2)assert.doesNotThrow(open,`discard ${n+1}`);else assert.throws(open,/refactor_journal_invalid/,'third discard');
124
+ }
125
+ // A re-asked intent must carry the next attempt; without it the replay refuses.
126
+ fs.writeFileSync(journalFile(project),base);appendRow(project,good);
127
+ appendRow(project,{type:'intent',key:last.key,kind:'host',input:intent.input});assert.throws(open,/refactor_journal_invalid/,'missing attempt');
128
+ // An old journal (no discard rows) replays exactly as before.
129
+ fs.writeFileSync(journalFile(project),base);
130
+ const replay=createCmRefactorHost(config,{call:async()=>assert.fail('a recorded answer is replayed')});
131
+ const again=await replay.handle({operation:'resume'});assert.equal(again.reason,'refactor_analysis_invalid');
132
+ assert.equal(fs.readFileSync(journalFile(project),'utf8').split('\n').filter(line=>line.includes('"type":"discard"')).length,0);
133
+ });
134
+
135
+ test('a discard that is not the most recent intent, or outside a blocked run, is refused',{timeout:60000},async t=>{
136
+ const {config,project}=fixture(t),host=createCmRefactorHost(config,{call:async(kind,payload)=>response(kind,payload)});
137
+ assert.equal((await host.handle({operation:'start'})).stage,'awaiting_finish');
138
+ const analysis=rows(project).find(row=>row.type==='intent'&&row.key==='host/analysis');
139
+ const result=await host.handle({operation:'resume',discard:{key:'host/analysis',requestDigest:digest(analysis.input),evidence:'not blocked'}});
140
+ assert.equal(result.reason,'refactor_discard_unavailable');
141
+ const records=openRefactorRecords(path.dirname(journalFile(project)),{discardable:refactorDiscardable});records.acquire();
142
+ assert.throws(()=>records.discard({key:'host/analysis',requestDigest:digest(analysis.input),evidence:'old'}),/refactor_discard_not_last/);records.release();
143
+ const plan=path.join(path.dirname(project),'plan.json');
144
+ fs.writeFileSync(path.join(path.dirname(project),'drive-config.json'),JSON.stringify(config));
145
+ fs.writeFileSync(plan,JSON.stringify({config:'drive-config.json',discard:{key:'host/analysis',requestDigest:digest(analysis.input),evidence:'old'}}));
146
+ const driver=spawnSync(process.execPath,[path.join(root,'scripts/cm-refactor-drive.mjs'),'--plan',plan,'resume'],{encoding:'utf8'});
147
+ assert.equal(driver.status,2);assert.match(driver.stderr,/只能作废最后一个文字应答/);
148
+ });
149
+
150
+ test('notify classifies refactor discard blocks as stuck',async()=>{
151
+ const {classifyDriveResult}=await import('../runtime/js/notify.mjs');
152
+ for(const reason of ['refactor_analysis_invalid','refactor_unknown_effect','refactor_discard_limit','refactor_discard_not_last'])
153
+ assert.equal(classifyDriveResult('cm-refactor',{result:{stage:'blocked',reason,recovery:{discards:[],lastAnswer:null,unknown:[]}}}),'stuck',reason);
154
+ });
155
+
156
+ test('a re-asked call is reconciled only as its own attempt; a receipt of the discarded attempt is refused',{timeout:60000},async t=>{
157
+ const {config}=fixture(t);
158
+ const lost=createCmRefactorHost(config,{call:async(kind,payload)=>{if(kind==='refactor_apply')throw Error('lost');return response(kind,payload);}});
159
+ assert.equal((await lost.handle({operation:'start'})).stage,'blocked');
160
+ let blocked=await createCmRefactorHost(config,{call:async kind=>{assert.equal(kind,'refactor_recover');return {decision:'unknown',evidence:'gone'};}}).handle({operation:'resume'});
161
+ const first=blocked.recovery.unknown[0];let asked;
162
+ blocked=await createCmRefactorHost(config,{call:async(kind,payload)=>{asked=payload;throw Error('lost again');}})
163
+ .handle({operation:'resume',discard:{key:first.key,requestDigest:first.requestDigest,evidence:'session lost it'}});
164
+ assert.deepEqual(asked.recovery,{key:first.key,attempt:2});
165
+ const second=blocked.recovery.unknown[0];assert.equal(second.attempt,2);assert.notEqual(second.requestDigest,first.requestDigest);
166
+ const proposal={value:response('refactor_apply',asked),durationMs:1};
167
+ const stale=await createCmRefactorHost(config,{call:async(kind,payload)=>{assert.equal(payload.attempt,2);
168
+ return {decision:'completed',result:proposal,evidence:'receipt of attempt 1'};}}).handle({operation:'resume'});
169
+ assert.equal(stale.reason,'refactor_recover_attempt_mismatch');
170
+ const done=await createCmRefactorHost(config,{call:async(kind,payload)=>kind==='refactor_recover'
171
+ ?{decision:'completed',attempt:2,result:proposal,evidence:'receipt of attempt 2'}:response(kind,payload)}).handle({operation:'resume'});
172
+ assert.equal(done.stage,'awaiting_finish',JSON.stringify(done));
173
+ });
174
+
175
+ test('real host: a non-empty but invalid review is not published and can be discarded and asked again',{timeout:60000},async t=>{
176
+ const {config,temp,project}=fixture(t);let bad=1;
177
+ const respond=message=>{const value=response(message.kind,message.payload);
178
+ if(message.kind==='refactor_review'&&bad-->0)value.markdown=value.markdown.replace(/handoff_sha256: [0-9a-f]+/,'handoff_sha256: '+'0'.repeat(64));
179
+ return value;};
180
+ let run=await serve(t,config,temp,respond,[{operation:'start'}]);
181
+ const blocked=run.results[0];assert.equal(blocked.reason,'refactor_review_invalid',JSON.stringify(blocked));
182
+ const review=path.join(project,'docs/refactors/.reviews/refactor-extract-T-REFACTOR-extract-r1.md');assert.equal(fs.existsSync(review),false);
183
+ const {key,requestDigest}=blocked.recovery.lastAnswer;assert.equal(key,'host/a1/review');
184
+ run=await serve(t,config,temp,respond,[{operation:'resume',discard:{key,requestDigest,evidence:'handoff digest was wrong'}}]);
185
+ assert.equal(run.results[0].stage,'awaiting_finish',JSON.stringify(run.results[0]));assert.ok(fs.existsSync(review));
186
+ });
187
+
188
+ test('a lost confirmation is asked again at most twice, each time recorded; then refactor_confirm_reask_limit',{timeout:60000},async t=>{
189
+ const {config,project}=fixture(t);
190
+ assert.equal((await createCmRefactorHost(config,{call:async(kind,payload)=>response(kind,payload)}).handle({operation:'start'})).stage,'awaiting_finish');
191
+ const asked=[];
192
+ const lose=createCmRefactorHost(config,{call:async(kind,payload)=>{asked.push(payload);throw Error('confirmation lost');}});
193
+ assert.equal((await lose.handle({operation:'finish'})).stage,'blocked');
194
+ for(let n=1;n<=2;n++){
195
+ const result=await createCmRefactorHost(config,{call:async(kind,payload)=>{asked.push(payload);throw Error('lost again');}}).handle({operation:'finish'});
196
+ assert.equal(result.stage,'blocked');assert.notEqual(result.reason,'refactor_confirm_reask_limit');
197
+ }
198
+ assert.deepEqual(asked.map(item=>item.recovery?.attempt??1),[1,2,3]);
199
+ const limited=await createCmRefactorHost(config,{call:async()=>assert.fail('no third re-ask')}).handle({operation:'finish'});
200
+ assert.equal(limited.reason,'refactor_confirm_reask_limit');assert.match(limited.guidance.summary,/2 次/);
201
+ const discards=rows(project).filter(row=>row.type==='discard');
202
+ assert.deepEqual(discards.map(row=>[row.kind,row.reason,row.attempt]),[['refactor_confirm','answer_missing',1],['refactor_confirm','answer_missing',2]]);
203
+ // Replay rebuilds both records (the shared per-kind limit is enforced on replay, see the over-limit test).
204
+ const records=openRefactorRecords(path.dirname(journalFile(project)),{discardable:refactorDiscardable});
205
+ assert.equal(records.discards.length,2);
206
+ });
@@ -15,16 +15,21 @@
15
15
  // status, cancel none handle status/cancel.
16
16
  // baseline/judge/mutation/cheap checks 均由 workflow.mjs command/createHostCheck
17
17
  // 在项目内真实执行、记录退出码;没有可从答案文件填写的命令证据。
18
- // unknown command/host 的恢复需原调用回执,本驾驶员没有回执 runner,预检拒绝。
18
+ // unknown command/host 的恢复需原调用回执,本驾驶员没有回执 runner,预检拒绝;
19
+ // 例外:refactor_confirm 未知时宿主按 V7 重新问人,以及 PLAN.discard
20
+ // {key,requestDigest,evidence} 作废最后一个文字应答(已记录被拒或结果未知)后重问。
21
+ // 重问的确认(attempt>1)驾驶员从不预先作答:先让宿主登记新调用,再停下并给出
22
+ // key/attempt/gate/requestDigest;下一次 resume 只采用绑定这次调用的 confirm-reask.json。
19
23
  import fs from 'node:fs';
20
24
  import path from 'node:path';
21
25
  import {fileURLToPath} from 'node:url';
22
26
  import {createCmRefactorHost} from '../runtime/js/cm-refactor/host.mjs';
23
- import {openRefactorRecords} from '../runtime/js/cm-refactor/records.mjs';
27
+ import {openRefactorRecords,MAX_DISCARDS_PER_KIND,effectDigest} from '../runtime/js/cm-refactor/records.mjs';
28
+ import {refactorDiscardable,REFACTOR_REASKABLE_KINDS} from '../runtime/js/cm-refactor/workflow.mjs';
24
29
  import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
25
30
  import {readLearningRetrospectiveContent} from '../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
26
31
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
27
- import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
32
+ import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,deliberatelyUnanswered} from '../runtime/js/cm-ai/drive-core.mjs';
28
33
 
29
34
  const HOST=fileURLToPath(new URL('./cm-refactor-host.mjs',import.meta.url));
30
35
  const KNOWN=new Set(['start','resume','finish','prepare_judge_revision','status','cancel']);
@@ -132,6 +137,15 @@ function validate(kind,value,config,root){
132
137
  }
133
138
  function answer(row,answers,root){
134
139
  const {kind,payload}=row,value=answers[kind];
140
+ // V7: a re-asked confirmation (attempt > 1) is answered only from the new
141
+ // decision file bound to that key and attempt, never from confirm.json.
142
+ if(kind==='refactor_confirm'&&(payload.recovery?.attempt??1)>1){
143
+ const {recovery,...rest}=payload,attempt=recovery.attempt;
144
+ const requestDigest=digest({input:{kind,payload:rest},attempt});
145
+ throw deliberatelyUnanswered(`confirm_reask_decision_required:宿主已登记重问的确认 ${recovery.key}(gate ${payload.gate}、attempt ${attempt}、requestDigest ${requestDigest}),`
146
+ +`驾驶员不预先作答。请当前用户核对后写 ${path.join(root??'answers','confirm-reask.json')}:`
147
+ +`{"key":"${recovery.key}","attempt":${attempt},"gate":"${payload.gate}","requestDigest":"${requestDigest}","decision":"approved|rejected"},再 resume;旧的 confirm.json 与其他调用的决定都不会使用`);
148
+ }
135
149
  if(kind==='refactor_confirm')return {decision:value[payload.gate]};
136
150
  if(kind==='refactor_review'){
137
151
  const chosen=payload.attempt===2?answers.refactor_review_r2??value:value;
@@ -154,7 +168,7 @@ function answer(row,answers,root){
154
168
  }
155
169
  function main(){
156
170
  if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
157
- process.stdout.write('用法: cm-refactor-drive.mjs --plan PLAN.json <start|resume|finish|prepare_judge_revision|status|cancel>\nPLAN: config, answers;prepare_judge_revision 另需 judgeRevision。命令由宿主执行。\n');return;
171
+ process.stdout.write('用法: cm-refactor-drive.mjs --plan PLAN.json <start|resume|finish|prepare_judge_revision|status|cancel>\nPLAN: config, answers;prepare_judge_revision 另需 judgeRevision;resume 可带 discard {key,requestDigest,evidence} 作废最后一个文字应答后重问(每种最多 2 次)。命令由宿主执行。\n');return;
158
172
  }
159
173
  const {operation,plan,base}=loadPlanFile({name:'cm-refactor-drive.mjs',known:KNOWN});
160
174
  requireFields(plan,['config']);
@@ -173,14 +187,26 @@ function main(){
173
187
  for(const mutation of config.mutations){valid(config.scope.includes(mutation.path)&&nonempty(mutation.find)
174
188
  &&typeof mutation.replace==='string'&&mutation.find!==mutation.replace,`config.mutations: ${mutation.path}`);}
175
189
  const directory=path.join(config.specs??path.join(config.project,'docs'),'refactors',config.slug);
176
- let records;try{records=openRefactorRecords(directory);}catch(error){stop(2,`恢复记录无效: ${error.code??error.message}`);}
190
+ let records;try{records=openRefactorRecords(directory,{discardable:refactorDiscardable});}catch(error){stop(2,`恢复记录无效: ${error.code??error.message}`);}
177
191
  if(operation==='start'&&records.context)stop(2,`start 已有运行记录,请用 resume: ${path.join(directory,'execution.jsonl')}`);
178
192
  if(['resume','finish','prepare_judge_revision'].includes(operation)&&!records.context)
179
193
  stop(2,`恢复记录不存在: ${path.join(directory,'execution.jsonl')}`);
180
194
  if(records.context&&records.context.configDigest!==digest(config))stop(2,'resume 配置绑定不匹配');
195
+ if(Object.hasOwn(plan,'discard')){
196
+ if(operation!=='resume')stop(2,'PLAN.discard 只能配合 resume');
197
+ const value=plan.discard,entry=records.effects.get(value?.key),last=records.recovery.lastAnswer,unknown=records.recovery.unknown;
198
+ valid(object(value)&&Object.keys(value).sort().join(',')==='evidence,key,requestDigest'&&nonempty(value.evidence)&&value.evidence.length<=2000,
199
+ 'PLAN.discard 需要 key/requestDigest/evidence(取自宿主 status 的 recovery)');
200
+ if(!entry||entry.kind!=='host'||!REFACTOR_REASKABLE_KINDS.includes(entry.input.kind)
201
+ ||effectDigest(entry)!==value.requestDigest||!(last?.key===value.key||unknown.at(-1)?.key===value.key))
202
+ stop(2,'PLAN.discard 只能作废最后一个文字应答(宿主反问,已记录被拒或结果未知);命令、写盘与已发布的审查不能作废');
203
+ if(records.discards.filter(item=>item.kind===entry.input.kind).length>=MAX_DISCARDS_PER_KIND)
204
+ stop(2,`${entry.input.kind} 本运行已作废 ${MAX_DISCARDS_PER_KIND} 次,宿主会报 refactor_discard_limit;交人处理`);
205
+ }
181
206
  if(['resume','finish','prepare_judge_revision'].includes(operation))for(const [key,entry] of records.effects)
182
- if(['host','command'].includes(entry.kind)&&!Object.hasOwn(entry,'result'))
183
- stop(2,`缺少原执行回执 runner: ${entry.kind} ${key};不能从静态答案文件恢复`);
207
+ if(['host','command'].includes(entry.kind)&&!Object.hasOwn(entry,'result')
208
+ &&!(entry.kind==='host'&&entry.input.kind==='refactor_confirm')&&plan.discard?.key!==key)
209
+ stop(2,`缺少原执行回执 runner: ${entry.kind} ${key};不能从静态答案文件恢复。只读的文字应答可在 PLAN.discard 写 {key,requestDigest,evidence} 作废后重问`);
184
210
  if(operation==='prepare_judge_revision'){
185
211
  requireFields(plan,['judgeRevision']);
186
212
  valid(object(plan.judgeRevision)&&Array.isArray(plan.judgeRevision.paths)&&plan.judgeRevision.paths.length>0
@@ -229,9 +255,27 @@ function main(){
229
255
  stop(2,'步骤 finish 会反问 refactor_confirm(finish),但 confirm.json.finish 缺失');
230
256
  if(operation==='start'&&answers.refactor_confirm?.g0==='approved'&&!answers.refactor_review)
231
257
  stop(2,'步骤 start 会反问 refactor_review,但 review.json 缺失');
258
+ // V7: a re-asked confirmation (attempt > 1) the host registered and the driver
259
+ // left unanswered is answered only from confirm-reask.json bound to its exact
260
+ // key, attempt, gate and request digest; anything else is refused, never reused.
261
+ let confirmation=null;
262
+ const unanswered=[...records.effects].filter(([,entry])=>entry.kind==='host'&&!Object.hasOwn(entry,'result')).at(-1);
263
+ if(['resume','finish'].includes(operation)&&unanswered&&unanswered[1].input.kind==='refactor_confirm'&&(unanswered[1].attempt??1)>1){
264
+ const [key,entry]=unanswered,attempt=entry.attempt,gate=entry.input.payload.gate,requestDigest=effectDigest(entry);
265
+ const file=path.join(answerRoot??base,'confirm-reask.json'),expected=`{"key":"${key}","attempt":${attempt},"gate":"${gate}","requestDigest":"${requestDigest}","decision":"approved|rejected"}`;
266
+ if(!ownFile(file))stop(2,`confirm_reask_decision_required:重问的确认 ${key}(gate ${gate}、attempt ${attempt})已由宿主登记、尚未作答;请当前用户核对后写 ${file}:${expected};旧的 confirm.json 不会沿用`);
267
+ const value=readJson(file,'refactor_confirm_reask');
268
+ if(!object(value)||value.key!==key||value.attempt!==attempt||value.gate!==gate||value.requestDigest!==requestDigest)
269
+ stop(2,`confirm_reask_decision_stale:${file} 绑定的是 ${object(value)?`${value.key} attempt ${value.attempt} gate ${value.gate}`:'无效内容'},不是当前登记的 ${key}(gate ${gate}、attempt ${attempt}、requestDigest ${requestDigest});不会使用,请按 ${expected} 重写`);
270
+ valid(Object.keys(value).sort().join(',')==='attempt,decision,gate,key,requestDigest'&&['approved','rejected'].includes(value.decision),
271
+ `confirm-reask.json 须为 ${expected}`);
272
+ if(operation!=='resume')stop(2,`重问的确认 ${key} 已登记未作答,先用 resume 交回这次的新决定`);
273
+ confirmation={key,attempt,requestDigest,decision:value.decision,evidence:`当前用户对重问确认 ${key} attempt ${attempt} 的新决定(confirm-reask.json)`};
274
+ }
232
275
  stderr(`预检通过:${operation}`);
233
276
  driveHost({host:HOST,args:['serve','--config',configPath],cwd:config.project,operation,
234
- request:operation==='prepare_judge_revision'?{judgeRevision:plan.judgeRevision}:{},answers,paths:{},
277
+ request:operation==='prepare_judge_revision'?{judgeRevision:plan.judgeRevision}:plan.discard?{discard:plan.discard}
278
+ :confirmation?{confirmation}:{},answers,paths:{},
235
279
  answerFor:row=>answer(row,answers,answerRoot)});
236
280
  }
237
281
  main();
@@ -75,3 +75,47 @@ test('mutation probes catch skipped answer preflight and dropped resume binding'
75
75
  out=g.run('resume',mutant('records.context.configDigest!==digest(config)','false'));
76
76
  assert.notEqual(out.status,2,'mutation reached host instead of rejecting resume binding');
77
77
  });
78
+
79
+ // V7: the driver never pre-answers a re-asked confirmation. The host registers the
80
+ // new attempt, the driver stops naming key/attempt/gate/requestDigest, and only a
81
+ // decision file bound to exactly that call is used on the next resume.
82
+ import {createCmRefactorHost} from '../runtime/js/cm-refactor/host.mjs';
83
+ import {openRefactorRecords,effectDigest} from '../runtime/js/cm-refactor/records.mjs';
84
+ import {refactorDiscardable} from '../runtime/js/cm-refactor/workflow.mjs';
85
+ const lastConfirm=f=>{const records=openRefactorRecords(path.dirname(f.store),{discardable:refactorDiscardable});
86
+ const [key,entry]=[...records.effects].filter(([,item])=>item.kind==='host'&&item.input.kind==='refactor_confirm').at(-1);
87
+ return {key,attempt:entry.attempt??1,gate:entry.input.payload.gate,requestDigest:effectDigest(entry),answered:Object.hasOwn(entry,'result')};};
88
+ async function reaskFlow(t,crashWindow){
89
+ const f=setup(t);assert.equal(f.run('start').status,0);
90
+ const lost=await createCmRefactorHost(f.config,{call:async()=>{throw Error('finish confirmation lost');}}).handle({operation:'finish'});
91
+ assert.equal(lost.stage,'blocked');
92
+ if(crashWindow){
93
+ // The host appended the lost confirmation's discard and exited before the re-asked intent.
94
+ const records=openRefactorRecords(path.dirname(f.store),{discardable:refactorDiscardable});records.acquire();
95
+ try{const entry=records.effects.get('host/finish-1');
96
+ records.discard({key:'host/finish-1',requestDigest:effectDigest(entry),evidence:'confirmation lost; host exited before re-asking'});}
97
+ finally{records.release();}
98
+ assert.equal(fs.readFileSync(f.store,'utf8').trimEnd().split('\n').map(line=>JSON.parse(line)).at(-1).type,'discard');
99
+ }
100
+ // confirm.json still says finish: approved; the driver must not use it for the re-ask.
101
+ let out=f.run('finish');assert.notEqual(out.status,0);
102
+ const asked=lastConfirm(f);assert.deepEqual([asked.key,asked.attempt,asked.gate,asked.answered],['host/finish-1',2,'finish',false]);
103
+ assert.match(out.stderr,/confirm_reask_decision_required/);assert.match(out.stderr,new RegExp(asked.requestDigest));
104
+ out=f.run('resume');assert.equal(out.status,2);assert.match(out.stderr,/confirm_reask_decision_required/);
105
+ const reask=path.join(f.answers,'confirm-reask.json');
106
+ // A wrong gate, another attempt and another digest are refused and never used.
107
+ for(const stale of [{...asked,gate:'g0'},{...asked,attempt:1},{...asked,requestDigest:'0'.repeat(64)}]){
108
+ write(reask,{key:stale.key,attempt:stale.attempt,gate:stale.gate,requestDigest:stale.requestDigest,decision:'approved'});
109
+ out=f.run('resume');assert.equal(out.status,2);assert.match(out.stderr,/confirm_reask_decision_stale/);
110
+ assert.equal(lastConfirm(f).answered,false);
111
+ }
112
+ write(reask,{key:asked.key,attempt:asked.attempt,gate:asked.gate,requestDigest:asked.requestDigest,decision:'rejected'});
113
+ out=f.run('resume');assert.equal(out.status,0,out.stderr);assert.equal(lastConfirm(f).answered,true);
114
+ assert.equal(JSON.parse(out.stdout).result.stage,'awaiting_finish');
115
+ // The new decision (rejected) is the one recorded, not confirm.json's approved.
116
+ const rows=fs.readFileSync(f.store,'utf8').trimEnd().split('\n').map(line=>JSON.parse(line));
117
+ const adopted=rows.findLast(row=>row.type==='result'&&row.key==='host/finish-1');
118
+ assert.equal(adopted.result.value.decision,'rejected');assert.equal(adopted.result.confirmation.source,'operator_confirmed');
119
+ }
120
+ test('a re-asked confirmation is registered first, then answered only from a decision bound to that call',t=>reaskFlow(t,false));
121
+ test('crash between the discard and the re-asked intent: the same stop, the same bound decision',t=>reaskFlow(t,true));
@@ -49,7 +49,10 @@ test('behavior regression restores only the controlled file and blocks review',a
49
49
  test('stale independent-review header cannot bypass existing N5',async t=>{
50
50
  const {config}=fixture(t),host=createCmRefactorHost(config,{call:async(kind,payload)=>response(kind,payload,'stale-review')});
51
51
  const result=await host.handle({requestId:'start',operation:'start'});
52
- assert.equal(result.stage,'blocked');assert.match(result.reason,/digest/);
52
+ // Validated before publication: nothing immutable is written, the answer stays discardable.
53
+ assert.equal(result.stage,'blocked');assert.equal(result.reason,'refactor_review_invalid');assert.match(result.reasonDetail,/digest/);
54
+ assert.equal(result.recovery.lastAnswer.kind,'refactor_review');assert.match(result.guidance.nextStep,/discard/);
55
+ assert.equal(result.reports.some(file=>file.endsWith('-r1.md')),false);
53
56
  });
54
57
 
55
58
  async function finishInProcess(t,config,temp){
@@ -119,17 +122,18 @@ test('interrupted host invocation needs reconciliation, then resumes without rep
119
122
  const finished=await reopened.handle({requestId:'finish',operation:'finish'});assert.equal(finished.stage,'done',JSON.stringify(finished));
120
123
  });
121
124
 
122
- test('pending finish keeps its key; approved finish replays frozen budget after archival interruption',async t=>{
123
- const {config,project}=fixture(t);let confirmations=0,reconciliations=0;
125
+ // V7: a lost confirmation is asked of the person again under the same key; the
126
+ // host never adopts a reconciled answer bound to the lost call (no refactor_recover).
127
+ test('pending finish keeps its key and asks the person again; approved finish replays frozen budget after archival interruption',async t=>{
128
+ const {config,project}=fixture(t);let confirmations=0,reasks=0;
124
129
  const host=createCmRefactorHost(config,{call:async(kind,payload)=>{
125
130
  if(kind==='refactor_confirm'&&payload.gate==='finish'){confirmations++;throw Error('lost finish response');}return response(kind,payload);}});
126
131
  assert.equal((await host.handle({requestId:'start',operation:'start'})).stage,'awaiting_finish');
127
132
  assert.equal((await host.handle({requestId:'finish',operation:'finish'})).stage,'blocked');
128
133
  const recovered=createCmRefactorHost(config,{call:async(kind,payload)=>{
129
- assert.equal(kind,'refactor_recover');assert.equal(payload.input.kind,'refactor_confirm');reconciliations++;
130
- return {decision:'completed',result:{value:{decision:'approved'},durationMs:51},evidence:'Synthetic original confirmation receipt'};}});
134
+ assert.equal(kind,'refactor_confirm');assert.equal(payload.gate,'finish');reasks++;return {decision:'approved'};}});
131
135
  const finished=await recovered.handle({requestId:'finish',operation:'finish'});assert.equal(finished.stage,'done',JSON.stringify(finished));
132
- assert.equal(confirmations,1);assert.equal(reconciliations,1);
136
+ assert.equal(confirmations,1);assert.equal(reasks,1);
133
137
  const file=path.join(project,'docs/refactors/extract/execution.jsonl'),rows=fs.readFileSync(file,'utf8').trimEnd().split('\n');
134
138
  const index=rows.findIndex(line=>{const row=JSON.parse(line);return row.type==='result'&&row.key==='host/finish-1';});assert.ok(index>=0);
135
139
  // Isolated crash-prefix fixture: approval persisted, later archive/checkpoint records did not.
@@ -56,6 +56,8 @@ printf '%s\n' '==> Running the Codex-sandbox tests that CI cannot host'
56
56
  scripts/cm-ai-batch-host.test.mjs \
57
57
  scripts/cm-ai-bootstrap.test.mjs \
58
58
  scripts/cm-ai-host.test.mjs \
59
+ scripts/cm-ai-host-cli-workflow.test.mjs \
60
+ scripts/cm-ai-host-protected.test.mjs \
59
61
  scripts/cm-ai-multi-root.test.mjs \
60
62
  scripts/cm-ai-nested-execution.test.mjs \
61
63
  scripts/cm-fix-protected-edits.test.mjs \