@aibyzero/cm-workflow 0.16.4 → 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 (283) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +22 -0
  3. package/CHANGELOG.md +57 -0
  4. package/README.md +22 -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 +48 -7
  17. package/docs/js-workflow-control.md +293 -33
  18. package/docs/live-evidence-drivers.md +62 -0
  19. package/docs/next-steps.md +15 -10
  20. package/docs/runtime-failover.md +1 -1
  21. package/docs/untested-branches.md +27 -4
  22. package/docs/user-guide.md +23 -8
  23. package/install-codex.sh +28 -11
  24. package/package.json +1 -1
  25. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  26. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  27. package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
  28. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  29. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
  30. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  31. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  32. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +208 -34
  33. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  34. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  35. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +181 -57
  36. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +15 -58
  37. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  38. package/runtime/js/cm-ai/codex-review-adapter.mjs +56 -17
  39. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  40. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  41. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  42. package/runtime/js/cm-ai/drive-bootstrap.mjs +315 -0
  43. package/runtime/js/cm-ai/drive-core.mjs +47 -9
  44. package/runtime/js/cm-ai/durable-runner-state.mjs +413 -56
  45. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  46. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  47. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  48. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  49. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  50. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  51. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  52. package/runtime/js/cm-ai/external-models.mjs +52 -0
  53. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  54. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  55. package/runtime/js/cm-ai/host-bootstrap.mjs +126 -29
  56. package/runtime/js/cm-ai/host-check.mjs +30 -4
  57. package/runtime/js/cm-ai/host-conversation-execution.mjs +66 -20
  58. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  59. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  60. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  61. package/runtime/js/cm-ai/host-qa-executor.mjs +23 -9
  62. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +23 -6
  63. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  64. package/runtime/js/cm-ai/host-session.mjs +12 -4
  65. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  66. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +16 -5
  67. package/runtime/js/cm-ai/host.mjs +1 -1
  68. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  69. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  70. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  71. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  72. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  73. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  74. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  75. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  76. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  77. package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
  78. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  79. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  80. package/runtime/js/cm-ai/provider-review-observation.mjs +68 -9
  81. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  82. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  83. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  84. package/runtime/js/cm-ai/review-package.mjs +438 -31
  85. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  86. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  87. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  88. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  89. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  90. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  91. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  92. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  93. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  94. package/runtime/js/cm-ai/task-runner.mjs +658 -75
  95. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  96. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  97. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  98. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  99. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  100. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  101. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  102. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  103. package/runtime/js/cm-fix/execution.mjs +279 -52
  104. package/runtime/js/cm-fix/final-review.mjs +18 -10
  105. package/runtime/js/cm-fix/host-review.mjs +32 -9
  106. package/runtime/js/cm-fix/host.mjs +6 -1
  107. package/runtime/js/cm-fix/layout.mjs +1 -1
  108. package/runtime/js/cm-fix/progress.mjs +5 -0
  109. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  110. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  111. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  112. package/runtime/js/cm-prd/analysis.mjs +2 -1
  113. package/runtime/js/cm-prd/change.mjs +28 -10
  114. package/runtime/js/cm-prd/draft.mjs +5 -2
  115. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  116. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  117. package/runtime/js/cm-prd/review-publication.mjs +27 -15
  118. package/runtime/js/cm-prd/review-time.mjs +29 -0
  119. package/runtime/js/cm-prd/self-check.mjs +6 -3
  120. package/runtime/js/cm-prd/session.mjs +53 -6
  121. package/runtime/js/cm-prd/summary.mjs +3 -1
  122. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  123. package/runtime/js/cm-security/finalize.mjs +32 -0
  124. package/runtime/js/spec-task-line.mjs +117 -0
  125. package/runtime/js/specs-status.mjs +10 -3
  126. package/runtime/review.md +5 -0
  127. package/runtime/task-gates.md +6 -0
  128. package/runtime/workflow-config.md +10 -1
  129. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  130. package/scripts/cm-ai-admission.mjs +18 -11
  131. package/scripts/cm-ai-admission.test.mjs +65 -1
  132. package/scripts/cm-ai-batch-drive.mjs +135 -34
  133. package/scripts/cm-ai-batch-drive.test.mjs +209 -3
  134. package/scripts/cm-ai-batch-host.mjs +63 -24
  135. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  136. package/scripts/cm-ai-batch-run.mjs +101 -34
  137. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  138. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  139. package/scripts/cm-ai-bootstrap-flow.test.mjs +159 -0
  140. package/scripts/cm-ai-bootstrap-merge.test.mjs +162 -0
  141. package/scripts/cm-ai-bootstrap.test.mjs +174 -89
  142. package/scripts/cm-ai-conversation-entry-ops.test.mjs +97 -2
  143. package/scripts/cm-ai-develop-driver-gaps.test.mjs +924 -0
  144. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  145. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  146. package/scripts/cm-ai-drive.mjs +526 -60
  147. package/scripts/cm-ai-drive.test.mjs +336 -10
  148. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  149. package/scripts/cm-ai-host.mjs +142 -43
  150. package/scripts/cm-ai-host.test.mjs +232 -12
  151. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  152. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  153. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  154. package/scripts/cm-ai-progress.test.mjs +521 -0
  155. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  156. package/scripts/cm-ai-qa-config-revision.test.mjs +187 -15
  157. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  158. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  159. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  160. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  161. package/scripts/cm-ai-review-failure.test.mjs +977 -0
  162. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  163. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  164. package/scripts/cm-ai-run.mjs +206 -62
  165. package/scripts/cm-ai-run.test.mjs +6 -4
  166. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  167. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  168. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  169. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  170. package/scripts/cm-ai-supersede.test.mjs +571 -17
  171. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  172. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  173. package/scripts/cm-capability-gate.test.mjs +21 -2
  174. package/scripts/cm-check-drive.test.mjs +2 -1
  175. package/scripts/cm-check-host.test.mjs +1 -1
  176. package/scripts/cm-check-runtime.sh +12 -1
  177. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  178. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  179. package/scripts/cm-claude-probe.test.mjs +10 -2
  180. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  181. package/scripts/cm-claude-worker.test.mjs +11 -4
  182. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  183. package/scripts/cm-codex-plugin-metadata.py +83 -0
  184. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  185. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  186. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  187. package/scripts/cm-efficiency-offline.mjs +35 -0
  188. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  189. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  190. package/scripts/cm-efficiency-response.test.mjs +117 -0
  191. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  192. package/scripts/cm-external-batch-host.test.mjs +157 -0
  193. package/scripts/cm-external-fix-host.test.mjs +281 -0
  194. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  195. package/scripts/cm-external-group-models.test.mjs +60 -0
  196. package/scripts/cm-external-model-host.test.mjs +180 -0
  197. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  198. package/scripts/cm-external-models.test.mjs +89 -0
  199. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  200. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  201. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  202. package/scripts/cm-failover.mjs +8 -8
  203. package/scripts/cm-fix-abandon.test.mjs +123 -5
  204. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  205. package/scripts/cm-fix-drive.mjs +70 -23
  206. package/scripts/cm-fix-drive.test.mjs +36 -1
  207. package/scripts/cm-fix-final-review.test.mjs +11 -6
  208. package/scripts/cm-fix-host.mjs +24 -14
  209. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  210. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  211. package/scripts/cm-fix-review-budget.test.mjs +147 -0
  212. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  213. package/scripts/cm-host-check.test.mjs +6 -3
  214. package/scripts/cm-host-qa-executor.test.mjs +213 -17
  215. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  216. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  217. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  218. package/scripts/cm-live-evidence.test.mjs +64 -0
  219. package/scripts/cm-log-event.mjs +25 -2
  220. package/scripts/cm-log-event.py +15 -0
  221. package/scripts/cm-log-event.test.mjs +31 -0
  222. package/scripts/cm-model-setup.mjs +79 -0
  223. package/scripts/cm-prd-completion.test.mjs +75 -0
  224. package/scripts/cm-prd-draft.test.mjs +14 -0
  225. package/scripts/cm-prd-drive.mjs +32 -11
  226. package/scripts/cm-prd-drive.test.mjs +15 -0
  227. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  228. package/scripts/cm-prd-host.mjs +13 -4
  229. package/scripts/cm-prd-review-gate.mjs +126 -81
  230. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  231. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  232. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  233. package/scripts/cm-prd-self-check.test.mjs +6 -0
  234. package/scripts/cm-prd-summary.test.mjs +9 -0
  235. package/scripts/cm-release-smoke.sh +5 -1
  236. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  237. package/scripts/cm-review-inventory.test.mjs +253 -1
  238. package/scripts/cm-runtime-i18n.mjs +15 -4
  239. package/scripts/cm-runtime-install.mjs +8 -4
  240. package/scripts/cm-runtime.mjs +116 -23
  241. package/scripts/cm-runtime.test.mjs +121 -12
  242. package/scripts/cm-security.test.mjs +32 -0
  243. package/scripts/cm-spec-manifest.mjs +28 -10
  244. package/scripts/cm-spec-manifest.test.mjs +8 -4
  245. package/scripts/cm-spec-task-line.test.mjs +138 -0
  246. package/scripts/cm-specs-status.test.mjs +12 -1
  247. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  248. package/scripts/cm-task-gate.mjs +164 -20
  249. package/scripts/cm-task-gate.py +2 -1
  250. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  251. package/scripts/cm-test-drive.mjs +10 -4
  252. package/scripts/cm-test-drive.test.mjs +14 -1
  253. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  254. package/scripts/cm-usage-report.py +22 -3
  255. package/scripts/cm-workflow-config.mjs +10 -1
  256. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  257. package/scripts/fixtures/claude-review-process.mjs +1 -0
  258. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  259. package/scripts/fixtures/process-cleanup.mjs +101 -0
  260. package/scripts/test-cm-log-event.py +2 -0
  261. package/scripts/test-cm-native-usage.py +62 -0
  262. package/scripts/test-cm-prd-review-gate.py +2 -1
  263. package/scripts/test-external-model-setup.py +91 -0
  264. package/scripts/test-model-configuration-write.py +201 -0
  265. package/scripts/test-npm-install.py +11 -2
  266. package/scripts/test-scan-public-safety.py +1 -1
  267. package/scripts/test-spec-manifest.py +16 -8
  268. package/scripts/test-task-gate.py +2 -2
  269. package/scripts/test-workflow-config.py +1 -0
  270. package/scripts/validate-public-repo.py +1 -0
  271. package/skills/cm-ai/SKILL.md +2 -2
  272. package/skills/cm-ai/references/N1-init.md +1 -1
  273. package/skills/cm-ai/references/N8-finish.md +5 -0
  274. package/skills/cm-ai/references/js-host.md +270 -43
  275. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  276. package/skills/cm-fix/SKILL.md +1 -1
  277. package/skills/cm-fix/references/js-host.md +52 -3
  278. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  279. package/skills/cm-prd/references/js-host.md +6 -0
  280. package/skills/cm-runtime/SKILL.md +29 -6
  281. package/skills/cm-security/SKILL.md +4 -2
  282. package/skills/cm-security/references/scan-contract.md +1 -0
  283. package/templates/cm-workflow.yml +1 -1
