@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
@@ -9,6 +9,7 @@ import {fileURLToPath} from 'node:url';
9
9
  import {buildManifest} from './cm-spec-manifest.mjs';
10
10
  import {readRunDefinition,openControlRun} from './cm-ai-run.mjs';
11
11
  import {createConversationExecution} from './cm-ai-host.mjs';
12
+ import {syntheticReviewConfig} from './cm-ai-host-fixture.mjs';
12
13
  import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
13
14
 
14
15
  const home=fs.mkdtempSync(path.join(os.tmpdir(),'cm-launch-diagnostics-home-'));
@@ -29,10 +30,11 @@ function fixture(t){
29
30
  fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Fixture\n');
30
31
  const config=path.join(root,'run.json'),review=path.join(root,'review.json'),workflow=path.join(root,'workflow.json');
31
32
  fs.writeFileSync(config,JSON.stringify({version:1,specsDir,codeProject,feature,identity,scope:['target.mjs'],requirements:['requirements.md']}));
32
- fs.writeFileSync(review,JSON.stringify({model:'fixture',preflight:{}}));
33
+ fs.writeFileSync(review,JSON.stringify(syntheticReviewConfig(codeProject,'claude')));
33
34
  fs.writeFileSync(workflow,JSON.stringify({documentationPaths:[],applicableAgentFiles:[],qa:null}));
34
35
  const env={...process.env,CM_WORKFLOW_HOME:path.join(root,'home'),CM_WORKFLOW_LOG_HOME:path.join(root,'logs'),NODE_NO_WARNINGS:'1'};
35
36
  const host=(mode,{hostContext='session-a',extra=[]}={})=>{
37
+ fs.writeFileSync(review,JSON.stringify(syntheticReviewConfig(codeProject,extra.includes('claude')?'claude':'codex')));
36
38
  const result=spawnSync(process.execPath,[cli,'serve','--config',config,'--mode',mode,'--host-context',hostContext,
37
39
  '--allow-development',...extra],{encoding:'utf8',env,timeout:20000,
38
40
  input:JSON.stringify({version:1,operation:'status',requestId:'status',identity})+'\n'});
@@ -46,7 +48,7 @@ test('create without --review-config is refused with the reason and leaves no ru
46
48
  const f=fixture(t);
47
49
  const refused=f.host('create');
48
50
  assert.equal(refused.status,1);assert.equal(refused.error.code,'review_configuration_required');
49
- assert.match(refused.error.reason,/--review-config/);assert.match(refused.error.reason,/preflight/);
51
+ assert.match(refused.error.reason,/--review-config/);assert.match(refused.error.reason,/自动派发 fresh Review/);
50
52
  assert.equal(fs.existsSync(path.join(f.specsDir,'.reviews','.execution',identity.runId)),false);
51
53
  const created=f.host('create',{extra:['--review-config',f.review]});
52
54
  assert.equal(created.status,0,created.stderr);
@@ -94,6 +96,7 @@ test('driver PLAN without runtime reaches the host diagnosis for a Claude run',t
94
96
  const plan=path.join(f.root,'plan.json');
95
97
  fs.writeFileSync(plan,JSON.stringify({config:'run.json',mode:'resume',hostContext:'session-a',
96
98
  permissions:['--review-config','review.json']}));
99
+ fs.writeFileSync(f.review,JSON.stringify(syntheticReviewConfig(f.codeProject,'codex')));
97
100
  const result=spawnSync(process.execPath,[driver,'--plan',plan,'status'],{encoding:'utf8',env:f.env,timeout:30000});
98
101
  assert.notEqual(result.status,0);
99
102
  assert.match(result.stderr,/fingerprint_mismatch/);assert.match(result.stderr,/--runtime:创建时为 claude/);
@@ -107,7 +110,6 @@ test('invalid_arguments names the argument',t=>{
107
110
  [['--browser-qa','available','--review-config',f.review],/没有适用的交互式 QA/],
108
111
  [['--no-such-flag'],/未知参数:--no-such-flag/],
109
112
  [['--review-config',f.review,'--review-config',f.review],/参数重复:--review-config/],
110
- [['--allow-review-attempt','3','--review-config',f.review],/只接受 1 或 2/],
111
113
  [['--input-limit','12'],/--input-limit/],
112
114
  ]){
113
115
  const result=f.host('create',{extra});
@@ -0,0 +1,53 @@
1
+ // Synthetic, hash-valid historical envelopes exercise the actual CLI before
2
+ // fingerprint reconstruction. They are refusal fixtures, not review evidence.
3
+ import test from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import {spawnSync} from 'node:child_process';
9
+ import {fileURLToPath} from 'node:url';
10
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
11
+ const root=fileURLToPath(new URL('..',import.meta.url));
12
+ function fixture(t,payload){
13
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-legacy-history-')));
14
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
15
+ const specsDir=path.join(dir,'specs'),codeProject=path.join(dir,'code'),identity={repositoryId:'fixture',runId:'old-run-fixture',taskId:'T-001',attempt:1};
16
+ fs.mkdirSync(codeProject);fs.mkdirSync(specsDir);
17
+ const execution=path.join(specsDir,'.reviews','.execution',identity.runId);
18
+ fs.mkdirSync(execution,{recursive:true,mode:0o700});
19
+ fs.chmodSync(path.join(specsDir,'.reviews','.execution'),0o700);
20
+ const body={version:1,seq:1,id:'registration',kind:'intent',payload,previousDigest:null};
21
+ const state={version:1,identity:{repositoryId:identity.repositoryId,runId:identity.runId},
22
+ fingerprints:{workflow:digest('old-workflow'),config:digest('old-config'),inputs:digest('old-inputs')},records:[{...body,digest:digest(body)}]};
23
+ const file=path.join(execution,'state.json');fs.writeFileSync(file,JSON.stringify({...state,revision:digest(state)})+'\n',{mode:0o600});
24
+ const config=path.join(dir,'run.json');fs.writeFileSync(config,JSON.stringify({version:1,specsDir,codeProject,feature:'1.work',identity,scope:['a.js'],requirements:[]}));
25
+ const before=fs.readFileSync(file);
26
+ const invoke=(script,args)=>spawnSync(process.execPath,[path.join(root,'scripts',script),...args],{encoding:'utf8',input:'',timeout:10000,
27
+ env:{...process.env,CM_WORKFLOW_HOME:path.join(dir,'home'),CM_WORKFLOW_LOG_HOME:path.join(dir,'logs')}});
28
+ return {config,file,before,invoke,execution};
29
+ }
30
+ for(const field of ['grant','authorizationAt'])test(`legacy ${field} refuses at both CLI entries before fingerprint/preflight and never writes`,t=>{
31
+ const f=fixture(t,{type:'review-invocation-registered',[field]:field==='grant'?{kind:'cm-review-dispatch-grant'}:1});
32
+ for(const [script,args] of [
33
+ ['cm-ai-run.mjs',['serve','--config',f.config,'--mode','resume']],
34
+ ['cm-ai-host.mjs',['serve','--config',f.config,'--mode','resume','--host-context','fixture-host','--allow-development']],
35
+ ]){
36
+ const run=f.invoke(script,args);assert.equal(run.status,1,run.stderr);
37
+ const error=JSON.parse(run.stderr.trim().split('\n').at(-1)).error;
38
+ assert.equal(error.code,'runner_invocation');assert.match(error.reason,/旧授权协议不支持恢复/);
39
+ assert.match(error.reason,/inspect-history --config/);assert.doesNotMatch(error.reason,/沿用原文件和参数/);
40
+ assert.equal(run.stdout,'');assert.deepEqual(fs.readFileSync(f.file),f.before);
41
+ assert.deepEqual(fs.readdirSync(f.execution),['state.json']);
42
+ }
43
+ const inspected=f.invoke('cm-ai-run.mjs',['inspect-history','--config',f.config]);assert.equal(inspected.status,0,inspected.stderr);
44
+ const history=JSON.parse(inspected.stdout);assert.equal(history.records[0].type,'review-invocation-registered');
45
+ assert.equal(history.records[0].legacyReviewGrant,true);assert.deepEqual(fs.readFileSync(f.file),f.before);
46
+ assert.equal(Object.hasOwn(history.records[0],'grant'),false);
47
+ });
48
+ test('read-only history validates store digest and never bypasses corrupt evidence',t=>{
49
+ const f=fixture(t,{type:'review-invocation-registered',grant:{}});
50
+ const raw=JSON.parse(f.before);raw.records[0].payload.grant.changed=true;fs.writeFileSync(f.file,JSON.stringify(raw)+'\n');
51
+ const bytes=fs.readFileSync(f.file),run=f.invoke('cm-ai-run.mjs',['inspect-history','--config',f.config]);
52
+ assert.equal(run.status,1);assert.match(run.stderr,/store_corrupt/);assert.equal(run.stdout,'');assert.deepEqual(fs.readFileSync(f.file),bytes);
53
+ });
@@ -0,0 +1,54 @@
1
+ // Light runtime modules are copied on their own into partial runtimes (scripts/cm-check-drive.test.mjs
2
+ // copies a hand-picked list). The authority here is Node's real module resolver: copy ONLY the allowed
3
+ // files into a fresh temp dir and import the module in a child process. Every import syntax is covered
4
+ // (import{...}from, export ... from, multi-line, top-level dynamic import), with no scanner to fool.
5
+ import test from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import {spawnSync} from 'node:child_process';
11
+ import {fileURLToPath,pathToFileURL} from 'node:url';
12
+ import {CHECK_DRIVE_COPIED_FILES} from './cm-check-drive-files.mjs';
13
+
14
+ const root=fileURLToPath(new URL('..',import.meta.url));
15
+ const GUIDANCE='runtime/js/cm-ai/operator-guidance.mjs';
16
+
17
+ // Copy exactly `files` (optionally appending `append` to `entry`) and import `entry` from the copy.
18
+ function importFromCopy(t,entry,files,append=''){
19
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-light-module-')));
20
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
21
+ for(const file of files){
22
+ fs.mkdirSync(path.dirname(path.join(dir,file)),{recursive:true});fs.copyFileSync(path.join(root,file),path.join(dir,file));
23
+ }
24
+ if(append)fs.appendFileSync(path.join(dir,entry),append);
25
+ return spawnSync(process.execPath,['--input-type=module','-e',`await import(${JSON.stringify(pathToFileURL(path.join(dir,entry)).href)});`],
26
+ {encoding:'utf8',cwd:dir});
27
+ }
28
+
29
+ test('operator-guidance.mjs imports with only itself copied',t=>{
30
+ const run=importFromCopy(t,GUIDANCE,[GUIDANCE]);assert.equal(run.status,0,run.stderr);
31
+ });
32
+ test('operator-guidance.mjs imports from exactly the partial runtime cm-check-drive.test.mjs copies',t=>{
33
+ const run=importFromCopy(t,GUIDANCE,CHECK_DRIVE_COPIED_FILES);assert.equal(run.status,0,run.stderr);
34
+ });
35
+
36
+ // Negative controls: each added import reaches a file the partial copy does not have, so the real
37
+ // resolver must fail. They run against the copy, never the repository file.
38
+ const REACH=[
39
+ ['compact import{...}from with an alias',"\nimport{readRunnerHistory as probe}from './durable-runner-state.mjs';\n"],
40
+ ['multi-line import',"\nimport {\n readRunnerHistory,\n runnerStatus,\n} from './durable-runner-state.mjs';\n"],
41
+ ['import sharing a line with other code',"\nconst unrelated=1;import x from './task-runner.mjs';\n"],
42
+ ['export ... from',"\nexport {readRunnerHistory} from './durable-runner-state.mjs';\n"],
43
+ ['top-level dynamic import',"\nawait import('./durable-runner-state.mjs');\n"],
44
+ ];
45
+ for(const [name,append] of REACH)
46
+ test(`guard fails when operator-guidance.mjs gains a ${name}`,t=>{
47
+ const run=importFromCopy(t,GUIDANCE,CHECK_DRIVE_COPIED_FILES,append);
48
+ assert.notEqual(run.status,0,'the import must not resolve in the partial runtime');
49
+ assert.match(run.stderr,/ERR_MODULE_NOT_FOUND/);
50
+ });
51
+ test('guard fails when operator-guidance.mjs gains an import of a file only the wider cm-check copy has',t=>{
52
+ const run=importFromCopy(t,GUIDANCE,[GUIDANCE],"\nimport x from './effect-contract.mjs'\n");
53
+ assert.notEqual(run.status,0);assert.match(run.stderr,/ERR_MODULE_NOT_FOUND/);
54
+ });
@@ -253,8 +253,7 @@ test('integrated original multi-root conversation completes one task and resumes
253
253
  retrospective:{status:'no_new_lesson',candidates:[],reason:null}},edits:definition.scope.map(file=>({
254
254
  path:file,beforeSha256:payload.expected[file],content:'export const value = 2;\\n'}))};
255
255
  }
256
- if(kind==='qa_assess')return {scores:{scope:1,risk:1,accumulation:1,boundary:1},
257
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}};
256
+ if(kind==='qa_assess')return {confirmed:true};
258
257
  assert.equal(kind,'documentation_inspect');
259
258
  for(const file of definition.scope)assert.equal(fs.readFileSync(path.join(definition.codeProject,file),'utf8'),'export const value = 2;\\n');
260
259
  const {syncId,identity,packageDigest,contextDigest}=payload;
@@ -263,11 +262,12 @@ test('integrated original multi-root conversation completes one task and resumes
263
262
  }};
264
263
  const review={model:'fixture',disabledSkills:[],preflight:{passed:true,provider:'claude',cli_model:'fixture',prompt_transport:'stdin',
265
264
  config_fingerprint:claudeReviewFingerprint({cwd:definition.codeProject,model:'fixture'})}};
266
- const execution=createConversationExecution(definition,'multi-root-host',bridge,review,mode==='create'?null:1,
265
+ const execution=createConversationExecution(definition,'multi-root-host',bridge,review,null,
267
266
  workflow,true,'claude',{protection});
268
267
  const run=await openControlRun(definition,mode,execution);
269
268
  assert(run.host,JSON.stringify(run));
270
- try{const result=await run.host.handle({version:1,operation:'advance',requestId:'advance',identity:definition.identity});
269
+ // Preserve the explicit pre-review checkpoint; advance now also performs review and closeout.
270
+ try{const result=await run.host.handle({version:1,operation:mode==='create'?'start':'advance',requestId:mode==='create'?'start':'advance',identity:definition.identity});
271
271
  process.stdout.write(JSON.stringify({result,calls,checkpoint:run.checkpoint()}));}finally{run.close();}`;
272
272
  const invoke=mode=>JSON.parse(execFileSync(process.execPath,['--input-type=module','-e',source,configFile,mode],
273
273
  {env,encoding:'utf8',timeout:18000,maxBuffer:2*1024*1024}));
@@ -36,8 +36,7 @@ function workflowCli(args,codeProject,documentationStatus='completed'){
36
36
  const row=JSON.parse(line);
37
37
  if(row.type==='host_request'){
38
38
  calls.push(row.kind);let value;
39
- if(row.kind==='qa_assess')value={scores:{scope:1,risk:1,accumulation:1,boundary:1},
40
- changes:{api:false,migration:false,authentication:false,authorization:false,payment:false}};
39
+ if(row.kind==='qa_assess')value={confirmed:true};
41
40
  else{
42
41
  assert.equal(row.kind,'documentation_inspect','no unprotected write/check request');
43
42
  assert.equal(fs.readFileSync(path.join(codeProject,'README.md'),'utf8'),'# Updated\n');
@@ -74,8 +73,7 @@ async function fixture(fn){
74
73
  "require('node:assert/strict').equal(require('node:fs').readFileSync('a.js','utf8'),'new\\n')"]}],
75
74
  reviewerPreflight:{passed:true,cli_model:'synthetic',prompt_transport:'stdin',
76
75
  config_fingerprint:configFingerprint({cwd:codeProject,model:'synthetic'})}};
77
- const authority={authorizeDevelopment:()=>({status:'approved'}),
78
- authorizeReview:()=>assert.fail('No real review authorization'),hostDecision:{status:'denied',code:'permission_denied'}};
76
+ const authority={authorizeDevelopment:()=>({status:'approved'})};
79
77
  try{await fn({root,definition,config,authority});}finally{fs.rmSync(root,{recursive:true,force:true});}
80
78
  }
81
79
 
@@ -99,12 +97,12 @@ for(const runtime of ['codex','claude'])test(`protected ${runtime} conversation
99
97
  const wrong={...definition,scope:['b.js']};
100
98
  await assert.rejects(openControlRun(wrong,'create',execution),{code:'execution_definition_mismatch'});
101
99
  let run=await openControlRun(definition,'create',execution);
102
- try{const result=await run.host.handle(request('advance'));assert.equal(result.code,'decision_required',JSON.stringify(result));}
100
+ try{const result=await run.host.handle(request('start'));assert.equal(result.code,null,JSON.stringify(result));}
103
101
  finally{run.close();}
104
102
  assert.equal(fs.readFileSync(path.join(definition.codeProject,'a.js'),'utf8'),'new\n');
105
103
  assert.equal(calls,1);
106
104
  run=await openControlRun(definition,'resume',make());
107
- try{const result=await run.host.handle(request('advance'));assert.equal(result.code,'decision_required');assert.equal(calls,1);}
105
+ try{const result=await run.host.handle(request('start'));assert.equal(result.code,null);assert.equal(calls,1);}
108
106
  finally{run.close();}
109
107
  assert.match(fs.readFileSync(path.join(definition.specsDir,definition.feature,'tasks.md'),'utf8'),/\[ \]/);
110
108
  }));
