@aibyzero/cm-workflow 0.16.7 → 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 (182) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +39 -3
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/compat/claude-commands/cm-notify.md +3 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +61 -4
  10. package/docs/next-steps.md +8 -2
  11. package/docs/user-guide.md +204 -0
  12. package/package.json +2 -1
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
  17. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  18. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  19. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  20. package/runtime/js/cm-ai/drive-core.mjs +26 -4
  21. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  22. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  23. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  24. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  25. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  26. package/runtime/js/cm-ai/host-check.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  28. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  29. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  30. package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
  31. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  32. package/runtime/js/cm-ai/host-session.mjs +47 -7
  33. package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
  34. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  35. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  36. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  37. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  38. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  39. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  40. package/runtime/js/cm-ai/review-package.mjs +10 -1
  41. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  42. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  43. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  44. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  45. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  46. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  47. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  48. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  49. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  50. package/runtime/js/cm-fix/execution.mjs +356 -187
  51. package/runtime/js/cm-fix/host.mjs +2 -1
  52. package/runtime/js/cm-fix/investigation.mjs +25 -9
  53. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  54. package/runtime/js/cm-fix/progress.mjs +15 -3
  55. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  56. package/runtime/js/cm-fix/repair.mjs +11 -3
  57. package/runtime/js/cm-fix/test-author.mjs +10 -3
  58. package/runtime/js/cm-idea/session.mjs +67 -4
  59. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  60. package/runtime/js/cm-prd/session.mjs +43 -0
  61. package/runtime/js/cm-refactor/records.mjs +98 -8
  62. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  63. package/runtime/js/cm-test/host.mjs +10 -3
  64. package/runtime/js/cm-test/session.mjs +45 -6
  65. package/runtime/js/notify-run.mjs +26 -0
  66. package/runtime/js/notify-safe-read.mjs +49 -0
  67. package/runtime/js/notify-send.mjs +312 -0
  68. package/runtime/js/notify.mjs +492 -0
  69. package/runtime/js/policy-binding-compat.mjs +54 -0
  70. package/runtime/model-efficiency.md +17 -0
  71. package/scripts/ci-test-shards.mjs +67 -0
  72. package/scripts/ci-test-shards.test.mjs +64 -0
  73. package/scripts/ci-test-weights.json +222 -0
  74. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  75. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  76. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  77. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  78. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  79. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  80. package/scripts/cm-ai-batch-drive.mjs +55 -10
  81. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  82. package/scripts/cm-ai-batch-host.mjs +132 -13
  83. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  84. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  85. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  86. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  87. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  88. package/scripts/cm-ai-batch-run.mjs +189 -22
  89. package/scripts/cm-ai-batch-run.test.mjs +22 -334
  90. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  91. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  92. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  93. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  94. package/scripts/cm-ai-drive.mjs +68 -23
  95. package/scripts/cm-ai-drive.test.mjs +37 -2
  96. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  97. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  98. package/scripts/cm-ai-host-fixture.mjs +268 -0
  99. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  100. package/scripts/cm-ai-host.mjs +28 -16
  101. package/scripts/cm-ai-host.test.mjs +17 -759
  102. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  103. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  104. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  105. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  106. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  107. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  108. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
  109. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  110. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  111. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  112. package/scripts/cm-ai-run.mjs +15 -6
  113. package/scripts/cm-ai-supersede.test.mjs +486 -41
  114. package/scripts/cm-check-drive-files.mjs +8 -0
  115. package/scripts/cm-check-drive.test.mjs +2 -5
  116. package/scripts/cm-check-runtime.sh +4 -2
  117. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  118. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  119. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  120. package/scripts/cm-claude-worker.test.mjs +18 -2
  121. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  122. package/scripts/cm-fix-abandon.test.mjs +249 -10
  123. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  124. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  125. package/scripts/cm-fix-drive.mjs +34 -8
  126. package/scripts/cm-fix-host.mjs +8 -7
  127. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  128. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  129. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  130. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  131. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  132. package/scripts/cm-host-documentation.test.mjs +49 -0
  133. package/scripts/cm-host-qa-executor.test.mjs +143 -10
  134. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  135. package/scripts/cm-idea-drive.mjs +49 -11
  136. package/scripts/cm-idea-drive.test.mjs +66 -0
  137. package/scripts/cm-idea-host.mjs +106 -16
  138. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  139. package/scripts/cm-init-drive.mjs +41 -7
  140. package/scripts/cm-init-host.mjs +61 -12
  141. package/scripts/cm-log-event.mjs +49 -12
  142. package/scripts/cm-notify-command.test.mjs +900 -0
  143. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  144. package/scripts/cm-notify.mjs +469 -0
  145. package/scripts/cm-notify.test.mjs +685 -0
  146. package/scripts/cm-patrol.mjs +83 -0
  147. package/scripts/cm-patrol.test.mjs +161 -0
  148. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  149. package/scripts/cm-prd-drive.mjs +18 -5
  150. package/scripts/cm-prd-drive.test.mjs +15 -0
  151. package/scripts/cm-prd-host.mjs +37 -4
  152. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  153. package/scripts/cm-prd-review-gate.mjs +56 -0
  154. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  155. package/scripts/cm-refactor-drive.mjs +52 -8
  156. package/scripts/cm-refactor-drive.test.mjs +44 -0
  157. package/scripts/cm-refactor-host.test.mjs +10 -6
  158. package/scripts/cm-release-smoke.sh +2 -0
  159. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  160. package/scripts/cm-test-drive.mjs +21 -5
  161. package/scripts/cm-token-report.mjs +497 -0
  162. package/scripts/cm-token-report.test.mjs +346 -0
  163. package/scripts/fixtures/claude-review-process.mjs +1 -1
  164. package/scripts/policy-binding-compat.test.mjs +99 -0
  165. package/scripts/scan-public-safety.py +4 -0
  166. package/scripts/validate-public-repo.py +4 -0
  167. package/skills/cm-ai/SKILL.md +7 -3
  168. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  169. package/skills/cm-ai/references/js-host-modes.md +90 -0
  170. package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
  171. package/skills/cm-ai/references/js-host-recovery.md +311 -0
  172. package/skills/cm-ai/references/js-host.md +76 -331
  173. package/skills/cm-check/SKILL.md +3 -3
  174. package/skills/cm-fix/SKILL.md +2 -0
  175. package/skills/cm-fix/references/js-host.md +56 -10
  176. package/skills/cm-idea/references/js-host.md +27 -2
  177. package/skills/cm-init/references/js-host.md +16 -3
  178. package/skills/cm-notify/SKILL.md +34 -0
  179. package/skills/cm-prd/SKILL.md +2 -0
  180. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  181. package/skills/cm-refactor/references/js-host.md +17 -0
  182. package/skills/cm-test/references/js-host.md +14 -1
