@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,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 only the reachable revision answer after documentation retry 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,[2]);
192
+ assert.deepEqual(batchDevelopAttempts(status,'1.work/T-002',[]),[2]);
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
+ });
@@ -6,6 +6,8 @@ import path from 'node:path';
6
6
  import {spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {buildManifest} from './cm-spec-manifest.mjs';
9
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
10
+ import {claudeReviewFingerprint} from '../runtime/js/cm-ai/worker-claude.mjs';
9
11
  import {cmInitRuleTargets} from '../runtime/js/cm-init/draft-generation.mjs';
10
12
  import {bootstrapDriverGap} from './cm-ai-drive.mjs';
11
13
  import {inspectDriverBootstrap,readBootstrapRulesAnswers,createBootstrapRulesResponder} from '../runtime/js/cm-ai/drive-bootstrap.mjs';
@@ -46,7 +48,8 @@ function fixture(t,{scaffolded=false,nested=false}={}){
46
48
  identity:{repositoryId:'app',runId:`bootstrap-${key}`,taskId,attempt:1},scope,requirements:[]}));
47
49
  const writeBootstrap=value=>fs.writeFileSync(path.join(root,'bootstrap.json'),JSON.stringify({selection:value}));
48
50
  // create requires a bound review configuration; this placeholder grants no review.
49
- fs.writeFileSync(path.join(root,'placeholder-review.json'),JSON.stringify({model:'fixture',preflight:{}}));
51
+ fs.writeFileSync(path.join(root,'placeholder-review.json'),JSON.stringify({model:'fixture',preflight:{passed:true,provider:'claude',cli_model:'fixture',prompt_transport:'stdin',
52
+ config_fingerprint:claudeReviewFingerprint({cwd:codeProject,model:'fixture'})}}));
50
53
  const plan=(key,mode,permissions,extra={})=>{
51
54
  const file=path.join(root,`plan-${Math.random().toString(36).slice(2)}.json`);
52
55
  const bound=permissions.includes('--review-config')?permissions:[...permissions,'--review-config','placeholder-review.json'];
@@ -174,17 +177,35 @@ test('rules answer files are validated before the host starts',t=>{
174
177
  f.write('init-verify.json',verifyAnswer());f.write('init-verify-a1.json',verifyAnswer());
175
178
  assertRefusedBeforeLaunch(f,run(),/init-verify\.json 与 init-verify-a1\.json 不能同时存在/);
176
179
  fs.rmSync(path.join(f.answers,'init-verify-a1.json'));
177
- // A revision written before its findings exist is refused, even when preloaded.
178
- const pattern=/advance 不能带 --allow-review-attempt 1 直接进入第 2 轮.*\.reviews\/bootstrap-T-002-r1\.md.*init-verify-a2\.json/;
179
- assertRefusedBeforeLaunch(f,run({permissions:['--allow-review-attempt','1']}),pattern);
180
- const {generate:revision}=rulesDocuments(f,2);f.write('init-generate-a2.json',revision);f.write('init-verify-a2.json',verifyAnswer());
181
- assertRefusedBeforeLaunch(f,run({permissions:['--allow-review-attempt','1']}),pattern);
182
180
  // The host inspects the raw draft before merging AGENTS.md lessons; so does the driver.
183
181
  rulesDocuments(f,1);fs.writeFileSync(path.join(f.codeProject,'AGENTS.md'),'## 项目教训\n\n- 骨架教训\n');
184
182
  f.write(generate.documents[0].contentFile,' \n');
185
183
  assertRefusedBeforeLaunch(f,run(),/^\[drive\] init-generate\.json 无效: init_draft_invalid/m);
186
184
  });
187
185
 
186
+ // The claude review preflight needs the macOS loopback sandbox; keep this case
187
+ // darwin-only like the other review-dispatching cases in this file.
188
+ test('direct review holds the first revision even when attempt-2 answers are preloaded',
189
+ {skip:process.platform!=='darwin'},t=>{
190
+ const held=fixture(t,{scaffolded:true});held.writeRun('T-001',Object.keys(scaffold));held.writeRun('T-002',[...held.targets]);
191
+ held.writeBootstrap(selection);prepareRules(held,1);reviewFixture(held);
192
+ const paused=held.drive(held.plan('T-002','create',[...rulesPermissions,'--review-config','review.json']),'advance');
193
+ assert.equal(paused.status,0,paused.stderr);assert.equal(result(paused).state,'changes_requested');
194
+ assert.equal(result(paused).code,'revision_answer_required');assert.equal(result(paused).identity.attempt,2);
195
+ assert.equal(fs.existsSync(path.join(held.answers,'init-generate-a2.json')),false);
196
+ const heldRows=JSON.parse(fs.readFileSync(path.join(held.store('T-002'),'state.json'))).records;
197
+ assert.equal(heldRows.filter(row=>row.payload.type==='effect-intent'&&row.payload.effect.kind==='develop').length,1);
198
+ const preloaded=fixture(t,{scaffolded:true});preloaded.writeRun('T-001',Object.keys(scaffold));preloaded.writeRun('T-002',[...preloaded.targets]);
199
+ preloaded.writeBootstrap(selection);const initial=prepareRules(preloaded,1);prepareRules(preloaded,2);reviewFixture(preloaded);
200
+ const premature=preloaded.drive(preloaded.plan('T-002','create',[...rulesPermissions,'--review-config','review.json']),'advance');
201
+ assert.equal(premature.status,0,premature.stderr);assert.equal(result(premature).state,'changes_requested');
202
+ assert.equal(result(premature).code,'revision_answer_required');
203
+ const prematureRows=JSON.parse(fs.readFileSync(path.join(preloaded.store('T-002'),'state.json'))).records;
204
+ assert.equal(prematureRows.filter(row=>row.payload.type==='effect-intent'&&row.payload.effect.kind==='develop').length,1);
205
+ assert.equal(read(preloaded,'.claude/rules/testing.md'),initial['.claude/rules/testing.md'],'preloaded a2 bytes are never consumed before findings');
206
+ assert.equal(prematureRows.filter(row=>row.payload.type==='review-invocation-registered').length,1);
207
+ });
208
+
188
209
  test('attempt 1 refuses existing instructions the host would not overwrite',t=>{
189
210
  const f=fixture(t,{scaffolded:true});f.writeRun('T-002',[...f.targets]);f.writeBootstrap(selection);prepareRules(f,1);
190
211
  const run=()=>f.drive(f.plan('T-002','create',rulesPermissions),'advance');
@@ -329,9 +350,9 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
329
350
  edits:Object.fromEntries(scope.map(file=>[file,`t001/${file}`]))});
330
351
  reviewFixture(f);
331
352
  const review=['--review-config','review.json'];
332
- let run=f.drive(f.plan('T-001','create',[...rulesPermissions,...review]),'advance');
353
+ let run=f.drive(f.plan('T-001','create',[...rulesPermissions,...review]),'start');
333
354
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'awaiting_review');
334
- run=f.drive(f.plan('T-001','resume',[...rulesPermissions,...review,'--allow-review-attempt','1'],{packageDigest:result(run).packageDigest}),'decision');
355
+ run=f.drive(f.plan('T-001','resume',[...rulesPermissions,...review],{packageDigest:result(run).packageDigest}),'decision');
335
356
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'approved');
336
357
  run=f.drive(f.plan('T-001','resume',[...rulesPermissions,...review]),'advance');
