@aibyzero/cm-workflow 0.16.7 → 0.16.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +39 -3
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/compat/claude-commands/cm-notify.md +3 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +61 -4
  10. package/docs/next-steps.md +8 -2
  11. package/docs/user-guide.md +204 -0
  12. package/package.json +2 -1
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
  17. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  18. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  19. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  20. package/runtime/js/cm-ai/drive-core.mjs +26 -4
  21. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  22. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  23. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  24. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  25. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  26. package/runtime/js/cm-ai/host-check.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  28. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  29. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  30. package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
  31. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  32. package/runtime/js/cm-ai/host-session.mjs +47 -7
  33. package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
  34. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  35. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  36. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  37. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  38. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  39. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  40. package/runtime/js/cm-ai/review-package.mjs +10 -1
  41. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  42. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  43. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  44. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  45. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  46. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  47. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  48. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  49. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  50. package/runtime/js/cm-fix/execution.mjs +356 -187
  51. package/runtime/js/cm-fix/host.mjs +2 -1
  52. package/runtime/js/cm-fix/investigation.mjs +25 -9
  53. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  54. package/runtime/js/cm-fix/progress.mjs +15 -3
  55. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  56. package/runtime/js/cm-fix/repair.mjs +11 -3
  57. package/runtime/js/cm-fix/test-author.mjs +10 -3
  58. package/runtime/js/cm-idea/session.mjs +67 -4
  59. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  60. package/runtime/js/cm-prd/session.mjs +43 -0
  61. package/runtime/js/cm-refactor/records.mjs +98 -8
  62. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  63. package/runtime/js/cm-test/host.mjs +10 -3
  64. package/runtime/js/cm-test/session.mjs +45 -6
  65. package/runtime/js/notify-run.mjs +26 -0
  66. package/runtime/js/notify-safe-read.mjs +49 -0
  67. package/runtime/js/notify-send.mjs +312 -0
  68. package/runtime/js/notify.mjs +492 -0
  69. package/runtime/js/policy-binding-compat.mjs +54 -0
  70. package/runtime/model-efficiency.md +17 -0
  71. package/scripts/ci-test-shards.mjs +67 -0
  72. package/scripts/ci-test-shards.test.mjs +64 -0
  73. package/scripts/ci-test-weights.json +222 -0
  74. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  75. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  76. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  77. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  78. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  79. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  80. package/scripts/cm-ai-batch-drive.mjs +55 -10
  81. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  82. package/scripts/cm-ai-batch-host.mjs +132 -13
  83. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  84. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  85. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  86. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  87. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  88. package/scripts/cm-ai-batch-run.mjs +189 -22
  89. package/scripts/cm-ai-batch-run.test.mjs +22 -334
  90. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  91. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  92. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  93. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  94. package/scripts/cm-ai-drive.mjs +68 -23
  95. package/scripts/cm-ai-drive.test.mjs +37 -2
  96. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  97. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  98. package/scripts/cm-ai-host-fixture.mjs +268 -0
  99. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  100. package/scripts/cm-ai-host.mjs +28 -16
  101. package/scripts/cm-ai-host.test.mjs +17 -759
  102. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  103. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  104. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  105. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  106. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  107. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  108. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
  109. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  110. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  111. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  112. package/scripts/cm-ai-run.mjs +15 -6
  113. package/scripts/cm-ai-supersede.test.mjs +486 -41
  114. package/scripts/cm-check-drive-files.mjs +8 -0
  115. package/scripts/cm-check-drive.test.mjs +2 -5
  116. package/scripts/cm-check-runtime.sh +4 -2
  117. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  118. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  119. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  120. package/scripts/cm-claude-worker.test.mjs +18 -2
  121. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  122. package/scripts/cm-fix-abandon.test.mjs +249 -10
  123. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  124. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  125. package/scripts/cm-fix-drive.mjs +34 -8
  126. package/scripts/cm-fix-host.mjs +8 -7
  127. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  128. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  129. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  130. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  131. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  132. package/scripts/cm-host-documentation.test.mjs +49 -0
  133. package/scripts/cm-host-qa-executor.test.mjs +143 -10
  134. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  135. package/scripts/cm-idea-drive.mjs +49 -11
  136. package/scripts/cm-idea-drive.test.mjs +66 -0
  137. package/scripts/cm-idea-host.mjs +106 -16
  138. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  139. package/scripts/cm-init-drive.mjs +41 -7
  140. package/scripts/cm-init-host.mjs +61 -12
  141. package/scripts/cm-log-event.mjs +49 -12
  142. package/scripts/cm-notify-command.test.mjs +900 -0
  143. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  144. package/scripts/cm-notify.mjs +469 -0
  145. package/scripts/cm-notify.test.mjs +685 -0
  146. package/scripts/cm-patrol.mjs +83 -0
  147. package/scripts/cm-patrol.test.mjs +161 -0
  148. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  149. package/scripts/cm-prd-drive.mjs +18 -5
  150. package/scripts/cm-prd-drive.test.mjs +15 -0
  151. package/scripts/cm-prd-host.mjs +37 -4
  152. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  153. package/scripts/cm-prd-review-gate.mjs +56 -0
  154. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  155. package/scripts/cm-refactor-drive.mjs +52 -8
  156. package/scripts/cm-refactor-drive.test.mjs +44 -0
  157. package/scripts/cm-refactor-host.test.mjs +10 -6
  158. package/scripts/cm-release-smoke.sh +2 -0
  159. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  160. package/scripts/cm-test-drive.mjs +21 -5
  161. package/scripts/cm-token-report.mjs +497 -0
  162. package/scripts/cm-token-report.test.mjs +346 -0
  163. package/scripts/fixtures/claude-review-process.mjs +1 -1
  164. package/scripts/policy-binding-compat.test.mjs +99 -0
  165. package/scripts/scan-public-safety.py +4 -0
  166. package/scripts/validate-public-repo.py +4 -0
  167. package/skills/cm-ai/SKILL.md +7 -3
  168. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  169. package/skills/cm-ai/references/js-host-modes.md +90 -0
  170. package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
  171. package/skills/cm-ai/references/js-host-recovery.md +311 -0
  172. package/skills/cm-ai/references/js-host.md +76 -331
  173. package/skills/cm-check/SKILL.md +3 -3
  174. package/skills/cm-fix/SKILL.md +2 -0
  175. package/skills/cm-fix/references/js-host.md +56 -10
  176. package/skills/cm-idea/references/js-host.md +27 -2
  177. package/skills/cm-init/references/js-host.md +16 -3
  178. package/skills/cm-notify/SKILL.md +34 -0
  179. package/skills/cm-prd/SKILL.md +2 -0
  180. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  181. package/skills/cm-refactor/references/js-host.md +17 -0
  182. package/skills/cm-test/references/js-host.md +14 -1
