@aibyzero/cm-workflow 0.16.5 → 0.16.6

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 (177) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +14 -0
  3. package/CHANGELOG.md +7 -0
  4. package/README.md +11 -4
  5. package/THIRD_PARTY_NOTICES.md +9 -0
  6. package/VERSION +1 -1
  7. package/docs/architecture.md +43 -0
  8. package/docs/execution-optimizations.md +33 -0
  9. package/docs/external-models.md +114 -0
  10. package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
  11. package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
  12. package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
  13. package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
  14. package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
  15. package/docs/human-correction.md +31 -0
  16. package/docs/installation.md +28 -7
  17. package/docs/js-workflow-control.md +48 -0
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/untested-branches.md +27 -4
  21. package/docs/user-guide.md +23 -8
  22. package/install-codex.sh +28 -11
  23. package/package.json +1 -1
  24. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  25. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  26. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +79 -20
  27. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +1 -4
  28. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
  29. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  30. package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
  31. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  32. package/runtime/js/cm-ai/drive-bootstrap.mjs +20 -10
  33. package/runtime/js/cm-ai/drive-core.mjs +9 -3
  34. package/runtime/js/cm-ai/durable-runner-state.mjs +117 -14
  35. package/runtime/js/cm-ai/effect-contract.mjs +1 -1
  36. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  37. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  38. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  39. package/runtime/js/cm-ai/external-models.mjs +52 -0
  40. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  41. package/runtime/js/cm-ai/host-bootstrap.mjs +70 -20
  42. package/runtime/js/cm-ai/host-check.mjs +30 -4
  43. package/runtime/js/cm-ai/host-conversation-execution.mjs +50 -16
  44. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  45. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  46. package/runtime/js/cm-ai/host-qa-executor.mjs +2 -2
  47. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
  48. package/runtime/js/cm-ai/host-session.mjs +1 -1
  49. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
  50. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  51. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  52. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  53. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  54. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  55. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  56. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  57. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  58. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  59. package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
  60. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  61. package/runtime/js/cm-ai/review-package.mjs +11 -0
  62. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  63. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  64. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  65. package/runtime/js/cm-ai/task-runner.mjs +171 -25
  66. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  67. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  68. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  69. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  70. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  71. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  72. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  73. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  74. package/runtime/js/cm-fix/execution.mjs +183 -40
  75. package/runtime/js/cm-fix/final-review.mjs +18 -10
  76. package/runtime/js/cm-fix/host-review.mjs +25 -6
  77. package/runtime/js/cm-fix/host.mjs +4 -1
  78. package/runtime/js/cm-fix/layout.mjs +1 -1
  79. package/runtime/js/cm-fix/progress.mjs +4 -0
  80. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  81. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  82. package/runtime/js/cm-prd/review-publication.mjs +23 -13
  83. package/runtime/js/cm-prd/review-time.mjs +29 -0
  84. package/runtime/js/cm-prd/session.mjs +53 -6
  85. package/runtime/js/cm-security/finalize.mjs +32 -0
  86. package/runtime/review.md +5 -0
  87. package/runtime/task-gates.md +6 -0
  88. package/runtime/workflow-config.md +10 -1
  89. package/scripts/cm-ai-batch-drive.mjs +50 -21
  90. package/scripts/cm-ai-batch-drive.test.mjs +47 -2
  91. package/scripts/cm-ai-batch-host.mjs +37 -14
  92. package/scripts/cm-ai-batch-run.mjs +71 -27
  93. package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
  94. package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
  95. package/scripts/cm-ai-bootstrap.test.mjs +80 -87
  96. package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
  97. package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
  98. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
  99. package/scripts/cm-ai-drive.mjs +59 -25
  100. package/scripts/cm-ai-drive.test.mjs +97 -1
  101. package/scripts/cm-ai-host.mjs +64 -24
  102. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  103. package/scripts/cm-ai-progress.test.mjs +521 -0
  104. package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
  105. package/scripts/cm-ai-review-failure.test.mjs +71 -11
  106. package/scripts/cm-ai-run.mjs +58 -14
  107. package/scripts/cm-ai-run.test.mjs +2 -1
  108. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  109. package/scripts/cm-check-drive.test.mjs +1 -0
  110. package/scripts/cm-check-runtime.sh +11 -0
  111. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  112. package/scripts/cm-claude-probe.test.mjs +1 -1
  113. package/scripts/cm-codex-plugin-metadata.py +83 -0
  114. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  115. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  116. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  117. package/scripts/cm-efficiency-offline.mjs +35 -0
  118. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  119. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  120. package/scripts/cm-efficiency-response.test.mjs +117 -0
  121. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  122. package/scripts/cm-external-batch-host.test.mjs +157 -0
  123. package/scripts/cm-external-fix-host.test.mjs +281 -0
  124. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  125. package/scripts/cm-external-group-models.test.mjs +60 -0
  126. package/scripts/cm-external-model-host.test.mjs +180 -0
  127. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  128. package/scripts/cm-external-models.test.mjs +89 -0
  129. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  130. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  131. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  132. package/scripts/cm-fix-drive.mjs +28 -13
  133. package/scripts/cm-fix-final-review.test.mjs +11 -6
  134. package/scripts/cm-fix-host.mjs +17 -10
  135. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  136. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  137. package/scripts/cm-fix-review-budget.test.mjs +7 -1
  138. package/scripts/cm-host-qa-executor.test.mjs +21 -0
  139. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  140. package/scripts/cm-live-evidence.test.mjs +64 -0
  141. package/scripts/cm-log-event.mjs +8 -2
  142. package/scripts/cm-log-event.py +15 -0
  143. package/scripts/cm-model-setup.mjs +79 -0
  144. package/scripts/cm-prd-drive.mjs +32 -11
  145. package/scripts/cm-prd-drive.test.mjs +15 -0
  146. package/scripts/cm-prd-host.mjs +13 -4
  147. package/scripts/cm-release-smoke.sh +5 -1
  148. package/scripts/cm-runtime-i18n.mjs +15 -4
  149. package/scripts/cm-runtime-install.mjs +8 -4
  150. package/scripts/cm-runtime.mjs +116 -23
  151. package/scripts/cm-runtime.test.mjs +121 -12
  152. package/scripts/cm-security.test.mjs +32 -0
  153. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  154. package/scripts/cm-task-gate.mjs +146 -10
  155. package/scripts/cm-task-gate.py +1 -0
  156. package/scripts/cm-test-drive.mjs +10 -4
  157. package/scripts/cm-test-drive.test.mjs +14 -1
  158. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  159. package/scripts/cm-usage-report.py +22 -3
  160. package/scripts/cm-workflow-config.mjs +10 -1
  161. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  162. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  163. package/scripts/fixtures/process-cleanup.mjs +3 -1
  164. package/scripts/test-cm-native-usage.py +62 -0
  165. package/scripts/test-external-model-setup.py +91 -0
  166. package/scripts/test-model-configuration-write.py +201 -0
  167. package/scripts/test-npm-install.py +10 -1
  168. package/skills/cm-ai/SKILL.md +2 -2
  169. package/skills/cm-ai/references/N8-finish.md +5 -0
  170. package/skills/cm-ai/references/js-host.md +13 -5
  171. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  172. package/skills/cm-fix/SKILL.md +1 -1
  173. package/skills/cm-fix/references/js-host.md +30 -2
  174. package/skills/cm-runtime/SKILL.md +29 -6
  175. package/skills/cm-security/SKILL.md +4 -2
  176. package/skills/cm-security/references/scan-contract.md +1 -0
  177. package/templates/cm-workflow.yml +1 -1
@@ -7,7 +7,7 @@ import {captureReviewBaseline,createReviewPackage} from '../runtime/js/cm-ai/rev
7
7
  import {createHostHandoff} from '../runtime/js/cm-ai/host-handoff.mjs';
8
8
  import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authority.mjs';
9
9
  import {createCodexReviewRun} from '../runtime/js/cm-ai/codex-review-adapter.mjs';
10
- import {createFixFinalReview,inspectFixFinalResult,inspectFixRepairReview,fixRevisionReviewConfiguration} from '../runtime/js/cm-fix/final-review.mjs';
10
+ import {createFixFinalReview,inspectFixFinalResult,inspectFixRepairReview,fixRevisionReviewConfiguration,fixFinalReviewConfiguration} from '../runtime/js/cm-fix/final-review.mjs';
11
11
  import {prepareFixRepair} from '../runtime/js/cm-fix/repair.mjs';