@@ -0,0 +1,153 @@
1
+ // A round-2 develop the host answer limit cut off (call_timeout) while the code
2
+ // root still equals the reviewed round-1 package is a retryable block; advance
3
+ // journals develop-timeout-retry and redoes the same round with a new effect id.
4
+ import test from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import {openControlRun} from './cm-ai-run.mjs';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
11
+ import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
12
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
13
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
14
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
15
+ import {readRunnerHistory} from '../runtime/js/cm-ai/durable-runner-state.mjs';
16
+
17
+ const learning={outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
18
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}};
19
+ function fixture(t){
20
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-develop-timeout-')));
21
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
22
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),feature='1.work';
23
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
24
+ fs.writeFileSync(path.join(codeProject,'a.mjs'),'old\n');
25
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'fixture\n');
26
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
27
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-002: fixture\n');
28
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
29
+ return {root,codeProject,specsDir,feature,store:path.join(specsDir,'.reviews','.execution','timeout-run','state.json')};
30
+ }
31
+ const identity=attempt=>({repositoryId:'develop-timeout',runId:'timeout-run',taskId:'T-002',attempt});
32
+ const definition=f=>({version:1,specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
33
+ identity:identity(1),scope:['a.mjs'],requirements:['requirements.md']});
34
+ // answers: one per developer call in this host; 'hang' never answers (the
35
+ // session missed the host limit), a string is written to a.mjs and answered.
36
+ function execution(f,answers){
37
+ const queue=[...answers];
38
+ const reviewer={id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',
39
+ allowed:true,available:true,contexts:['review-one','review-two'],run:(value,{onEvent})=>{
40
+ onEvent({event:'thread.started',provider_thread:`review-thread-${value.identity.attempt}`});
41
+ onEvent({event:'turn.started',item_type:null});onEvent({event:'item.completed',item_type:'agent_message'});
42
+ onEvent({event:'turn.completed',item_type:null});onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
43
+ const pkg=value.payload.reviewPackage;
44
+ return {status:'succeeded',value:{verdict:'changes_requested',packageDigest:pkg.packageDigest,examinedPaths:reviewPaths(pkg),
45
+ findings:[{id:'F1',severity:'P2',path:'a.mjs',message:'Revise',evidence:'Fixture finding'}],summary:'Fixture review'}};
46
+ }};
47
+ return {configuration:{kind:'develop-timeout-v1'},timeoutMs:1500,excludedContexts:['control'],
48
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:createCodexDeveloperRun({
49
+ requestedModel:'fixture',worker:async()=>{
50
+ const worker=queue.shift();
51
+ if(worker==='hang')return new Promise(()=>{});
52
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),worker);return {status:'succeeded',value:learning};}})},
53
+ reviewers:[reviewer],reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control'],
54
+ authorize:(value,{authorizationAt})=>{const body={version:1,kind:'cm-review-dispatch-grant',
55
+ grantId:'grant',adapterId:'codex-review-adapter',invocationId:value.invocationId,
56
+ requestDigest:value.requestDigest,identity:value.identity,reviewerId:'reviewer',
57
+ logicalContextId:value.contextId,packageDigest:value.payload.reviewPackage.packageDigest,
58
+ hostContextId:'control',decisionId:'approved',decision:'approved',issuedAt:authorizationAt,
59
+ expiresAt:authorizationAt+60000};return {...body,grantDigest:digest(body)};}},
60
+ hostDecision:{status:'approved'},check:createHostCheck({cwd:f.codeProject,
61
+ commands:[{id:'syntax',command:[process.execPath,'-e','0']}]})};
62
+ }
63
+ async function session(f,mode,answers,operations){
64
+ const run=await openControlRun(definition(f),mode,execution(f,answers));
65
+ const results=[];
66
+ try{
67
+ for(const [operation,attempt,extra] of operations)
68
+ results.push(await run.host.handle({version:1,operation,requestId:`${operation}-${results.length}`,identity:identity(attempt),...extra}));
69
+ }finally{run.close();}
70
+ return results;
71
+ }
72
+ const records=f=>JSON.parse(fs.readFileSync(f.store,'utf8')).records;
73
+ // Round 1 delivered and reviewed (changes_requested), then the round-2 develop
74
+ // times out with nothing written.
75
+ async function timedOutRoundTwo(f){
76
+ const [timedOut]=await session(f,'create',['round-1\n','hang'],[['advance',1]]);
77
+ return timedOut;
78
+ }
79
+
80
+ test('develop_call_timeout: a timed-out round-2 develop with an unchanged code root redoes the round with a new effect id',async t=>{
81
+ const f=fixture(t);
82
+ const timedOut=await timedOutRoundTwo(f);
83
+ // The live answer already reads the disk: nothing was written, so the block is retryable.
84
+ assert.equal(timedOut.state,'blocked',JSON.stringify(timedOut));assert.equal(timedOut.code,'develop_call_timeout');
85
+ assert.equal(timedOut.pendingAction,'resume');assert.equal(timedOut.guidance.recoveryOperation,'advance');
86
+ assert.match(timedOut.guidance.summary,/开发应答超时、代码未改动/);
87
+ // The journal holds exactly what older runtimes wrote: unknown/call_timeout.
88
+ const before=records(f),checkpoint=before.at(-1).payload;
89
+ assert.equal(checkpoint.effectId,'develop-2');
90
+ assert.deepEqual([checkpoint.checkpoint.state,checkpoint.checkpoint.code],['unknown','call_timeout']);
91
+ assert.equal(checkpoint.checkpoint.calls.at(-1).terminal,'unknown');
92
+ assert.equal(readRunnerHistory(before,before[0].payload.config,3).state.state,'unknown');
93
+ // A writer that wrote after the limit is never silently adopted. This fixture's
94
+ // developer is a provider model whose worker identity is journaled (it never
95
+ // spawned), so the only exit is the confirmed develop_redo (V9), not advance.
96
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'late edit\n');
97
+ const [changed]=await session(f,'resume',['round-2\n'],[['status',2],['advance',2]]);
98
+ assert.deepEqual([changed.state,changed.code,changed.pendingAction],['blocked','develop_answer_missing','develop_redo']);
99
+ assert.equal(records(f).length,before.length,'status/advance on a changed root must not append');
100
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'round-1\n');
101
+ const [status,redone]=await session(f,'resume',['round-2\n'],[['status',2],['advance',2]]);
102
+ assert.deepEqual([status.state,status.code,status.pendingAction],['blocked','develop_call_timeout','resume']);
103
+ // The same advance goes on to the round-2 review, which is this run's last.
104
+ assert.deepEqual([redone.state,redone.code,redone.identity.attempt],['blocked','review_limit',2],JSON.stringify(redone));
105
+ const after=records(f);
106
+ assert.deepEqual(after.slice(0,before.length),before,'journal is append-only');
107
+ const added=after.slice(before.length).map(row=>row.payload.type==='effect-intent'?`intent:${row.payload.effect.id}`:row.payload.type);
108
+ assert.deepEqual(added.slice(0,3),['develop-timeout-retry','intent:develop-2-retry-1','effect-checkpoint']);
109
+ assert.equal(after[before.length+2].payload.checkpoint.state,'awaiting_review');
110
+ assert.equal(after[before.length].payload.basis,'reviewed_package');
111
+ assert.ok(added.includes('intent:review-2'));
112
+ const replayed=readRunnerHistory(after,after[0].payload.config,3).state;
113
+ assert.equal(replayed.code,'review_limit');assert.equal(replayed.receipts.length,2,'review rounds are not reset');
114
+ });
115
+
116
+ // Codex round 1 (P2): the released block keeps its start binding. A crash after
117
+ // develop-timeout-retry, or a write between the status check and dispatch,
118
+ // must not carry unreviewed edits into the redo.
119
+ function truncateAfter(f,type){
120
+ const state=JSON.parse(fs.readFileSync(f.store,'utf8'));
121
+ const index=state.records.findIndex(row=>row.payload.type===type);assert.ok(index>0);
122
+ const {revision,...body}=state;body.records=state.records.slice(0,index+1);
123
+ fs.writeFileSync(f.store,JSON.stringify({...body,revision:digest(body)})+'\n');
124
+ return body.records;
125
+ }
126
+ test('develop_call_timeout: the released block re-verifies the round start before dispatch',async t=>{
127
+ const f=fixture(t);
128
+ await timedOutRoundTwo(f);
129
+ // (a) The host wrote develop-timeout-retry and exited before the develop intent.
130
+ const [, redone]=await session(f,'resume',['round-2\n'],[['status',2],['advance',2]]);
131
+ assert.equal(redone.identity.attempt,2);
132
+ const prefix=truncateAfter(f,'develop-timeout-retry');
133
+ assert.equal(readRunnerHistory(prefix,prefix[0].payload.config,3).state.code,'develop_call_timeout');
134
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'late edit\n');
135
+ const [crashed]=await session(f,'resume',['should-not-run\n'],[['advance',2]]);
136
+ assert.deepEqual([crashed.state,crashed.code,crashed.pendingAction],['unknown','call_timeout','reconcile']);
137
+ assert.equal(records(f).length,prefix.length,'no develop intent after a changed root');
138
+ assert.equal(fs.readFileSync(path.join(f.codeProject,'a.mjs'),'utf8'),'late edit\n');
139
+ // (b) Equal at the status check, changed right before dispatch: refused, nothing dispatched.
140
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'round-1\n');
141
+ const target=path.join(f.codeProject,'a.mjs'),open=fs.openSync;
142
+ // The first read of a.mjs inside executeEffect is its dispatch-time check;
143
+ // every earlier read (the route's status checks) still sees the round start.
144
+ let raced,changed=false;const limit=Error.stackTraceLimit;Error.stackTraceLimit=50;
145
+ fs.openSync=(file,...rest)=>{
146
+ if(file===target&&!changed&&/executeEffect/.test(new Error().stack)){changed=true;fs.writeFileSync(target,'raced edit\n');}
147
+ return open(file,...rest);};
148
+ try{[raced]=await session(f,'resume',['should-not-run\n'],[['advance',2]]);}finally{fs.openSync=open;Error.stackTraceLimit=limit;}
149
+ assert.ok(changed,'the dispatch-time check read the root');
150
+ assert.deepEqual([raced.outcome,raced.code],['rejected','develop_timeout_root_changed'],JSON.stringify(raced));
151
+ assert.equal(records(f).length,prefix.length,'no develop intent after a raced change');
152
+ assert.equal(fs.readFileSync(target,'utf8'),'raced edit\n');
153
+ });
@@ -409,11 +409,12 @@ test('#19 a live delivery that deletes an in-scope requirement blocks retryably
409
409
  const intents=records(f).filter(row=>row.payload.type==='effect-intent').map(row=>row.payload.effect.id);
410
410
  assert.deepEqual(intents,['develop-1','develop-1-retry-1']);
411
411
  });