337
358
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'fixture_completed');
@@ -339,7 +360,7 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
339
360
 
340
361
  f.writeRun('T-002',[...f.targets]);f.writeBootstrap(selection);
341
362
  // Missing answers are refused before the T-002 run exists.
342
- assertRefusedBeforeLaunch(f,f.drive(f.plan('T-002','create',[...rulesPermissions,...review]),'advance'),/init-generate\.json/);
363
+ assertRefusedBeforeLaunch(f,f.drive(f.plan('T-002','create',[...rulesPermissions,...review]),'start'),/init-generate\.json/);
343
364
  // Attempt 1 records a real lesson: the host writes it back into AGENTS.md after the rules.
344
365
  const lesson={status:'lesson_candidate',candidates:[{classification:'structured',trigger:'SwiftUI rules bootstrap',
345
366
  action:'Keep scripts/verify.sh as the structure check',evidence:['scripts/verify.sh']}],reason:null};
@@ -348,7 +369,7 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
348
369
  const matches=(docs)=>{for(const file of f.targets)if(file==='AGENTS.md'){
349
370
  assert(read(f,file).startsWith(docs[file]),file);assert.match(read(f,file),/## 项目教训[\s\S]*Keep scripts\/verify\.sh/);}
350
371
  else assert.equal(read(f,file),docs[file],file);};
351
- run=f.drive(f.plan('T-002','create',[...rulesPermissions,...review]),'advance');
372
+ run=f.drive(f.plan('T-002','create',[...rulesPermissions,...review]),'start');
352
373
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'awaiting_review',run.stdout);
353
374
  assert.match(run.stderr,/应答 init_generate/);assert.match(run.stderr,/应答 init_verify/);assert.match(run.stderr,/应答 check/);
354
375
  assert.doesNotMatch(run.stderr,/应答 develop/);
@@ -356,16 +377,18 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
356
377
  const waiting=result(run).packageDigest,state=path.join(f.store('T-002'),'state.json');
357
378
  // Review may lead straight into attempt 2 inside this advance: the revision must wait for findings.
358
379
  let before=fs.readFileSync(state);
359
- run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review,'--allow-review-attempt','1']),'advance');
360
- assert.equal(run.status,2,run.stderr);
361
- assert.match(run.stderr,new RegExp(`须在读取首轮审查 findings 之后编写:请先以 decision 和当前 packageDigest ${waiting}.*bootstrap-T-002-r1\\.md`));
362
- assert.deepEqual(fs.readFileSync(state),before);
363
- run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review,'--allow-review-attempt','1'],{packageDigest:waiting}),'decision');
380
+ run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review]),'advance');
381
+ assert.equal(run.status,0,run.stderr);
382
+ assert.equal(result(run).state,'changes_requested');assert.equal(result(run).code,'revision_answer_required');
383
+ const afterReview=JSON.parse(fs.readFileSync(state)).records;
384
+ assert.deepEqual(afterReview.slice(0,JSON.parse(before).records.length),JSON.parse(before).records);
385
+ assert.equal(afterReview.filter(row=>row.payload.type==='effect-intent'&&row.payload.effect.kind==='develop').length,1);
386
+ run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review],{packageDigest:waiting}),'decision');
364
387
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'changes_requested');
365
388
  assert(fs.existsSync(path.join(f.specsDir,'.reviews','bootstrap-T-002-r1.md')));