@@ -214,8 +212,7 @@ let input='';process.stdin.on('data',chunk=>input+=chunk);process.stdin.on('end'
214
212
  documentationPaths:['README.md'],applicableAgentFiles:[]};
215
213
  fs.writeFileSync(workflowFile,JSON.stringify(workflow));
216
214
  const args=['serve','--config',runFile,'--mode','create','--host-context','host','--allow-development',
217
- '--protected-config',protectedFile,'--allow-provider-development-attempt','1','--review-config',reviewFile,
218
- '--allow-review-attempt','1','--workflow-config',workflowFile,'--allow-qa'];
215
+ '--protected-config',protectedFile,'--allow-provider-development-attempt','1','--review-config',reviewFile,'--workflow-config',workflowFile,'--allow-qa'];
219
216
  const denied=spawnSync(process.execPath,[fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url)),...args.slice(0,-1)],{encoding:'utf8',timeout:5000});
220
217
  assert.equal(denied.status,1);assert(denied.stderr.includes('qa_authorization_required'));
221
218
  assert(!fs.existsSync(path.join(config.specsRoot,'.reviews')));
@@ -243,21 +240,21 @@ let input='';process.stdin.on('data',chunk=>input+=chunk);process.stdin.on('end'
243
240
  assert.equal(logs.find(row=>row.event==='test_run'&&row.phase==='complete').result,'PASS');
244
241
  return;
245
242
  }