@@ -25,7 +25,7 @@
25
25
  // fix_repair, fix_retrospective; host-qa-fix-owner.mjs
26
26
  // forwards to cm-fix host.run/handle.
27
27
  // fix_action selected cm-fix step; host-qa-fix-owner.mjs fix_action.
28
- // status/cancel/abandon_review/abandon_effect/bootstrap_review_recover/fix_status/context_refresh: none; cm-ai-conversation-entry.mjs
28
+ // status/cancel/abandon_review/abandon_effect/bootstrap_review_recover/develop_redo/fix_status/context_refresh: none; cm-ai-conversation-entry.mjs
29
29
  // status/cancel/context_refresh; host-qa-fix-owner.mjs fix_status.
30
30
  // verification_precheck optional execution.verificationGate in
31
31
  // host-conversation-execution.mjs; CLI has no runner for it.
@@ -56,7 +56,7 @@ import {codeProjectPaths,resolveCodeProjects} from '../runtime/js/cm-ai/code-pro
56
56
  import {parseHostInputLimit} from '../runtime/js/cm-ai/host-session.mjs';
57
57
  import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
58
58
  import {readCloseoutReport} from '../runtime/js/cm-ai/knowledge-closeout.mjs';
59
- import {readRunnerHistory,attemptBaseline} from '../runtime/js/cm-ai/durable-runner-state.mjs';
59
+ import {readRunnerHistory,attemptBaseline,projectedRunnerStatus,RECHECK_CODES,DOCUMENTATION_SYNC_CODES} from '../runtime/js/cm-ai/durable-runner-state.mjs';
60
60
  import {developmentRetryable} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
61
61
  import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost,planCheckTimeout} from '../runtime/js/cm-ai/drive-core.mjs';
62
62
  import {attemptAnswerName,inspectDriverBootstrap,readBootstrapRulesAnswers,createBootstrapRulesResponder} from '../runtime/js/cm-ai/drive-bootstrap.mjs';
@@ -64,7 +64,7 @@ import {driverLiveEvidence} from '../runtime/js/cm-ai/live-evidence.mjs';
64
64
 
65
65
  // PLAN.liveEvidence: fresh current-session evidence; see docs/live-evidence-drivers.md.
66
66
  const HOST=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
67
- const OPERATIONS=new Set(['advance','start','resume','status','cancel','reconcile_review','abandon_review','abandon_effect','bootstrap_review_recover','decision','complete','qa','qa_result',
67
+ const OPERATIONS=new Set(['advance','start','resume','status','cancel','reconcile_review','abandon_review','abandon_effect','bootstrap_review_recover','develop_redo','decision','complete','qa','qa_result',
68
68
  'fix_status','fix_advance','fix_action','fix_run','run_finalize','context_refresh','finish']);
69
69
  const ADVANCE=new Set(['advance','start','resume']);
70
70
  const PACKAGE_OPERATIONS=new Set(['decision','complete','qa','qa_result','context_refresh','finish','run_finalize']);
@@ -72,11 +72,17 @@ const TEST_RUN_OPERATIONS=new Set(['qa_result','context_refresh','finish','run_f
72
72
  const FIX_ASKS={advance:['fix_learning','fix_diagnose'],author_tests:['fix_learning','fix_test_author'],
73
73
  repair:['fix_learning','fix_repair'],retrospective:['fix_learning','fix_retrospective'],
74
74
  red_test:['fix_learning'],baseline:['fix_learning'],regression:['fix_learning'],
75
- post_review_regression:['fix_learning'],prepare_revision:['fix_learning']};
75
+ post_review_regression:['fix_learning'],prepare_revision:['fix_learning'],rediagnose:['fix_learning','fix_diagnose']};
76
76
  const FIX_ACTIONS=new Set(['red_test','baseline','author_tests','repair','regression','retrospective',
77
77
  'learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5',
78
78
  'post_review_regression','publish_dossier','walkthrough','finish','prepare_revision',
79
- 'cause_review_package','cause_review','reconcile_review','abandon_step','abandon_review']);
79
+ 'cause_review_package','cause_review','reconcile_review','abandon_step','abandon_review',
80
+ 'rediagnose','rerun_blocked_step','recover_final_review','revision_test_check']);
81
+ // Q23: parent launch flag per recovery fixOperation (host-qa-fix-owner.mjs QA_FIX_ACTION_FLAGS).
82
+ const FIX_ACTION_FLAGS={abandon_step:'--allow-qa-fix-abandon',abandon_review:'--allow-qa-fix-abandon-review',
83
+ rediagnose:'--allow-qa-fix-rediagnosis',rerun_blocked_step:'--allow-qa-fix-rerun-blocked-step',
84
+ recover_final_review:'--allow-qa-fix-final-review-recovery',revision_test_check:'--allow-qa-fix-regression'};
85
+ const FIX_REASONED=['abandon_step','abandon_review','rediagnose','rerun_blocked_step','recover_final_review'];
80
86
  const FILES={develop:'develop.json',qa_assess:'qa-assess.json',documentation_inspect:'documentation-inspect.json',
81
87
  documentation_sync:'documentation-sync.json',fix_learning:'learning.json',fix_diagnose:'diagnosis.json',
82
88
  fix_test_author:'test-edits.json',fix_repair:'repair-edits.json',fix_retrospective:'retrospective.json'};
@@ -85,13 +91,13 @@ const PAIR_FLAGS=new Set(['--external-models-config','--allow-review-attempt','-
85
91
  '--protected-conversation-config','--protected-config','--revise-qa-config','--qa-config-revision-reason','--qa-environment-failure',
86
92
  '--qa-fix-owner-config','--qa-fix-template-config','--qa-fix-review-config','--browser-qa',
87
93
  '--bootstrap-config','--allow-provider-development-attempt','--supersede-reason','--spec-rebind-reason',
88
- '--review-runtime','--feature']);
94
+ '--review-runtime','--feature','--qa-fix-final-review-recovery-invocation']);
89
95
  const FLAG_FLAGS=new Set(['--execution-optimizations','--external-models','--allow-development','--allow-qa','--allow-qa-fix-start','--auto-qa-fix',
90
96
  '--verification-precheck',
91
- '--allow-bootstrap-write','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--rerun-unknown-qa','--rerun-blocked-qa','--failover',
97
+ '--allow-bootstrap-write','--allow-abandon-review','--allow-abandon-effect','--allow-bootstrap-review-recovery','--allow-develop-redo','--rerun-unknown-qa','--rerun-blocked-qa','--failover',
92
98
  '--supersede-reviewed-evidence','--accept-superseded-code-drift','--rebind-spec-material',
93
99
  ...['red-test','baseline','regression','learning-writeback','walkthrough','finish','abandon','abandon-review',
94
- 'test-author','repair','cause-review','final-review'].map(name=>`--allow-qa-fix-${name}`)]);
100
+ 'test-author','repair','cause-review','final-review','rediagnosis','rerun-blocked-step','final-review-recovery'].map(name=>`--allow-qa-fix-${name}`)]);
95
101
  const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