366
389
 
367
390
  before=fs.readFileSync(state);
368
- const again=()=>f.drive(f.plan('T-002','resume',[...rulesPermissions,...review]),'advance');
391
+ const again=()=>f.drive(f.plan('T-002','resume',[...rulesPermissions,...review]),'start');
369
392
  run=again();assert.equal(run.status,2,run.stderr);
370
393
  assert.match(run.stderr,/第 2 轮规范修订,但答案文件不存在: .*init-generate-a2\.json.*bootstrap-T-002-r1\.md/);
371
394
  assert.deepEqual(fs.readFileSync(state),before);
@@ -377,7 +400,13 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
377
400
  const marker=path.join(f.root,'ran.marker');
378
401
  prepareRules(f,2,{commands:[{id:'marker',command:['/bin/sh','-c',`echo ran > ${marker}`]}]});
379
402
  for(const extra of [{hostContext:'another-session'},{runtime:'codex'}]){
380
- run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review],extra),'advance');
403
+ let launchReview=review;
404
+ if(extra.runtime==='codex'){
405
+ fs.writeFileSync(path.join(f.root,'wrong-runtime-review.json'),JSON.stringify({model:'fixture',preflight:{passed:true,
406
+ cli_model:'fixture',prompt_transport:'stdin',config_fingerprint:configFingerprint({cwd:f.codeProject,model:'fixture'})}}));
407
+ launchReview=['--review-config','wrong-runtime-review.json'];
408
+ }
409
+ run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...launchReview],extra),'start');
381
410
  assert.equal(run.status,1,run.stderr);assert.match(run.stderr,/fingerprint_mismatch/);
382
411
  assert.doesNotMatch(run.stderr,/\[drive init_verify/);
383
412
  assert.equal(fs.existsSync(marker),false);assert.deepEqual(fs.readFileSync(state),before);
@@ -396,7 +425,7 @@ test('real host drives split-root T-001 scaffold, then T-002 rules with a revisi
396
425
  assert.notEqual(second['.claude/rules/testing.md'],first['.claude/rules/testing.md']);
397
426
  // The driver's decision request carries the run definition's attempt-1 identity;
398
427
  // the second review runs inside advance with the attempt-2 review grant.
399
- run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review,'--allow-review-attempt','2']),'advance');
428
+ run=f.drive(f.plan('T-002','resume',[...rulesPermissions,...review]),'advance');
400
429
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'fixture_completed',run.stdout);
401
430
  assert.match(fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'utf8'),/\[x\] T-002/);
402
431
  const handoff=JSON.parse(fs.readFileSync(path.join(f.specsDir,'.reviews','bootstrap-T-002-a2-handoff.json'),'utf8'));