246
- const invoke=(mode,flags=[],attempt='1')=>{
243
+ const invoke=(mode,flags=[],attempt='1',operation='advance')=>{
247
244
  const child=spawnSync(process.execPath,[fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url)),
248
245
  'serve','--config',runFile,'--mode',mode,'--host-context','host','--allow-development',
249
246
  '--protected-config',protectedFile,'--allow-provider-development-attempt',attempt,'--review-config',reviewFile,...flags],
250
- {encoding:'utf8',input:JSON.stringify(request('advance'))+'\n',timeout:12000});
247
+ {encoding:'utf8',input:JSON.stringify({...request(operation),identity:{...identity,attempt:Number(attempt)}})+'\n',timeout:12000});
251
248
  assert.equal(child.status,0,child.stderr);
252
249
  const rows=child.stdout.trim().split('\n').map(JSON.parse);
253
250
  assert(!rows.some(row=>row.type==='host_request'),'protected mode never asks current host to perform unprotected writes');
254
- return rows.find(row=>row.requestId==='advance').result;
251
+ return rows.find(row=>row.requestId===operation).result;
255
252
  };
256
- assert.equal(invoke('create').state,'awaiting_review');
253
+ assert.equal(invoke('create',[],'1','start').state,'awaiting_review');
257
254
  assert.equal(fs.readFileSync(calls,'utf8'),'developer\n');