96
102
  const nonempty=value=>typeof value==='string'&&value.trim().length>0;
97
103
  // Needs the resolved --bootstrap-config path in permissions.
@@ -107,6 +113,11 @@ export const abandonEffectPlanError=(operation,plan,permissions)=>operation!=='a
107
113
  &&typeof plan.reason==='string'&&plan.reason.trim().length>0
108
114
  &&Buffer.byteLength(plan.reason,'utf8')<=500&&!/[\r\n\0]/.test(plan.reason)?null:
109
115
  'abandon_effect 需要 resume、--allow-abandon-effect 与单行 reason(最多 500 UTF-8 字节)';
116
+ export const developRedoPlanError=(operation,plan,permissions)=>operation!=='develop_redo'?null:
117
+ plan.mode==='resume'&&permissions.includes('--allow-develop-redo')
118
+ &&typeof plan.reason==='string'&&plan.reason.trim().length>0
119
+ &&Buffer.byteLength(plan.reason,'utf8')<=500&&!/[\r\n\0]/.test(plan.reason)?null:
120
+ 'develop_redo 需要 resume、--allow-develop-redo 与单行 reason(最多 500 UTF-8 字节),并先确认会话已停止修改代码';
110
121
  export const bootstrapReviewRecoveryPlanError=(operation,plan,permissions)=>operation!=='bootstrap_review_recover'?null:
111
122
  plan.mode==='resume'&&permissions.includes('--allow-bootstrap-review-recovery')
112
123
  &&typeof plan.reason==='string'&&plan.reason.trim().length>0