412
- test('#19 an out-of-scope write still wins over a missing requirement and stays unknown',t=>{
412
+ // A53: the out-of-scope write still wins, now as the named, retryable re-check block.
413
+ test('#19 an out-of-scope write still wins over a missing requirement and names the path',t=>{
413
414
  const f=fixture(t,{scope:['target.mjs','requirements.md'],files:{'target.mjs':'export const value = 42;\n'}});
414
415
  const run=liveSession(f,{mode:'create',act:"fs.unlinkSync(cwd+'/requirements.md');fs.writeFileSync(cwd+'/outside.mjs','x');"});
415
- assert.equal(run.status,1,run.stderr);
416
- assert.equal(result(run).state,'unknown');assert.equal(result(run).code,'out_of_scope');
416
+ assert.equal(result(run).state,'blocked',run.stdout);assert.equal(result(run).code,'develop_out_of_scope');
417
+ assert.match(result(run).reason,/outside\.mjs/);assert.equal(result(run).pendingAction,'resume');
417
418
  });
418
419
  // Round 2 (Codex re-review of 304cbfb): a develop-gate block after a
419
420
  // changes_requested review must be retryable at attempt 2 as it is at attempt 1.
@@ -0,0 +1,424 @@
1
+ // Q16/Q17: documentation_sync runs inside the final task's develop, after the
2
+ // session already answered the develop. A sync that never answers, answers
3
+ // blocked, or writes outside the documentation paths must not end in an
4
+ // exit-less unknown, and must never redispatch develop.
5
+ import test from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import {openControlRun} from './cm-ai-run.mjs';
10
+ import {gapFixture,gapExecution,identity,records,added} from './cm-ai-answer-gap-fixture.mjs';
11
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
12
+
13
+ // paths: the documentation paths (README.md first, always written by {write}).
14
+ const docFixture=(t,name,paths=['README.md'])=>{
15
+ const f=gapFixture(t,name);
16
+ fs.writeFileSync(path.join(f.codeProject,'README.md'),'# Before\n');
17
+ f.calls.documentation=0;f.docPaths=paths;
18
+ return f;
19
+ };
20
+ const docDefinition=f=>({version:1,specsDir:f.specsDir,codeProject:f.codeProject,feature:f.feature,
21
+ identity:identity(1),scope:['a.mjs',...f.docPaths],requirements:['requirements.md']});
22
+ // sync: one item per documentation_sync call: 'hang' never answers, {write}
23
+ // writes README.md (or {other} writes a.mjs) and answers {status} (default completed).
24
+ function docExecution(f,{developer=[],sync=[],verdicts=[]}={}){
25
+ const queue=[...sync];
26
+ return {...gapExecution(f,{developer,verdicts}),...(f.timeoutMs?{timeoutMs:f.timeoutMs}:{}),documentationSync:{paths:f.docPaths,run:async(request,signal)=>{
27
+ f.calls.documentation++;
28
+ const item=queue.shift();
29
+ if(item===undefined)throw Object.assign(new Error('unexpected documentation call'),{code:'unexpected_documentation_call'});
30
+ if(item.write!==undefined)fs.writeFileSync(path.join(f.codeProject,'README.md'),item.write);
31
+ if(item.other!==undefined)fs.writeFileSync(path.join(f.codeProject,'a.mjs'),item.other);
32
+ if(item.hang)return new Promise((_,reject)=>signal.addEventListener('abort',()=>reject(Object.assign(new Error('cancelled'),{code:'cancelled'})),{once:true}));
33
+ if(item.throw)throw Object.assign(new Error(item.throw),{code:item.throw});
34
+ return item.answer??{status:item.status??'completed'};
35
+ }}};
36
+ }
37
+ async function docSession(f,mode,execution,operations,options={}){
38
+ const run=await openControlRun(docDefinition(f),mode,execution,options);
39
+ const results=[];
40
+ try{
41
+ for(const [operation,attempt,extra] of operations)
42
+ results.push(await run.host.handle({version:1,operation,requestId:`${operation}-${results.length}`,identity:identity(attempt),...extra}));
43
+ }finally{run.close();}
44
+ return results;
45
+ }
46
+ const readme=f=>fs.readFileSync(path.join(f.codeProject,'README.md'),'utf8');
47
+ const code=f=>fs.readFileSync(path.join(f.codeProject,'a.mjs'),'utf8');
48
+
49
+ // R3: the operator's stop confirmation (develop_redo + reason), journaled as
50
+ // documentation-sync-retry. Nothing else lets a documentation-only redo start.
51
+ const confirm=(f,reason='会话已停止修改文档')=>docSession(f,'resume',docExecution(f),
52
+ [['develop_redo',1,{reason}]],{allowDevelopRedo:true}).then(([result])=>result);
53
+ // Every failure kind waits for develop_redo first: advance alone reports and
54
+ // journals nothing, and documentation_sync is not asked again.
55
+ async function assertWaitsForStop(f,code){
56
+ const before=records(f),calls=f.calls.documentation;
57
+ const [reported,refused]=await docSession(f,'resume',docExecution(f),[['advance',1],['develop_redo',1,{reason:'已停'}]]);
58
+ assert.deepEqual([reported.outcome,reported.code,reported.pendingAction],['reported',code,'develop_redo'],JSON.stringify(reported));
59
+ assert.deepEqual([refused.outcome,refused.code],['rejected','develop_redo_authorization_required']);
60
+ assert.deepEqual(records(f),before);assert.equal(f.calls.documentation,calls);
61
+ }
62
+
63
+ test('Q16: a documentation_sync that never answers waits for the stop confirmation even with the docs unchanged, then redoes only documentation_sync',async t=>{
64
+ const f=docFixture(t,'doc-timeout');
65
+ const [stuck]=await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{hang:true}]}),[['advance',1]]);
66
+ assert.deepEqual([stuck.state,stuck.code,stuck.pendingAction],['blocked','documentation_sync_answer_missing','develop_redo'],JSON.stringify(stuck));
67
+ assert.match(stuck.reason,/只重发文档同步/);assert.match(stuck.reason,/call_timeout/);assert.match(stuck.reason,/--allow-develop-redo/);
68
+ assert.equal(stuck.guidance.recoveryOperation,'develop_redo');assert.match(stuck.guidance.summary,/不需要重新开发/);
69
+ // The journal keeps the raw shape: unknown, with the developer answer recorded before the sync.
70
+ const raw=records(f).at(-1).payload.checkpoint;
71
+ assert.deepEqual([raw.state,raw.code,raw.calls.at(-1).terminal],['unknown','documentation_sync_answer_missing','unknown']);
72
+ const started=records(f).find(row=>row.payload.type==='documentation-sync-started');
73
+ assert.deepEqual(started.payload.documents.map(item=>item.path),['README.md']);
74
+ assert.equal(raw.calls.at(-1).documentationSync,started.digest);
75
+ assert.equal(f.calls.developer,1);assert.equal(code(f),'delivered\n');
76
+ await assertWaitsForStop(f,'documentation_sync_answer_missing');
77
+ const before=records(f);
78
+ const confirmed=await confirm(f);
79
+ assert.deepEqual([confirmed.outcome,confirmed.code,confirmed.pendingAction],['recorded','documentation_sync_answer_missing','resume'],JSON.stringify(confirmed));
80
+ assert.equal(confirmed.guidance.recoveryOperation,'advance');
81
+ const record=records(f).at(-1).payload;
82
+ assert.deepEqual([record.type,record.code,record.reason,record.startDigest,record.invocationId],
83
+ ['documentation-sync-retry','documentation_sync_answer_missing','会话已停止修改文档',started.digest,raw.calls.at(-1).invocationId]);
84
+ const [delivered]=await docSession(f,'resume',docExecution(f,{sync:[{write:'# After\n'}],verdicts:['approved']}),[['advance',1]]);
85
+ // The developer is never dispatched again: its journaled answer is reused.
86
+ assert.equal(f.calls.developer,1);assert.equal(f.calls.documentation,2);
87
+ assert.deepEqual(added(f,before).slice(0,3),['documentation-sync-retry','intent:develop-1-retry-1','documentation-sync-started'],JSON.stringify(added(f,before)));
88
+ const checkpoint=records(f).find((row,index)=>index>before.length&&row.payload.type==='effect-checkpoint').payload.checkpoint;
89
+ assert.equal(checkpoint.state,'awaiting_review',JSON.stringify(checkpoint.code));
90
+ // The review package still compares with the task baseline: develop and docs edits are both reviewed.
91
+ const changed=Object.fromEntries(checkpoint.reviewPackage.changes.map(change=>[change.path,
92
+ Buffer.from(change.before.contentBase64,'base64').toString()]));
93
+ assert.deepEqual(changed,{'README.md':'# Before\n','a.mjs':'old\n'});
94
+ assert.ok(added(f,before).includes('intent:review-1'),JSON.stringify(delivered));
95
+ assert.deepEqual(records(f).slice(0,before.length),before,'journal is append-only');
96
+ });
97
+
98
+ test('Q17: a documentation_sync answered blocked also waits for the stop confirmation; after the user fixes the docs only documentation_sync is redone',async t=>{
99
+ const f=docFixture(t,'doc-blocked');
100
+ const [stuck]=await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{status:'blocked'}]}),[['advance',1]]);
101
+ assert.deepEqual([stuck.state,stuck.code,stuck.pendingAction],['blocked','documentation_sync_answer_blocked','develop_redo'],JSON.stringify(stuck));
102
+ assert.match(stuck.reason,/已应答也只结束了宿主的等待/);
103
+ await assertWaitsForStop(f,'documentation_sync_answer_blocked');
104
+ // The user fixes the docs, confirms the session stopped, then advance re-asks only documentation_sync.
105
+ fs.writeFileSync(path.join(f.codeProject,'README.md'),'# Fixed by the user\n');
106
+ assert.equal((await confirm(f)).outcome,'recorded');
107
+ const [next]=await docSession(f,'resume',docExecution(f,{sync:[{}],verdicts:['approved']}),[['advance',1]]);
108
+ assert.equal(f.calls.developer,1);assert.equal(f.calls.documentation,2);
109
+ assert.notEqual(next.code,'documentation_sync_answer_blocked',JSON.stringify(next));
110
+ assert.equal(readme(f),'# Fixed by the user\n');
111
+ });
112
+
113
+ test('Q17: a documentation_sync that wrote outside the documentation paths is refused until those paths are restored',async t=>{
114
+ const f=docFixture(t,'doc-scope');
115
+ const [stuck]=await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{write:'# After\n',other:'rewritten by docs\n'}]}),[['advance',1]]);
116
+ assert.deepEqual([stuck.state,stuck.code,stuck.pendingAction],['blocked','documentation_sync_out_of_scope','develop_redo'],JSON.stringify(stuck));
117
+ assert.match(stuck.reason,/a\.mjs/);
118
+ await assertWaitsForStop(f,'documentation_sync_out_of_scope');
119
+ assert.equal((await confirm(f)).outcome,'recorded');
120
+ const before=records(f);
121
+ const [refused]=await docSession(f,'resume',docExecution(f),[['advance',1]]);
122
+ assert.deepEqual([refused.outcome,refused.code],['rejected','documentation_sync_out_of_scope'],JSON.stringify(refused));
123
+ assert.match(refused.reason,/a\.mjs/);
124
+ assert.equal(records(f).length,before.length);assert.equal(f.calls.documentation,1);
125
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'delivered\n');
126
+ const [ok]=await docSession(f,'resume',docExecution(f,{sync:[{}],verdicts:['approved']}),[['advance',1]]);
127
+ assert.equal(f.calls.developer,1);assert.equal(f.calls.documentation,2);
128
+ assert.notEqual(ok.outcome,'rejected',JSON.stringify(ok));
129
+ });
130
+
131
+ test('R3 on resume: docs changed after the confirmation (the old writer still alive) are refused until confirmed again; other files are refused outright',async t=>{
132
+ const f=docFixture(t,'doc-after-stop');
133
+ await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{write:'# Half\n',hang:true}]}),[['advance',1]]);
134
+ // The confirmation is journaled; the host then exits before any redo intent.
135
+ assert.equal((await confirm(f)).outcome,'recorded');
136
+ // The old writer was still alive: it writes the docs after the confirmation.
137
+ fs.writeFileSync(path.join(f.codeProject,'README.md'),'# Written late\n');
138
+ const before=records(f);
139
+ const [refused]=await docSession(f,'resume',docExecution(f),[['advance',1]]);
140
+ assert.deepEqual([refused.outcome,refused.code],['rejected','documentation_sync_changed_after_stop'],JSON.stringify(refused));
141
+ assert.equal(records(f).length,before.length);assert.equal(f.calls.documentation,1);
142
+ // Confirmed again (now really stopped): spends no extra retry.
143
+ assert.equal((await confirm(f,'旧会话已确认停止')).outcome,'recorded');
144
+ const {readRunnerHistory}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
145
+ assert.equal(readRunnerHistory(records(f),records(f)[0].payload.config,3).answerGaps.documentationSync,1);
146
+ // A non-documentation change after the confirmation is refused, too.
147
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'changed later\n');
148
+ const [scope]=await docSession(f,'resume',docExecution(f),[['advance',1]]);
149
+ assert.deepEqual([scope.outcome,scope.code],['rejected','documentation_sync_out_of_scope'],JSON.stringify(scope));
150
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'delivered\n');
151
+ const [ok]=await docSession(f,'resume',docExecution(f,{sync:[{}],verdicts:['approved']}),[['advance',1]]);
152
+ assert.notEqual(ok.outcome,'rejected',JSON.stringify(ok));
153
+ assert.equal(f.calls.developer,1);assert.equal(f.calls.documentation,2);
154
+ });
155
+
156
+ test('Q16/Q17: documentation_sync retries are capped at two per run, then an explicit limit',async t=>{
157
+ const f=docFixture(t,'doc-limit');
158
+ await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{status:'blocked'}]}),[['advance',1]]);
159
+ for(const answer of [{answer:{status:'later'}},{status:'blocked'}]){
160
+ assert.equal((await confirm(f)).outcome,'recorded');
161
+ const [next]=await docSession(f,'resume',docExecution(f,{sync:[answer]}),[['advance',1]]);
162
+ assert.equal(next.state,'blocked',JSON.stringify(next));
163
+ }
164
+ assert.equal(f.calls.developer,1);assert.equal(f.calls.documentation,3);
165
+ const [limit]=await docSession(f,'resume',docExecution(f),[['status',1]]);
166
+ assert.deepEqual([limit.state,limit.code,limit.pendingAction],['blocked','documentation_sync_retry_limit','none'],JSON.stringify(limit));
167
+ assert.match(limit.reason,/--supersede-reviewed-evidence/);assert.equal(limit.guidance.recoveryOperation,null);
168
+ const third=await confirm(f);
169
+ assert.equal(third.outcome,'rejected',JSON.stringify(third));
170
+ assert.deepEqual(records(f).filter(row=>row.payload.type==='documentation-sync-retry').map(row=>row.payload.code),
171
+ ['documentation_sync_answer_blocked','documentation_sync_answer_invalid']);
172
+ // Retries hold no call or effect slot: three develop effects, no counted call.
173
+ const {readRunnerHistory,developBudget,projectedRunnerStatus}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
174
+ const history=readRunnerHistory(records(f),records(f)[0].payload.config,3);
175
+ assert.deepEqual(developBudget(history.state),{calls:0,effects:0});
176
+ assert.equal(projectedRunnerStatus(history,records(f)[0].payload.config).code,'documentation_sync_retry_limit');
177
+ });
178
+
179
+ test('Q16: drivers prepare no developer answer for a documentation block, before or after the confirmation',async t=>{
180
+ const f=docFixture(t,'doc-driver');
181
+ await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{hang:true}]}),[['advance',1]]);
182
+ const {readRunnerHistory,projectedRunnerStatus}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
183
+ const {projectDevelopAttempts}=await import('./cm-ai-drive.mjs');
184
+ const {batchDevelopAttempts}=await import('./cm-ai-batch-drive.mjs');
185
+ const project=()=>{const config=records(f)[0].payload.config;return projectedRunnerStatus(readRunnerHistory(records(f),config,3),config);};
186
+ // Before the confirmation the journal alone shows no retryable block.
187
+ assert.deepEqual([project().state,project().code],['unknown','documentation_sync_answer_missing']);
188
+ await confirm(f);
189
+ const status=project();
190
+ assert.deepEqual([status.state,status.code],['blocked','documentation_sync_answer_missing']);
191
+ assert.deepEqual(projectDevelopAttempts(status,'advance',[]).attempts,[]);
192
+ assert.deepEqual(batchDevelopAttempts(status,'1.work/T-002',[]),[]);
193
+ });
194
+
195
+ test('older journals keep their projection: a develop that failed out_of_scope without a documentation record stays unknown',async t=>{
196
+ const f=docFixture(t,'doc-legacy');
197
+ // What runtimes before the documentation record wrote for Q17: the developer
198
+ // run itself threw out_of_scope (no documentation-sync-started, no marked call).
199
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'delivered\n');
200
+ await docSession(f,'create',gapExecution(f,{developer:[{beforeDispatch:'out_of_scope'}]}),[['advance',1]]);
201
+ assert.deepEqual([records(f).at(-1).payload.checkpoint.state,records(f).at(-1).payload.checkpoint.code],['unknown','out_of_scope']);
202
+ assert.ok(!records(f).some(row=>row.payload.type==='documentation-sync-started'));
203
+ const before=records(f);
204
+ const [status]=await docSession(f,'resume',gapExecution(f),[['status',1]]);
205
+ assert.deepEqual([status.state,status.code,status.pendingAction],['unknown','out_of_scope','reconcile'],JSON.stringify(status));
206
+ assert.deepEqual(records(f),before);
207
+ });
208
+
209
+ // Q16 (review r1 #3): the record accepts every documentation path the workflow
210
+ // configuration accepts (up to 256), so a large list never ends in store_failure.
211
+ // Documentation paths sit inside the task scope, itself capped at 256 paths
212
+ // (review-package FILE_COUNT), so with a.mjs and the AGENTS.md Learning path a run reaches 254; the record's own
213
+ // 256 bound is checked on replay below.
214
+ for(const count of [65,254])
215
+ test(`documentation-sync-started holds ${count} documentation paths`,async t=>{
216
+ const paths=['README.md',...Array.from({length:count-1},(_,index)=>`docs/d${String(index).padStart(3,'0')}.md`)];
217
+ const f=docFixture(t,`doc-many-${count}`,paths);
218
+ fs.mkdirSync(path.join(f.codeProject,'docs'));
219
+ const [result]=await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{write:'# After\n'}]}),[['advance',1]]);
220
+ assert.notEqual(result.code,'store_failure',JSON.stringify(result));
221
+ const started=records(f).find(row=>row.payload.type==='documentation-sync-started');
222
+ assert.equal(started.payload.documents.length,count);
223
+ const checkpoint=records(f).find(row=>row.payload.type==='effect-checkpoint').payload.checkpoint;
224
+ assert.equal(checkpoint.state,'awaiting_review',JSON.stringify([checkpoint.code,checkpoint.reason]));
225
+ });
226
+
227
+ test('the documentation record accepts 256 documentation paths and refuses 257',async()=>{
228
+ const {validDocumentationStates,MAX_DOCUMENTATION_PATHS}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
229
+ const {validateHostWorkflowConfiguration}=await import('../runtime/js/cm-ai/host-workflow-capabilities.mjs');
230
+ const docs=count=>Array.from({length:count},(_,i)=>`docs/d${String(i).padStart(3,'0')}.md`);
231
+ // Same bound as the workflow configuration.
232
+ assert.equal(MAX_DOCUMENTATION_PATHS,256);
233
+ validateHostWorkflowConfiguration({qa:null,documentationPaths:docs(256),applicableAgentFiles:[]});
234
+ assert.throws(()=>validateHostWorkflowConfiguration({qa:null,documentationPaths:docs(257),applicableAgentFiles:[]}));
235
+ assert.equal(validDocumentationStates(docs(256).map(p=>({path:p,sha256:null})),docs(257)).length,256);
236
+ assert.throws(()=>validDocumentationStates(docs(257).map(p=>({path:p,sha256:null})),docs(257)),{code:'runner_documentation'});
237
+ });
238
+
239
+ // Review r1 #2: a develop-scope file that Git ignores (a.mjs here) is kept by
240
+ // the task baseline; the documentation start must keep it too, so an edit to it
241
+ // during or after documentation_sync is caught before a stale answer is reused.
242
+ const ignoredFixture=(t,name)=>{
243
+ const f=docFixture(t,name);
244
+ const {spawnSync}=awaitSpawn;
245
+ // Git ignore queries make each capture slower than the 1.5 s fixture limit.
246
+ f.timeoutMs=20000;
247
+ fs.writeFileSync(path.join(f.codeProject,'.gitignore'),'a.mjs\n');
248
+ for(const args of [['init','-q'],['add','.gitignore','README.md','requirements.md'],
249
+ ['-c','user.name=t','-c','user.email=t@example.invalid','commit','-q','-m','init']]){
250
+ const result=spawnSync('git',['-C',f.codeProject,...args],{encoding:'utf8'});assert.equal(result.status,0,result.stderr);
251
+ }
252
+ return f;
253
+ };
254
+ const awaitSpawn=await import('node:child_process');
255
+ test('a gitignored develop-scope file written by documentation_sync is out of scope',async t=>{
256
+ const f=ignoredFixture(t,'doc-ignored-during');
257
+ const [stuck]=await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{write:'# After\n',other:'rewritten by docs\n'}]}),[['advance',1]]);
258
+ assert.equal(stuck.code,'documentation_sync_out_of_scope',JSON.stringify(stuck));
259
+ assert.match(stuck.reason,/a\.mjs/);
260
+ });
261
+ test('a gitignored develop-scope file changed after a failed documentation_sync blocks the retry',async t=>{
262
+ const f=ignoredFixture(t,'doc-ignored-after');
263
+ const [stuck]=await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{status:'blocked'}]}),[['advance',1]]);
264
+ assert.equal(stuck.code,'documentation_sync_answer_blocked',JSON.stringify(stuck));
265
+ fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'changed after the sync\n');
266
+ assert.equal((await confirm(f)).outcome,'recorded');
267
+ const before=records(f);
268
+ const [refused]=await docSession(f,'resume',docExecution(f),[['advance',1]]);
269
+ assert.deepEqual([refused.outcome,refused.code],['rejected','documentation_sync_out_of_scope'],JSON.stringify(refused));
270
+ assert.equal(records(f).length,before.length);assert.equal(f.calls.documentation,1);
271
+ });
272
+
273
+ test('guidance for every documentation block names develop_redo first and never a develop redo',async()=>{
274
+ const {operatorGuidance}=await import('../runtime/js/cm-ai/operator-guidance.mjs');
275
+ const {DOCUMENTATION_SYNC_CODES}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
276
+ for(const code of DOCUMENTATION_SYNC_CODES){
277
+ const base={workflow:'cm-ai',state:'blocked',code,identity:{taskId:'T-002'}};
278
+ const stop=operatorGuidance({...base,pendingAction:'develop_redo'});
279
+ assert.equal(stop.recoveryOperation,'develop_redo',code);assert.match(stop.nextStep,/只重发文档同步/,code);
280
+ assert.doesNotMatch(stop.nextStep,/重发本轮开发/,code);
281
+ const ready=operatorGuidance({...base,pendingAction:'resume'});
282
+ assert.equal(ready.recoveryOperation,'advance',code);assert.match(ready.nextStep,/不重新开发/,code);
283
+ }
284
+ });
285
+
286
+ // Review r1 #4: the host dies during documentation_sync (intent and start
287
+ // record journaled, no checkpoint). abandon_effect records the interruption with
288
+ // the start binding; the run then redoes only documentation_sync, never develop,
289
+ // and the interruption counts toward the same two retries.
290
+ async function dieDuringSync(f,execution){
291
+ let entered;const inSync=new Promise(resolve=>{entered=resolve;});
292
+ const sync=execution.documentationSync.run;
293
+ execution.documentationSync.run=(request,signal)=>{entered();return sync(request,signal);};
294
+ const run=await openControlRun(docDefinition(f),fs.existsSync(f.store)?'resume':'create',execution);
295
+ const advancing=run.host.handle({version:1,operation:'advance',requestId:'advance-dying',identity:identity(1)});
296
+ advancing.catch(()=>{});
297
+ await inSync;run.close();
298
+ // The dead host's advance never settles; its closed store refuses any later write.
299
+ }
300
+ test('Q16 host exit during documentation_sync: abandon_effect, then only documentation_sync is redone, within the shared cap',async t=>{
301
+ const f=docFixture(t,'doc-interrupted');
302
+ await dieDuringSync(f,docExecution(f,{developer:['delivered\n'],sync:[{write:'# Half\n',hang:true}]}));
303
+ assert.equal(records(f).at(-1).payload.type,'documentation-sync-started',JSON.stringify(records(f).map(row=>row.payload.type)));
304
+ const [pending]=await docSession(f,'resume',docExecution(f),[['status',1]]);
305
+ assert.equal(pending.pendingAction,'abandon_effect',JSON.stringify(pending));
306
+ // Review r2 #4: before registration the hint already says only documentation_sync is resent.
307
+ assert.equal(pending.documentationSyncPending,true,JSON.stringify(pending));
308
+ assert.match(pending.guidance.nextStep,/只重发文档同步、不重新开发/);assert.doesNotMatch(pending.guidance.nextStep,/开发重发本轮/);
309
+ const [interrupted]=await docSession(f,'resume',docExecution(f),
310
+ [['abandon_effect',1,{reason:'旧宿主与会话都已退出'}]],{allowAbandonEffect:true});
311
+ assert.deepEqual([interrupted.state,interrupted.code,interrupted.pendingAction],['blocked','documentation_sync_interrupted','resume'],JSON.stringify(interrupted));
312
+ assert.equal(interrupted.guidance.recoveryOperation,'advance');
313
+ const record=records(f).at(-1).payload,started=records(f).find(row=>row.payload.type==='documentation-sync-started');
314
+ assert.deepEqual([record.type,record.startDigest,record.documents[0].path],['effect-interrupted',started.digest,'README.md']);
315
+ const before=records(f);
316
+ const [delivered]=await docSession(f,'resume',docExecution(f,{sync:[{write:'# Final\n'}],verdicts:['approved']}),[['advance',1]]);
317
+ assert.equal(f.calls.developer,1,'develop is never redispatched');assert.equal(f.calls.documentation,2);
318
+ const checkpoint=records(f).find((row,index)=>index>=before.length&&row.payload.type==='effect-checkpoint').payload.checkpoint;
319
+ assert.equal(checkpoint.state,'awaiting_review',JSON.stringify(delivered));
320
+ assert.equal(Buffer.from(checkpoint.reviewPackage.changes.find(change=>change.path==='a.mjs').before.contentBase64,'base64').toString(),'old\n');
321
+ const {readRunnerHistory}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
322
+ assert.equal(readRunnerHistory(records(f),records(f)[0].payload.config,3).answerGaps.documentationSync,1);
323
+ });
324
+ test('Q16 host exit during documentation_sync after both retries are spent: abandon_effect only voids the run',async t=>{
325
+ const f=docFixture(t,'doc-interrupted-cap');
326
+ await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{status:'blocked'}]}),[['advance',1]]);
327
+ assert.equal((await confirm(f)).outcome,'recorded');
328
+ await docSession(f,'resume',docExecution(f,{sync:[{status:'blocked'}]}),[['advance',1]]);
329
+ assert.equal((await confirm(f)).outcome,'recorded');
330
+ await dieDuringSync(f,docExecution(f,{sync:[{hang:true}]}));
331
+ const [voided]=await docSession(f,'resume',docExecution(f),[['abandon_effect',1,{reason:'旧宿主已退出'}]],{allowAbandonEffect:true});
332
+ assert.deepEqual([voided.state,voided.code],['cancelled','effect_abandoned'],JSON.stringify(voided));
333
+ assert.equal(f.calls.developer,1);
334
+ });
335
+ test('Q16 host exit during a documentation_sync retry: the interruption is the second retry, the developer answer survives, a third failure hits the cap',async t=>{
336
+ const f=docFixture(t,'doc-interrupted-after-retry');
337
+ await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{status:'blocked'}]}),[['advance',1]]);
338
+ assert.equal((await confirm(f)).outcome,'recorded');
339
+ await dieDuringSync(f,docExecution(f,{sync:[{hang:true}]}));
340
+ const [interrupted]=await docSession(f,'resume',docExecution(f),[['abandon_effect',1,{reason:'旧宿主与会话都已退出'}]],{allowAbandonEffect:true});
341
+ assert.equal(interrupted.code,'documentation_sync_interrupted',JSON.stringify(interrupted));
342
+ const {readRunnerHistory}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
343
+ assert.equal(readRunnerHistory(records(f),records(f)[0].payload.config,3).answerGaps.documentationSync,2);
344
+ // The developer answer of the first run is what the second documentation_sync is built on.
345
+ const [delivered]=await docSession(f,'resume',docExecution(f,{sync:[{status:'blocked'}]}),[['advance',1]]);
346
+ assert.equal(f.calls.developer,1);
347
+ assert.equal(delivered.code,'documentation_sync_retry_limit',JSON.stringify(delivered));
348
+ assert.equal(f.calls.documentation,3,'first, the interrupted retry, the last attempt');
349
+ });
350
+
351
+ // Review r2 #1: the host dies after the redo's new effect-intent, before its new
352
+ // documentation-sync-started. The torn tail is made by dropping that last record
353
+ // (the chain and the revision are re-sealed, as the store would have left them).
354
+ function dropLastRecord(f){
355
+ const state=JSON.parse(fs.readFileSync(f.store,'utf8'));
356
+ state.records.pop();const {revision,...data}=state;
357
+ fs.writeFileSync(f.store,JSON.stringify({...data,revision:digest(data)})+'\n');
358
+ }
359
+ test('Q16 host exit between a documentation redo\'s intent and its start record: abandon_effect redoes only documentation_sync within the cap',async t=>{
360
+ const f=docFixture(t,'doc-intent-only');
361
+ await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{status:'blocked'}]}),[['advance',1]]);
362
+ assert.equal((await confirm(f)).outcome,'recorded');
363
+ await dieDuringSync(f,docExecution(f,{sync:[{hang:true}]}));
364
+ const first=records(f).find(row=>row.payload.type==='documentation-sync-started');
365
+ dropLastRecord(f);
366
+ assert.equal(records(f).at(-1).payload.type,'effect-intent',JSON.stringify(records(f).map(row=>row.payload.type)));
367
+ const {readRunnerHistory}=await import('../runtime/js/cm-ai/durable-runner-state.mjs');
368
+ const probe=readRunnerHistory(records(f),records(f)[0].payload.config,3);
369
+ assert.equal(probe.pendingDocumentation?.digest,first.digest,'the redo inherits the failed start');
370
+ const [pending]=await docSession(f,'resume',docExecution(f),[['status',1]]);
371
+ assert.equal(pending.pendingAction,'abandon_effect',JSON.stringify(pending));
372
+ const [interrupted]=await docSession(f,'resume',docExecution(f),
373
+ [['abandon_effect',1,{reason:'旧宿主与会话都已退出'}]],{allowAbandonEffect:true});
374
+ assert.deepEqual([interrupted.state,interrupted.code,interrupted.pendingAction],['blocked','documentation_sync_interrupted','resume'],JSON.stringify(interrupted));
375
+ const record=records(f).at(-1).payload;
376
+ assert.deepEqual([record.type,record.startDigest],['effect-interrupted',first.digest]);
377
+ assert.equal(readRunnerHistory(records(f),records(f)[0].payload.config,3).answerGaps.documentationSync,2);
378
+ const before=records(f);
379
+ const [delivered]=await docSession(f,'resume',docExecution(f,{sync:[{write:'# Final\n'}],verdicts:['approved']}),[['advance',1]]);
380
+ assert.equal(f.calls.developer,1,'develop is never redispatched');assert.equal(f.calls.documentation,3);
381
+ const checkpoint=records(f).find((row,index)=>index>=before.length&&row.payload.type==='effect-checkpoint').payload.checkpoint;
382
+ assert.equal(checkpoint.state,'awaiting_review',JSON.stringify(delivered));
383
+ });
384
+ test('Q16 host exit between a documentation redo\'s intent and its start record, with both retries spent: abandon_effect only voids the run',async t=>{
385
+ const f=docFixture(t,'doc-intent-only-cap');
386
+ await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{status:'blocked'}]}),[['advance',1]]);
387
+ assert.equal((await confirm(f)).outcome,'recorded');
388
+ await docSession(f,'resume',docExecution(f,{sync:[{status:'blocked'}]}),[['advance',1]]);
389
+ assert.equal((await confirm(f)).outcome,'recorded');
390
+ await dieDuringSync(f,docExecution(f,{sync:[{hang:true}]}));
391
+ dropLastRecord(f);
392
+ const [voided]=await docSession(f,'resume',docExecution(f),[['abandon_effect',1,{reason:'旧宿主已退出'}]],{allowAbandonEffect:true});
393
+ assert.deepEqual([voided.state,voided.code],['cancelled','effect_abandoned'],JSON.stringify(voided));
394
+ assert.equal(f.calls.developer,1);
395
+ });
396
+
397
+ // Review r2 #3: a documentation redo carries the Learning input bound to the
398
+ // delivered develop answer, so a LESSONS.md edited while the run waited (it is
399
+ // outside the documentation paths and the code root) does not end as runner_learning.
400
+ for(const kind of ['answer_missing','answer_invalid','answer_blocked','out_of_scope','interrupted'])
401
+ test(`Q16/Q17 a LESSONS.md edited during the wait does not block the documentation redo (${kind})`,async t=>{
402
+ const f=docFixture(t,`doc-learning-${kind}`);
403
+ const failure={answer_missing:{hang:true},answer_invalid:{throw:'invalid_result'},answer_blocked:{status:'blocked'},
404
+ out_of_scope:{other:'rewritten by docs\n'}}[kind];
405
+ if(kind==='interrupted'){
406
+ await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[{hang:true}]}),[['advance',1]]);
407
+ await confirm(f);
408
+ await dieDuringSync(f,docExecution(f,{sync:[{hang:true}]}));
409
+ const [done]=await docSession(f,'resume',docExecution(f),[['abandon_effect',1,{reason:'旧宿主与会话都已退出'}]],{allowAbandonEffect:true});
410
+ assert.equal(done.code,'documentation_sync_interrupted',JSON.stringify(done));
411
+ }else{
412
+ await docSession(f,'create',docExecution(f,{developer:['delivered\n'],sync:[failure]}),[['advance',1]]);
413
+ if(kind==='out_of_scope')fs.writeFileSync(path.join(f.codeProject,'a.mjs'),'delivered\n');
414
+ assert.equal((await confirm(f)).outcome,'recorded');
415
+ }
416
+ fs.writeFileSync(path.join(f.specsDir,'LESSONS.md'),'## 待触发备忘\n- [待触发] 等待期间新增\n');
417
+ const before=records(f);
418
+ const [redone]=await docSession(f,'resume',docExecution(f,{sync:[{write:'# Final\n'}],verdicts:['approved']}),[['advance',1]]);
419
+ assert.notEqual(redone.code,'runner_learning',JSON.stringify(redone));
420
+ assert.equal(f.calls.developer,1,'develop is never redispatched');
421
+ const intent=records(f).slice(before.length).find(row=>row.payload.type==='effect-intent');
422
+ assert.deepEqual(intent.payload.effect.learningInput,records(f).find(row=>row.payload.type==='effect-intent').payload.effect.learningInput);
423
+ assert.ok(records(f).some((row,index)=>index>=before.length&&row.payload.type==='effect-checkpoint'),JSON.stringify(redone));
424
+ });