@aibyzero/cm-workflow 0.16.8 → 0.17.0

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 (226) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +22 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/cm-control-policy-v2.md +331 -0
  7. package/docs/execution-optimizations.md +1 -1
  8. package/docs/external-models.md +3 -3
  9. package/docs/human-correction.md +5 -5
  10. package/docs/installation.md +1 -1
  11. package/docs/js-workflow-control.md +119 -78
  12. package/docs/next-steps.md +19 -2
  13. package/docs/untested-branches.md +2 -3
  14. package/docs/user-guide.md +105 -5
  15. package/package.json +2 -1
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  17. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +103 -68
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +79 -27
  19. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  20. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  21. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  22. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  23. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +883 -69
  25. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  26. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  27. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  28. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  29. package/runtime/js/cm-ai/host-check.mjs +4 -1
  30. package/runtime/js/cm-ai/host-conversation-execution.mjs +33 -24
  31. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  32. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  33. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  34. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +53 -9
  35. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  36. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  37. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +43 -3
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  41. package/runtime/js/cm-ai/host.mjs +1 -2
  42. package/runtime/js/cm-ai/operator-guidance.mjs +89 -3
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  44. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  45. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  46. package/runtime/js/cm-ai/review-package.mjs +26 -5
  47. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  48. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  49. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  50. package/runtime/js/cm-ai/task-runner.mjs +629 -121
  51. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  52. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  53. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  54. package/runtime/js/cm-fix/execution.mjs +176 -48
  55. package/runtime/js/cm-fix/host.mjs +2 -1
  56. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  57. package/runtime/js/cm-fix/progress.mjs +13 -3
  58. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  59. package/runtime/js/cm-fix/repair.mjs +11 -3
  60. package/runtime/js/cm-fix/test-author.mjs +10 -3
  61. package/runtime/js/cm-idea/session.mjs +67 -4
  62. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  63. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  64. package/runtime/js/cm-prd/review-host.mjs +1 -1
  65. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  66. package/runtime/js/cm-prd/session.mjs +43 -0
  67. package/runtime/js/cm-refactor/records.mjs +98 -8
  68. package/runtime/js/cm-refactor/workflow.mjs +80 -10
  69. package/runtime/js/cm-test/host.mjs +10 -3
  70. package/runtime/js/cm-test/session.mjs +45 -6
  71. package/runtime/js/notify-safe-read.mjs +49 -0
  72. package/runtime/js/notify-send.mjs +313 -0
  73. package/runtime/js/notify.mjs +164 -37
  74. package/runtime/js/policy-binding-compat.mjs +55 -0
  75. package/runtime/review.md +52 -7
  76. package/runtime/task-gates.md +107 -9
  77. package/scripts/ci-test-shards.mjs +67 -0
  78. package/scripts/ci-test-shards.test.mjs +64 -0
  79. package/scripts/ci-test-weights.json +222 -0
  80. package/scripts/cm-ai-abandon-effect-position.test.mjs +71 -10
  81. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  82. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  83. package/scripts/cm-ai-answer-gap-fixture.mjs +89 -0
  84. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  85. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  86. package/scripts/cm-ai-batch-drive.mjs +98 -34
  87. package/scripts/cm-ai-batch-drive.test.mjs +124 -16
  88. package/scripts/cm-ai-batch-host.mjs +167 -29
  89. package/scripts/cm-ai-batch-host.test.mjs +303 -31
  90. package/scripts/cm-ai-batch-run-fixture.mjs +452 -0
  91. package/scripts/cm-ai-batch-run-member-stops.test.mjs +26 -0
  92. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  93. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  94. package/scripts/cm-ai-batch-run.mjs +213 -25
  95. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  96. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  97. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  98. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  99. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  100. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  101. package/scripts/cm-ai-develop-answer-invalid.test.mjs +97 -0
  102. package/scripts/cm-ai-develop-call-timeout.test.mjs +146 -0
  103. package/scripts/cm-ai-develop-driver-gaps.test.mjs +37 -23
  104. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  105. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  106. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  107. package/scripts/cm-ai-drive.mjs +142 -58
  108. package/scripts/cm-ai-drive.test.mjs +70 -84
  109. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  110. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  111. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +267 -0
  113. package/scripts/cm-ai-host-fixture.mjs +296 -0
  114. package/scripts/cm-ai-host-protected.test.mjs +253 -0
  115. package/scripts/cm-ai-host.mjs +122 -100
  116. package/scripts/cm-ai-host.test.mjs +35 -776
  117. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  118. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  119. package/scripts/cm-ai-light-modules.test.mjs +54 -0
  120. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  121. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  122. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  123. package/scripts/cm-ai-progress.test.mjs +10 -8
  124. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  125. package/scripts/cm-ai-protected-scope.test.mjs +8 -5
  126. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  127. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  128. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  129. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +95 -13
  130. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  131. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  132. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +59 -14
  133. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  134. package/scripts/cm-ai-review-failure.test.mjs +137 -32
  135. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  136. package/scripts/cm-ai-review-timeout.test.mjs +132 -67
  137. package/scripts/cm-ai-run.mjs +91 -28
  138. package/scripts/cm-ai-run.test.mjs +11 -38
  139. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  140. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  141. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  142. package/scripts/cm-ai-supersede.test.mjs +489 -51
  143. package/scripts/cm-blocked-reason.test.mjs +2 -3
  144. package/scripts/cm-capability-gate.test.mjs +33 -1
  145. package/scripts/cm-check-drive-files.mjs +8 -0
  146. package/scripts/cm-check-drive.test.mjs +2 -5
  147. package/scripts/cm-check-runtime.sh +4 -2
  148. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  149. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  150. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  151. package/scripts/cm-claude-worker.test.mjs +23 -5
  152. package/scripts/cm-controlled-correction.test.mjs +469 -0
  153. package/scripts/cm-external-batch-host.test.mjs +30 -11
  154. package/scripts/cm-external-model-host.test.mjs +1 -1
  155. package/scripts/cm-external-model-recovery.test.mjs +32 -12
  156. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  157. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  158. package/scripts/cm-fix-abandon.test.mjs +163 -10
  159. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  160. package/scripts/cm-fix-drive.mjs +25 -7
  161. package/scripts/cm-fix-host.mjs +8 -7
  162. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  163. package/scripts/cm-fix-review-recovery.test.mjs +36 -1
  164. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  165. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  166. package/scripts/cm-host-documentation.test.mjs +49 -0
  167. package/scripts/cm-host-qa-executor.test.mjs +23 -12
  168. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  169. package/scripts/cm-host-review-authority.test.mjs +0 -31
  170. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  171. package/scripts/cm-idea-drive.mjs +49 -11
  172. package/scripts/cm-idea-drive.test.mjs +66 -0
  173. package/scripts/cm-idea-host.mjs +106 -16
  174. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  175. package/scripts/cm-init-drive.mjs +41 -7
  176. package/scripts/cm-init-host.mjs +61 -12
  177. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  178. package/scripts/cm-log-event.mjs +21 -10
  179. package/scripts/cm-notify-command.test.mjs +936 -0
  180. package/scripts/cm-notify-read-drift.test.mjs +270 -0
  181. package/scripts/cm-notify.mjs +481 -0
  182. package/scripts/cm-notify.test.mjs +312 -23
  183. package/scripts/cm-patrol.test.mjs +3 -2
  184. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  185. package/scripts/cm-prd-drive.mjs +18 -5
  186. package/scripts/cm-prd-drive.test.mjs +15 -0
  187. package/scripts/cm-prd-host.mjs +37 -4
  188. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  189. package/scripts/cm-prd-review-gate.mjs +56 -0
  190. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  191. package/scripts/cm-refactor-drive.mjs +52 -8
  192. package/scripts/cm-refactor-drive.test.mjs +44 -0
  193. package/scripts/cm-refactor-host.test.mjs +10 -6
  194. package/scripts/cm-release-smoke.sh +2 -0
  195. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  196. package/scripts/cm-task-gate.mjs +368 -34
  197. package/scripts/cm-task-gate.py +2 -0
  198. package/scripts/cm-task-gate.test.mjs +252 -4
  199. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  200. package/scripts/cm-test-drive.mjs +21 -5
  201. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  202. package/scripts/fixtures/claude-review-process.mjs +1 -1
  203. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  204. package/scripts/policy-binding-compat.test.mjs +103 -0
  205. package/scripts/scan-public-safety.py +4 -0
  206. package/scripts/validate-public-repo.py +4 -0
  207. package/skills/cm-ai/SKILL.md +8 -6
  208. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  209. package/skills/cm-ai/references/N4-review.md +11 -21
  210. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  211. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  212. package/skills/cm-ai/references/js-host-modes.md +35 -14
  213. package/skills/cm-ai/references/js-host-qa-recovery.md +85 -11
  214. package/skills/cm-ai/references/js-host-recovery.md +181 -21
  215. package/skills/cm-ai/references/js-host.md +76 -32
  216. package/skills/cm-check/SKILL.md +3 -3
  217. package/skills/cm-fix/SKILL.md +12 -0
  218. package/skills/cm-fix/references/js-host.md +44 -5
  219. package/skills/cm-idea/references/js-host.md +27 -2
  220. package/skills/cm-init/references/js-host.md +17 -4
  221. package/skills/cm-notify/SKILL.md +34 -0
  222. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  223. package/skills/cm-prd/references/js-host.md +1 -1
  224. package/skills/cm-refactor/SKILL.md +12 -0
  225. package/skills/cm-refactor/references/js-host.md +17 -0
  226. package/skills/cm-test/references/js-host.md +14 -1