@@ -414,7 +425,7 @@ export function readRunJournal(definition){
414
425
  const snapshot=readExecutionSnapshot({specsRoot:definition.specsDir,identity:{
415
426
  repositoryId:definition.identity.repositoryId,runId:definition.identity.runId}});
416
427
  const first=snapshot.records[0];
417
- return {history:readRunnerHistory(snapshot.records,first.payload.config,3),baseline:first.payload.baseline,
428
+ return {history:readRunnerHistory(snapshot.records,first.payload.config,3),config:first.payload.config,baseline:first.payload.baseline,
418
429
  frame:journalRestBytes(snapshot.records)};
419
430
  }
420
431
  function reachableDevelopAttempts({plan,operation,journal,permissions}){
@@ -426,11 +437,23 @@ function reachableDevelopAttempts({plan,operation,journal,permissions}){
426
437
  if(journal.error)stop(2,`无法只读检查恢复存档: ${journal.error.code??journal.error.message}`);
427
438
  // learning is the journal's Learning result the next develop effect starts from
428
439
  // (bootstrap rules bind their on-disk files to its recorded evidence).
429
- return {...projectDevelopAttempts(journal.history.state,operation,permissions),learning:journal.history.state.learningResult??null};
440
+ // Q28: decide from what the host will show (projected answer-gap blocks), not the raw replay state.
441
+ return {...projectDevelopAttempts(projectedRunnerStatus(journal.history,journal.config),operation,permissions),
442
+ learning:journal.history.state.learningResult??null};
430
443
  }
431
444
  export function projectDevelopAttempts(status,operation,permissions){
432
445
  const {state,attempt,reviewPackage}=status;
433
- if(developmentRetryable(status))return {attempts:[attempt],reviewFirst:false,packageDigest:null};
446
+ // One advance can continue past the round-1 review into round 2 when it holds
447
+ // --allow-review-attempt 1 (Codex round 1 on Q28): preflight that round too.
448
+ const reviewAfterDevelop=operation==='advance'&&attempt===1
449
+ &&permissions.some((flag,index)=>flag==='--allow-review-attempt'&&permissions[index+1]==='1');
450
+ // A re-check (check_answer_*) re-runs only the checks: no developer answer for
451
+ // this round, only for the round its review may lead to.
452
+ // Q16/Q17: a documentation-only redo reuses the journaled developer answer.
453
+ if(state==='blocked'&&(RECHECK_CODES.includes(status.code)||DOCUMENTATION_SYNC_CODES.includes(status.code)))
454
+ return {attempts:reviewAfterDevelop?[2]:[],reviewFirst:false,reviewAfterDevelop,holdable:true,packageDigest:null};
455
+ if(developmentRetryable(status))
456
+ return {attempts:reviewAfterDevelop?[1,2]:[attempt],reviewFirst:false,reviewAfterDevelop,holdable:true,packageDigest:null};
434
457
  if(state==='ready'&&attempt===1&&operation==='advance'
435
458
  &&permissions.some((flag,index)=>flag==='--allow-review-attempt'&&permissions[index+1]==='1'))
436
459
  return {attempts:[1,2],reviewFirst:false,reviewAfterDevelop:true,packageDigest:null};
@@ -456,7 +479,10 @@ function predictedQaAsks(definition,qa){
456
479
  const taskWasPending=!completed.has(definition.identity.taskId);
457
480
  completed.add(definition.identity.taskId);
458
481
  const pendingAfter=context.pending-(taskWasPending?1:0);
459
- const cases=plan.cases.filter(item=>pendingAfter===0||item.taskIds.every(taskId=>completed.has(taskId)));
482
+ // A case bound only to [DROPPED] tasks is never planned, so never asked.
483
+ const dropped=new Set(context.dropped);
484
+ const cases=plan.cases.filter(item=>!(item.taskIds.length>0&&item.taskIds.every(taskId=>dropped.has(taskId))))
485
+ .filter(item=>pendingAfter===0||item.taskIds.every(taskId=>completed.has(taskId)));
460
486
  const asks=[];
461
487
  // The current executor still calls logic() for mapped cases; command evidence
462
488
  // only affects the later verdict. Keep the preflight conservative until that
@@ -534,7 +560,7 @@ export function validateCmAiAnswer(kind,value,root){
534
560
  }
535
561
  function load(){
536
562
  if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
537
- process.stdout.write('用法: cm-ai-drive.mjs --plan PLAN.json <operation>\nPLAN: config, mode, hostContext, originalHostContext (换会话 resume 必填), runtime, permissions, answers, checks, checkTimeoutMs。\nchecks 每项为 {id,command,timeoutMs?};checkTimeoutMs 与每项 timeoutMs 为 1..3600000 整数,默认 900000 ms(15 分钟)。\nabandon_review 需要 mode:resume、permissions:["--allow-abandon-review"] 与 PLAN.reason;abandon_effect 需要 mode:resume、permissions:["--allow-abandon-effect"] 与 PLAN.reason(均为单行、最多 500 UTF-8 字节)。 bootstrap_review_recover 需要 mode:resume、permissions:["--allow-bootstrap-review-recovery"] 与 PLAN.reason;只核对原运行的已写规则与 handoff,不需要答案文件。\n人工答案放 answers/;check 只运行 PLAN.checks,不读取静态执行证据。bootstrap T-001 骨架可用;T-002 规范任务(纯规范 scope、单代码根、非 --protected-config)读 answers/init-generate.json({status:"generated",documents:[{path,contentFile}]},覆盖全部 targets)与 answers/init-verify.json(commands 为驾驶员实跑的草稿命令 {id,command,timeoutMs?},可选 commandsNotRun;checks 只含 globs/file_references/constraint_preservation/rule_applicability;constraintChanges:[];application/retrospective 沿原 Learning);第 1 轮也可用 *-a1.json,第 2 轮只读 init-generate-a2.json 与 init-verify-a2.json,且须先 decision 读取首轮 findings,不能带 --allow-review-attempt 跨轮。commands 在宿主接受启动后、发送操作前由驾驶员实跑(须先带 --allow-bootstrap-write 等宿主授权;受保护模式在 specs 沙箱内),失败或改动了预检核对的文件即退出 2 且不发送操作(create 时改用 resume 重跑);结果只来自实跑,答案文件不能提供。\n'
563
+ process.stdout.write('用法: cm-ai-drive.mjs --plan PLAN.json <operation>\nPLAN: config, mode, hostContext, originalHostContext (换会话 resume 必填), runtime, permissions, answers, checks, checkTimeoutMs。\nchecks 每项为 {id,command,timeoutMs?};checkTimeoutMs 与每项 timeoutMs 为 1..3600000 整数,默认 900000 ms(15 分钟)。\nabandon_review 需要 mode:resume、permissions:["--allow-abandon-review"] 与 PLAN.reason;abandon_effect 需要 mode:resume、permissions:["--allow-abandon-effect"] 与 PLAN.reason(均为单行、最多 500 UTF-8 字节)。develop_redo 需要 mode:resume、permissions:["--allow-develop-redo"] 与 PLAN.reason,先确认会话已停止修改代码。 bootstrap_review_recover 需要 mode:resume、permissions:["--allow-bootstrap-review-recovery"] 与 PLAN.reason;只核对原运行的已写规则与 handoff,不需要答案文件。\n人工答案放 answers/;check 只运行 PLAN.checks,不读取静态执行证据。bootstrap T-001 骨架可用;T-002 规范任务(纯规范 scope、单代码根、非 --protected-config)读 answers/init-generate.json({status:"generated",documents:[{path,contentFile}]},覆盖全部 targets)与 answers/init-verify.json(commands 为驾驶员实跑的草稿命令 {id,command,timeoutMs?},可选 commandsNotRun;checks 只含 globs/file_references/constraint_preservation/rule_applicability;constraintChanges:[];application/retrospective 沿原 Learning);第 1 轮也可用 *-a1.json,第 2 轮只读 init-generate-a2.json 与 init-verify-a2.json,且须先 decision 读取首轮 findings,不能带 --allow-review-attempt 跨轮。commands 在宿主接受启动后、发送操作前由驾驶员实跑(须先带 --allow-bootstrap-write 等宿主授权;受保护模式在 specs 沙箱内),失败或改动了预检核对的文件即退出 2 且不发送操作(create 时改用 resume 重跑);结果只来自实跑,答案文件不能提供。\n'
538
564
  +'develop.json.edits 每项是 scope 路径到下列之一:"内容文件"(写入;已有文件保留权限,新文件 0644)、{"file":"内容文件","mode":"0755"|"0644"}、{"mode":"0755"|"0644"}(只改已有文件权限)、{"delete":true}(删除已有文件)。改名 = 删旧路径 + 写新路径,两者都要在 scope 内;同时列在 requirements 里的路径不能删除。\n'
539
565
  +'启动前拒绝:单个 scope 文件超过 1 MiB、审查材料(按审查包快照:scope、requirements 与树中全部 AGENTS.md 正文)合计超过 2 MiB 或超过 256 个文件、交付后与任务基线完全相同(edits 为空或内容和权限都没变)、开发检查点(含 handoff 与 AGENTS.md 回写,按宿主同一套构建代码计)装不进运行存档单条 1 MiB 记录减去为有界审查与完成记录推出的预留,或任务基线装不进一条记录。受保护模式(--protected-conversation-config)只收合法 UTF-8 文本,应答大于 --input-limit(默认 65536)时提示应加的值。\n'
540
566
  +'runId 需 8–128 个字符(运行日志要求),create 前检查。resume 时按存档里的当前轮次发送 identity,第 2 轮的 decision/complete/qa 等无需手改。\n');
@@ -570,6 +596,8 @@ function load(){
570
596
  if(abandonError)stop(2,abandonError);
571
597
  const abandonEffectError=abandonEffectPlanError(operation,plan,permissions);
572
598
  if(abandonEffectError)stop(2,abandonEffectError);
599
+ const developRedoError=developRedoPlanError(operation,plan,permissions);
600
+ if(developRedoError)stop(2,developRedoError);
573
601
  const bootstrapRecoveryError=bootstrapReviewRecoveryPlanError(operation,plan,permissions);
574
602
  if(bootstrapRecoveryError)stop(2,bootstrapRecoveryError);
575
603
  const config=path.resolve(base,plan.config),answers=plan.answers?path.resolve(base,plan.answers):null;
@@ -606,7 +634,7 @@ function load(){
606
634
  &&permissions[i]!=='--allow-review-attempt'&&permissions[i]!=='--browser-qa'
607
635
  &&permissions[i]!=='--qa-config-revision-reason'&&permissions[i]!=='--qa-environment-failure'&&permissions[i]!=='--allow-provider-development-attempt'
608
636
  &&permissions[i]!=='--supersede-reason'&&permissions[i]!=='--spec-rebind-reason'&&permissions[i]!=='--input-limit'
609
- &&permissions[i]!=='--review-runtime'&&permissions[i]!=='--feature'){
637
+ &&permissions[i]!=='--review-runtime'&&permissions[i]!=='--feature'&&permissions[i]!=='--qa-fix-final-review-recovery-invocation'){
610
638
  const file=path.resolve(base,permissions[i+1]);if(!fs.existsSync(file))stop(2,`${permissions[i]} 文件不存在: ${file}`);
611
639
  permissions[i+1]=file;permissionFiles.push(file);i++;
612
640
  }
@@ -639,9 +667,14 @@ function load(){
639
667
  if(operation==='fix_action'){
640
668
  if(plan.fixOperation==='reconcile_review'&&(plan.mode!=='resume'||!nonempty(plan.invocationId)))stop(2,'fix reconciliation requires resume and original invocationId');
641
669
  if(!FIX_ACTIONS.has(plan.fixOperation))stop(2,'fix_action 需要宿主支持的 fixOperation');
642
- const abandonFlag=plan.fixOperation==='abandon_review'?'--allow-qa-fix-abandon-review':'--allow-qa-fix-abandon';
643
- if(['abandon_step','abandon_review'].includes(plan.fixOperation)&&(!nonempty(plan.reason)
644
- ||!permissions.includes(abandonFlag)))stop(2,`${plan.fixOperation} 需要 reason 与 ${abandonFlag}`);
670
+ const actionFlag=FIX_ACTION_FLAGS[plan.fixOperation];
671
+ if(actionFlag&&!permissions.includes(actionFlag))stop(2,`${plan.fixOperation} 需要 ${actionFlag}`);
672
+ if(FIX_REASONED.includes(plan.fixOperation)&&!(nonempty(plan.reason)&&Buffer.byteLength(plan.reason,'utf8')<=1000
673
+ &&!/[\r\n\0\u0085\u2028\u2029]/.test(plan.reason)))stop(2,`${plan.fixOperation} 需要单行 reason(最多 1000 UTF-8 字节)`);
674
+ if(plan.fixOperation==='rediagnose'&&plan.mode!=='resume')stop(2,'rediagnose 需要 mode:resume');
675
+ if(plan.fixOperation==='recover_final_review'&&(plan.mode!=='resume'||!nonempty(plan.invocationId)
676
+ ||!/^[a-f0-9]{64}$/.test(plan.reviewPackageDigest??'')||plan.previousInvocationStopped!==true))
677
+ stop(2,'recover_final_review 需要 mode:resume、原 invocationId、子运行终审包 reviewPackageDigest,以及确认旧审查进程已停的 previousInvocationStopped:true');
645
678
  asks.push(...(FIX_ASKS[plan.fixOperation]??[]));
646
679
  }
647
680
  let live;
@@ -668,11 +701,19 @@ function load(){
668
701
  :{attempts:[],reviewFirst:false,packageDigest:null};
669
702
  const bootstrapAnswers=rules
670
703
  ?readBootstrapRulesAnswers({answers,operation,definition,plan,permissions,bootstrap,reachable}):null;
671
- const developAnswers=new Map(),deliveries=[];
704
+ const developAnswers=new Map(),deliveries=[];let holdRevision=false;
672
705
  if(asks.includes('develop'))for(const attempt of reachable.attempts){
673
706
  const file=answerPath(answers??'',developFilename(answers??'',attempt));
674
707
  if(!answers||!fs.existsSync(file)){
675
708
  const reviewFile=`.reviews/${definition.feature.replace(/^\d+\./,'')}-${definition.identity.taskId}-r1.md`;
709
+ // Resuming a retryable block: let the redo and its review run, then stop
710
+ // at changes_requested (revision_answer_required) instead of asking a
711
+ // round-2 develop nobody can answer.
712
+ if(reachable.reviewAfterDevelop&&reachable.holdable&&attempt===2){
713
+ holdRevision=true;
714
+ stderr(`没有 ${path.basename(file)}:本次 advance 的首轮审查若要求修改,任务会停在 changes_requested(revision_answer_required),不会发起第 2 轮开发;读取 ${reviewFile} 的 findings,写 answers/develop-a2.json 后再 advance`);
715
+ continue;
716
+ }
676
717
  if(reachable.reviewAfterDevelop&&attempt===2)
677
718
  stop(2,`缺少 ${file};本次 advance 带 --allow-review-attempt 1,宿主完成首轮审查后可能直接进入第 2 轮 develop。可选:1) 从 PLAN.permissions 移除 --allow-review-attempt 1,先 advance 到 awaiting_review;再用该运行返回的 packageDigest 执行 decision,读取 ${reviewFile} 的 findings;若要求修改,写 answers/develop-a2.json 后 advance。2) 若有意一次跑完,预先写 answers/develop-a2.json 后重试 advance。develop-a2.json 必须针对首轮 findings 修改;与第 1 轮被要求修改的代码逐字节相同时,第 2 轮停在 blocked/develop_unchanged_after_review,不送审,改好后再 advance。`);
678
719
  if(reachable.reviewFirst)stop(2,`缺少 ${path.basename(file)};请先以 decision 和当前 packageDigest ${reachable.packageDigest} 单独运行审查,读取 .reviews/${definition.feature.replace(/^\d+\./,'')}-${definition.identity.taskId}-r${attempt-1}.md 中的 findings,写 answers/develop-a${attempt}.json 后再 advance`);
@@ -691,13 +732,15 @@ function load(){
691
732
  exact:!permissions.includes('--bootstrap-config')})});
692
733
  const unique=[...new Set(asks.filter(kind=>FILES[kind]&&kind!=='develop'))];
693
734
  const answer=preflightAnswers(unique,kind=>{
694
- const file=answerPath(answers??'',FILES[kind]);
735
+ // A rediagnosis is a new conclusion; never reuse the first diagnosis file (same as cm-fix-drive).
736
+ const file=answerPath(answers??'',operation==='fix_action'&&plan.fixOperation==='rediagnose'&&kind==='fix_diagnose'
737
+ ?'diagnosis-rediagnosis.json':FILES[kind]);
695
738
  if(!answers||!fs.existsSync(file))stop(2,`步骤 ${operation} 会反问 ${kind},但答案文件不存在: ${file}`);
696
739
  const value=readJson(file,kind);validateCmAiAnswer(kind,value,answers);return value;
697
740
  });
698
741
  if(answer.documentation_sync)for(const target of Object.keys(answer.documentation_sync.edits))
699
742
  if(!workflow.documentationPaths.includes(target))stop(2,`documentation-sync.json.edits 越过文档 scope: ${target}`);
700
- return {...loaded,definition,identity,permissions,config,answers,answer,developAnswers,live,executionPolicy,
743
+ return {...loaded,definition,identity,permissions,config,answers,answer,developAnswers,live,executionPolicy,holdRevision,
701
744
  bootstrapRules:bootstrapAnswers&&createBootstrapRulesResponder({definition,plan,bootstrap,answers:bootstrapAnswers,
702
745
  // Same execution as the task checks: the host's specs sandbox in protected mode, else the driver's own.
703
746
  specsRoot:protectedMode?definition.specsDir:null,watch:[config,...permissionFiles]})};
@@ -774,13 +817,15 @@ async function answerFor(row,answer,paths,control){
774
817
  export function buildCmAiDriveRequest(operation,plan,definition,identity=definition.identity){
775
818
  return {version:1,identity,
776
819
  ...(operation==='reconcile_review'?{invocationId:plan.invocationId}:{}),
777
- ...(['abandon_review','abandon_effect','bootstrap_review_recover'].includes(operation)?{reason:plan.reason}:{}),
820
+ ...(['abandon_review','abandon_effect','bootstrap_review_recover','develop_redo'].includes(operation)?{reason:plan.reason}:{}),
778
821
  ...(PACKAGE_OPERATIONS.has(operation)?{packageDigest:plan.packageDigest}:{}),
779
822
  ...(TEST_RUN_OPERATIONS.has(operation)?{testRunId:plan.testRunId}:{}),
780
823
  ...(['fix_status','fix_advance','fix_action','fix_run'].includes(operation)?{
781
824
  packageDigest:plan.packageDigest,testRunId:plan.testRunId,
782
825
  ...(operation==='fix_action'?{fixOperation:plan.fixOperation,...(plan.fixOperation==='reconcile_review'?{invocationId:plan.invocationId}:{}),
783
- ...(['abandon_step','abandon_review'].includes(plan.fixOperation)?{reason:plan.reason}:{})}: {})}: {})};
826
+ ...(FIX_REASONED.includes(plan.fixOperation)?{reason:plan.reason}:{}),
827
+ ...(plan.fixOperation==='recover_final_review'?{invocationId:plan.invocationId,reviewPackageDigest:plan.reviewPackageDigest,
828
+ previousInvocationStopped:plan.previousInvocationStopped}:{})}: {})}: {})};
784
829
  }
785
830
  export function buildCmAiDriveHostArgs(plan,permissions,config){
786
831
  return ['serve','--config',config,'--mode',plan.mode,'--host-context',plan.hostContext,
@@ -804,7 +849,7 @@ async function main(){
804
849
  // Rules init_verify commands really run once the host has accepted the launch
805
850
  // (host_ready) and before the operation is sent: a failure never becomes an
806
851
  // unknown develop effect, and the host's own launch validation came first.
807
- driveHost({host:HOST,args:buildCmAiDriveHostArgs(plan,permissions,config),cwd:definition.codeProject,operation,request,
852
+ driveHost({host:HOST,args:[...buildCmAiDriveHostArgs(plan,permissions,config),...(loaded.holdRevision?['--hold-revision']:[])],cwd:definition.codeProject,operation,request,
808
853
  answers:answer,paths:{answers:loaded.answers},answerFor,
809
854
  ...(loaded.bootstrapRules?{beforeRequest:()=>loaded.bootstrapRules.prepare(plan.mode)}:{})});
810
855
  }
@@ -285,9 +285,11 @@ test('driver resumes an interrupted develop and sends the bound abandon_effect r
285
285
  reason:'Old host and its checks have exited'});
286
286
  const result=f.drive(plan,'abandon_effect');assert.equal(result.status,0,result.stderr);
287
287
  const response=JSON.parse(result.stdout).result;
288
- assert.equal(response.state,'cancelled');assert.equal(response.code,'effect_abandoned');
288
+ // V8: the run continues from develop_interrupted instead of being voided.
289
+ assert.equal(response.state,'blocked');assert.equal(response.code,'develop_interrupted');
290
+ assert.equal(response.pendingAction,'resume');
289
291
  const saved=JSON.parse(fs.readFileSync(f.store,'utf8'));
290
- assert.deepEqual(saved.records.slice(-2).map(row=>row.payload.type),['effect-intent','effect-abandoned']);
292
+ assert.deepEqual(saved.records.slice(-2).map(row=>row.payload.type),['effect-intent','effect-interrupted']);
291
293
  });
292
294
  test('real host drives split-root bootstrap scaffold, then refuses rules without answer files before creating T-002 run',
293
295
  {skip:process.platform!=='darwin'},t=>{
@@ -456,6 +458,14 @@ test('cases bound to another unfinished task do not require QA runners yet',t=>{
456
458
  assert.doesNotMatch(run.stderr,/缺少真实执行 runner/);
457
459
  assert(fs.existsSync(f.store),run.stderr);
458
460
  });
461
+ test('cases bound only to a dropped task never require QA runners',t=>{
462
+ const f=fixture(t);prepared(f);
463
+ fs.writeFileSync(path.join(f.specsDir,'1.work','tasks.md'),'- [ ] T-001: current\n- [ ] ~~T-002: column~~ `[DROPPED v2: 暂缓]`\n');
464
+ const run=f.drive(qaFixture(f,[{kind:'logic',expected:'Dropped logic',taskIds:['T-002']},
465
+ {kind:'browser',expected:'Dropped browser',taskIds:['T-002']}]),'advance');
466
+ assert.doesNotMatch(run.stderr,/缺少真实执行 runner/);
467
+ assert(fs.existsSync(f.store),run.stderr);
468
+ });
459
469
  test('protected conversation still requires the authored develop answer',t=>{
460
470
  const f=fixture(t);fs.writeFileSync(path.join(f.root,'protection.json'),JSON.stringify({checkCommands:[
461
471
  {id:'syntax',command:[process.execPath,'--check','target.mjs']}],timeoutMs:60000}));
@@ -546,6 +556,31 @@ test('QA-fix child action requires its own answer before any host request',t=>{
546
556
  {fix_repair:{'target.mjs':'repair.txt'}},f.answers),
547
557
  {outcome:'repaired',edits:[{path:'target.mjs',beforeSha256:'old-hash',content:'export const value = 43;\n'}]});
548
558
  });
559
+ test('Q23 QA-fix recovery fixOperations need their parent flag and fields before any host request',t=>{
560
+ const f=fixture(t);prepared(f);assert.equal(f.drive(f.plan(),'advance').status,0);
561
+ const binding={feature:'1.work',identity,packageDigest:'a'.repeat(64),testRunId:'qa-child'};
562
+ fs.writeFileSync(path.join(f.root,'fix-owner.json'),JSON.stringify({specsRoot:f.specsDir,identity:{...identity,runId:'fix-run'},
563
+ configuration:{hostContextId:'drive-host-a',reproduction:{cwd:f.codeProject},qaSource:binding}}));
564
+ const base={mode:'resume',originalHostContext:'drive-host-a',packageDigest:'a'.repeat(64),testRunId:'qa-child',
565
+ permissions:['--qa-fix-owner-config','fix-owner.json','--allow-qa-fix-start']};
566
+ const run=(extra,flags=[])=>f.drive(f.plan({...base,...extra,permissions:[...base.permissions,...flags]}),'fix_action');
567
+ let result=run({fixOperation:'rediagnose',reason:'审查要求补证'});
568
+ assert.equal(result.status,2);assert.match(result.stderr,/--allow-qa-fix-rediagnosis/);
569
+ result=run({fixOperation:'rediagnose',reason:'审查要求补证'},['--allow-qa-fix-rediagnosis']);
570
+ assert.equal(result.status,2);assert.match(result.stderr,/learning\.json/);
571
+ f.write('learning.json',{status:'no_relevant_lesson',summary:'No applicable project lesson'});
572
+ f.write('diagnosis.json',{status:'diagnosed',rootCause:'first',affectedPaths:['a.mjs'],affectedModules:['a'],plan:'p',crossLayer:false});
573
+ result=run({fixOperation:'rediagnose',reason:'审查要求补证'},['--allow-qa-fix-rediagnosis']);
574
+ assert.equal(result.status,2);assert.match(result.stderr,/diagnosis-rediagnosis\.json/);
575
+ result=run({fixOperation:'rerun_blocked_step'},['--allow-qa-fix-rerun-blocked-step']);
576
+ assert.equal(result.status,2);assert.match(result.stderr,/reason/);
577
+ result=run({fixOperation:'recover_final_review',reason:'旧审查已停',invocationId:'final-1',reviewPackageDigest:'b'.repeat(64)},
578
+ ['--allow-qa-fix-final-review-recovery']);
579
+ assert.equal(result.status,2);assert.match(result.stderr,/previousInvocationStopped/);
580
+ result=run({fixOperation:'recover_final_review',reason:'旧审查已停',invocationId:'final-1',reviewPackageDigest:'b'.repeat(64),
581
+ previousInvocationStopped:true},['--allow-qa-fix-final-review-recovery','--qa-fix-final-review-recovery-invocation','final-1']);
582
+ assert.equal(result.status,1,result.stderr);assert.match(result.stderr,/qa_fix_parent_not_completed/);
583
+ });
549
584
  test('QA-fix answer travels through the shared JSONL core',t=>{
550
585
  const f=fixture(t),host=path.join(f.root,'child-host.mjs'),wrapper=path.join(f.root,'child-drive.mjs');
551
586
  fs.writeFileSync(host,`process.stdout.write(JSON.stringify({type:'host_ready',sessionId:'child'})+'\\n');
@@ -0,0 +1,138 @@
1
+ // A standalone cm-fix run that changed a completed cm-ai task's files, was
2
+ // independently reviewed and closed normally, is a later reviewed delivery of
3
+ // that task's code root (2026-10-08, AI潮 author-column-T-010 after
4
+ // api-native-reading-fix-story-return: --rerun-blocked-qa stopped at
5
+ // correction_review_required naming only the fix's reviewed files).
6
+ import test,{after} from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import {buildManifest} from './cm-spec-manifest.mjs';
12
+ import {openControlRun} from './cm-ai-run.mjs';
13
+ import {createCodexDeveloperRun} from '../runtime/js/cm-ai/codex-developer-adapter.mjs';
14
+ import {createHostCheck} from '../runtime/js/cm-ai/host-check.mjs';
15
+ import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authority.mjs';
16
+ import {reviewPaths} from '../runtime/js/cm-ai/review-runner.mjs';
17
+ import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
18
+ import {createFixHost} from '../runtime/js/cm-fix/host.mjs';
19
+ import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
20
+ import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
21
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
22
+ import {completedReviewedDeliveries} from '../runtime/js/cm-ai/reviewed-deliveries.mjs';
23
+
24
+ const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-run-delivery-'));
25
+ const saved={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
26
+ process.env.CM_WORKFLOW_HOME=path.join(isolated,'home');process.env.CM_WORKFLOW_LOG_HOME=path.join(isolated,'logs');
27
+ after(()=>{
28
+ for(const [key,value] of Object.entries(saved)){if(value===undefined)delete process.env[key];else process.env[key]=value;}
29
+ fs.rmSync(isolated,{recursive:true,force:true});
30
+ });
31
+ const events=(onEvent,thread)=>{
32
+ for(const event of [{event:'thread.started',provider_thread:thread},{event:'turn.started',item_type:null},
33
+ {event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},
34
+ {event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
35
+ };
36
+
37
+ // A cm-ai task completes (value 0 -> 1, QA PASS, run_done); then a standalone
38
+ // cm-fix run in the same specs and code root repairs value 1 -> 2, stopping
39
+ // before or after its normal closeout.
40
+ async function completedTaskThenFix({finish}){
41
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(isolated,'project-')));
42
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs');fs.mkdirSync(codeProject);
43
+ fs.mkdirSync(path.join(specsDir,'1.value'),{recursive:true});
44
+ for(const name of ['requirements','design'])fs.writeFileSync(path.join(specsDir,'1.value',`${name}.md`),'# Synthetic fixture');
45
+ fs.writeFileSync(path.join(specsDir,'1.value','tasks.md'),'- [ ] T-001: implement\n');
46
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['1.value'],specFiles:buildManifest(specsDir)}));
47
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=0;');
48
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'Value should be 2.');
49
+ fs.writeFileSync(path.join(codeProject,'red.mjs'),"import {value} from './value.mjs';if(value!==2){console.error('BUG');process.exit(1)}");
50
+ fs.writeFileSync(path.join(codeProject,'existing.mjs'),"import {value} from './value.mjs';if(typeof value!=='number')process.exit(1)");
51
+ fs.writeFileSync(path.join(codeProject,'.cm-workflow.json'),JSON.stringify({version:1,policies:{delivery:'diff'}}));
52
+ const authority=createHostReviewAuthority({hostContextId:'parent-host',reviewerId:'reviewer',adapterId:'codex-review-adapter',
53
+ decide:async()=>({status:'approved'})});
54
+ const execution={configuration:{kind:'synthetic-parent'},timeoutMs:2000,excludedContexts:['parent-host'],hostDecision:null,
55
+ hostDecisionProvider:authority.hostDecisionProvider,
56
+ developer:{provider:'codex',requestedModel:'synthetic',contextId:'author',run:createCodexDeveloperRun({requestedModel:'synthetic',worker:async()=>{
57
+ fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=1;');
58
+ return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
59
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};}})},
60
+ reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic',allowed:true,available:true,
61
+ contexts:['parent-review-1','parent-review-2'],run:async(request,{onEvent})=>{
62
+ events(onEvent,`synthetic-review-${request.identity.runId}`);
63
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:request.payload.reviewPackage.packageDigest,
64
+ examinedPaths:reviewPaths(request.payload.reviewPackage),findings:[],summary:'Synthetic review'}};}}],
65
+ reviewInvocation:{developerThreadId:'author',excludedThreadIds:['parent-host'],authorize:authority.authorize},
66
+ check:createHostCheck({cwd:codeProject,commands:[{id:'existing',command:[process.execPath,'existing.mjs']}]}),
67
+ qaLogHome:path.join(root,'logs'),qaDecisionProvider:{timeoutMs:1000,decide:async binding=>({decisionId:`qa-${binding.identity.runId}`,
68
+ identity:binding.identity,packageDigest:binding.packageDigest,status:'triggered',reason:'feature_complete',score:null,at:'2026-10-08T01:00:00Z'})},
69
+ qaExecutor:{mode:'commands',caseCount:1,timeoutMs:1000,run:async binding=>{
70
+ const report=path.join(specsDir,'.reviews',`${binding.testRunId}.md`);fs.writeFileSync(report,'Synthetic QA PASS');
71
+ return {result:'PASS',passed:1,failed:0,blocked:0,report};}},
72
+ applicableAgentFiles:[],documentationProvider:{timeoutMs:1000,inspect:async binding=>({
73
+ syncId:binding.syncId,identity:binding.identity,packageDigest:binding.packageDigest,contextDigest:binding.contextDigest,
74
+ status:'completed',reason:'Synthetic documentation unchanged',at:'2026-10-08T02:00:00Z'})}};
75
+ const identity={repositoryId:'fixture',runId:'parent-run',taskId:'T-001',attempt:1};
76
+ const definition={version:1,specsDir,codeProject,feature:'1.value',identity,scope:['value.mjs'],requirements:['requirements.md']};
77
+ const parent=await openControlRun(definition,'create',execution);
78
+ try{assert.equal((await parent.host.handle({version:1,requestId:'first',operation:'advance',identity})).code,'run_done');}
79
+ finally{parent.close();}
80
+
81
+ const fixIdentity={repositoryId:'fixture',runId:'story-fix',taskId:'T-FIX-story-fix',attempt:1};
82
+ const permissions=['--allow-reproduction','--allow-red-test','--allow-baseline','--allow-repair','--allow-regression','--allow-final-review','--allow-walkthrough','--allow-finish'];
83
+ const review={model:'synthetic',disabledSkills:[],preflight:{passed:true,cli_model:'synthetic',prompt_transport:'stdin',
84
+ config_fingerprint:configFingerprint({cwd:codeProject,model:'synthetic',disabledSkills:[]})}};
85
+ let reviews=0;
86
+ const reviewHost=createFixReviewHost({codeProject,hostContextId:'fix-host',review,permissions,workerFactory:()=>async({prompt},{onEvent})=>{
87
+ reviews++;const data=JSON.parse(prompt.split('<cm-review-data-json>\n')[1]);events(onEvent,`synthetic-fix-review-${reviews}`);
88
+ return {status:'succeeded',value:{verdict:'approved',packageDigest:data.reviewPackage.packageDigest,examinedPaths:data.examinedPaths,
89
+ findings:[],summary:'Synthetic independent fix review'}};}});
90
+ const config={identity:fixIdentity,defect:'Value must be 2',
91
+ reproduction:{cwd:codeProject,command:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000},
92
+ redTest:{cwd:codeProject,testFiles:['red.mjs'],command:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000},
93
+ baseline:{cwd:codeProject,testFiles:['existing.mjs'],commands:[{id:'existing',command:[process.execPath,'existing.mjs']}],timeoutMs:2000},
94
+ repair:{scope:['value.mjs'],requirements:['requirements.md']},
95
+ walkthrough:{timeoutMs:2000,flows:[{id:'value',modules:['value'],steps:['Read value'],expected:['2'],kind:'commands',command:[process.execPath,'red.mjs']}]}};
96
+ const configuration={hostContextId:'fix-host',...config,causeReview:reviewHost.reviewer};delete configuration.identity;
97
+ const learning={contextDigest:digest([]),files:[],application:{contextDigest:digest([]),status:'no_relevant_lesson',summary:'No fixture instructions'}};
98
+ const bridge={async call(kind){
99
+ if(kind==='fix_diagnose')return {status:'diagnosed',rootCause:'Wrong constant',plan:'Change 1 to 2',affectedPaths:['value.mjs'],
100
+ affectedModules:['value'],crossLayer:false,investigation:{discardedAlternatives:[],boundaryAnalysis:null}};
101
+ if(kind==='fix_repair'){fs.writeFileSync(path.join(codeProject,'value.mjs'),'export const value=2;');return {outcome:'repaired'};}
102
+ if(kind==='fix_retrospective')return {status:'no_new_lesson',candidates:[],reason:null};
103
+ throw Error(kind);
104
+ }};
105
+ const owner=openFixExecution({specsRoot:specsDir,identity:fixIdentity,configuration,create:true},{...reviewHost.execution,bridge,prepare:async()=>learning});
106
+ try{
107
+ const host=createFixHost({owner,config:{...config,specsRoot:specsDir},permissions,authority:reviewHost.authority,finalAuthority:reviewHost.finalAuthority});
108
+ for(const operation of ['advance','red_test','baseline','repair','regression','retrospective','handoff','final_review','publish_review',
109
+ 'check_n5','post_review_regression','walkthrough',...(finish?['finish']:[])]){
110
+ const result=await host.handle({requestId:operation,operation});assert(!result?.error,`${operation}: ${JSON.stringify(result)}`);
111
+ }
112
+ assert.equal(owner.status().stage,finish?'completed':'closeout_required');
113
+ }finally{owner.close();}
114
+ assert(reviews>=1);
115
+ const status=async()=>{const run=await openControlRun(definition,'resume',execution);
116
+ try{return await run.host.handle({version:1,requestId:`status-${Math.random()}`,operation:'status',identity});}finally{run.close();}};
117
+ return {codeProject,specsDir,identity,status};
118
+ }
119
+
120
+ test('a completed, independently reviewed cm-fix run is a later reviewed delivery; an unreviewed edit is still refused',{timeout:120000},async()=>{
121
+ const {codeProject,specsDir,identity,status}=await completedTaskThenFix({finish:true});
122
+ const deliveries=completedReviewedDeliveries({specsRoot:specsDir,root:codeProject,identity});
123
+ assert.deepEqual(deliveries.map(item=>[item.runId,item.taskId,item.packages.map(entry=>entry.pkg.changes.map(change=>change.path))]),
124
+ [['story-fix','T-FIX-story-fix',[['value.mjs']]]]);
125
+ assert(Number.isSafeInteger(deliveries[0].packages[0].reviewedAt));
126
+ const accepted=await status();
127
+ assert.equal(accepted.state,'fixture_completed');assert.equal(accepted.code,null,JSON.stringify(accepted));
128
+ fs.writeFileSync(path.join(codeProject,'existing.mjs'),"import {value} from './value.mjs';if(value!==2)process.exit(1)");
129
+ const refused=await status();
130
+ assert.equal(refused.code,'correction_review_required');assert.equal(refused.reason,'未经审查的改动:existing.mjs');
131
+ });
132
+
133
+ test('a cm-fix run that has not reached its normal completed closeout is not a reviewed delivery',{timeout:120000},async()=>{
134
+ const {codeProject,specsDir,identity,status}=await completedTaskThenFix({finish:false});
135
+ assert.deepEqual(completedReviewedDeliveries({specsRoot:specsDir,root:codeProject,identity}),[]);
136
+ const refused=await status();
137
+ assert.equal(refused.code,'correction_review_required');assert.equal(refused.reason,'未经审查的改动:value.mjs');
138
+ });