258
- assert.equal(invoke('resume').state,'awaiting_review');
255
+ assert.equal(invoke('resume',[],'1','start').state,'awaiting_review');
259
256
  assert.equal(fs.readFileSync(calls,'utf8'),'developer\n');
260
- let result=invoke('resume',['--allow-review-attempt','1']);
257
+ let result=invoke('resume',[]);
261
258
  if(launch==='revision'){
262
259
  assert.equal(result.state,'changes_requested');assert.equal(result.identity.attempt,2);
263
260
  assert.equal(result.code,'provider_development_authorization_required');
@@ -266,9 +263,9 @@ let input='';process.stdin.on('data',chunk=>input+=chunk);process.stdin.on('end'
266
263
  const before=fs.readFileSync(journal);assert(!before.includes('"id":"develop-2"'));
267
264
  assert.equal(invoke('resume').code,'provider_development_authorization_required');
268
265
  assert.deepEqual(fs.readFileSync(journal),before,'waiting for permission does not mutate the journal');
269
- result=invoke('resume',[],'2');assert.equal(result.state,'awaiting_review');
266
+ result=invoke('resume',[],'2','start');assert.equal(result.state,'awaiting_review');
270
267
  assert.equal(fs.readFileSync(calls,'utf8'),'developer\nreview\ndeveloper\n');
271
- result=invoke('resume',['--allow-review-attempt','2'],'2');
268
+ result=invoke('resume',[],'2');
272
269
  }
273
270
  assert.equal(result.state,'fixture_completed',JSON.stringify(result));
274
271
  assert.equal(result.code,'qa_decision_required');
@@ -281,8 +278,8 @@ let input='';process.stdin.on('data',chunk=>input+=chunk);process.stdin.on('end'
281
278
  }
282
279
  const execution=await createCodexExecution(config,authority);
283
280
  run=await openControlRun(definition,'create',execution);
284
- const result=await run.host.handle(request('advance'));
285
- assert.equal(result.state,'awaiting_review',JSON.stringify(result));assert.equal(result.outcome,'denied');
281
+ const result=await run.host.handle(request('start'));
282
+ assert.equal(result.state,'awaiting_review',JSON.stringify(result));assert.equal(result.outcome,'advanced');
286
283
  assert.equal(fs.readFileSync(calls,'utf8'),'developer\n');
287
284
  assert.equal(fs.readFileSync(path.join(definition.codeProject,'a.js'),'utf8'),'new\n');
288
285
  const task=path.join(definition.specsDir,definition.feature,'tasks.md');
@@ -293,7 +290,7 @@ let input='';process.stdin.on('data',chunk=>input+=chunk);process.stdin.on('end'
293
290
  assert(!handoff.changed_files.some(file=>file.startsWith('specs/')));
294
291
  run.close();run=null;
295
292
  run=await openControlRun(definition,'resume',await createCodexExecution(config,authority));
296
- assert.equal((await run.host.handle(request('advance'))).state,'awaiting_review');
293
+ assert.equal((await run.host.handle(request('start'))).state,'awaiting_review');
297
294
  assert.equal(fs.readFileSync(calls,'utf8'),'developer\n');
298
295
  assert.equal(fs.readFileSync(task,'utf8'),'- [ ] T-001: implement\n');
299
296
  }finally{run?.close();process.env.PATH=previousPath;}
@@ -82,13 +82,38 @@ test('batch guidance matches its narrower control surface and never advertises s
82
82
  assert.equal(wrapped.pendingAction,blocked.pendingAction);assert.equal(wrapped.guidance.recoveryOperation,'advance');
83
83
  assert.match(guidanceText(wrapped),/原批次入口/);assert.doesNotMatch(guidanceText(wrapped),/--mode/);
84
84
  assert.match(guidanceText(batchMemberResult(member('blocked','completion_checks_changed','complete'))),/成员宿主继续完成复核/);
85
- for(const [state,code,action] of [['unknown','execution_error','abandon_effect'],
86
- ['unknown','execution_error','abandon_review'],['blocked','bootstrap_review_mismatch','bootstrap_review_recover']]){
87
- const output=batchMemberResult(member(state,code,action));
88
- assert.equal(output.guidance.recoveryOperation,null);assert.doesNotMatch(guidanceText(output),/--allow-/);
89
- assert.match(guidanceText(output),/批次入口不支持/);
85
+ // Q24: the batch entry forwards these to the stopped member, so guidance names the batch grant and operation.
86
+ for(const [state,code,action,flag] of [['unknown','execution_error','abandon_effect','--allow-abandon-effect'],
87
+ ['unknown','execution_error','abandon_review','--allow-abandon-review'],['blocked','bootstrap_review_mismatch','bootstrap_review_recover','--allow-bootstrap-review-recovery'],
88
+ ['blocked','develop_answer_missing','develop_redo','--allow-develop-redo']]){
89
+ const output=batchMemberResult(member(state,code,action),{taskKey:'1.work/T-002'});
90
+ assert.equal(output.guidance.recoveryOperation,action);assert.equal(output.guidance.authorizationGranted,false);
91
+ assert(guidanceText(output).includes(`${flag} 1.work/T-002`),guidanceText(output));
92
+ assert.match(guidanceText(output),new RegExp(`批次操作 ${action}`));assert.doesNotMatch(guidanceText(output),/--mode/);
90
93
  }
91
94
  const rebound=batchMemberResult(member('blocked','spec_drift','spec_rebind'));
92
95
  assert.equal(rebound.pendingAction,'none');assert.match(rebound.guidance.nextStep,/不能换绑/);
93
96
  assert.equal(rebound.guidance.recoveryOperation,null);
94
97
  });
98
+
99
+ test('V5 review redispatch limit and unprovable review ends name the supersede exit, never a retry',()=>{
100
+ const identity={repositoryId:'r',runId:'run',taskId:'T-001',attempt:1};
101
+ const limit=operatorGuidance({workflow:'cm-ai',identity,state:'blocked',code:'review_redispatch_limit',pendingAction:'none'});
102
+ assert.equal(limit.recoveryOperation,null);assert.match(limit.nextStep,/supersede-reviewed-evidence/);assert.match(limit.summary,/2 次/);
103
+ for(const refusal of ['review_process_unverified','review_observation_invalid','review_boundary_unverified','review_abandon_budget_exhausted']){
104
+ const g=operatorGuidance({workflow:'cm-ai',identity,state:'unknown',code:'transport_incomplete',pendingAction:'reconcile',reviewAbandonRefusal:refusal});
105
+ assert.equal(g.recoveryOperation,null);assert.match(g.nextStep,/supersede-reviewed-evidence/);assert.equal(g.authorizationGranted,false);
106
+ }
107
+ });
108
+
109
+ test('Q06/Q07/Q15 a stopped QA call and a blocked documentation check name their operator exits',()=>{
110
+ const unknown=explain('fixture_completed','qa_execution_unknown','reconcile');
111
+ assert.match(unknown.nextStep,/--rerun-unknown-qa/);assert.match(unknown.nextStep,/设备已空闲/);assert.equal(unknown.authorizationGranted,false);
112
+ const docs=explain('fixture_completed','documentation_sync_blocked','none');
113
+ assert.match(docs.nextStep,/finish/);assert.equal(docs.recoveryOperation,null);
114
+ });
115
+
116
+ test('V5 the second no-result redispatch asks for the operator stop confirmation, never a plain advance',()=>{
117
+ const g=explain('blocked','review_transport_timeout','abandon_review',{reviewRedispatchStopRequired:true});
118
+ assert.equal(g.recoveryOperation,'abandon_review');assert.match(g.nextStep,/确认原审查进程/);assert.equal(g.authorizationGranted,false);
119
+ });
@@ -7,6 +7,7 @@ import childProcess,{spawn,spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {buildManifest} from './cm-spec-manifest.mjs';
9
9
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
10
+ import {installSyntheticReview,syntheticReviewConfig} from './cm-ai-host-fixture.mjs';
10
11
  import {createConversationExecution} from './cm-ai-host.mjs';
11
12
  import {createCmAiConversationEntry} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
12
13
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
@@ -35,14 +36,15 @@ function fixture(t){
35
36
  fs.writeFileSync(path.join(answers,'target.txt'),'export const value=42;\n');
36
37
  fs.writeFileSync(path.join(answers,'develop.json'),JSON.stringify({status:'succeeded',value:{outcome:'implemented',
37
38
  application:{status:'no_relevant_lesson',note:null},retrospective:{status:'no_new_lesson',candidates:[],reason:null}},edits:{'target.mjs':'target.txt'}}));
38
- fs.writeFileSync(path.join(root,'review.json'),JSON.stringify({model:'fixture',preflight:{}}));
39
+ fs.writeFileSync(path.join(root,'review.json'),JSON.stringify(syntheticReviewConfig(codeProject)));
39
40
  const plan=(checks,extra={})=>{
40
41
  const file=path.join(root,'plan.json');
42
+ fs.writeFileSync(path.join(root,'review.json'),JSON.stringify(syntheticReviewConfig(codeProject,extra.runtime??'codex')));
41
43
  fs.writeFileSync(file,JSON.stringify({config:'run.json',mode:'create',hostContext:'progress-fixture-host',
42
44
  permissions:['--review-config','review.json'],answers:'answers',checks,...extra}));return file;
43
45
  };
44
- const env={...process.env,CM_WORKFLOW_HOME:path.join(root,'home'),CM_WORKFLOW_LOG_HOME:path.join(root,'logs')};
45
- const run=(checks,extra={})=>spawnSync(process.execPath,[driver,'--plan',plan(checks,extra),'advance'],{encoding:'utf8',timeout:30000,env});
46
+ const local=installSyntheticReview({root,codeProject});const env=local.env;
47
+ const run=(checks,extra={},operation='start')=>spawnSync(process.execPath,[driver,'--plan',plan(checks,extra),operation],{encoding:'utf8',timeout:30000,env});
46
48
  return {root,specsDir,codeProject,feature,definition,statusPath,old,env,plan,run,
47
49
  status:()=>JSON.parse(fs.readFileSync(statusPath,'utf8')),
48
50
  events:()=>fs.readFileSync(path.join(specsDir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse)};
@@ -62,7 +64,7 @@ for(const runtime of ['codex','claude'])test(`${runtime}: live check replaces ol
62
64
  const events=f.events().filter(row=>row.event==='progress');
63
65
  assert(events.some(row=>row.phase==='start'&&row.phase_name==='developing'));
64
66
  assert(events.some(row=>row.phase==='start'&&row.phase_name==='checking'));
65
- assert(!events.some(row=>row.phase_name==='reviewing'),'No reviewer invocation was authorized');
67
+ assert(!events.some(row=>row.phase_name==='reviewing'),'start stops after development without dispatching review');
66
68
  for(const start of events.filter(row=>row.phase==='start'))assert(events.some(row=>row.phase==='complete'&&row.operation_id===start.operation_id));
67
69
  assert(fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'utf8').includes('- [ ] T-001'));
68
70
  });
@@ -102,12 +104,12 @@ test('guidance survives original-run status and recovery without writing it into
102
104
  const after=snapshot();assert.deepEqual(after.records.slice(0,before.records.length),before.records);
103
105
  assert.equal(JSON.stringify(after.records).includes('recoveryOperation'),false);
104
106
  assert(fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'utf8').includes('- [ ] T-001'));
105
- assert(!f.events().some(row=>row.phase_name==='reviewing'),'no independent review grant');
107
+ assert(!f.events().some(row=>row.phase_name==='reviewing'),'start recovery preserves the development stage');
106
108
  });
107
109
 
108
110
  test('a quiet command announces its start before finishing and preserves the JSON result channel',async t=>{
109
111
  const f=fixture(t),plan=f.plan([check('quiet',"setTimeout(()=>process.exit(0),700)")]);
110
- const child=spawn(process.execPath,[driver,'--plan',plan,'advance'],{env:f.env,stdio:['ignore','pipe','pipe']});
112
+ const child=spawn(process.execPath,[driver,'--plan',plan,'start'],{env:f.env,stdio:['ignore','pipe','pipe']});
111
113
  let out='',err='',seen=false,code;
112
114
  const timer=setTimeout(()=>child.kill('SIGKILL'),20000);t.after(()=>{clearTimeout(timer);if(child.exitCode===null)child.kill('SIGKILL');});
113
115
  child.stdout.on('data',b=>{out+=b;});child.stderr.on('data',b=>{
@@ -437,14 +439,14 @@ for(const verdict of ['approved','changes_requested'])test(`${verdict}: review p
437
439
  assert.equal(f.status().state,'awaiting_review');assert.equal(fs.existsSync(observed),false);
438
440
  const plan=f.plan(undefined,{mode:'resume',originalHostContext:'progress-fixture-host',answers:undefined,
439
441
  packageDigest:JSON.parse(first.stdout).result.packageDigest,
440
- permissions:['--review-config','review.json','--allow-review-attempt','1']});
442
+ permissions:['--review-config','review.json']});
441
443
  const run=spawnSync(process.execPath,[driver,'--plan',plan,'decision'],{env:f.env,encoding:'utf8',timeout:30000});
442
444
  assert.equal(run.status,0,run.stderr);assert.equal(JSON.parse(run.stdout).result.state,verdict,run.stdout+run.stderr);
443
445
  assert.equal(JSON.parse(fs.readFileSync(observed)).state,'reviewing');assert.equal(f.status().state,verdict);
444
446
  assert.equal(f.status().attempt,verdict==='approved'?1:2);
445
447
  assert(fs.readFileSync(path.join(f.specsDir,f.feature,'tasks.md'),'utf8').includes('- [ ] T-001'));
446
448
  if(verdict==='approved'){
447
- const completed=f.run([check('ok','0')],{mode:'resume',originalHostContext:'progress-fixture-host'});
449
+ const completed=f.run([check('ok','0')],{mode:'resume',originalHostContext:'progress-fixture-host'},'advance');
448
450
  assert.equal(completed.status,0,completed.stderr);
449
451
  assert.equal(JSON.parse(completed.stdout).result.state,'fixture_completed',completed.stdout+completed.stderr);
450
452
  assert.equal(f.status().state,'fixture_completed');assert.equal(f.status().node,'N5');
@@ -16,6 +16,7 @@ import {captureReviewBaseline,createReviewPackage} from '../runtime/js/cm-ai/rev
16
16
  import {explainReviewedDrift} from '../runtime/js/cm-ai/fix-code-association.mjs';
17
17
  import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
18
18
  import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
19
+ import {createTaskRunner} from '../runtime/js/cm-ai/task-runner.mjs';
19
20
 
20
21
  const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-project-qa-gate-'));
21
22
  const saved={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
@@ -63,19 +64,15 @@ function project(){
63
64
  return {status:'succeeded',value:{verdict:result,packageDigest:review.payload.reviewPackage.packageDigest,
64
65
  examinedPaths:reviewPaths(review.payload.reviewPackage),findings:result==='approved'?[]:
65
66
  [{id:'F1',severity:'P2',path:'b.mjs',message:'Again',evidence:'Synthetic'}],summary:'Synthetic review'}};}}],
66
- reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control'],authorize:(review,{authorizationAt})=>{
67
- const body={version:1,kind:'cm-review-dispatch-grant',grantId:`grant-${review.identity.runId}-${review.identity.attempt}`,
68
- adapterId:'codex-review-adapter',invocationId:review.invocationId,requestDigest:review.requestDigest,identity:review.identity,
69
- reviewerId:'reviewer',logicalContextId:review.contextId,packageDigest:review.payload.reviewPackage.packageDigest,hostContextId:'control',
70
- decisionId:'decision',decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
71
- return {...body,grantDigest:digest(body)};}},
72
- hostDecision:{status:'approved'},check:createHostCheck({cwd:codeProject,commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]}),
67
+ reviewInvocation:{developerThreadId:'author-thread',excludedThreadIds:['control']},check:createHostCheck({cwd:codeProject,commands:[{id:'syntax',command:[process.execPath,'--check','a.mjs']}]}),
73
68
  qaLogHome:logHome,applicableAgentFiles:[],
74
69
  documentationProvider:{timeoutMs:5000,inspect:async binding=>{state.documentation++;
75
70
  return {syncId:binding.syncId,identity:binding.identity,packageDigest:binding.packageDigest,contextDigest:binding.contextDigest,
76
71
  status:'completed',reason:'Documentation checked',at:'2026-09-28T00:00:00Z'};}},
77
- qaDecisionProvider:{timeoutMs:1000,decide:async binding=>({decisionId:`qa-${binding.identity.runId}`,identity:binding.identity,
78
- packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-09-28T00:00:00Z',...decision})},
72
+ qaDecisionProvider:{timeoutMs:1000,decide:async binding=>{assert.equal(binding.changedFiles.source,'review_package');
73
+ assert(binding.changedFiles.paths.includes(feature==='1.work'?'a.mjs':'b.mjs'));
74
+ return ({decisionId:`qa-${binding.identity.runId}`,identity:binding.identity,
75
+ packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-09-28T00:00:00Z',...decision});}},
79
76
  qaExecutor:createExecutor({specsDir,codeProject,feature,requirements:['requirements.md'],runtime:'codex',
80
77
  commands:[{id:'unit',command:[process.execPath,'--check','a.mjs'],caseIds:[]}],environment,timeoutMs:60000,logHome,
81
78
  browser:browser??(async browserRequest=>{
@@ -98,6 +95,36 @@ function project(){
98
95
  }
99
96
  const status=p=>JSON.parse(fs.readFileSync(path.join(p.specsDir,'.cm-status.json'),'utf8'));
100
97
 
98
+ test('qaChangedFiles rejects stale_qa before completion and for a mismatched digest after completion',async()=>{
99
+ const p=project(),identity=p.first.identity;
100
+ const terminal=(request,result)=>({version:1,invocationId:request.invocationId,
101
+ contextId:request.contextId,provider:request.provider,effectiveModel:'fixture',status:'succeeded',accepted:true,result});
102
+ const runner=createTaskRunner({root:p.codeProject,identity,scope:p.first.scope,requirements:p.first.requirements,
103
+ excludedContexts:['control'],timeoutMs:5000,
104
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'developer',run:request=>{
105
+ fs.writeFileSync(path.join(p.codeProject,'a.mjs'),'export const a=1;\n');
106
+ return terminal(request,{outcome:'implemented'});}},
107
+ reviewers:[{id:'reviewer',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
108
+ contexts:['review-one','review-two'],run:request=>terminal(request,{verdict:'approved',
109
+ packageDigest:request.payload.reviewPackage.packageDigest,examinedPaths:reviewPaths(request.payload.reviewPackage),
110
+ findings:[],summary:'Synthetic review'})}],
111
+ check:()=>[{id:'syntax',command:[process.execPath,'--check','a.mjs'],outcome:'passed',exitCode:0,evidence:'fixture'}],
112
+ commit:()=>({outcome:'fixture_completed'})});
113
+ const effect=kind=>({version:1,id:`${kind}-1`,identity,kind});
114
+ const developed=await runner.executeEffect(effect('develop'));
115
+ assert.equal(developed.state,'awaiting_review',JSON.stringify(developed));
116
+ const reviewed=await runner.executeEffect(effect('review'));
117
+ assert.equal(reviewed.state,'approved',JSON.stringify(reviewed));
118
+ assert.throws(()=>runner.qaChangedFiles(reviewed.packageDigest),{code:'stale_qa'});
119
+ const completed=await runner.executeEffect(effect('complete'));
120
+ assert.equal(completed.state,'fixture_completed',JSON.stringify(completed));
121
+ assert.equal(completed.packageDigest,reviewed.packageDigest);
122
+ const wrongDigest=(completed.packageDigest[0]==='0'?'1':'0')+completed.packageDigest.slice(1);
123
+ assert.throws(()=>runner.qaChangedFiles(wrongDigest),{code:'stale_qa'});
124
+ assert.deepEqual(runner.qaChangedFiles(completed.packageDigest),{paths:['a.mjs'],source:'review_package'});
125
+ assert.equal(runner.status().state,'fixture_completed');
126
+ });
127
+
101
128
  test('#17 an earlier feature whose QA is BLOCKED keeps the project from run_done until it is recovered; #18 its recovery survives a later reviewed task',async()=>{
102
129
  const p=project();
103
130
  const blocked=await p.advance(p.first,p.firstExecution(),'create');
@@ -362,7 +389,7 @@ test('#17 a skip is fine while tasks remain, but a terminal feature whose latest
362
389
  fs.writeFileSync(tasks,'- [ ] T-001: first\n- [ ] T-002: fixture\n');p.reapprove();
363
390
  const first=p.definition('1.work','T-001',['a.mjs']);
364
391
  const skipped=await p.advance(first,p.execution('1.work',{write:()=>fs.writeFileSync(path.join(p.codeProject,'a.mjs'),'export const a=1;\n'),
365
- decision:{status:'skipped',reason:'risk_score_below_threshold',score:4}}),'create');
392
+ decision:{status:'skipped',reason:'no_fixed_trigger',score:null}}),'create');
366
393
  assert.equal(skipped.code,'context_refreshed',JSON.stringify(skipped));
367
394
  const midway=inspectCmAiAdmission({specsDir:p.specsDir,codeProject:p.codeProject});
368
395
  assert.equal(midway.nextTask.id,'T-002');assert(!midway.warnings.some(line=>line.includes('QA 未通过')),JSON.stringify(midway.warnings));
@@ -89,8 +89,7 @@ async function runnerFixture(t,scope){
89
89
  check:()=>{throw new Error('checks must not run');},
90
90
  taskCompletion:{reviewsDir,handoffs:[1,2].map(n=>path.join(reviewsDir,`api-native-reading-T-006-a${n}-handoff.json`))},
91
91
  taskLearning:{feature:FEATURE,hostHandoff:true},
92
- reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main'],
93
- authorize:()=>{throw new Error('review must not be authorized');}}};
92
+ reviewInvocation:{developerThreadId:'actual-developer',excludedThreadIds:['actual-main']}};
94
93
  const make=mode=>createTaskRunner({...options,persistence:{store,mode,version:3}});
95
94
  const statePath=path.join(reviewsDir,'.execution',identity.runId,'state.json');
96
95
  const reopen=()=>{store.close();store=openTaskExecutionStore({...owner,create:false});return make('resume');};
@@ -180,15 +179,19 @@ test('a stranded T-006 journal replays as blocked/protected_scope and its record
180
179
  assert.deepEqual(fs.readFileSync(f.statePath),legacyBytes);
181
180
  });
182
181
 
183
- test('the same unknown developer shape without a protected scope is still unknown',async t=>{
182
+ test('the same unknown developer shape without a protected scope is not protected_scope (pinned root: develop_dispatch_failed)',async t=>{
184
183
  const f=await runnerFixture(t,['code.js']);
185
184
  f.setDeveloper(()=>{throw new Error('adapter failure');});
186
185
  const result=await f.make().executeEffect(f.develop());
187
- assert.equal(result.state,'unknown');assert.equal(result.code,'execution_error');assert.equal(f.developerCalls(),1);
186
+ assert.equal(result.state,'blocked');assert.equal(result.code,'develop_dispatch_failed');assert.equal(f.developerCalls(),1);
188
187
  // The genuine pre-gate shape has the same call fields the T-006 rewrite uses.
189
188
  assert.deepEqual(Object.keys(result.calls[0]),['invocationId','contextId','provider','requestedModel','effectiveModel',
190
189
  'channel','started','terminal','requestDigest','resultDigest']);
191
190
  assert.equal(result.calls[0].terminal,'unknown');assert.equal(result.calls[0].resultDigest,null);
192
191
  const resumed=f.reopen();
193
- assert.equal(resumed.status().state,'unknown');assert.equal(resumed.status().code,'execution_error');
192
+ // The journal keeps unknown/execution_error; with the code root still at the
193
+ // round start, status offers the plain pre-dispatch redo (answer gaps, P1-3).
194
+ const history=readRunnerHistory(f.records(),f.records()[0].payload.config,3);
195
+ assert.deepEqual([history.state.state,history.state.code],['unknown','execution_error']);
196
+ assert.deepEqual([resumed.status().state,resumed.status().code],['blocked','develop_dispatch_failed']);
194
197
  });