@@ -1,4 +1,4 @@
1
- import test from 'node:test';
1
+ import test,{after} from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
3
  import fs from 'node:fs';
4
4
  import os from 'node:os';
@@ -14,6 +14,15 @@ import {createFixReviewHost} from '../runtime/js/cm-fix/host-review.mjs';
14
14
  import {configFingerprint} from '../runtime/js/cm-ai/codex-config.mjs';
15
15
  import {fixHandoffEvidence,fixDefectHandoffEvidence} from '../runtime/js/cm-fix/handoff.mjs';
16
16
 
17
+ // Never write the real ~/.cm-workflow home or its global log from this suite.
18
+ const isolatedHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-abandon-home-'));
19
+ const savedHome={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
20
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedHome,'home');process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedHome,'logs');
21
+ after(()=>{
22
+ for(const [key,value] of Object.entries(savedHome)){if(value===undefined)delete process.env[key];else process.env[key]=value;}
23
+ fs.rmSync(isolatedHome,{recursive:true,force:true});
24
+ });
25
+
17
26
  const diagnosis={status:'diagnosed',rootCause:'Wrong value',affectedPaths:['value.mjs'],
18
27
  affectedModules:['value'],plan:'Correct value',crossLayer:false};
19
28
 
@@ -41,11 +50,13 @@ async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,les
41
50
  permissions:['--allow-final-review','--allow-cause-review','--allow-repair'],workerFactory:()=>async({prompt},{onEvent})=>{
42
51
  reviews++;
43
52
  const data=JSON.parse(prompt.split('<cm-review-data-json>\n')[1]);
44
- onEvent({event:'thread.started',provider_thread:`fixture-review-${reviews}`});
45
- if(reviewMode==='lost'||reviewMode==='second_lost'&&reviews===2)throw Error('Synthetic lost review result');
53
+ onEvent({event:'thread.started',provider_thread:`fixture-review-${reviewMode==='first_lost_same_thread'?1:reviews}`});
54
+ if(reviewMode==='lost'||['second_lost','second_lost_retry'].includes(reviewMode)&&reviews===2
55
+ ||['first_lost','first_lost_same_thread'].includes(reviewMode)&&reviews===1)throw Error('Synthetic lost review result');
46
56
  for(const event of [{event:'turn.started',item_type:null},{event:'item.completed',item_type:'agent_message'},
47
57
  {event:'turn.completed',item_type:null},{event:'process_closed',exit_code:0,signal:null,timed_out:false}])onEvent(event);
48
- const verdict=['changes_requested','second_lost'].includes(reviewMode)?'changes_requested':'approved';
58
+ const verdict=['changes_requested','second_lost'].includes(reviewMode)||reviewMode==='second_lost_retry'&&reviews===1
59
+ ?'changes_requested':'approved';
49
60
  return {status:'succeeded',value:{verdict,packageDigest:data.reviewPackage.packageDigest,
50
61
  examinedPaths:data.examinedPaths,
51
62
  findings:verdict==='changes_requested'?[{id:'F1',severity:'P2',path:'value.mjs',message:'Revise value',evidence:'Fixture'}]:[],
@@ -60,7 +71,7 @@ async function fixture(t,{observation=false,reviewMode=null,crossLayer=false,les
60
71
  return crossLayer?{...diagnosis,crossLayer:true}:diagnosis;
61
72
  }
62
73
  if(kind==='fix_repair'){
63
- if(['changes_requested','second_lost'].includes(reviewMode)&&payload.identity.attempt===2&&loseRevisionRepair){
74
+ if(['changes_requested','second_lost','second_lost_retry'].includes(reviewMode)&&payload.identity.attempt===2&&loseRevisionRepair){
64
75
  loseRevisionRepair=false;throw Error('Lost revision repair answer');
65
76
  }
66
77
  fs.writeFileSync(path.join(cwd,'value.mjs'),payload.identity.attempt===2?'export const value=2; // revised\n':'export const value=2;\n');
@@ -381,3 +392,110 @@ test('revision final review cannot use local abandonment',async t=>{
381
392
  assert.equal(f.owner().status().pending,'revision_final_review');
382
393
  assert.throws(()=>f.owner().abandonStep({authorized:true,reason:'Review result lost'}),{code:'fix_abandon_unavailable'});
383
394
  });
395
+
396
+ // #15: a registered cause or second-round final review with no review result
397
+ // gets one audited abandonment and a retry on a fresh reviewer thread.
398
+ const causeDecide=async f=>{const pkg=f.owner().causeReviewPackage();
399
+ await f.reviewHost.authority.hostDecisionProvider.decide({identity:f.identity,packageDigest:pkg.packageDigest},new AbortController().signal);};
400
+ const reviewEvents=f=>fs.readFileSync(path.join(f.specsRoot,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse)
401
+ .filter(row=>row.event==='abandon');
402
+
403
+ test('#15 a no-result cause review is abandoned once, audited, and retried on a fresh reviewer thread',async t=>{
404
+ const f=await fixture(t,{reviewMode:'first_lost',crossLayer:true});
405
+ assert.equal((await f.owner().advance({authorized:true})).stage,'cause_review_required');
406
+ await causeDecide(f);
407
+ const lost=await f.owner().reviewCause();
408
+ assert.equal(lost.stage,'unknown');assert.equal(lost.pending,'cause_review');assert.equal(lost.reviewAbandonable,'cause_review');
409
+ const before=fs.readFileSync(f.statePath);
410
+ assert.throws(()=>f.owner().abandonStep({authorized:true,reason:'Review result lost'}),{code:'fix_abandon_unavailable'});
411
+ assert.throws(()=>f.owner().abandonReview({authorized:false,reason:'Review result lost'}),{code:'fix_review_abandon_authorization_required'});
412
+ assert.throws(()=>f.owner().abandonReview({authorized:true,reason:'two\nlines'}),{code:'fix_review_abandon_reason_required'});
413
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
414
+ const abandoned=f.owner().abandonReview({authorized:true,reason:'Reviewer process confirmed stopped'});
415
+ assert.equal(abandoned.stage,'cause_review_required');
416
+ assert.equal(abandoned.causeReviewAbandonment.providerThreadId,'fixture-review-1');
417
+ assert.equal(abandoned.causeReviewAbandonment.resultDigest,null);
418
+ assert.equal(f.reopen().status().stage,'cause_review_required');
419
+ await causeDecide(f);
420
+ assert.equal((await f.owner().reviewCause()).stage,'red_test_required');
421
+ const ids=f.records().map(row=>row.id).filter(id=>id.startsWith('fix-cause'));
422
+ assert.deepEqual(ids,['fix-cause-registered','fix-cause-started','fix-cause-abandoned',
423
+ 'fix-cause-retry-registered','fix-cause-retry-started','fix-cause-retry-result']);
424
+ assert.equal(f.records().find(row=>row.id==='fix-cause-retry-started').payload.providerThreadId,'fixture-review-2');
425
+ assert.equal(f.reviews(),2);
426
+ assert(fs.existsSync(path.join(f.specsRoot,'.reviews','fix-abandon-cause-r1.md')));
427
+ assert.deepEqual(reviewEvents(f).map(row=>[row.phase,row.pending,row.reason]),[['cause_review','cause_review','Reviewer process confirmed stopped']]);
428
+ assert.equal(f.reopen().status().stage,'red_test_required');
429
+ assert.equal(f.owner().status().causeReview.providerThreadId,'fixture-review-2');
430
+ });
431
+
432
+ test('#15 a second no-result cause review exhausts the one-time budget without changing the store',async t=>{
433
+ const f=await fixture(t,{reviewMode:'lost',crossLayer:true});
434
+ await f.owner().advance({authorized:true});await causeDecide(f);
435
+ assert.equal((await f.owner().reviewCause()).stage,'unknown');
436
+ f.owner().abandonReview({authorized:true,reason:'First reviewer stopped'});
437
+ await causeDecide(f);
438
+ const again=await f.owner().reviewCause();
439
+ assert.equal(again.stage,'unknown');assert.equal(again.reviewAbandonBudgetExhausted,true);assert.equal(again.reviewAbandonable,undefined);
440
+ const before=fs.readFileSync(f.statePath);
441
+ assert.throws(()=>f.owner().abandonReview({authorized:true,reason:'Second reviewer stopped'}),{code:'fix_review_abandon_budget_exhausted'});
442
+ assert.deepEqual(fs.readFileSync(f.statePath),before);
443
+ });
444
+
445
+ test('#15 an abandonment record must bind the exact registration and thread',async t=>{
446
+ const f=await fixture(t,{reviewMode:'lost',crossLayer:true});
447
+ await f.owner().advance({authorized:true});await causeDecide(f);await f.owner().reviewCause();
448
+ const registration=f.records().find(row=>row.id==='fix-cause-registered');
449
+ const forged={invocationId:registration.payload.request.invocationId,registrationDigest:'0'.repeat(64),
450
+ providerThreadId:'fixture-review-1',resultDigest:null,reason:'Forged',abandonedAt:Date.now()};
451
+ assert.throws(()=>f.append('fix-cause-abandoned','result',forged),{code:'fix_review_abandon_mismatch'});
452
+ });
453
+
454
+ test('#15 the fix host needs the dedicated --allow-abandon-review for abandon_review and its status points to it',async t=>{
455
+ const f=await fixture(t,{reviewMode:'lost',crossLayer:true});
456
+ await f.owner().advance({authorized:true});await causeDecide(f);await f.owner().reviewCause();
457
+ const config={...f.configuration,specsRoot:f.specsRoot,identity:f.identity};
458
+ // Local step abandonment authority does not extend to a reviewer invocation.
459
+ for(const permissions of [['--allow-reproduction'],['--allow-reproduction','--allow-abandon']]){
460
+ const refused=createFixHost({owner:f.owner(),config,permissions});
461
+ await assert.rejects(refused.handle({requestId:'abandon',operation:'abandon_review',reason:'Stopped'}),{code:'fix_review_abandon_authorization_required'});
462
+ }
463
+ const allowed=createFixHost({owner:f.owner(),config,permissions:['--allow-reproduction','--allow-abandon-review']});
464
+ assert.match((await allowed.handle({requestId:'status',operation:'status'})).progress.nextAction,/abandon_review/);
465
+ assert.equal((await allowed.handle({requestId:'abandon',operation:'abandon_review',reason:'Stopped'})).stage,'cause_review_required');
466
+ });
467
+
468
+ test('#15 a no-result second-round final review is abandoned once and retried on a fresh thread',async t=>{
469
+ const f=await fixture(t,{reviewMode:'second_lost_retry'});
470
+ await toRevision(f);await completeRevisionRepair(f);
471
+ await f.owner().runRegression({authorized:true});await f.owner().retrospect();
472
+ assert.equal(f.owner().createHandoff().stage,'revision_final_review_required');
473
+ const decide=async()=>{const pkg=f.owner().finalReviewPackage();
474
+ await f.reviewHost.finalAuthority.hostDecisionProvider.decide({identity:f.owner().status().revision.nextIdentity,
475
+ packageDigest:pkg.packageDigest},new AbortController().signal);};
476
+ await decide();
477
+ const lost=await f.owner().reviewFinal();
478
+ assert.equal(lost.stage,'unknown');assert.equal(lost.pending,'revision_final_review');
479
+ assert.equal(lost.reviewAbandonable,'revision_final_review');
480
+ assert.equal(f.owner().abandonReview({authorized:true,reason:'Second reviewer stopped'}).stage,'revision_final_review_required');
481
+ assert.equal(f.reopen().status().stage,'revision_final_review_required');
482
+ await decide();
483
+ assert.equal((await f.owner().reviewFinal()).stage,'revision_final_review_evidence_required');
484
+ const ids=f.records().map(row=>row.id).filter(id=>id.startsWith('fix-revision-final'));
485
+ assert.deepEqual(ids,['fix-revision-final-registered','fix-revision-final-started','fix-revision-final-abandoned',
486
+ 'fix-revision-final-retry-registered','fix-revision-final-retry-started','fix-revision-final-retry-result']);
487
+ assert.notEqual(f.records().find(row=>row.id==='fix-revision-final-retry-started').payload.providerThreadId,
488
+ f.records().find(row=>row.id==='fix-revision-final-started').payload.providerThreadId);
489
+ assert.equal(f.owner().publishReview().stage,'revision_completion_gate_required');
490
+ assert.equal(f.reopen().status().stage,'revision_completion_gate_required');
491
+ });
492
+
493
+ test('#15 the retried cause review refuses the abandoned reviewer thread',async t=>{
494
+ const f=await fixture(t,{reviewMode:'first_lost_same_thread',crossLayer:true});
495
+ await f.owner().advance({authorized:true});await causeDecide(f);await f.owner().reviewCause();
496
+ f.owner().abandonReview({authorized:true,reason:'Reviewer process confirmed stopped'});
497
+ await causeDecide(f);
498
+ const reused=await f.owner().reviewCause();
499
+ assert.equal(reused.stage,'unknown');assert.equal(reused.pending,'cause_review');
500
+ assert(!f.records().some(row=>row.id==='fix-cause-retry-started'));
501
+ });
@@ -57,6 +57,8 @@ test('cause package binds only selected current source and never advances the fi
57
57
  requestedModel:'synthetic',contextId:'logical-review',payload:{reviewPackage:first,priorReview:null}});
58
58
  assert.match(buildCauseReviewPrompt(request,provider),/pre-implementation review/);
59
59
  assert.match(buildCauseReviewPrompt(request,provider),/Rewrite all callers/);
60
+ assert.match(buildCauseReviewPrompt(request,provider),/approved requires zero P0, P1 and P2 findings/);
61
+ assert.match(buildCauseReviewPrompt(request,provider),/changes_requested requires at least one P0, P1 or P2 finding/);
60
62
  assert.throws(()=>buildReviewPrompt(request,provider));
61
63
  const expectation=JSON.stringify({request,developerThreadId:'author',excludedThreadIds:['fixture-host']});
62
64
  const observation={version:1,kind:'cm-provider-review-observation',requestDigest:request.requestDigest,
@@ -21,20 +21,23 @@
21
21
  // "runtime": "codex" | "claude", 缺省 codex
22
22
  // "reviewConfig": "review.json", 可选
23
23
  // "permissions": ["--allow-red-test", ...], 原样传给宿主,不另造一套词
24
- // "answers": "answers", 答案目录;abandon_step 可省略
25
- // "reason": "旧本地步骤结果丢失" abandon_step 必填,并需 --allow-abandon
24
+ // "answers": "answers", 答案目录;abandon_step / abandon_review 可省略
25
+ // "reason": "旧本地步骤结果丢失" abandon_step 必填并需 --allow-abandon;abandon_review 必填并需 --allow-abandon-review
26
+ // "inputLimit": 1048576 可选;宿主输入与应答上限(65536–4194304,默认 65536)
26
27
  // }
27
28
  //
28
29
  // answers/ 里按反问种类放文件,一种一个:
29
30
  // learning.json {status, summary} 恢复时若存档里已有记录会自动复用
30
- // diagnosis.json 诊断结论对象
31
+ // diagnosis.json 首次诊断结论对象
32
+ // diagnosis-rediagnosis.json 显式原运行重新诊断的新结论,不能复用首次文件
31
33
  // retrospective.json {status, candidates, reason}
32
- // test-edits.json {"仓库内路径": "本目录下的内容文件"}
33
- // repair-edits.json 同上
34
+ // test-edits.json {"仓库内路径": "本目录下的内容文件"};修订轮用 test-edits-a2.json
35
+ // repair-edits.json 同上;修订轮用 repair-edits-a2.json
34
36
  import fs from 'node:fs';
35
37
  import path from 'node:path';
36
38
  import {fileURLToPath} from 'node:url';
37
39
  import {fixEvidenceNames} from '../runtime/js/cm-fix/layout.mjs';
40
+ import {readExecutionSnapshot} from '../runtime/js/cm-ai/execution-snapshot.mjs';
38
41
  import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
39
42
 
40
43
  const here=path.dirname(fileURLToPath(import.meta.url));
@@ -45,7 +48,7 @@ const HOST=path.join(here,'cm-fix-host.mjs');
45
48
  // design_change_required uses red_test (or test_author_required/author_tests).
46
49
  // escalation_required uses publish_dossier/finish: neither requests answers.
47
50
  const ASKS={
48
- advance:['learning','diagnosis'],
51
+ advance:['learning','diagnosis'],rediagnose:['learning','diagnosis'],
49
52
  author_tests:['learning','test-edits'],
50
53
  repair:['learning','repair-edits'],
51
54
  retrospective:['learning','retrospective'],
@@ -55,18 +58,32 @@ const ASKS={
55
58
  const READ_ONLY=new Set(['status','final_review_package','completion_evidence','cause_review_package']);
56
59
  const KNOWN=new Set([...Object.keys(ASKS),...READ_ONLY,'cancel','handoff','publish_review','check_n5',
57
60
  'publish_dossier','learning_writeback','walkthrough','finish','final_review','cause_review',
58
- 'recover_final_review','abandon_step','resume','revision_test_check']);
61
+ 'reconcile_review','recover_final_review','abandon_step','abandon_review','resume','revision_test_check']);
59
62
 
60
63
  function loadPlan(){
61
64
  const {operation,plan,base}=loadPlanFile({name:'cm-fix-drive.mjs',known:KNOWN});
62
- requireFields(plan,['config','cwd','mode','hostContext','permissions',...(operation==='abandon_step'?[]:['answers'])]);
65
+ const abandoning=['abandon_step','abandon_review'].includes(operation);
66
+ requireFields(plan,['config','cwd','mode','hostContext','permissions',...(abandoning||operation==='reconcile_review'?[]:['answers'])]);
63
67
  if(!['create','resume'].includes(plan.mode))stop(2,'mode 只能是 create 或 resume');
64
- if(!Array.isArray(plan.permissions)||plan.permissions.some(p=>!/^--allow-[a-z-]+$/.test(p)))
65
- stop(2,'permissions 必须是 --allow-xxx 形式的数组,原样传给宿主');
66
- if(operation==='abandon_step'&&(!plan.permissions.includes('--allow-abandon')||typeof plan.reason!=='string'
68
+ if(!Array.isArray(plan.permissions))stop(2,'permissions must be an array');
69
+ for(let i=0;i<plan.permissions.length;i++){
70
+ const flag=plan.permissions[i];
71
+ if(flag==='--external-models-config'){
72
+ if(typeof plan.permissions[i+1]!=='string')stop(2,'external model configuration path required');
73
+ plan.permissions[++i]=path.resolve(base,plan.permissions[i]);
74
+ }else if(!['--execution-optimizations','--external-models'].includes(flag)&&!/^--allow-[a-z-]+$/.test(flag))stop(2,'invalid permissions');
75
+ }
76
+ if(operation==='reconcile_review'&&(plan.mode!=='resume'||typeof plan.invocationId!=='string'||!plan.invocationId))stop(2,'reconcile_review requires resume and original invocationId');
77
+ const abandonFlag=operation==='abandon_review'?'--allow-abandon-review':'--allow-abandon';
78
+ if(abandoning&&(!plan.permissions.includes(abandonFlag)||typeof plan.reason!=='string'
67
79
  ||!plan.reason.trim().length||Buffer.byteLength(plan.reason,'utf8')>1000||/[\r\n\0\u0085\u2028\u2029]/.test(plan.reason)))
68
- stop(2,'abandon_step 需要 PLAN.reason(单行,最多 1000 字节)和 --allow-abandon');
80
+ stop(2,`${operation} 需要 PLAN.reason(单行,最多 1000 字节)和 ${abandonFlag}`);
81
+ if(operation==='rediagnose'&&(plan.mode!=='resume'||!plan.permissions.includes('--allow-rediagnosis')
82
+ ||typeof plan.reason!=='string'||!plan.reason.trim()||Buffer.byteLength(plan.reason,'utf8')>1000
83
+ ||/[\r\n\0\u0085\u2028\u2029]/.test(plan.reason)))stop(2,'rediagnose 需要 mode:resume、--allow-rediagnosis 和单行 reason');
69
84
  if(plan.originalHostContext&&plan.mode!=='resume')stop(2,'originalHostContext 只在 resume 时有意义');
85
+ if(Object.hasOwn(plan,'inputLimit')&&!(Number.isSafeInteger(plan.inputLimit)&&plan.inputLimit>=65536&&plan.inputLimit<=4194304))
86
+ stop(2,'inputLimit 需要 65536–4194304 的整数(字节)');
70
87
  const resolve=p=>path.resolve(base,p);
71
88
  return {operation,plan,paths:{config:resolve(plan.config),answers:plan.answers?resolve(plan.answers):null,
72
89
  review:plan.reviewConfig?resolve(plan.reviewConfig):null}};
@@ -78,27 +95,53 @@ function recordedLearning(config,cwd){
78
95
  const archive=config.specsRoot??path.join(cwd,'docs','fixes');
79
96
  const state=path.join(archive,'.reviews','.execution',config.identity.runId,'state.json');
80
97
  const stored=readJson(state,'存档');
81
- const record=stored?.records?.find(row=>row.kind==='result'&&/^fix-learning-/.test(row.id));
82
- return record?.payload?.application??null;
98
+ let current=null;
99
+ for(const row of stored?.records??[]){
100
+ if(row.kind==='result'&&/^fix-learning-[1-9]\d*-[0-9a-f]{64}$/.test(row.id))current=row.payload;
101
+ else if(row.kind==='intent'&&row.id==='fix-rediagnosis-intent')current=row.payload.learning;
102
+ }
103
+ return current?.application??null;
104
+ }
105
+ function answerRound(config,operation,cwd){
106
+ if(!['repair','author_tests'].includes(operation))return 1;
107
+ const archive=config.specsRoot??path.join(cwd,'docs','fixes');
108
+ const state=path.join(archive,'.reviews','.execution',config.identity.runId,'state.json');
109
+ if(!fs.existsSync(state))return 1;
110
+ try{
111
+ const snapshot=readExecutionSnapshot({specsRoot:archive,identity:{
112
+ repositoryId:config.identity.repositoryId,runId:config.identity.runId}});
113
+ return snapshot.records.some(row=>row.id==='fix-revision-prepared')?2:1;
114
+ }catch(error){stop(2,`无法只读检查 cm-fix 修订轮次: ${error.code??error.message}`);}
115
+ }
116
+ function roundAnswerName(root,kind,round){
117
+ const legacy=`${kind}.json`,first=`${kind}-a1.json`;
118
+ if(round===1){
119
+ if(fs.existsSync(path.join(root,legacy))&&fs.existsSync(path.join(root,first)))
120
+ stop(2,`${legacy} 与 ${first} 不能同时存在`);
121
+ return fs.existsSync(path.join(root,first))?first:legacy;
122
+ }
123
+ return `${kind}-a${round}.json`;
83
124
  }
84
125
 
85
- function preflight({operation,plan,paths}){
126
+ export function preflight({operation,plan,paths}){
86
127
  const config=readJson(paths.config,'宿主配置');
87
128
  if(config===undefined)stop(2,`宿主配置不存在: ${paths.config}`);
88
129
  if(path.resolve(plan.cwd)!==path.resolve(config.reproduction?.cwd??''))
89
130
  stop(2,`PLAN.cwd 与 config.reproduction.cwd 不一致`);
131
+ const round=answerRound(config,operation,plan.cwd);
90
132
  const need=(kind,file)=>{const value=readJson(path.join(paths.answers,file),kind);
91
133
  if(value===undefined)stop(2,`步骤 ${operation} 会反问「${kind}」,但答案文件不存在: ${path.join(paths.answers,file)}\n 先把它写好,再来调驾驱员。缺答案而硬发指令,会把这次运行做死。`);
92
134
  return value;};
93
135
  const answers=preflightAnswers(ASKS[operation]??[],kind=>{
94
136
  if(kind==='learning'){
95
- const recorded=plan.mode==='resume'?recordedLearning(config,plan.cwd):null;
137
+ const recorded=plan.mode==='resume'&&operation!=='rediagnose'?recordedLearning(config,plan.cwd):null;
96
138
  if(recorded){stderr(`恢复:复用存档里已记的学习记录(${recorded.status})`);return recorded;}
97
139
  return need('学习记录','learning.json');
98
140
  }
99
- if(kind==='diagnosis')return need('诊断','diagnosis.json');
141
+ if(kind==='diagnosis')return need('诊断',operation==='rediagnose'?'diagnosis-rediagnosis.json':'diagnosis.json');
100
142
  if(kind==='retrospective')return need('复盘','retrospective.json');
101
- const map=need(kind==='test-edits'?'测试内容':'修复内容',`${kind}.json`);
143
+ const file=roundAnswerName(paths.answers,kind,round);
144
+ const map=need(kind==='test-edits'?'测试内容':'修复内容',file);
102
145
  for(const [target,local] of Object.entries(map)){
103
146
  const file=path.join(paths.answers,local);
104
147
  if(!fs.existsSync(file))stop(2,`${kind}.json 把 ${target} 指向 ${file},但那个文件不存在`);
@@ -125,13 +168,14 @@ function preflight({operation,plan,paths}){
125
168
  stderr(`注意:受保护模式的沙箱跑不了 tsx / vitest 这类要开本地 socket 的命令:${command.join(' ')}\n 见 skills/cm-fix/references/js-host.md「同仓 specs 的受保护修复」`);
126
169
  }
127
170
  }
128
- return {config,answers};
171
+ return {config,answers,round};
129
172
  }
130
173
 
131
174
  function hostArgs({plan,paths}){
132
175
  return [HOST,'serve','--config',paths.config,'--mode',plan.mode,'--host-context',plan.hostContext,'--allow-reproduction',
133
176
  ...(plan.originalHostContext?['--original-host-context',plan.originalHostContext]:[]),
134
177
  '--runtime',plan.runtime??'codex',
178
+ ...(Object.hasOwn(plan,'inputLimit')?['--input-limit',String(plan.inputLimit)]:[]),
135
179
  ...(paths.review?['--review-config',paths.review]:[]),
136
180
  ...plan.permissions];
137
181
  }
@@ -142,6 +186,9 @@ function answerFor(row,answers,paths){
142
186
  if(kind==='fix_diagnose')return answers.diagnosis;
143
187
  if(kind==='fix_retrospective')return answers.retrospective;
144
188
  if(kind==='fix_test_author'||kind==='fix_repair'){
189
+ const requestAttempt=payload.identity?.attempt??payload.request?.identity?.attempt;
190
+ if(requestAttempt!==undefined&&requestAttempt!==paths.round)
191
+ throw Error(`修订轮次 ${requestAttempt} 与已预检答案轮次 ${paths.round} 不一致`);
145
192
  const map=answers[kind==='fix_repair'?'repair-edits':'test-edits'],expected=payload.expected??{};
146
193
  const edits=[];
147
194
  for(const [target,local] of Object.entries(map)){
@@ -157,12 +204,12 @@ function answerFor(row,answers,paths){
157
204
 
158
205
  function main(){
159
206
  const loaded=loadPlan();
160
- const {answers}=preflight(loaded);
207
+ const {answers,round}=preflight(loaded);
161
208
  const {operation,plan,paths}=loaded;
162
209
  driveHost({host:HOST,args:hostArgs(loaded).slice(1),cwd:path.resolve(plan.cwd),operation,
163
- request:{...(operation==='abandon_step'?{reason:plan.reason}:{}),
210
+ request:{...(operation==='reconcile_review'?{invocationId:plan.invocationId}:{}),...(['abandon_step','abandon_review','rediagnose'].includes(operation)?{reason:plan.reason}:{}),
164
211
  ...(operation==='prepare_revision'&&Object.hasOwn(plan,'revisionTests')?{tests:plan.revisionTests}:{})},
165
- answers,paths,answerFor});
212
+ answers,paths:{...paths,round},answerFor});
166
213
  }
167
214
 
168
- main();
215
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))main();
@@ -1,4 +1,4 @@
1
- import test from 'node:test';
1
+ import test,{after} from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
3
  import {spawnSync} from 'node:child_process';
4
4
  import fs from 'node:fs';
@@ -10,6 +10,15 @@ import {openFixExecution} from '../runtime/js/cm-fix/execution.mjs';
10
10
  import {openExecutionStore} from '../runtime/js/cm-ai/execution-store.mjs';
11
11
  import {startFixRun} from '../runtime/js/cm-fix/start.mjs';
12
12
 
13
+ // Never write the real ~/.cm-workflow home or its global log from this suite.
14
+ const isolatedHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-drive-home-'));
15
+ const savedHome={CM_WORKFLOW_HOME:process.env.CM_WORKFLOW_HOME,CM_WORKFLOW_LOG_HOME:process.env.CM_WORKFLOW_LOG_HOME};
16
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedHome,'home');process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedHome,'logs');
17
+ after(()=>{
18
+ for(const [key,value] of Object.entries(savedHome)){if(value===undefined)delete process.env[key];else process.env[key]=value;}
19
+ fs.rmSync(isolatedHome,{recursive:true,force:true});
20
+ });
21
+
13
22
  // 驾驭员是宿主的中间人:开进程、发一条指令、代答反问、打结果。它的价值有两条要
14
23
  // 拿真宿主验:确实能把一轮开起来并走下去;答案没备齐时停在发指令之前,不把运行做死。
15
24
  const DRIVER=fileURLToPath(new URL('./cm-fix-drive.mjs',import.meta.url));
@@ -115,3 +124,29 @@ test('the driver abandons a local unknown step using only plan reason and flag',
115
124
  assert.equal(JSON.parse(result.stdout).result.stage,'reproduce');
116
125
  assert(JSON.parse(fs.readFileSync(statePath)).records.some(row=>row.id==='fix-abandoned-1'));
117
126
  });
127
+ test('#15 the driver refuses abandon_review without plan reason and --allow-abandon-review before launching the host',{skip},t=>{
128
+ const f=fixture(t);
129
+ for(const plan of [f.plan({mode:'resume',permissions:[],reason:'Reviewer stopped',answers:undefined}),
130
+ f.plan({mode:'resume',permissions:['--allow-abandon'],reason:'Reviewer stopped',answers:undefined}),
131
+ f.plan({mode:'resume',permissions:['--allow-abandon-review'],answers:undefined})]){
132
+ const refused=drive(plan,'abandon_review');
133
+ assert.equal(refused.status,2);assert.match(refused.stderr,/abandon_review 需要 PLAN\.reason/);
134
+ }
135
+ assert.equal(fs.existsSync(path.join(f.archive,'.reviews')),false);
136
+ });
137
+ test('revision repair requires its own answer before launching the host',{skip},t=>{
138
+ const f=fixture(t);
139
+ fs.writeFileSync(path.join(f.answers,'learning.json'),JSON.stringify(learning));
140
+ fs.writeFileSync(path.join(f.answers,'diagnosis.json'),JSON.stringify(diagnosis));
141
+ assert.equal(drive(f.plan(),'advance').status,0);
142
+ const statePath=path.join(f.archive,'.reviews','.execution','drive-demo','state.json');
143
+ const state=JSON.parse(fs.readFileSync(statePath));
144
+ const store=openExecutionStore({specsRoot:f.archive,identity:state.identity,fingerprints:state.fingerprints,create:false});
145
+ store.append({id:'fix-revision-prepared',kind:'result',payload:{nextIdentity:{...state.identity,attempt:2}},
146
+ expectedRevision:store.snapshot().revision});store.close();
147
+ fs.writeFileSync(path.join(f.answers,'repair-edits.json'),JSON.stringify({'value.mjs':'repair.txt'}));
148
+ const before=fs.readFileSync(statePath);
149
+ const run=drive(f.plan({mode:'resume',permissions:['--allow-repair']}),'repair');
150
+ assert.equal(run.status,2,run.stderr);assert.match(run.stderr,/repair-edits-a2\.json/);
151
+ assert.deepEqual(fs.readFileSync(statePath),before);
152
+ });
@@ -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,25 +1,30 @@
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';
6
8
  import {createFixHost} from '../runtime/js/cm-fix/host.mjs';
7
9
  import {createFixLearningPreparation} from '../runtime/js/cm-fix/learning.mjs';
8
10
  import {createHostToolBridge} from '../runtime/js/cm-ai/host-tool-bridge.mjs';
9
- import {serveCmAiHost} from '../runtime/js/cm-ai/host-session.mjs';
11
+ import {serveCmAiHost,parseHostInputLimit,inputLimitReason} from '../runtime/js/cm-ai/host-session.mjs';
10
12
  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] [--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');
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');
23
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');
24
29
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('Second-round retrospective uses the cumulative original baseline, including previously authored tests and Learning scope. It persists the current round reflection and reaches revision_handoff_ready or revision_learning_writeback_required; neither state completes the task or publishes a new handoff. From revision_handoff_ready, handoff publishes a separate a2 handoff containing cumulative changes, current reflection, original red evidence and prior review/Learning history; final_review_package then reads that bound package. Pending Learning blocks publication. final_review requires --allow-final-review, uses fresh-thread exclusions and carries prior findings; publish_review writes the original r2 evidence and review log, and check_n5 runs the original Learning-aware gate. Approval reaches revision_post_review_regression_required, not completion.\n');
25
30
  if(argv.length===1&&['--help','-h'].includes(argv[0]))output.write('prepare_revision requires --allow-repair and either a published first-round changes_requested review or an approved first-round review followed by a package-bound walkthrough result of failed. The latter preserves the approved verdict and carries separate walkthrough failure evidence; passed, blocked, unknown, or drifted evidence cannot authorize this repair. An approved first-round review followed by package-bound post-review regression defect_remaining or regressed can also prepare the second repair when all baseline commands produced complete results. The regression commands must match the first reviewed handoff; passed, inconclusive, unavailable or partial evidence is refused. Regression and walkthrough failure feedback are mutually exclusive and neither replaces the next independent review. It rereads project Learning and persists the second-round preparation in the original store, preserving first-round evidence. repair then uses the original business scope and findings with separate second-round records. regression requires --allow-regression and reruns the original test commands against the second repair, preserving the original red evidence. Success reaches revision_handoff_required, not completion; handoff and final_review use the second-round package; review evidence publication and N5 are connected; post_review_regression requires --allow-regression and reaches revision_closeout_required after the original checks; walkthrough requires --allow-walkthrough and binds the second-round package and identity; finish reuses the original closeout with --allow-finish, preserving first-round history and recording completion for attempt 2. Second-round learning_writeback requires --allow-learning-writeback, includes the resulting AGENTS.md in the cumulative review package and preserves prior Learning history; pending or unknown writeback cannot advance to handoff. A lost repair or regression result stays unknown and is not redispatched.\n');
@@ -31,8 +36,8 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
31
36
  need(['create','resume'].includes(argv[4]),'invalid_arguments');id(argv[6]);
32
37
  const extra=new Map();
33
38
  for(let index=8;index<argv.length;index++){
34
- const flag=argv[index];need(!extra.has(flag)&&['--runtime','--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-red-test','--allow-baseline','--allow-test-author','--allow-repair','--allow-regression','--allow-learning-writeback','--allow-walkthrough','--allow-finish'].includes(flag),'invalid_arguments');
35
- 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);
36
41
  else{need(typeof argv[index+1]==='string'&&!argv[index+1].startsWith('--'),'invalid_arguments');extra.set(flag,argv[++index]);}
37
42
  }
38
43
  // A run created in an earlier session keeps that session in its durable record.
@@ -43,10 +48,9 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
43
48
  const recoveryInvocationId=extra.get('--final-review-recovery-invocation')??null;
44
49
  if(recoveryInvocationId!==null){id(recoveryInvocationId);need(extra.has('--allow-final-review-recovery'),'fix_review_recovery_authorization_required');}
45
50
  const runtime=extra.get('--runtime')??'codex';need(['codex','claude'].includes(runtime),'invalid_runtime');
46
- const review=extra.has('--review-config')?readConversationReviewConfiguration(extra.get('--review-config')):null;
47
- need(runtime!=='claude'||!review||review.disabledSkills.length===0,'invalid_review_config');
48
- need(!extra.has('--allow-cause-review')||review!==null,'review_configuration_required');
49
- need(!extra.has('--allow-final-review')||review!==null,'review_configuration_required');
51
+ // Transport only, like the cm-ai hosts: lines and tool replies share one limit.
52
+ const inputLimit=parseHostInputLimit(extra.get('--input-limit'));
53
+ let review;
50
54
  const stat=fs.lstatSync(argv[2]);
51
55
  need(stat.isFile()&&!stat.isSymbolicLink()&&stat.size<=64*1024,'invalid_fix_config');
52
56
  const config=json(JSON.parse(fs.readFileSync(argv[2],'utf8')),64*1024);
@@ -55,6 +59,12 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
55
59
  ...(Object.hasOwn(config,'qaSource')?['qaSource']:[]),
56
60
  ...(Object.hasOwn(config,'redTest')?['redTest']:[]),...(Object.hasOwn(config,'baseline')?['baseline']:[]),
57
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');
58
68
  need(!extra.has('--allow-walkthrough')||config.walkthrough,'walkthrough_configuration_required');
59
69
  need(!Object.hasOwn(config,'qaSource')||extra.has('--allow-qa-fix'),'qa_fix_authorization_required');
60
70
  need(!extra.has('--allow-qa-fix')||Object.hasOwn(config,'qaSource'),'qa_fix_source_required');
@@ -65,11 +75,11 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
65
75
  need(!extra.has('--allow-regression')||(config.repair&&config.redTest&&config.baseline),'regression_configuration_required');
66
76
  const {reviewer,authority,finalAuthority,execution:reviewExecution}=createFixReviewHost({
67
77
  codeProject:config.reproduction.cwd,hostContextId:argv[6],runtime,review,
68
- permissions:[...extra.keys()],workerFactory:reviewWorkerFactory});
69
- bridge=createHostToolBridge();
78
+ permissions:[...extra.keys()],workerFactory:reviewWorkerFactory,externalModels,executionPolicy,specsDir:config.specsRoot??null});
79
+ bridge=createHostToolBridge({responseLimit:inputLimit});
70
80
  owner=openFixExecution({specsRoot:config.specsRoot??null,identity:config.identity,create:argv[4]==='create',
71
81
  hostContextId:argv[6],
72
- 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,
73
83
  ...(Object.hasOwn(config,'protectSpecs')?{protectSpecs:config.protectSpecs}:{}),
74
84
  ...(Object.hasOwn(config,'qaSource')?{qaSource:config.qaSource}:{}),
75
85
  ...(runtime==='claude'?{runtime}:{}),
@@ -86,12 +96,12 @@ export async function main(argv=process.argv.slice(2),{input=process.stdin,outpu
86
96
  const host=createFixHost({owner,config,runtime,permissions:[...extra.keys(),'--allow-reproduction'],authority,finalAuthority,recoveryInvocationId});
87
97
  const rawMode=input.isTTY&&typeof input.setRawMode==='function';
88
98
  if(rawMode)input.setRawMode(true);
89
- try{await serveCmAiHost({host,input,output,toolBridge:bridge});}
99
+ try{await serveCmAiHost({host,input,output,toolBridge:bridge,inputLimit});}
90
100
  finally{if(rawMode)input.setRawMode(false);}
91
101
  return 0;
92
102
  }catch(cause){
93
103
  const code=typeof cause?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(cause.code)?cause.code:'fix_host_failed';
94
- error.write(JSON.stringify({error:{code}})+'\n');return 1;
104
+ error.write(JSON.stringify({error:{code,...(code==='request_too_large'?{reason:inputLimitReason(cause.limit)}:{})}})+'\n');return 1;
95
105
  }finally{bridge?.close();owner?.close();}
96
106
  }
97
107
  if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url))process.exitCode=await main();
@@ -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
+ });