12
12
  import {createFixRedTest} from '../runtime/js/cm-fix/red-test.mjs';
13
13
  import {createFixBaseline} from '../runtime/js/cm-fix/baseline.mjs';
@@ -25,10 +25,15 @@ test('final review uses existing grant, prompt and normalized inspection without
25
25
  const handoffPath=path.join(temp,'fix-demo-T-FIX-demo-a1-handoff.json');
26
26
  createHostHandoff({root,baseline,checks,handoffPath,evidence:['learning: no_relevant_lesson','learning: retrospective no_new_lesson']});
27
27
  const pkg=createReviewPackage({root,baseline,checks,handoffPath});
28
- for(const mode of ['approved','changes_requested','denied','excluded','lost','timeout']){
28
+ for(const mode of ['approved','changes_requested','denied','excluded','excluded-prior-cause','excluded-revised-cause','lost','timeout']){
29
29
  const reviewer={reviewerId:'final-reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic',contextId:'logical-review',excludedThreadIds:mode==='excluded'?['actual-review']:mode==='changes_requested'?[...Array.from({length:32},(_,index)=>`configured-${index}`),'cause-reviewer']:[]};
30
- const configuration={hostContextId:'actual-host',reviewer};let registered=null,started=null,calls=0;
31
- const authority=createHostReviewAuthority({hostContextId:configuration.hostContextId,reviewerId:reviewer.reviewerId,adapterId:reviewer.adapterId,
30
+ const configuration=['changes_requested','excluded-prior-cause','excluded-revised-cause'].includes(mode)
31
+ ?fixFinalReviewConfiguration({hostContextId:'actual-host',causeReview:{...reviewer,
32
+ excludedThreadIds:mode==='changes_requested'?Array.from({length:32},(_,index)=>`configured-${index}`):[]}},
33
+ mode==='excluded-prior-cause'?['actual-review','revised-cause']:
34
+ mode==='excluded-revised-cause'?['prior-cause','actual-review']:['prior-cause','revised-cause'])
35
+ :{hostContextId:'actual-host',reviewer};let registered=null,started=null,calls=0;
36
+ const authority=createHostReviewAuthority({hostContextId:configuration.hostContextId,reviewerId:configuration.reviewer.reviewerId,adapterId:configuration.reviewer.adapterId,
32
37
  decide:async()=>mode==='denied'?{status:'denied',code:'permission_denied'}:{status:'approved'}});
33
38
  await authority.hostDecisionProvider.decide({identity,packageDigest:pkg.packageDigest},new AbortController().signal);
34
39
  const run=createCodexReviewRun(async({prompt},{onEvent})=>{
@@ -77,7 +82,7 @@ test('final review uses existing grant, prompt and normalized inspection without
77
82
  const nextPackage=createReviewPackage({root,baseline:nextBaseline,checks,handoffPath:nextHandoff});
78
83
  const nextConfiguration=fixRevisionReviewConfiguration(feedback,next);
79
84
  assert(nextConfiguration.reviewer.excludedThreadIds.includes('actual-review'));
80
- assert.equal(nextConfiguration.reviewer.excludedThreadIds.length,34);
85
+ assert.equal(nextConfiguration.reviewer.excludedThreadIds.length,35);
81
86
  for(const thread of ['actual-review','fresh-second-review']){
82
87
  await authority.hostDecisionProvider.decide({identity:next,packageDigest:nextPackage.packageDigest},signal);
83
88
  const nextRun=createFixFinalReview({reviewPackage:nextPackage,configuration:nextConfiguration,timeoutMs:2000},{authorize:authority.authorize,run:async(request,{onEvent})=>{
@@ -113,7 +118,7 @@ test('final review uses existing grant, prompt and normalized inspection without
113
118
  assert.equal(result.inspection.completionEligible,false);
114
119
  }
115
120
  if(mode==='denied'){assert.equal(calls,0);assert.equal(registered,null);}
116
- if(mode==='excluded')assert.equal(started,null);
121
+ if(mode.startsWith('excluded'))assert.equal(started,null);
117
122
  if(mode==='timeout'){
118
123
  assert.equal(result.reason,'timeout');
119
124
  assert.deepEqual(result.diagnostic,{phase:'transport',code:'timeout'});
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // Opt-in fix stages; cause review dispatch needs explicit launch authority and matching diagnostics.
3
+ import {readFixExecutionPolicy} from '../runtime/js/cm-ai/execution-policy.mjs';
4
+ import {readFixExternalModels} from '../runtime/js/cm-ai/external-group-models.mjs';
3
5
  import fs from 'node:fs';
4
6
  import {fileURLToPath} from 'node:url';
5
7
  import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
@@ -11,14 +13,16 @@ import {id,json,need,shape,digest} from '../runtime/js/cm-ai/effect-contract.mjs
11
13
  import {readConversationReviewConfiguration} from './cm-ai-host.mjs';
12
14
  import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
13
15
 
14
- const usage='cm-fix-host.mjs serve --config PATH --mode create|resume --host-context ID --allow-reproduction [--original-host-context ID] [--runtime codex|claude] [--input-limit BYTES] [--review-config PATH] [--allow-cause-review] [--allow-final-review] [--allow-test-author] [--allow-red-test] [--allow-baseline] [--allow-repair] [--allow-regression] [--allow-learning-writeback]\nCodex or Claude current-host operations: prepare_revision, revision_test_check, advance, cause_review_package, cause_review, author_tests, red_test, baseline, repair, regression, retrospective, learning_writeback, handoff, final_review_package, final_review, publish_review, check_n5, post_review_regression, status, cancel. Runtime defaults to codex; claude uses its own matching diagnostic receipt and cannot reuse Codex preflight or disabledSkills settings. Runtime selection is bound to recovery; switching providers requires a separate run. This selects existing adapters, not permission to call them. Each write/check needs its respective launch flag and configuration. Test authoring, repair, cause and final review dispatch require matching existing stdin diagnostics; diagnostic alone is not authorization. Passing regression stops at handoff_required. The read-only retrospective operation yields handoff_ready or learning_writeback_required. learning_writeback requires its own flag, preserves project instructions and includes AGENTS.md in the review scope; it does not authorize provider calls. handoff publishes the fixed specs-local handoff with Learning evidence and moves to final_review_required; no provider is called and no task is completed. final_review_package is read-only and returns the final content-bound review package. final_review requires its own flag and matching diagnostics; observations do not complete the task. publish_review projects the registered result into the existing review file; it does not dispatch or complete tasks. check_n5 runs the original Learning-aware gate; post_review_regression requires --allow-regression and reaches closeout_required, not completion.';
16
+ const usage='cm-fix-host.mjs serve --config PATH --mode create|resume --host-context ID --allow-reproduction [--original-host-context ID] [--execution-optimizations] [--external-models [--external-models-config PATH]] [--runtime codex|claude] [--input-limit BYTES] [--review-config PATH] [--allow-cause-review] [--allow-rediagnosis] [--allow-final-review] [--allow-test-author] [--allow-red-test] [--allow-baseline] [--allow-repair] [--allow-regression] [--allow-learning-writeback]\nCodex or Claude current-host operations: rediagnose, prepare_revision, revision_test_check, advance, cause_review_package, cause_review, author_tests, red_test, baseline, repair, regression, retrospective, learning_writeback, handoff, final_review_package, final_review, publish_review, check_n5, post_review_regression, status, cancel. Runtime defaults to codex; claude uses its own matching diagnostic receipt and cannot reuse Codex preflight or disabledSkills settings. Runtime selection is bound to recovery; switching providers requires a separate run. This selects existing adapters, not permission to call them. Each write/check needs its respective launch flag and configuration. Test authoring, repair, cause and final review dispatch require matching existing stdin diagnostics; diagnostic alone is not authorization. Passing regression stops at handoff_required. The read-only retrospective operation yields handoff_ready or learning_writeback_required. learning_writeback requires its own flag, preserves project instructions and includes AGENTS.md in the review scope; it does not authorize provider calls. handoff publishes the fixed specs-local handoff with Learning evidence and moves to final_review_required; no provider is called and no task is completed. final_review_package is read-only and returns the final content-bound review package. final_review requires its own flag and matching diagnostics; observations do not complete the task. publish_review projects the registered result into the existing review file; it does not dispatch or complete tasks. check_n5 runs the original Learning-aware gate; post_review_regression requires --allow-regression and reaches closeout_required, not completion.';
15
17
 
16
18
  export async function main(argv=process.argv.slice(2),{input=process.stdin,output=process.stdout,error=process.stderr,reviewWorkerFactory=null}={}){
19
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Optional --execution-optimizations freezes policy v1 for new runs only; recovery retains the original policy and legacy runs reject retrofit. See docs/execution-optimizations.md.\n');
17
20
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Design-change escalation: approved cause_review reaches design_change_required when redTest is configured (test_author_required first if needed); author_tests/red_test keep their original flags and evidence checks. Confirmed red reaches escalation_required, never baseline/repair/regression. Non-visual runs without redTest reach escalation_required directly after approval and record why no failing test exists. Visual runs require a matching visual redTest with testFiles:[] and must complete the visual red step before escalation; opening without it fails with fix_visual_configuration_required. publish_dossier saves an 升级立项 dossier; finish requires --allow-finish, records run_done phase escalation/result escalated and closes the owner with escalationRunEnded:true. Retained tests become acceptance checks for the suggested $cm-prd --change. Resume the same run after a crash; conflicting exits fail with fix_escalation_exit_conflict. Terminal escalated is not completed: no task_done, metrics, repair or parent QA completion.\n');
18
21
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Omit specsRoot or use null for a bare project: the same owner stores archives in docs/fixes and reviews in docs/fixes/.reviews, uses the original no-specs log mode, and skips METRICS. No specs skeleton is created. Visual-only reproduction/redTest may use kind:visual with cwd, timeoutMs, before:{path,sha256,kind:screenshot|video,description}, reason explaining why automated red cannot be written, environment, steps and expected; redTest also has testFiles:[]. No testAuthor or fake red/green command. Repair/regression/review/finish permissions remain mandatory. qa_browser returns actual after carrier metadata; missing evidence blocks.\n');
19
- if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Optional startup configuration protectSpecs:true uses the existing Codex native sandbox for reproduction, red/baseline/regression/walkthrough commands and fixed text edits, without a model call. Requires the local sandbox executable; it does not change the current Codex/Claude host or reviewer identity. Original action permissions remain required. fix_test_author/fix_repair with editMode=protected-text-v1 require {outcome,edits:[{path,beforeSha256,content}]} using the supplied scope/expected hashes; never write directly. Content is full UTF-8 text or null for deletion, blocked requires edits:[]. Original 64KiB response limit applies. Drift or failed writes retain the original unknown boundary; no automatic retry/rollback or protection-mode switching on resume.\n');
22
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Optional startup configuration protectSpecs:true uses the existing Codex native sandbox for reproduction, red/baseline/regression/walkthrough commands and fixed text edits, without a model call. Requires the local sandbox executable; it does not change the current Codex/Claude host or reviewer identity. Original action permissions remain required. fix_test_author/fix_repair with editMode=protected-text-v1 require {outcome,edits:[{path,beforeSha256,content}]} using the supplied scope/expected hashes; never write directly. Content is full UTF-8 text or null for deletion, blocked requires edits:[]. Default 64KiB response limit applies; --input-limit may explicitly raise transport to 4MiB, while protected text proposal limits remain 1MiB. Drift or failed writes retain the original unknown boundary; no automatic retry/rollback or protection-mode switching on resume.\n');
20
23
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('completion_evidence is read-only and available only after the original finish has completed and current evidence still validates. It returns the selected attempt, original reviewed package, handoff/review digests, completion event IDs and optional qaSource from the original owner. It does not complete or resume a parent task; JSON evidence alone is not authority.\n');
21
24
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('recover_final_review requires --allow-final-review-recovery and exact latest invocationId/packageDigest, previousInvocationStopped:true, and a nonempty reason. The legacy first continuation remains once-only. A further continuation additionally requires a fresh startup --final-review-recovery-invocation ID matching the latest unknown invocation, authorizing exactly one new call. Confirm the previous process stopped; this is a trusted host acknowledgment, not an automatic liveness check. Preparation dispatches nothing. Later final_review requires recovery permission and --allow-final-review; additional cycles require the same invocation binding after restart. Old records, task attempt, reviewed package and the original Review/N5/finish remain unchanged. No automatic retry, cancelled/complete-verdict recovery, missing-thread recovery, business-revision recovery or source-drift bypass. status adds a read-only progress projection, not authorization or current-source verification.\n');
25
+ if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('rediagnose requires --allow-rediagnosis, the original resumed run at rediagnosis_required and a nonempty single-line reason up to 1000 UTF-8 bytes. It appends one history-bound diagnosis without repeating reproduction or overwriting cause-r1. A fresh cause review must publish cause-r2 even for a revised single-layer cause. Second rejection reaches rediagnosis_review_limit_reached. Interrupted rediagnosis or its review is not automatically retried or abandoned. Standalone only.\n');
22
26
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('abandon_step requires --allow-abandon, stage unknown, an eligible local pending kind, and a nonempty single-line reason up to 1000 UTF-8 bytes. It records the abandoned intent and returns to the required stage; a later separate action redoes the step. At most eight abandonments per run. Review, Learning writeback and handoff remain unavailable.\n');
23
27
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('abandon_review requires its own --allow-abandon-review flag (not --allow-abandon) and the same reason rules. Each run may abandon the cause review once and the second-round final review once, only while that registered review has no review result (interrupted, timed out, disconnected or cancelled); confirm the old reviewer stopped first. It records the abandoned invocation and returns to the review stage; the retry needs the original review flag, a fresh grant and a new reviewer thread. Reviews wait for the review configuration timeoutMs (default 900000), not the reproduction timeout.\n');
24
28
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('N6 child configuration may include qaSource {feature, identity, packageDigest, testRunId, handoffDigest}; derive the separate fixed child identity with qaFixIdentity. It requires --allow-qa-fix in addition to existing action flags. Close the parent host first: the original specs-wide owner lock is shared. Creation/resume rechecks the current failed round, project, report and policy; the source is bound to the original fix configuration. This does not resume the parent or automatically rerun QA, and does not authorize provider calls, installation or Git.\n');
@@ -32,8 +36,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
32
36
  need(['create','resume'].includes(argv[4]),'invalid_arguments');id(argv[6]);
33
37
  const extra=new Map();
34
38
  for(let index=8;index<argv.length;index++){
35
- const flag=argv[index];need(!extra.has(flag)&&['--runtime','--input-limit','--review-config','--original-host-context','--final-review-recovery-invocation','--allow-qa-fix','--allow-cause-review','--allow-final-review','--allow-final-review-recovery','--allow-abandon','--allow-abandon-review','--allow-red-test','--allow-baseline','--allow-test-author','--allow-repair','--allow-regression','--allow-learning-writeback','--allow-walkthrough','--allow-finish'].includes(flag),'invalid_arguments');
36
- if(flag.startsWith('--allow-'))extra.set(flag,true);
39
+ const flag=argv[index];need(!extra.has(flag)&&['--execution-optimizations','--external-models','--external-models-config','--runtime','--input-limit','--review-config','--original-host-context','--final-review-recovery-invocation','--allow-qa-fix','--allow-rediagnosis','--allow-cause-review','--allow-final-review','--allow-final-review-recovery','--allow-abandon','--allow-abandon-review','--allow-red-test','--allow-baseline','--allow-test-author','--allow-repair','--allow-regression','--allow-learning-writeback','--allow-walkthrough','--allow-finish'].includes(flag),'invalid_arguments');
40
+ if(flag.startsWith('--allow-')||flag==='--external-models'||flag==='--execution-optimizations')extra.set(flag,true);
37
41
  else{need(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments');extra.set(flag,argv[++index]);}
38
42
  }
39
43
  // A run created in an earlier session keeps that session in its durable record.
@@ -46,10 +50,7 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
46
50
  const runtime=extra.get('--runtime')??'codex';need(['codex','claude'].includes(runtime),'invalid_runtime');
47
51
  // Transport only, like the cm-ai hosts: lines and tool replies share one limit.
48
52
  const inputLimit=parseHostInputLimit(extra.get('--input-limit'));
49
- const review=extra.has('--review-config')?readConversationReviewConfiguration(extra.get('--review-config')):null;
50
- need(runtime!=='claude'||!review||review.disabledSkills.length===0,'invalid_review_config');
51
- need(!extra.has('--allow-cause-review')||review!==null,'review_configuration_required');
52
- need(!extra.has('--allow-final-review')||review!==null,'review_configuration_required');
53
+ let review;
53
54
  const stat=fs.lstatSync(argv[2]);
54
55
  need(stat.isFile()&&!stat.isSymbolicLink()&&stat.size<=64*1024,'invalid_fix_config');
55
56
  const config=json(JSON.parse(fs.readFileSync(argv[2],'utf8')),64*1024);
@@ -58,6 +59,12 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
58
59
  ...(Object.hasOwn(config,'qaSource')?['qaSource']:[]),
59
60
  ...(Object.hasOwn(config,'redTest')?['redTest']:[]),...(Object.hasOwn(config,'baseline')?['baseline']:[]),
60
61
  ...(Object.hasOwn(config,'testAuthor')?['testAuthor']:[]),...(Object.hasOwn(config,'repair')?['repair']:[]),...(Object.hasOwn(config,'walkthrough')?['walkthrough']:[])]);
62
+ const executionPolicy=readFixExecutionPolicy({config,mode:argv[4],enabled:extra.has('--execution-optimizations')});
63
+ const externalModels=readFixExternalModels({config,mode:argv[4],enabled:extra.has('--external-models'),inputFile:extra.get('--external-models-config'),runtime});
64
+ review=extra.has('--review-config')?readConversationReviewConfiguration(extra.get('--review-config'),externalModels?.providers[runtime]??null):null;
65
+ need(runtime!=='claude'||!review||review.disabledSkills.length===0,'invalid_review_config');
66
+ need(!extra.has('--allow-cause-review')||review!==null,'review_configuration_required');
67
+ need(!extra.has('--allow-final-review')||review!==null,'review_configuration_required');
61
68
  need(!extra.has('--allow-walkthrough')||config.walkthrough,'walkthrough_configuration_required');
62
69
  need(!Object.hasOwn(config,'qaSource')||extra.has('--allow-qa-fix'),'qa_fix_authorization_required');
63
70
  need(!extra.has('--allow-qa-fix')||Object.hasOwn(config,'qaSource'),'qa_fix_source_required');
@@ -68,11 +75,11 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
68
75
  need(!extra.has('--allow-regression')||(config.repair&&config.redTest&&config.baseline),'regression_configuration_required');
69
76
  const {reviewer,authority,finalAuthority,execution:reviewExecution}=createFixReviewHost({
70
77
  codeProject:config.reproduction.cwd,hostContextId:argv[6],runtime,review,
71
- permissions:[...extra.keys()],workerFactory:reviewWorkerFactory});
78
+ permissions:[...extra.keys()],workerFactory:reviewWorkerFactory,externalModels,executionPolicy,specsDir:config.specsRoot??null});
72
79
  bridge=createHostToolBridge({responseLimit:inputLimit});
73
80
  owner=openFixExecution({specsRoot:config.specsRoot??null,identity:config.identity,create:argv[4]==='create',
74
81
  hostContextId:argv[6],
75
- configuration:{hostContextId:originalHostContext??argv[6],defect:config.defect,reproduction:config.reproduction,
82
+ configuration:{...(executionPolicy?{executionPolicy}:{}),...(externalModels?{externalModels}:{}),hostContextId:originalHostContext??argv[6],defect:config.defect,reproduction:config.reproduction,
76
83
  ...(Object.hasOwn(config,'protectSpecs')?{protectSpecs:config.protectSpecs}:{}),
77
84
  ...(Object.hasOwn(config,'qaSource')?{qaSource:config.qaSource}:{}),
78
85
  ...(runtime==='claude'?{runtime}:{}),
@@ -52,3 +52,15 @@ test('protected test-author response uses native edits and rejects late bytes, w
52
52
  await assert.rejects(bridge.call('fix_test_author',payload,controller.signal),{code:'cancelled'});
53
53
  }finally{fs.rmSync(cwd,{recursive:true,force:true});}
54
54
  });
55
+
56
+ // Real protected bridge and native sandbox, not just the file helper.
57
+ test('protected bridge commits a lock-sized text proposal above 64KiB',async()=>{
58
+ const cwd=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-edit-large-'))),specsRoot=path.join(cwd,'specs');
59
+ fs.mkdirSync(specsRoot);
60
+ const content=JSON.stringify({lockfileVersion:3,fixture:'x'.repeat(640000)});
61
+ const bridge=protectedFixBridge({cwd,specsRoot,timeoutMs:10000,bridge:{call:async(kind,payload)=>({outcome:'repaired',edits:[{path:'package-lock.json',beforeSha256:payload.expected['package-lock.json'],content}]})}});
62
+ try{
63
+ await bridge.call('fix_repair',{identity:{repositoryId:'test',runId:'large-edits',taskId:'T-FIX-large',attempt:1},codeProject:cwd,scope:['package-lock.json'],instructions:'Synthetic lock.'},new AbortController().signal);
64
+ assert.equal(fs.readFileSync(path.join(cwd,'package-lock.json'),'utf8'),content);
65
+ }finally{fs.rmSync(cwd,{recursive:true,force:true});}
66
+ });
@@ -0,0 +1,168 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
7
+ import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authority.mjs';
8
+ import {createCauseReviewRun} from '../runtime/js/cm-ai/codex-review-adapter.mjs';
9
+ import {createFixHost} from '../runtime/js/cm-fix/host.mjs';
10
+ import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
11
+ import {PassThrough,Writable} from 'node:stream';
12
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
13
+ import {preflight} from './cm-fix-drive.mjs';
14
+ import {spawnSync} from 'node:child_process';
15
+
16
+ async function fixture(t,fn,{secondVerdict='approved',secondThread='fresh-review-2',prepare=null,redTest=false}={}){
17
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-rediagnosis-')));
18
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
19
+ const code=path.join(root,'code'),specsRoot=path.join(root,'specs');fs.mkdirSync(code);fs.mkdirSync(specsRoot);
20
+ fs.writeFileSync(path.join(code,'value.mjs'),'export const value=1;');
21
+ const identity={repositoryId:'fixture',runId:'rediagnosis-run',taskId:'T-FIX-rediagnosis',attempt:1};
22
+ const reviewer={reviewerId:'cause-reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic',contextId:'independent-review',excludedThreadIds:[]};
23
+ const options={specsRoot,identity,create:true,configuration:{hostContextId:'fixture-host',defect:'Fixture mismatch',causeReview:reviewer,
24
+ reproduction:{cwd:code,command:[process.execPath,'-e',"require('node:fs').appendFileSync('visits','1');process.stderr.write('BUG');process.exit(3)"],expectedFailure:{exitCode:3,outputIncludes:'BUG'},timeoutMs:1000}}};
25
+ if(redTest)options.configuration.redTest={...options.configuration.reproduction,testFiles:['value.mjs']};
26
+ const authority=createHostReviewAuthority({hostContextId:'fixture-host',reviewerId:reviewer.reviewerId,adapterId:reviewer.adapterId,decide:async()=>({status:'approved'})});
27
+ let calls=0,diagnoses=0;const diagnosis={status:'diagnosed',rootCause:'Fixture old cause',plan:'Fixture plan',affectedPaths:['value.mjs'],affectedModules:['value'],crossLayer:true};
28
+ const causeReview={authorize:authority.authorize,run:createCauseReviewRun(async({prompt},{onEvent})=>{
29
+ const data=JSON.parse(prompt.split('<cm-review-data-json>\n')[1]);calls++;
30
+ for(const event of [{event:'thread.started',provider_thread:calls===1?'fresh-review-1':secondThread},{event:'turn.started',item_type:null},
31
+ {event:'item.completed',item_type:'agent_message'},{event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])assert.equal(onEvent(event),true);
32
+ return {status:'succeeded',value:{verdict:calls===1?'changes_requested':secondVerdict,packageDigest:data.reviewPackage.packageDigest,
33
+ examinedPaths:['value.mjs'],findings:(calls===1||secondVerdict==='changes_requested')?[{id:'F1',severity:'P2',path:'value.mjs',message:'Cause is incomplete',evidence:'Fixture finding'}]:[],summary:'Fixture independent review'}};
34
+ },'codex')};
35
+ const bridge={async call(kind,payload){assert.equal(kind,'fix_diagnose');diagnoses++;
36
+ if(diagnoses>1){assert.equal(payload.reviewFeedback.verdict,'changes_requested');return {...diagnosis,rootCause:'Fixture revised cause',crossLayer:false};}
37
+ return diagnosis;}};
38
+ let owner=openFixExecution(options,{bridge,causeReview,prepare});
39
+ const state=path.join(specsRoot,'.reviews/.execution',identity.runId,'state.json');
40
+ const review=async()=>{const pkg=owner.causeReviewPackage();await authority.hostDecisionProvider.decide({identity,packageDigest:pkg.packageDigest},new AbortController().signal);return owner.reviewCause();};
41
+ const reopen=(overrides={})=>{owner.close();owner=openFixExecution({...options,create:false},{bridge,causeReview,prepare,...overrides});return owner;};
42
+ try{await owner.advance({authorized:true});await review();assert.equal(owner.status().stage,'rediagnosis_required');
43
+ await fn({root,code,specsRoot,identity,options,authority,bridge,causeReview,state,review,reopen,owner:()=>owner,counts:()=>({calls,diagnoses})});
44
+ }finally{owner.close();}
45
+ }
46
+ test('original run rediagnoses after cause rejection, preserves history, and requires fresh independent review',async t=>fixture(t,async f=>{
47
+ const old=JSON.parse(fs.readFileSync(f.state)).records;
48
+ const first=fs.readFileSync(path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r1.md'));
49
+ let owner=f.reopen();await assert.rejects(owner.rediagnose({reason:'Address F1'}),{code:'fix_rediagnosis_authorization_required'});
50
+ const host=createFixHost({owner,config:{...f.options.configuration,...f.options},permissions:['--allow-rediagnosis']});
51
+ const input=new PassThrough();let output='';
52
+ const sink=new Writable({write(chunk,encoding,done){output+=chunk;done();}});
53
+ input.end(JSON.stringify({requestId:'redo',operation:'rediagnose',reason:'Address F1'})+'\n');
54
+ await serveCmAiHost({host,input,output:sink});
55
+ const changed=JSON.parse(output).result;
56
+ assert.equal(changed.stage,'cause_review_required');assert.equal(changed.completionEligible,false);
57
+ const next=JSON.parse(fs.readFileSync(f.state)).records;assert.deepEqual(next.slice(0,old.length),old);
58
+ assert.equal(fs.readFileSync(path.join(f.code,'visits'),'utf8'),'1');
59
+ owner=f.reopen();assert.equal(owner.status().stage,'cause_review_required');assert.equal(owner.status().diagnosis.rootCause,'Fixture revised cause');
60
+ assert.equal((await f.review()).stage,'red_test_required');
61
+ assert.deepEqual(fs.readFileSync(path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r1.md')),first);
62
+ assert.match(fs.readFileSync(path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r2.md'),'utf8'),/round: 2\nverdict: approved/);
63
+ owner=f.reopen();assert.equal(owner.status().stage,'red_test_required');
64
+ await assert.rejects(owner.rediagnose({authorized:true,reason:'Again'}),{code:'fix_rediagnosis_unavailable'});
65
+ assert.deepEqual(f.counts(),{calls:2,diagnoses:2});
66
+ }));
67
+ test('interrupted rediagnosis replays unknown and never repeats original reproduction or diagnosis',async t=>fixture(t,async f=>{
68
+ const before=JSON.parse(fs.readFileSync(f.state)).records;
69
+ f.bridge.call=async()=>{throw Error('Fixture lost result');};
70
+ const result=await f.owner().rediagnose({authorized:true,reason:'Address F1'});
71
+ assert.equal(result.stage,'unknown');assert.equal(result.pending,'rediagnosis');
72
+ const owner=f.reopen();assert.equal(owner.status().pending,'rediagnosis');
73
+ assert.equal((await owner.advance({authorized:true})).stage,'unknown');
74
+ await assert.rejects(owner.rediagnose({authorized:true,reason:'Retry'}),{code:'fix_rediagnosis_unavailable'});
75
+ assert.deepEqual(JSON.parse(fs.readFileSync(f.state)).records.slice(0,before.length),before);
76
+ assert.equal(fs.readFileSync(path.join(f.code,'visits'),'utf8'),'1');
77
+ }));
78
+ for(const failure of ['source','evidence','reason'])test(`rediagnosis refuses ${failure} before registering a new effect`,async t=>fixture(t,async f=>{
79
+ const before=fs.readFileSync(f.state);
80
+ if(failure==='source')fs.writeFileSync(path.join(f.code,'value.mjs'),'export const value=2;');
81
+ if(failure==='evidence')fs.writeFileSync(path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r2.md'),'Other evidence');
82
+ await assert.rejects(f.owner().rediagnose({authorized:true,reason:failure==='reason'?'bad\nreason':'Address F1'}),
83
+ {code:failure==='source'?'fix_rediagnosis_source_changed':failure==='evidence'?'fix_rediagnosis_evidence_conflict':'fix_rediagnosis_reason_invalid'});
84
+ assert.deepEqual(fs.readFileSync(f.state),before);
85
+ }));
86
+
87
+ test('a second cause rejection reaches a durable limit without allowing a third diagnosis or review',async t=>fixture(t,async f=>{
88
+ await f.owner().rediagnose({authorized:true,reason:'Address F1'});
89
+ assert.equal((await f.review()).stage,'rediagnosis_review_limit_reached');
90
+ const before=fs.readFileSync(f.state),owner=f.reopen();
91
+ assert.equal(owner.status().stage,'rediagnosis_review_limit_reached');
92
+ await assert.rejects(owner.rediagnose({authorized:true,reason:'Again'}),{code:'fix_rediagnosis_unavailable'});
93
+ await assert.rejects(f.review());
94
+ assert.deepEqual(fs.readFileSync(f.state),before);assert.deepEqual(f.counts(),{calls:2,diagnoses:2});
95
+ },{secondVerdict:'changes_requested'}));
96
+ test('the original reviewer thread cannot be reused as the revised cause review',async t=>fixture(t,async f=>{
97
+ await f.owner().rediagnose({authorized:true,reason:'Address F1'});
98
+ const result=await f.review();assert.notEqual(result.stage,'red_test_required');assert.equal(result.completionEligible,false);
99
+ const owner=f.reopen();assert.notEqual(owner.status().stage,'red_test_required');
100
+ assert.equal(fs.existsSync(path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r2.md')),false);
101
+ },{secondThread:'fresh-review-1'}));
102
+
103
+ const learningFor=summary=>{const contextDigest=digest([]);return {contextDigest,files:[],application:{contextDigest,status:'no_relevant_lesson',summary}};};
104
+ test('driver resumes with recorded application after real Learning writeback without an answer file',async t=>{
105
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'fix-drive-writeback-')));
106
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
107
+ const cwd=path.join(root,'code'),specsRoot=path.join(root,'specs'),answers=path.join(root,'answers');
108
+ for(const dir of [cwd,specsRoot,answers])fs.mkdirSync(dir);
109
+ fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=1;');
110
+ fs.writeFileSync(path.join(cwd,'red.mjs'),"import {value} from './value.mjs';if(value!==2){console.error('BUG');process.exit(1)}");
111
+ fs.writeFileSync(path.join(cwd,'existing.mjs'),"import {value} from './value.mjs';if(typeof value!=='number')process.exit(1)");
112
+ const identity={repositoryId:'fixture',runId:'writeback-run',taskId:'T-FIX-writeback',attempt:1};
113
+ const reproduction={cwd,command:[process.execPath,'red.mjs'],expectedFailure:{exitCode:1,outputIncludes:'BUG'},timeoutMs:2000};
114
+ const owner=openFixExecution({identity,specsRoot,create:true,configuration:{hostContextId:'fixture-host',defect:'Wrong constant',reproduction,
115
+ redTest:{...reproduction,testFiles:['red.mjs']},baseline:{cwd,testFiles:['existing.mjs'],commands:[{id:'existing',command:[process.execPath,'existing.mjs']}],timeoutMs:2000},
116
+ repair:{scope:['value.mjs'],requirements:['value.mjs']}}},{prepare:async()=>learningFor('Current application'),assertReviewReady(){},bridge:{async call(kind){
117
+ if(kind==='fix_diagnose')return {status:'diagnosed',rootCause:'Wrong constant',affectedPaths:['value.mjs'],affectedModules:['one'],crossLayer:false,plan:'Correct constant'};
118
+ if(kind==='fix_repair'){fs.writeFileSync(path.join(cwd,'value.mjs'),'export const value=2;');return {outcome:'repaired'};}
119
+ if(kind==='fix_retrospective')return {status:'lesson_candidate',candidates:[{classification:'structured',trigger:'Wrong constant',action:'Keep regression check',evidence:['red.mjs']}],reason:null};
120
+ throw Error(kind);
121
+ }}});
122
+ t.after(()=>owner.close());
123
+ await owner.advance({authorized:true});await owner.runRedTest({authorized:true});await owner.captureBaseline({authorized:true});
124
+ await owner.repair({authorized:true});await owner.runRegression({authorized:true});await owner.retrospect();owner.writeLearning({authorized:true});
125
+ assert.equal(owner.status().stage,'handoff_ready');
126
+ const state=path.join(specsRoot,'.reviews/.execution',identity.runId,'state.json'),before=fs.readFileSync(state);
127
+ const rows=JSON.parse(before).records;assert.ok(rows.some(row=>row.id==='fix-learning-writeback-result'&&!row.payload.application));
128
+ const config=path.join(root,'config.json');fs.writeFileSync(config,JSON.stringify({specsRoot,identity,reproduction}));
129
+ const script=`import {preflight} from ${JSON.stringify(new URL('./cm-fix-drive.mjs',import.meta.url).href)};console.log(JSON.stringify(preflight(${JSON.stringify({operation:'post_review_regression',plan:{cwd,mode:'resume'},paths:{config,answers}})}).answers));`;
130
+ const result=spawnSync(process.execPath,['--input-type=module','-e',script],{encoding:'utf8'});
131
+ assert.equal(result.status,0,result.stderr);
132
+ assert.deepEqual(JSON.parse(result.stdout).learning,owner.status().learning.application);
133
+ assert.equal(fs.existsSync(path.join(answers,'learning.json')),false);
134
+ assert.deepEqual(fs.readFileSync(state),before);
135
+ });
136
+ test('driver continuation after revised cause approval uses current Learning and reaches the real red gate',async t=>fixture(t,async f=>{
137
+ let owner=f.reopen({prepare:async()=>learningFor('Revised application after F1')});
138
+ await owner.rediagnose({authorized:true,reason:'Address F1'});await f.review();
139
+ assert.equal(owner.status().stage,'red_test_required');
140
+ const config=path.join(f.root,'driver-config.json'),answers=path.join(f.root,'answers');fs.mkdirSync(answers);
141
+ fs.writeFileSync(config,JSON.stringify({specsRoot:f.specsRoot,identity:f.identity,reproduction:f.options.configuration.reproduction}));
142
+ const selected=preflight({operation:'red_test',plan:{cwd:f.code,mode:'resume'},paths:{config,answers}});
143
+ assert.equal(selected.answers.learning.summary,owner.status().learning.application.summary);
144
+ owner=f.reopen({prepare:async()=>learningFor(selected.answers.learning.summary)});
145
+ assert.equal((await owner.runRedTest({authorized:true})).stage,'baseline_required');
146
+ assert.equal(fs.readFileSync(path.join(f.code,'visits'),'utf8'),'11');
147
+ },{prepare:async()=>learningFor('Original application'),redTest:true}));
148
+ for(const failure of ['source','evidence','symlink'])test(`rediagnosis rechecks ${failure} after awaited preparation and preserves its continuation`,async t=>fixture(t,async f=>{
149
+ const before=fs.readFileSync(f.state),r1=fs.readFileSync(path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r1.md'));
150
+ const owner=f.reopen({prepare:async()=>{
151
+ await Promise.resolve();
152
+ if(failure==='source')fs.writeFileSync(path.join(f.code,'value.mjs'),'export const value=999;');
153
+ else if(failure==='symlink')fs.symlinkSync('missing-review',path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r2.md'));
154
+ else fs.writeFileSync(path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r2.md'),'Occupied during preparation');
155
+ return learningFor('Fresh application');
156
+ }});
157
+ await assert.rejects(owner.rediagnose({authorized:true,reason:'Address F1'}),
158
+ {code:failure==='source'?'fix_rediagnosis_source_changed':'fix_rediagnosis_evidence_conflict'});
159
+ assert.deepEqual(fs.readFileSync(f.state),before);assert.equal(owner.status().stage,'rediagnosis_required');
160
+ assert.deepEqual(fs.readFileSync(path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r1.md')),r1);
161
+ assert.equal(fs.readFileSync(path.join(f.code,'visits'),'utf8'),'1');
162
+ assert.deepEqual(f.counts(),{calls:1,diagnoses:1});
163
+ if(failure==='source')fs.writeFileSync(path.join(f.code,'value.mjs'),'export const value=1;');
164
+ else fs.unlinkSync(path.join(f.specsRoot,'.reviews/fix-rediagnosis-cause-r2.md'));
165
+ const retry=f.reopen({prepare:async()=>learningFor('Fresh application')});
166
+ assert.equal((await retry.rediagnose({authorized:true,reason:'Address F1 after conflict cleared'})).stage,'cause_review_required');
167
+ assert.deepEqual(f.counts(),{calls:1,diagnoses:2});
168
+ }));
@@ -12,6 +12,7 @@ import {createHostReviewAuthority} from '../runtime/js/cm-ai/host-review-authori
12
12
  import {createCauseReviewRun} from '../runtime/js/cm-ai/codex-review-adapter.mjs';
13
13
  import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
14
14
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
15
+ import {EXECUTION_POLICY_V1} from '../runtime/js/cm-ai/execution-policy.mjs';
15
16
  import {buildCmAiDriveRequest} from './cm-ai-drive.mjs';
16
17
 
17
18
  const isolated=fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-review-budget-'));
@@ -122,7 +123,7 @@ test('#15 the shipped review host hands its review budget to the owner and the r
122
123
  const review=timeoutMs=>({model:'synthetic',disabledSkills:[],...(timeoutMs?{timeoutMs}:{}),preflight:{passed:true,cli_model:'synthetic',prompt_transport:'stdin',
123
124
  config_fingerprint:configFingerprint({cwd:codeProject,model:'synthetic',disabledSkills:[],promptTransport:'stdin'})}});
124
125
  const seen=[];
125
- const host=timeoutMs=>createFixReviewHost({codeProject,hostContextId:'host',review:review(timeoutMs),permissions:['--allow-cause-review'],
126
+ const host=(timeoutMs,executionPolicy=null)=>createFixReviewHost({codeProject,hostContextId:'host',review:review(timeoutMs),executionPolicy,permissions:['--allow-cause-review'],
126
127
  workerFactory:options=>{seen.push(options.timeoutMs);return async()=>({status:'failed',code:'unused'});}});
127
128
  const configured=host(1234).execution;
128
129
  assert.equal(configured.causeReview.timeoutMs,1234);assert.equal(configured.finalReview.timeoutMs,1234);
@@ -131,6 +132,11 @@ test('#15 the shipped review host hands its review budget to the owner and the r
131
132
  // The worker is built with the budget before the adapter validates the request.
132
133
  assert.throws(()=>configured.causeReview.run({},{signal:new AbortController().signal,onEvent:()=>true}),{code:'invalid_input'});
133
134
  assert.deepEqual(seen,[1234]);
135
+ const optimized=host(1234,EXECUTION_POLICY_V1).execution;
136
+ assert.throws(()=>optimized.causeReview.run({},{signal:new AbortController().signal,onEvent:()=>true}),{code:'invalid_input'});
137
+ assert.throws(()=>optimized.finalReview.run({},{signal:new AbortController().signal,onEvent:()=>true}),{code:'invalid_input'});
138
+ assert.deepEqual(seen,[1234,1234,1234]);
139
+ assert.equal(fs.existsSync(path.join(isolated,'logs')),false);
134
140
  });
135
141
 
136
142
  test('#15 the cm-ai driver forwards the QA-fix abandon_review reason inside fix_action',()=>{
@@ -47,6 +47,27 @@ function begin(f,executor) {
47
47
  return input;
48
48
  }
49
49
 
50
+ for(const protectedMode of [false,true])test(`progress R1: quiet QA command boundaries; protected=${protectedMode}`,
51
+ {skip:protectedMode&&spawnSync('codex',['--version']).status!==0},async()=>{
52
+ const f=fixture(),events=[],original=process.stderr.write;let captured='';
53
+ try{
54
+ fs.unlinkSync(path.join(f.configuration.specsDir,f.configuration.feature,'test-cases.json'));
55
+ f.configuration.commands=[{id:'quiet-qa',command:[process.execPath,'-e',
56
+ "setTimeout(()=>{console.log('fixture-raw-output');process.exit(0)},400)"],caseIds:[]}];
57
+ const executor=createHostQaExecutor({...f.configuration,...(protectedMode?{specsRoot:f.configuration.specsDir}:{})});
58
+ const binding=begin(f,executor);
59
+ process.stderr.write=function(chunk,...args){
60
+ captured+=String(chunk);if(String(chunk).includes('[check]'))events.push({text:String(chunk),at:Date.now()});
61
+ return original.call(this,chunk,...args);
62
+ };
63
+ const result=await executor.run(binding,new AbortController().signal);
64
+ assert.equal(result.result,'PASS');assert.equal(events.length,2,captured);
65
+ assert.match(events[0].text,/开始检查.*quiet-qa/);assert.match(events[1].text,/检查结束.*quiet-qa.*passed/);
66
+ assert(events[1].at-events[0].at>=300,'start must be visible during the quiet command');
67
+ assert(!captured.includes('fixture-raw-output'),'QA raw project output remains private');
68
+ }finally{process.stderr.write=original;f.cleanup();}
69
+ });
70
+
50
71
  for(const transport of ['synchronous','jsonl','coalesced-jsonl'])test(`incident sequence: immediate QA replies over ${transport}`,{timeout:30000},async()=>{
51
72
  const f=fixture(),bridge=createHostToolBridge(),input=new PassThrough(),output=new PassThrough();
52
73
  let serving;
@@ -0,0 +1,160 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
7
+ import {CLOSEOUT_AREAS,readCloseoutReport,readCloseoutPolicy} from '../runtime/js/cm-ai/knowledge-closeout.mjs';
8
+ import {createCmAiConversationEntry} from '../runtime/js/cm-ai/cm-ai-conversation-entry.mjs';
9
+ import {recordCmAiQaDecision} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
10
+ import {openControlRun,runConfigMaterial} from './cm-ai-run.mjs';
11
+ import {openTaskExecutionStore} from '../runtime/js/cm-ai/task-owner.mjs';
12
+ import {createCmAiHost} from '../runtime/js/cm-ai/host.mjs';
13
+ import {buildManifest} from './cm-spec-manifest.mjs';
14
+
15
+ const identity={repositoryId:'closeout',runId:'closeout-run',taskId:'T-001',attempt:1};
16
+ const policy={version:1,enabled:true},packageDigest='8'.repeat(64);
17
+ const report=()=>({version:1,items:CLOSEOUT_AREAS.map(area=>({area,
18
+ status:area==='memory'?'out_of_scope':area==='runtime'?'not_applicable':'checked',
19
+ evidence:['README.md'],detail:area==='memory'?'Personal memory is outside this run':'Controlled fixture evidence'}))});
20
+ const op=operation=>({version:1,operation,requestId:operation,identity,packageDigest,testRunId:null});
21
+ async function fixture(fn,{pending=false}={}){
22
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-closeout-'))),specsDir=path.join(root,'specs'),codeProject=path.join(root,'code'),feature='1.fixture';
23
+ fs.mkdirSync(path.join(specsDir,feature),{recursive:true});fs.mkdirSync(codeProject);
24
+ fs.writeFileSync(path.join(codeProject,'README.md'),'# Fixture\n');
25
+ for(const name of ['requirements.md','design.md'])fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
26
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),`- [${pending?' ':'x'}] T-001: fixture\n`);
27
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],specFiles:buildManifest(specsDir)}));
28
+ const current={state:'fixture_completed',code:null,identity,packageDigest};let effects=0;
29
+ const runner={status:()=>current,executeEffect:()=>{effects++;throw Error('unexpected effect');},run:async()=>current,cancel:()=>current};
30
+ const entry=extra=>createCmAiConversationEntry({specsDir,codeProject,feature,identity,runner,applicableAgentFiles:[],knowledgeCloseout:policy,...extra});
31
+ const seedQa=()=>recordCmAiQaDecision({specsDir,codeProject,feature,identity,packageDigest,logHome:path.join(root,'logs'),
32
+ decision:{decisionId:'old-qa-skip',identity,packageDigest,status:'skipped',reason:'Historical fixture',score:4,at:'2026-09-04T22:00:00Z'}});
33
+ const response=(request,extra={})=>({syncId:request.syncId,identity:request.identity,packageDigest:request.packageDigest,
34
+ contextDigest:request.contextDigest,status:'completed',reason:'Required docs verified in fixture',at:'2026-10-04T12:00:00Z',...extra});
35
+ const stateFile=path.join(specsDir,'.reviews','.execution',identity.runId,'state.json');
36
+ const definition={version:1,specsDir,codeProject,feature,identity,scope:['README.md'],requirements:[]};
37
+ const execution=(enabled)=>({configuration:{kind:'synthetic-host-v1',...(enabled===undefined?{}:{workflow:{knowledgeCloseout:enabled}})},timeoutMs:1000,
38
+ excludedContexts:['main'],hostDecision:null,check:()=>[],applicableAgentFiles:[],documentationProvider:{timeoutMs:1000,inspect:async()=>{throw Error('unexpected inspection');}},
39
+ developer:{provider:'codex',requestedModel:'fixture',contextId:'author',run:async()=>{throw Error('unexpected dispatch');}},
40
+ reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'fixture',allowed:true,available:true,
41
+ contexts:['review-1','review-2'],run:async()=>{throw Error('unexpected review');}}],
42
+ reviewInvocation:{developerThreadId:'author',excludedThreadIds:['main'],hostContextId:'main',authorize:async()=>{throw Error('unexpected grant');}}});
43
+ try{return await fn({root,specsDir,codeProject,feature,definition,entry,seedQa,response,stateFile,execution,effects:()=>effects});}
44
+ finally{fs.rmSync(root,{recursive:true,force:true});}
45
+ }
46
+ test('six-face report requires evidence and distinguishes denied reads and scope',()=>{
47
+ assert.deepEqual(readCloseoutReport(report()),report());
48
+ const denied=report();denied.items[2]={area:'documentation',status:'unverified',evidence:[],detail:'README.md: EACCES; not read'};
49
+ assert.equal(readCloseoutReport(denied).items[2].status,'unverified');
50
+ for(const mutation of [r=>r.items.pop(),r=>r.items[1].area='code',r=>r.items[0].evidence=[],
51
+ r=>r.items[0].status='passed',r=>r.items[0].grant=true,r=>r.version=2]){
52
+ const value=report();mutation(value);assert.throws(()=>readCloseoutReport(value));
53
+ }
54
+ assert.throws(()=>readCloseoutPolicy({version:2,enabled:true}),{code:'closeout_policy_unsupported'});
55
+ });
56
+ test('one inspection reports six faces; repeated finish/finalize deduplicates without writes to reviewed files',()=>fixture(async f=>{
57
+ f.seedQa();let calls=0;const before=fs.readFileSync(path.join(f.codeProject,'README.md'));
58
+ const entry=f.entry({documentationProvider:{timeoutMs:1000,inspect:async request=>{
59
+ calls++;assert.deepEqual(request.closeout,policy);return f.response(request,{closeout:report()});}}});
60
+ const finished=await entry.handle(op('finish'));assert.equal(finished.code,'documentation_synced');
61
+ assert.equal(finished.knowledgeCloseout.status,'reported');assert.equal(finished.knowledgeCloseout.items.length,6);
62
+ const final=await entry.handle(op('run_finalize'));assert.equal(final.state,'run_done');
63
+ assert.deepEqual(final.knowledgeCloseout,finished.knowledgeCloseout);
64
+ assert.equal((await entry.handle(op('run_finalize'))).deduplicated,true);assert.equal(calls,1);assert.equal(f.effects(),0);
65
+ assert.deepEqual(fs.readFileSync(path.join(f.codeProject,'README.md')),before);
66
+ }));
67
+ test('legacy answer on enabled run is explicitly not_completed and does not replace mandatory documentation block',()=>fixture(async f=>{
68
+ f.seedQa();let blocked=true;
69
+ const entry=f.entry({documentationProvider:{timeoutMs:1000,inspect:async request=>f.response(request,{status:blocked?'blocked':'completed'})}});
70
+ const first=await entry.handle(op('run_finalize'));assert.equal(first.code,'documentation_sync_blocked');
71
+ assert.equal(first.knowledgeCloseout.status,'not_completed');assert(!fs.readFileSync(path.join(f.specsDir,'运行日志.jsonl'),'utf8').includes('run_done'));
72
+ blocked=false;const second=await entry.handle(op('run_finalize'));assert.equal(second.state,'run_done');
73
+ assert.equal(second.knowledgeCloseout.status,'not_completed');assert.equal(second.knowledgeCloseout.reason,'report_not_provided');
74
+ }));
75
+ test('explicit OFF still performs mandatory inspection and records disabled',()=>fixture(async f=>{
76
+ f.seedQa();let calls=0;
77
+ const entry=f.entry({knowledgeCloseout:{version:1,enabled:false},documentationProvider:{timeoutMs:1000,inspect:async request=>{
78
+ calls++;assert.equal(request.closeout.enabled,false);return f.response(request);}}});
79
+ const result=await entry.handle(op('run_finalize'));assert.equal(result.state,'run_done');
80
+ assert.equal(result.knowledgeCloseout.status,'disabled');assert.equal(calls,1);
81
+ }));
82
+ for(const kind of ['timeout','cancel','failure','stale','drift','invalid_report'])
83
+ test(`inspection ${kind} cannot write run_done or accept a late report`,()=>fixture(async f=>{
84
+ f.seedQa();let resolve,entered;const started=new Promise(r=>entered=r);
85
+ const entry=f.entry({documentationProvider:{timeoutMs:kind==='timeout'?20:1000,inspect:async request=>{
86
+ entered();if(['timeout','cancel'].includes(kind))return new Promise(r=>resolve=()=>r(f.response(request,{closeout:report()})));
87
+ if(kind==='failure')throw Object.assign(Error('read denied'),{code:'EACCES'});
88
+ if(kind==='drift')fs.appendFileSync(path.join(f.specsDir,f.feature,'design.md'),'Changed after request\n');
89
+ const value=f.response(request,{closeout:report()});
90
+ if(kind==='stale')value.syncId='old-report';if(kind==='invalid_report')value.closeout.items[0].evidence=[];
91
+ return value;
92
+ }}});
93
+ const work=entry.handle(op('run_finalize'));await started;
94
+ if(kind==='cancel')await entry.handle({version:1,operation:'cancel',requestId:'cancel',identity});
95
+ const result=await work;assert.equal(result.outcome,'rejected',JSON.stringify(result));
96
+ assert.equal(result.knowledgeCloseout.status,'not_completed');assert.equal(f.effects(),0);
97
+ if(resolve){resolve();await new Promise(r=>setImmediate(r));}
98
+ assert(!fs.readFileSync(path.join(f.specsDir,'运行日志.jsonl'),'utf8').includes('run_done'));
99
+ }));
100
+ test('concurrent inspection is refused; restart inspects again under the original deduplicated finalizer',()=>fixture(async f=>{
101
+ f.seedQa();let release,request,entered;const started=new Promise(r=>entered=r);let calls=0;
102
+ const provider={timeoutMs:1000,inspect:async r=>{calls++;request=r;entered();return new Promise(resolve=>release=resolve);}};
103
+ const entry=f.entry({documentationProvider:provider});const active=entry.handle(op('finish'));await started;
104
+ assert.equal((await entry.handle(op('finish'))).code,'documentation_pending');release(f.response(request,{closeout:report()}));await active;
105
+ const first=await entry.handle(op('run_finalize'));assert.equal(first.state,'run_done');
106
+ const reopened=f.entry({documentationProvider:{timeoutMs:1000,inspect:async r=>{calls++;return f.response(r,{closeout:report()});}}});
107
+ assert.equal((await reopened.handle(op('run_finalize'))).deduplicated,true);assert.equal(calls,2);
108
+ }));
109
+ for(const enabled of [undefined,false])
110
+ test(`real store freezes create policy ${enabled===undefined?'default ON':'explicit OFF'} and refuses change`,()=>fixture(async f=>{
111
+ let run=await openControlRun(f.definition,'create',f.execution(enabled));run.close();
112
+ const before=fs.readFileSync(f.stateFile),snapshot=JSON.parse(before),saved=snapshot.records[0].payload.config.knowledgeCloseout;
113
+ assert.deepEqual(saved,{version:1,enabled:enabled!==false});
114
+ run=await openControlRun(f.definition,'resume',f.execution(enabled));run.close();assert.deepEqual(fs.readFileSync(f.stateFile),before);
115
+ await assert.rejects(openControlRun(f.definition,'resume',f.execution(enabled===false?true:false)),{code:'closeout_policy_changed'});
116
+ assert.deepEqual(fs.readFileSync(f.stateFile),before);
117
+ },{pending:true}));
118
+ test('real legacy init without closeout resumes byte-identically; explicit activation cannot migrate it',()=>fixture(async f=>{
119
+ const execution=f.execution(),material=runConfigMaterial(f.definition,execution);
120
+ const store=openTaskExecutionStore({tasksPath:path.join(f.specsDir,f.feature,'tasks.md'),feature:'fixture',specsRoot:f.specsDir,
121
+ identity:{repositoryId:identity.repositoryId,runId:identity.runId},create:true,
122
+ fingerprints:{workflow:digest('cm-ai-host-execution-v1'),config:digest(material),inputs:digest({feature:f.feature,task:identity.taskId})}});
123
+ try{createCmAiHost({runner:{root:f.codeProject,identity,scope:f.definition.scope,requirements:[],specification:{specsRoot:f.specsDir,feature:f.feature},
124
+ excludedContexts:execution.excludedContexts,developer:execution.developer,reviewers:execution.reviewers,reviewInvocation:execution.reviewInvocation,
125
+ check:()=>[],timeoutMs:1000,taskCompletion:{reviewsDir:path.join(f.specsDir,'.reviews'),handoffs:[1,2].map(n=>path.join(f.specsDir,'.reviews',`fixture-T-001-a${n}-handoff.json`))},
126
+ taskLearning:{feature:f.feature,hostHandoff:true},persistence:{store,mode:'create',version:3}},entry:{specsDir:f.specsDir,codeProject:f.codeProject,
127
+ feature:f.feature,identity,hostDecision:null,applicableAgentFiles:[],documentationProvider:execution.documentationProvider}});}finally{store.close();}
128
+ const before=fs.readFileSync(f.stateFile);assert(!Object.hasOwn(JSON.parse(before).records[0].payload.config,'knowledgeCloseout'));
129
+ const resumed=await openControlRun(f.definition,'resume',execution);resumed.close();assert.deepEqual(fs.readFileSync(f.stateFile),before);
130
+ await assert.rejects(openControlRun(f.definition,'resume',f.execution(true)),{code:'closeout_policy_changed'});
131
+ assert.deepEqual(fs.readFileSync(f.stateFile),before);
132
+ },{pending:true}));
133
+ for(const saved of [policy,{version:1,enabled:false},null])
134
+ test(`empty original initializer selects only its original fingerprint: ${saved?.enabled??'legacy'}`,()=>fixture(async f=>{
135
+ const execution=f.execution(),material=runConfigMaterial(f.definition,execution,{knowledgeCloseout:saved});
136
+ const store=openTaskExecutionStore({tasksPath:path.join(f.specsDir,f.feature,'tasks.md'),feature:'fixture',specsRoot:f.specsDir,
137
+ identity:{repositoryId:identity.repositoryId,runId:identity.runId},create:true,
138
+ fingerprints:{workflow:digest('cm-ai-host-execution-v1'),config:digest(material),inputs:digest({feature:f.feature,task:identity.taskId})}});store.close();
139
+ const run=await openControlRun(f.definition,'resume',execution);run.close();
140
+ assert.deepEqual(JSON.parse(fs.readFileSync(f.stateFile)).records[0].payload.config.knowledgeCloseout??null,saved);
141
+ },{pending:true}));
142
+
143
+ for(const mutation of ['unsupported-version','stripped-policy','changed-boolean'])
144
+ test(`resume refuses ${mutation} without falling back or changing evidence`,()=>fixture(async f=>{
145
+ const run=await openControlRun(f.definition,'create',f.execution());run.close();
146
+ const snapshot=JSON.parse(fs.readFileSync(f.stateFile));
147
+ const config=snapshot.records[0].payload.config;
148
+ if(mutation==='unsupported-version')config.knowledgeCloseout.version=2;
149
+ if(mutation==='stripped-policy')delete config.knowledgeCloseout;
150
+ if(mutation==='changed-boolean')config.knowledgeCloseout.enabled=false;
151
+ // Even a fully recomputed journal hash chain cannot authorize a different
152
+ // policy than the original configuration fingerprint.
153
+ let previousDigest=null;
154
+ for(const row of snapshot.records){row.previousDigest=previousDigest;const {digest:checksum,...body}=row;row.digest=digest(body);previousDigest=row.digest;}
155
+ const {revision,...body}=snapshot;snapshot.revision=digest(body);
156
+ fs.writeFileSync(f.stateFile,JSON.stringify(snapshot)+'\n');const before=fs.readFileSync(f.stateFile);
157
+ await assert.rejects(openControlRun(f.definition,'resume',f.execution()),error=>
158
+ error.code===(mutation==='unsupported-version'?'closeout_policy_unsupported':'fingerprint_mismatch'));
159
+ assert.deepEqual(fs.readFileSync(f.stateFile),before);
160
+ },{pending:true}));