@@ -411,7 +440,7 @@ test('a failing init_verify command really runs after the host accepts the launc
411
440
  // The session's semantic groups say verified; only the real command decides the commands group.
412
441
  fs.writeFileSync(path.join(f.codeProject,'scripts/verify.sh'),'echo strict-check-ran >&2\n'+scaffold['scripts/verify.sh']);
413
442
  prepareRules(f,1,{commands:[{id:'strict',command:['/bin/sh','scripts/verify.sh','--strict'],timeoutMs:60000}]});
414
- const failed=f.drive(f.plan('T-002','create',permissions),'advance');
443
+ const failed=f.drive(f.plan('T-002','create',permissions),'start');
415
444
  assert.equal(failed.status,2,failed.stderr);
416
445
  assert.match(failed.stderr,/init-verify\.json 的命令在发送操作前实跑未通过:strict: failed(host check exited 1)/);
417
446
  assert.match(failed.stderr,/PLAN\.mode 改为 resume/);
@@ -422,7 +451,7 @@ test('a failing init_verify command really runs after the host accepts the launc
422
451
  assert.equal(fs.existsSync(path.join(f.codeProject,'.claude')),false);
423
452
  // Fix the draft's command list; the host-created ready run then advances on resume.
424
453
  const contents=prepareRules(f,1);
425
- const fixed=f.drive(f.plan('T-002','resume',permissions),'advance');
454
+ const fixed=f.drive(f.plan('T-002','resume',permissions),'start');
426
455
  assert.equal(fixed.status,0,fixed.stderr);assert.equal(result(fixed).state,'awaiting_review',fixed.stdout);
427
456
  assert.match(fixed.stderr,/\[drive init_verify verify /);
428
457
  for(const file of f.targets)assert.equal(read(f,file),contents[file],file);
@@ -436,7 +465,7 @@ test('rules written by this run survive a failed task check: fix the environment
436
465
  // The task check depends on an environment marker outside the code root.
437
466
  const checks=[{id:'environment',command:['/bin/sh','-c','test -f ../environment.ready']}];
438
467
  const contents=prepareRules(f,1);
439
- let run=f.drive(f.plan('T-002','create',permissions,{checks}),'advance');
468
+ let run=f.drive(f.plan('T-002','create',permissions,{checks}),'start');
440
469
  assert.equal(run.status,0,run.stderr);
441
470
  assert.equal(result(run).state,'blocked',run.stdout);assert.equal(result(run).code,'develop_checks_not_passed');
442
471
  assert.equal(result(run).pendingAction,'resume');
@@ -444,24 +473,24 @@ test('rules written by this run survive a failed task check: fix the environment
444
473
  // Rules edited by someone else after this run wrote them are refused before launch.
445
474
  const state=path.join(f.store('T-002'),'state.json'),before=fs.readFileSync(state);
446
475
  fs.appendFileSync(path.join(f.codeProject,'.claude/rules/security.md'),'foreign edit\n');
447
- run=f.drive(f.plan('T-002','resume',permissions,{checks}),'advance');
476
+ run=f.drive(f.plan('T-002','resume',permissions,{checks}),'start');
448
477
  assert.equal(run.status,2,run.stderr);assert.match(run.stderr,/\.claude\/rules\/security\.md 与本运行已记录的写入不一致/);
449
478
  assert.deepEqual(fs.readFileSync(state),before);
450
479
  fs.writeFileSync(path.join(f.codeProject,'.claude/rules/security.md'),contents['.claude/rules/security.md']);
451
480
  // The rules effect only enters the admitted next task (host-bootstrap.mjs run()).
452
481
  const tasks=path.join(f.specsDir,f.feature,'tasks.md'),taskList=fs.readFileSync(tasks,'utf8');
453
482
  fs.writeFileSync(tasks,taskList.replace('[ ] T-002','[x] T-002'));
454
- run=f.drive(f.plan('T-002','resume',permissions,{checks}),'advance');
483
+ run=f.drive(f.plan('T-002','resume',permissions,{checks}),'start');
455
484
  assert.equal(run.status,2,run.stderr);
456
485
  assert.match(run.stderr,/T-002 不是当前可进入的 bootstrap 任务(nextTask 无,宿主以 bootstrap_task_required 拒绝);驾驶员不运行 init-verify 命令/);
457
486
  assert.deepEqual(fs.readFileSync(state),before);
458
487
  fs.writeFileSync(tasks,taskList);
459
488
  fs.writeFileSync(path.join(f.root,'environment.ready'),'ok\n');
460
- run=f.drive(f.plan('T-002','resume',permissions,{checks}),'advance');
489
+ run=f.drive(f.plan('T-002','resume',permissions,{checks}),'start');
461
490
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'awaiting_review',run.stdout);
462
491
  assert.equal(result(run).identity.attempt,1);
463
492
  for(const file of f.targets)assert.equal(read(f,file),contents[file],file);
464
- run=f.drive(f.plan('T-002','resume',[...permissions,'--allow-review-attempt','1'],{checks,packageDigest:result(run).packageDigest}),'decision');
493
+ run=f.drive(f.plan('T-002','resume',[...permissions],{checks,packageDigest:result(run).packageDigest}),'decision');
465
494
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'approved',run.stdout);
466
495
  run=f.drive(f.plan('T-002','resume',permissions,{checks}),'advance');
467
496
  assert.equal(run.status,0,run.stderr);assert.equal(result(run).state,'fixture_completed',run.stdout);