@@ -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 \
@@ -6,16 +6,17 @@ import path from 'node:path';
6
6
  import {createHash} from 'node:crypto';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {spawnSync} from 'node:child_process';
9
- import {checkN4,checkN5,implementationSha256,prepareHumanCorrection,publishHumanCorrectionReview,
9
+ import {captureBaseline,checkN4,checkN5,implementationSha256,prepareHumanCorrection,publishHumanCorrectionReview,
10
10
  prepareMarkDone,verifyMarkDonePlan} from './cm-task-gate.mjs';
11
11
 
12
12
  const sha=file=>createHash('sha256').update(fs.readFileSync(file)).digest('hex');
13
13
  function fixture(t){
14
14
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-human-correction-')));
15
15
  t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
16
- const reviewsDir=path.join(root,'.reviews');fs.mkdirSync(reviewsDir);
16
+ const reviewsDir=path.join(root,'specs','.reviews');fs.mkdirSync(reviewsDir,{recursive:true});
17
17
  fs.mkdirSync(path.join(root,'src'));const code=path.join(root,'src/example.ts');fs.writeFileSync(code,'old');
18
- const tasks=path.join(root,'tasks.md');fs.writeFileSync(tasks,'- [ ] T-001: fixture\n');
18
+ const tasks=path.join(root,'specs','tasks.md');fs.writeFileSync(tasks,'- [ ] T-001: fixture\n');
19
+ captureBaseline({projectRoot:root,reviewsDir,feature:'login',task:'T-001'});
19
20
  const payload=attempt=>({schema_version:1,task_id:'T-001',attempt,status:'ready_for_review',changed_files:['src/example.ts'],
20
21
  implementation_sha256:implementationSha256(root,['src/example.ts']),
21
22
  verification:[{command:'fixture',status:'passed',evidence:'synthetic fixture'}],
@@ -27,9 +28,9 @@ function fixture(t){
27
28
  fs.writeFileSync(handoff,JSON.stringify(payload(attempt)));review(file,handoff,attempt,verdict);history.push(handoff,file);
28
29
  }
29
30
  const original=history.map(sha);fs.writeFileSync(code,'fixed');
30
- const draft=path.join(root,'draft.json');fs.writeFileSync(draft,JSON.stringify(payload(2)));
31
+ const draft=path.join(reviewsDir,'draft.json');fs.writeFileSync(draft,JSON.stringify(payload(2)));
31
32
  const selectors={handoff:draft,reviewsDir,feature:'login',task:'T-001',projectRoot:root,
32
- humanAuthorized:true,reason:'Human approved exact selector correction after original blocked round 2.'};
33
+ reason:'Correct exact selector after original blocked round 2.'};
33
34
  const prepare=()=>prepareHumanCorrection(selectors);
34
35
  const finish=(record,verdict='approved')=>{
35
36
  const selected={...selectors,...record,tasksPath:tasks};
@@ -39,6 +40,36 @@ function fixture(t){
39
40
  return {root,reviewsDir,code,tasks,draft,history,original,selectors,review,prepare,finish};
40
41
  }
41
42
 
43
+ test('library default human correction preserves results without an editing baseline',t=>{
44
+ const f=fixture(t);fs.unlinkSync(path.join(f.reviewsDir,'login-T-001-baseline.json'));
45
+ const record=f.prepare(),selected={...f.selectors,...record};
46
+ assert.equal(JSON.stringify(checkN4(selected)),JSON.stringify({gate:'n4',task:'T-001',attempt:2,
47
+ outcome:'ready_for_review',content_bound:true,handoff_sha256:sha(record.handoff),correction_sha256:record.correction_sha256}));
48
+ const done=f.finish(record);
49
+ assert.equal(JSON.stringify(checkN5(done)),JSON.stringify({gate:'n5',task:'T-001',attempt:2,
50
+ outcome:'approved',review:record.review,content_bound:true,correction_sha256:record.correction_sha256}));
51
+ const plan=prepareMarkDone(done);assert.equal(plan.evidence.length,8);
52
+ assert.deepEqual(verifyMarkDonePlan(done,plan.planDigest),{outcome:'matched',planDigest:plan.planDigest});
53
+ assert.deepEqual(f.history.map(sha),f.original);
54
+ });
55
+
56
+ test('human correction CLI and internal opt-in still require an editing baseline',t=>{
57
+ const f=fixture(t);fs.unlinkSync(path.join(f.reviewsDir,'login-T-001-baseline.json'));
58
+ const record=f.prepare(),selected={...f.selectors,...record};
59
+ assert.throws(()=>checkN4({...selected,inventory:'required'}),/missing editing baseline/);
60
+ const script=fileURLToPath(new URL('./cm-task-gate.mjs',import.meta.url));
61
+ const cli=command=>spawnSync(process.execPath,[script,command,'--handoff',record.handoff,
62
+ '--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001','--project-root',f.root,
63
+ '--correction',record.correction,...(command==='prepare-mark-done'?['--tasks',f.tasks]:[])],{encoding:'utf8'});
64
+ const n4=cli('check-n4');assert.equal(n4.status,1);assert.match(n4.stderr,/missing editing baseline/);
65
+ const done=f.finish(record);
66
+ assert.throws(()=>checkN5({...done,inventory:'required'}),/missing editing baseline/);
67
+ for(const command of ['check-n5','prepare-mark-done']){
68
+ const result=cli(command);assert.equal(result.status,1);assert.match(result.stderr,/missing editing baseline/);
69
+ }
70
+ assert.deepEqual(f.history.map(sha),f.original);assert.match(fs.readFileSync(f.tasks,'utf8'),/\[ \]/);
71
+ });
72
+
42
73
  test('one-shot human correction retains blocked history and completes through the existing locked adapter',t=>{
43
74
  const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
44
75
  assert.equal(checkN4(selected).outcome,'ready_for_review');
@@ -54,20 +85,19 @@ test('one-shot human correction retains blocked history and completes through th
54
85
  assert.throws(()=>checkN5({...done,handoff:f.history[2],correction:null}),/implementation content changed/);
55
86
  });
56
87
 
57
- test('correction authorization, original verdict, full scope, and mandatory Learning cannot be omitted',t=>{
88
+ test('correction reason, original verdict, full scope, and mandatory Learning cannot be omitted',t=>{
58
89
  const f=fixture(t);
59
- assert.throws(()=>prepareHumanCorrection({...f.selectors,humanAuthorized:false}),/authorization/);
60
90
  assert.throws(()=>prepareHumanCorrection({...f.selectors,reason:''}),/reason/);
61
91
  const draft=JSON.parse(fs.readFileSync(f.draft));draft.evidence=['unbound application'];fs.writeFileSync(f.draft,JSON.stringify(draft));
62
92
  assert.throws(()=>prepareHumanCorrection({...f.selectors,allowLegacyUnbound:true}),/Learning/);
63
- assert.equal(fs.readdirSync(f.reviewsDir).length,4);
93
+ assert.equal(fs.readdirSync(f.reviewsDir).length,6);
64
94
  draft.evidence=['learning: no_relevant_lesson','learning: retrospective no_new_lesson'];draft.changed_files=['src/new.ts'];
65
95
  fs.writeFileSync(path.join(f.root,'src/new.ts'),'new');draft.implementation_sha256=implementationSha256(f.root,draft.changed_files);
66
96
  fs.writeFileSync(f.draft,JSON.stringify(draft));assert.throws(()=>f.prepare(),/full original/);
67
97
  f.review(f.history[3],f.history[2],2,'approved');assert.throws(()=>f.prepare(),/blocked round 2/);
68
98
  });
69
99
 
70
- test('original evidence, correction handoff, implementation and authorization record drift invalidate approval',t=>{
100
+ test('original evidence, correction handoff, implementation and source record drift invalidate approval',t=>{
71
101
  const f=fixture(t),record=f.prepare(),done=f.finish(record),plan=prepareMarkDone(done);
72
102
  for(const file of [...f.history,record.correction,record.handoff,record.review,done.receipt??path.join(f.reviewsDir,'login-T-001-human-correction-receipt.json'),f.code]){
73
103
  const bytes=fs.readFileSync(file);fs.appendFileSync(file,'\nchanged');
@@ -87,13 +117,13 @@ test('blocked correction review is sealed once and cannot be replaced by a new a
87
117
  assert.throws(()=>f.prepare(),/already exists/);
88
118
  });
89
119
 
90
- test('old review or self-degraded review cannot authorize a correction',t=>{
120
+ test('old review or self-degraded review does not meet correction declaration and binding requirements',t=>{
91
121
  const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
92
122
  f.review(record.review,record.handoff,2,'approved');
93
- assert.throws(()=>publishHumanCorrectionReview(selected),/fresh independent/);
123
+ assert.throws(()=>publishHumanCorrectionReview(selected),/independent: true.*bound/);
94
124
  f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
95
125
  fs.writeFileSync(record.review,fs.readFileSync(record.review,'utf8').replace('codex-subagent','self-degraded').replace('independent: true','independent: false').replace('scope:','degraded_reason: fixture\nscope:'));
96
- assert.throws(()=>publishHumanCorrectionReview(selected),/fresh independent/);
126
+ assert.throws(()=>publishHumanCorrectionReview(selected),/independent: true.*bound/);
97
127
  });
98
128
 
99
129
  test('correction file identities reject symlinks, hardlinks, sibling selection and duplicate record fields',t=>{
@@ -108,10 +138,33 @@ test('correction file identities reject symlinks, hardlinks, sibling selection a
108
138
  assert.throws(()=>checkN4(selected),/non-symlink/);
109
139
  });
110
140
 
111
- test('CLI human correction refuses missing human authorization and exposes the fixed review record',t=>{
141
+ test('CLI correction works without an authorization flag and rejects the removed flag',t=>{
112
142
  const f=fixture(t),script=fileURLToPath(new URL('./cm-task-gate.mjs',import.meta.url));
113
- const args=['prepare-human-correction','--handoff',f.draft,'--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001','--project-root',f.root,'--reason','Explicit human correction'];
114
- const denied=spawnSync(process.execPath,[script,...args],{encoding:'utf8'});assert.equal(denied.status,1);assert.match(denied.stderr,/authorization/);
115
- const result=spawnSync(process.execPath,[script,...args,'--human-authorized'],{encoding:'utf8'});
143
+ const args=['prepare-human-correction','--handoff',f.draft,'--reviews-dir',f.reviewsDir,'--feature','login','--task','T-001','--project-root',f.root,'--reason','Correct exact selector'];
144
+ const removed=spawnSync(process.execPath,[script,...args,'--human-authorized'],{encoding:'utf8'});
145
+ assert.equal(removed.status,1);assert.match(removed.stderr,/invalid arguments/);
146
+ const result=spawnSync(process.execPath,[script,...args],{encoding:'utf8'});
116
147
  assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).attempt,2);
117
148
  });
149
+
150
+
151
+ test('correction review declarations and candidate package bindings remain mandatory',t=>{
152
+ const f=fixture(t),record=f.prepare(),selected={...f.selectors,...record};
153
+ f.review(record.review,record.handoff,2,'approved',record.correction_sha256);
154
+ const original=fs.readFileSync(record.review,'utf8');
155
+ for(const [before,after] of [
156
+ ['independent: true','independent: yes'],
157
+ ['reviewer: codex-subagent','reviewer: arbitrary'],
158
+ ['handoff_sha256: '+sha(record.handoff),'handoff_sha256: '+'0'.repeat(64)],
159
+ ['correction_sha256: '+record.correction_sha256,'correction_sha256: '+'0'.repeat(64)],
160
+ ['verdict: approved','verdict: blocked'],
161
+ ]){
162
+ fs.writeFileSync(record.review,original.replace(before,after));
163
+ assert.throws(()=>publishHumanCorrectionReview(selected),undefined,before);
164
+ assert.equal(fs.existsSync(path.join(f.reviewsDir,'login-T-001-human-correction-receipt.json')),false);
165
+ }
166
+ fs.writeFileSync(record.review,original);
167
+ publishHumanCorrectionReview(selected);
168
+ assert.equal(checkN5(selected).outcome,'approved');
169
+ assert.deepEqual(f.history.map(sha),f.original);
170
+ });