@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
@@ -19,7 +19,7 @@ import {createHash} from 'node:crypto';
19
19
  import {createHostCheck} from './host-check.mjs';
20
20
  import {inspectCmAiAdmission,inspectCmAiBootstrapTask,matchesCmAiTaskSelection} from './cm-ai-admission.mjs';
21
21
  import {readBootstrapConfiguration,readConversationProtection} from '../../../scripts/cm-ai-host.mjs';
22
- import {mergeBootstrapAgents} from './host-bootstrap.mjs';
22
+ import {mergeBootstrapAgents,committedBootstrapBasis} from './host-bootstrap.mjs';
23
23
  import {createCmAiTaskLearningApplication,createCmAiTaskLearningRetrospective} from './cm-ai-context-refresh.mjs';
24
24
  import {cmInitRuleTargets,validateCmInitSelection} from '../cm-init/draft-generation.mjs';
25
25
  import {inspectCmInitDraft,readCmInitSource} from '../cm-init/draft-inspection.mjs';
@@ -37,6 +37,9 @@ const refuse=(ok,line)=>{if(!ok)stop(2,line);};
37
37
  const envelope=result=>Buffer.byteLength(JSON.stringify({type:'host_result',sessionId:'0'.repeat(36),
38
38
  callId:'0'.repeat(36),requestDigest:'0'.repeat(64),result}),'utf8');
39
39
  const learningSection=source=>/^## 项目教训[ \t]*\r?$/gmu.test(source);
40
+ const committedBasis=(definition,targets)=>committedBootstrapBasis({specsDir:definition.specsDir,
41
+ codeProject:definition.codeProject,feature:definition.feature,taskId:definition.identity.taskId,
42
+ instructionPaths:targets});
40
43
  const sha=bytes=>bytes===null?null:createHash('sha256').update(bytes).digest('hex');
41
44
 
42
45
  export function attemptAnswerName(root,name,attempt){
@@ -107,25 +110,30 @@ function readGenerate(root,name,{definition,bootstrap,learning}){
107
110
  inspected(definition.codeProject,documents,bootstrap.selection,name);
108
111
  refuse(envelope({status:'generated',documents})<=RESPONSE_LIMIT,
109
112
  `${name} 的正文合计超过宿主单次回复 64 KiB 上限;精简规范正文,不要截断`);
110
- // Same expectations as host-bootstrap.mjs run(): files this run already wrote are
111
- // bound to the journal's recorded evidence (revision or same-attempt retry);
112
- // without it only an AGENTS.md carrying a Learning section may pre-exist.
113
+ // Same baseline as host-bootstrap.mjs: this run's prior evidence wins, then
114
+ // a completed same-feature rule task may authorize clean committed targets.
113
115
  const project=definition.codeProject,prior=learning?.bootstrap??null,writeback=learning?.writeback??null;
116
+ const basis=committedBasis(definition,targets);
117
+ refuse(basis!==null,`前序规则任务已完成,但固定目标没有可用的 HEAD 提交基准(bootstrap_instruction_conflict);`
118
+ +'请恢复已提交的规则文件与暂存区,或在新提交后使用新 runId');
114
119
  for(const file of targets){
115
120
  const bytes=readTarget(project,file);
116
- if(prior===null)refuse(bytes===null||file==='AGENTS.md'&&learningSection(bytes.toString('utf8')),
117
- `规范目标已存在: ${file};本运行尚未写入规范,只允许带「## 项目教训」段的 AGENTS.md,宿主不覆盖已有规则(bootstrap_instruction_conflict)`);
121
+ if(prior===null){
122
+ const expected=basis?.files.find(item=>item.path===file)?.sha256??null;
123
+ refuse(basis!==undefined?sha(bytes)===expected:bytes===null||file==='AGENTS.md'&&learningSection(bytes.toString('utf8')),
124
+ `规范目标 ${file} 与本运行可信基准不一致(bootstrap_instruction_conflict);先还原已提交内容,或用新 runId 绑定新的提交`);
125
+ }
118
126
  else{
119
127
  const expected=file==='AGENTS.md'&&writeback?.outcome==='written'?writeback.agentsFile.sha256
120
128
  :prior.files.find(item=>item.path===file)?.afterSha256??null;
121
129
  refuse(sha(bytes)===expected,`规范目标 ${file} 与本运行已记录的写入不一致(期望 ${expected??'不存在'},当前 ${sha(bytes)??'不存在'});`
122
- +'宿主会以 bootstrap_instruction_conflict 停在 unknown,先还原该文件');
130
+ +'驾驶员预检已拒绝启动宿主;先还原该文件');
123
131
  }
124
132
  }
125
133
  const existing=readTarget(project,'AGENTS.md')?.toString('utf8')??'';
126
134
  let merged;
127
- try{merged=mergeBootstrapAgents(existing,documents.find(item=>item.path==='AGENTS.md').content);}
128
- catch{stop(2,`${name} 的 AGENTS.md 必须逐字保留当前 AGENTS.md 中「## 项目教训」段以外的全部内容(宿主只把该段按原字节合入);否则宿主以 bootstrap_instruction_conflict 停在 unknown`);}
135
+ try{merged=mergeBootstrapAgents(existing,documents.find(item=>item.path==='AGENTS.md').content,{refresh:basis!==undefined});}
136
+ catch{stop(2,`${name} 的 AGENTS.md 必须逐字保留当前「## 项目教训」段;驾驶员预检已拒绝启动宿主`);}
129
137
  inspected(project,documents.map(item=>item.path==='AGENTS.md'?{path:item.path,content:merged}:item),
130
138
  bootstrap.selection,`${name}(合入当前 AGENTS.md 后)`);
131
139
  return documents;
@@ -290,8 +298,10 @@ export function createBootstrapRulesResponder({definition,plan,bootstrap,answers
290
298
  if(payload.project!==definition.codeProject)throw Error('init_verify 项目根与运行定义不一致');
291
299
  if(!isDeepStrictEqual(payload.categories,CATEGORIES))throw Error('init_verify 核验分组与合同不一致');
292
300
  // The host verifies the final documents: current AGENTS.md lessons are merged in.
301
+ const currentBasis=committedBasis(definition,bootstrap.targets);
302
+ const refresh=currentBasis!==undefined&&currentBasis!==null;
293
303
  const expected=documents.map(item=>item.path==='AGENTS.md'
294
- ?{path:item.path,content:mergeBootstrapAgents(agentsBefore(definition.codeProject),item.content)}:item);
304
+ ?{path:item.path,content:mergeBootstrapAgents(agentsBefore(definition.codeProject),item.content,{refresh})}:item);
295
305
  if(!Array.isArray(payload.documents)||!isDeepStrictEqual(documentMap(payload.documents),documentMap(expected)))
296
306
  throw Error('宿主核验的草稿与 init-generate 答案(含合入的项目教训段)不一致');
297
307
  const answer=answers.get(attempt).verify,run=executed.get(attempt);
@@ -3,6 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {spawn} from 'node:child_process';
5
5
  import readline from 'node:readline';
6
+ import {guidanceText} from './operator-guidance.mjs';
6
7
 
7
8
  export const stderr=line=>process.stderr.write(`[drive] ${line}\n`);
8
9
  export const stop=(code,line)=>{stderr(line);process.exit(code);};
@@ -53,6 +54,7 @@ const rejectedReplyHint=code=>code==='host_response_too_large'
53
54
  // A returned refusal closes the session without any operation and exits 2.
54
55
  export function driveHost({host,args,cwd,operation,request={},answers,paths,answerFor,beforeRequest=null}){
55
56
  const child=spawn(process.execPath,[host,...args],{cwd,stdio:['pipe','pipe','pipe']});
57
+ const control=new AbortController();
56
58
  child.stderr.on('data',chunk=>process.stderr.write(chunk));
57
59
  // After a rejected reply the session is ended; later rows get no answer.
58
60
  const send=value=>{if(!child.stdin.writableEnded)child.stdin.write(JSON.stringify(value)+'\n');};
@@ -69,7 +71,8 @@ export function driveHost({host,args,cwd,operation,request={},answers,paths,answ
69
71
  }
70
72
  if(row.type==='host_request'){
71
73
  let result;
72
- try{result=await answerFor(row,answers,paths);}catch(error){stderr(`应答 ${row.kind} 失败:${error.message}`);result=null;}
74
+ try{result=await answerFor(row,answers,paths,{signal:control.signal});}catch(error){stderr(`应答 ${row.kind} 失败:${error.message}`);result=null;}
75
+ if(control.signal.aborted)return;
73
76
  if(result===null){
74
77
  stderr(`宿主问了预检没覆盖的问题 ${row.kind},无法应答;这一步会留在 unknown`);
75
78
  send({type:'host_close',sessionId:row.sessionId});return;
@@ -81,6 +84,7 @@ export function driveHost({host,args,cwd,operation,request={},answers,paths,answ
81
84
  if(row.type==='host_response'){
82
85
  if(row.accepted===false&&rejected===null){
83
86
  rejected=typeof row.code==='string'?row.code:'host_response_rejected';
87
+ control.abort();
84
88
  stderr(`宿主拒收了应答:${rejected};${rejectedReplyHint(rejected)}。驾驶员不再等待,已结束会话;宿主会把这一步记为 unknown`);
85
89
  child.stdin.end();
86
90
  }
@@ -88,13 +92,15 @@ export function driveHost({host,args,cwd,operation,request={},answers,paths,answ
88
92
  }
89
93
  if(row.requestId==='drive'){
90
94
  done=true;
95
+ control.abort();
91
96
  process.stdout.write(JSON.stringify(row,null,2)+'\n');
97
+ const guidance=guidanceText(row.result);if(guidance)stderr(guidance);
92
98
  if(row.result?.stage)stderr(`stage = ${row.result.stage}`);
93
99
  if(row.error)stderr(`宿主拒绝:${row.error.code}(真实原因和位置在上面 [host] 那行 diagnostic 里)`);
94
100
  process.exitCode=hostResponseFailed(row)||rejected!==null?1:0;
95
101
  child.stdin.end();
96
102
  }
97
103
  });
98
- child.on('error',error=>{stderr(`宿主启动失败:${error.message}`);process.exitCode=1;});
99
- child.on('exit',code=>{if(!done&&!refused){stderr(`宿主在给出结果前退出了,exit ${code}`);process.exitCode=1;}});
104
+ child.on('error',error=>{control.abort();stderr(`宿主启动失败:${error.message}`);process.exitCode=1;});
105
+ child.on('exit',code=>{control.abort();if(!done&&!refused){stderr(`宿主在给出结果前退出了,exit ${code}`);process.exitCode=1;}});
100
106
  }
@@ -1,12 +1,16 @@
1
+ import {readExecutionPolicy} from './execution-policy.mjs';
2
+ import {readExternalModels} from './external-models.mjs';
1
3
  import {beforeFirstQaRound,qaRevisionFollows,readQaConfigRevision} from './qa-config-revision.mjs';
4
+ import {readCloseoutPolicy} from './knowledge-closeout.mjs';
2
5
  // Host-only S3b2b journal grammar. Data validation grants no provider authority.
3
- import {digest,need,shape,id,text,hex,json,validIdentity,validTaskLearningInput,validCallTimeout,validBlockedReason,requestFor,JOURNAL_REASON_LIMIT} from './effect-contract.mjs';
4
- import {readReviewBaseline,readReviewPackage,reviewSpecsPath} from './review-package.mjs';
6
+ import {digest,need,shape,id,text,hex,json,validIdentity,validTaskLearningInput,validCallTimeout,validBlockedReason,requestFor,JOURNAL_REASON_LIMIT,boundedReason} from './effect-contract.mjs';
7
+ import {readReviewBaseline,readReviewPackage,reviewSpecsPath,reviewMaterialLimitReason} from './review-package.mjs';
5
8
  import {reviewResult,reviewReceipt} from './review-runner.mjs';
6
9
  import {checkCompletion} from './gate-bridge.mjs';
7
10
  import path from 'node:path';
8
11
  import {readCommitIntent,readCommitResult} from './task-commit-codec.mjs';
9
- import {inspectProviderReview,hasProviderReviewResult,inspectProviderReviewFailure,REVIEWER_PROVIDER_FAILURES} from './provider-review-observation.mjs';
12
+ import {inspectProviderReview,hasProviderReviewResult,inspectProviderReviewFailure,inspectProviderReviewReconciliation,REVIEWER_PROVIDER_FAILURES} from './provider-review-observation.mjs';
13
+ import {readReconciliationReceipt} from './review-reconciliation.mjs';
10
14
  import {readCmAiProjectLearningWriteback} from './cm-ai-learning-writer.mjs';
11
15
  import {readCmAiTaskLearningApplication} from './cm-ai-context-refresh.mjs';
12
16
  import {reviewExclusions} from './effect-contract.mjs';
@@ -23,7 +27,7 @@ const prefix=(a,b)=>{need(b.length>=a.length,'runner_history_mismatch');same(a,b
23
27
  const uuid=s=>need(typeof s==='string' && /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(s),'runner_session');
24
28
  const states=['ready','awaiting_review','approved','changes_requested','fixture_completed','blocked','unknown','cancelled','pending_review'];
25
29
  export const stageAllowed=(kind,state,code=null,reviewVerdict=null)=>
26
- kind==='develop'&&state==='blocked'&&['developer_result_invalid','verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed'].includes(code)
30
+ kind==='develop'&&state==='blocked'&&['developer_result_invalid','verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','develop_unchanged_after_review','develop_empty_changes','develop_requirement_missing','develop_package_too_large','bootstrap_verification_failed','bootstrap_instruction_conflict'].includes(code)
27
31
  ||kind==='review'&&state==='pending_review'&&REVIEW_RETRY_CODES.includes(code)
28
32
  ||kind==='complete'&&state==='blocked'&&(['completion_checks_changed','completion_package_changed'].includes(code)
29
33
  ||code==='review_package_changed'&&reviewVerdict==='approved')
@@ -136,6 +140,22 @@ export function validateTaskLearningReviewPackage(rawPackage,writeback,learningI
136
140
  &&(agents===null||agents.after?.sha256===writeback.agentsFile.sha256),'runner_learning');
137
141
  return true;
138
142
  }
143
+ // Only a completed bootstrap development whose package construction failed can
144
+ // be reconciled locally. Its developer call, checks and Learning writeback are
145
+ // already durable; a second develop would lose the original review baseline.
146
+ export function bootstrapReviewRecoverable(s,pending=null,configuration=null) {
147
+ const last=s.cache.at(-1),call=s.calls.at(-1);
148
+ return configuration?.mode==='instructions'&&pending===null&&s.attempt===1
149
+ &&(s.state==='unknown'&&s.code==='execution_error'
150
+ ||s.state==='blocked'&&s.code==='bootstrap_review_mismatch')
151
+ &&s.reviewPackage===null&&s.receipt===null&&s.reviewInvocation===null
152
+ &&last?.effect.kind==='develop'&&last.effect.identity.attempt===s.attempt
153
+ &&last.result.state===s.state&&last.result.code===s.code
154
+ &&call?.terminal==='succeeded'&&s.learningResult?.bootstrap!=null
155
+ &&s.learningResult.writeback?.outcome!=='writeback_pending'
156
+ &&Array.isArray(s.currentChecks)&&s.currentChecks.length>0
157
+ &&s.currentChecks.every(item=>item.outcome==='passed'&&(item.kind==='visual'||item.exitCode===0));
158
+ }
139
159
  // limit only widens the builder's own copy check so a caller can measure an
140
160
  // oversized record exactly; the store still refuses it (JOURNAL_PAYLOAD_LIMIT).
141
161
  export const runnerPayload=(type,fields,version=1,limit=undefined)=>{need([1,2].includes(version),'runner_version');
@@ -299,12 +319,12 @@ function readInvocationResult(p,registration,started,effect,config) {
299
319
  if(p.inspection===null)need(p.reconciliationRequired===true,'runner_invocation'); // legacy result
300
320
  else {
301
321
  same(p.inspection,check);need(p.outcome==='timed_out','runner_invocation');
302
- need(p.reconciliationRequired===hasProviderReviewResult(observation.events),'runner_invocation');
322
+ need(p.reconciliationRequired===(Boolean(config.externalModels||config.executionPolicy)||hasProviderReviewResult(observation.events)),'runner_invocation');
303
323
  }
304
324
  need(check.providerThreadId===started,'runner_invocation');
305
325
  need(p.outcome==='cancelled'?check.observationStatus==='cancelled':check.code==='transport_timeout','runner_invocation');
306
326
  } else if(p.outcome==='failed') {
307
- shape(p,common);need(p.reconciliationRequired===false,'runner_invocation');
327
+ shape(p,common);need(p.reconciliationRequired===Boolean(config.externalModels||config.executionPolicy),'runner_invocation');
308
328
  const observation=json(p.observation,512*1024);
309
329
  const failure=inspectProviderReviewFailure(JSON.stringify(observation),JSON.stringify(expectation));
310
330
  need(failure!==null,'runner_invocation');same(p.inspection,failure);
@@ -387,10 +407,12 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
387
407
  need(evidence.invocationId===added[0]?.invocationId,'runner_learning');
388
408
  for(const file of evidence.files){
389
409
  const previous=before.learningResult?.bootstrap?.files.find(item=>item.path===file.path);
410
+ const initial=config.bootstrap?.committedBasis
411
+ ?config.bootstrap.committedBasis.files.find(item=>item.path===file.path)?.sha256??null
412
+ :file.path==='AGENTS.md'?effect.learningInput.learningFiles.find(item=>item.scope==='project'
413
+ &&item.path==='AGENTS.md')?.sha256??null:null;
390
414
  const expected=file.path==='AGENTS.md'&&previous&&before.learningResult.writeback.outcome==='written'
391
- ?before.learningResult.writeback.agentsFile.sha256:previous?.afterSha256
392
- ??(file.path==='AGENTS.md'?effect.learningInput.learningFiles.find(item=>item.scope==='project'
393
- &&item.path==='AGENTS.md')?.sha256??null:null);
415
+ ?before.learningResult.writeback.agentsFile.sha256:previous?.afterSha256??initial;
394
416
  need(file.beforeSha256===expected,'runner_learning');
395
417
  }
396
418
  }
@@ -411,7 +433,7 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
411
433
  ||Object.hasOwn(original,'specification')&&s.state==='blocked'&&s.code==='spec_drift'
412
434
  // The host gate rejected the delivery after Learning was already written
413
435
  // back: the writeback stands, only the review package was not built.
414
- ||s.state==='blocked'&&['verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed'].includes(s.code)
436
+ ||s.state==='blocked'&&['verification_precheck_failed','check_output_out_of_scope','develop_checks_not_passed','bootstrap_instruction_conflict'].includes(s.code)
415
437
  ||added[0]&&['failed','unavailable','auth_required','permission_denied'].includes(added[0].terminal),'runner_learning');
416
438
  }
417
439
  if(digest(s.reviewPackage)!==digest(before.reviewPackage)) {
@@ -440,6 +462,16 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
440
462
  need(before.attempt===2&&before.priorReview?.verdict==='changes_requested','runner_develop');
441
463
  expectedState='blocked';expectedCode=s.code;
442
464
  }
465
+ if(added[0]?.terminal==='succeeded'&&s.code==='bootstrap_review_mismatch'){
466
+ need(config.bootstrap?.mode==='instructions'&&s.reviewPackage===null&&s.learningResult?.bootstrap!=null,
467
+ 'runner_develop');
468
+ expectedState='blocked';expectedCode=s.code;
469
+ }
470
+ if(added.length===0&&s.code==='bootstrap_instruction_conflict'){
471
+ need(config.bootstrap?.mode==='instructions','runner_develop');
472
+ same(s.learningResult,before.learningResult);
473
+ expectedState='blocked';expectedCode=s.code;
474
+ }
443
475
  if(added[0] && ['failed','unavailable','auth_required','permission_denied'].includes(added[0].terminal)) {
444
476
  expectedState='blocked';expectedCode=invalidDeveloperCall(added[0])
445
477
  ?'developer_result_invalid':['protected_edit_stale','bootstrap_verification_failed'].includes(added[0].failureResult?.code)
@@ -545,13 +577,35 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
545
577
  need(s.cancelAfterCommit===(controls.cancelAfterCommit||before.cancelAfterCommit),'runner_control');
546
578
  need(s.cancellationRequested===(!!controls.cancelled||!!controls.cancelAfterCommit||before.cancellationRequested),'runner_control');
547
579
  if(controls.cancelled)need(s.state==='cancelled','runner_control');
580
+ // Runners before the retryable package-limit transition journaled this exact
581
+ // host gate as unknown/limit_exceeded. Reproject only the unambiguous case:
582
+ // development succeeded, every check passed, and no review package exists.
583
+ // The original record remains byte-for-byte in the journal; a resumed frame
584
+ // carries the corrected projection forward.
585
+ if(effect.kind==='develop'&&before.attempt===1&&config.bootstrap?.mode!=='instructions'
586
+ &&s.state==='unknown'&&s.code==='limit_exceeded'
587
+ &&added[0]?.terminal==='succeeded'&&digest(s.reviewPackage)===digest(before.reviewPackage)
588
+ &&s.receipt===null&&Array.isArray(s.currentChecks)&&s.currentChecks.length>0
589
+ &&s.currentChecks.every(item=>item.outcome==='passed'&&(item.kind==='visual'||item.exitCode===0))
590
+ &&reviewMaterialLimitReason(s.reason)){
591
+ const recovered=structuredClone(s);
592
+ const detail=(s.reason??'review material exceeded its bounded size').replace(/^limit_exceeded:\s*/, '');
593
+ recovered.state='blocked';recovered.code='develop_package_too_large';
594
+ recovered.reason=boundedReason('develop_package_too_large: ',[detail],
595
+ '; shrink the changed files or move generated artifacts out of scope, then resume to redo this attempt');
596
+ recovered.cache.at(-1).result=runnerStatus(recovered,config);
597
+ return recovered;
598
+ }
548
599
  return structuredClone(s);
549
600
  }
550
601
 
551
602
  function completionConfig(config,version){
552
603
  shape(config,['root','identity','scope','requirements','excludedContexts','timeoutMs','developer','reviewers','completion',
553
604
  ...(version===3?['reviewInvocation']:[]),...(Object.hasOwn(config,'taskLearning')?['taskLearning']:[]),
554
- ...['bootstrap','codeProjectPaths'].filter(key=>Object.hasOwn(config,key))]);
605
+ ...['bootstrap','codeProjectPaths','knowledgeCloseout','externalModels','executionPolicy'].filter(key=>Object.hasOwn(config,key))]);
606
+ if(Object.hasOwn(config,'knowledgeCloseout'))readCloseoutPolicy(config.knowledgeCloseout);
607
+ if(Object.hasOwn(config,'executionPolicy')){same(config.executionPolicy,readExecutionPolicy(config.executionPolicy));need(version===3,'execution_policy_runner_version');}
608
+ if(Object.hasOwn(config,'externalModels')){same(config.externalModels,readExternalModels(config.externalModels));need(version===3,'external_model_runner_version');}
555
609
  if(Object.hasOwn(config,'codeProjectPaths')){
556
610
  same(config.codeProjectPaths,validateCodeProjectPaths(config.codeProjectPaths));
557
611
  assertCodeProjectSelections(config.codeProjectPaths,[...config.scope,...config.requirements]);
@@ -620,6 +674,9 @@ export function readRunnerHistory(raw,config,version=1) {
620
674
  const reviewConfig=(calls=[])=>({...config,reviewInvocation:{...config.reviewInvocation,
621
675
  excludedThreadIds:reviewExclusions({excludedThreadIds:[...config.reviewInvocation.excludedThreadIds,...joinedHosts]},
622
676
  calls,config.developer.contextId)}});
677
+ const reconciliationBinding=()=>({effectId:lastReview.effect.id,invocationId:lastReview.request.invocationId,
678
+ registeredDigest:lastReview.registrationRecord.digest,startedDigest:lastReview.startedRecord?.digest??null,
679
+ resultDigest:lastReview.resultRecord.digest});
623
680
  for(const [index,r] of records.entries()) {
624
681
  if(index>0)need(records[index-1].payload.type!=='effect-abandoned','runner_abandon');
625
682
  boundRunnerRecord(r,index+1);
@@ -656,6 +713,19 @@ export function readRunnerHistory(raw,config,version=1) {
656
713
  need(r.kind==='result'&&index===1&&pending===null&&state.state==='ready'&&supersession===null,'supersede_record_invalid');
657
714
  supersession=readEvidenceSupersession(p.record,{feature:config.taskLearning.feature,
658
715
  taskId:config.identity.taskId,newRunId:config.identity.runId});
716
+ } else if(version===3&&p.type==='bootstrap-review-recovered') {
717
+ shape(p,[...common,'fromDigest','reviewPackage','reason','at']);
718
+ need(r.kind==='result'&&p.fromDigest===records[index-1].digest
719
+ &&bootstrapReviewRecoverable(state,pending,config.bootstrap),'bootstrap_review_recovery_unavailable');
720
+ need(typeof p.reason==='string'&&p.reason.trim().length>0&&Buffer.byteLength(p.reason,'utf8')<=500
721
+ &&!/[\r\n\0]/.test(p.reason),'bootstrap_review_recovery_unavailable');
722
+ need(typeof p.at==='string'&&Number.isFinite(Date.parse(p.at))&&new Date(p.at).toISOString()===p.at,
723
+ 'bootstrap_review_recovery_unavailable');
724
+ packageLink(p.reviewPackage,original,state.attempt,state.currentChecks);
725
+ validateTaskLearningReviewPackage(p.reviewPackage,state.learningResult.writeback,
726
+ state.cache.at(-1).effect.learningInput,state.learningResult.bootstrap,config.bootstrap);
727
+ state.reviewPackage=readReviewPackage(p.reviewPackage);
728
+ state.state='awaiting_review';state.code=null;state.reason=null;
659
729
  } else if(p.type==='effect-intent') {
660
730
  shape(p,[...common,'effect']);need(r.kind==='intent' && pending===null,'runner_intent');
661
731
  const e=p.effect;shape(e,['version','id','identity','kind',...(Object.hasOwn(e,'learningInput')?['learningInput']:[])]);
@@ -694,6 +764,34 @@ export function readRunnerHistory(raw,config,version=1) {
694
764
  invocation.result=readInvocationResult(p,invocation.registration,invocation.started,pending,reviewConfig(beforeIntent.calls));
695
765
  if(invocation.result.outcome==='cancelled')need(controls.cancelled===true,'runner_control');
696
766
  resultRecord=r;
767
+ } else if(version===3&&['review-invocation-receipt','review-invocation-reconciled'].includes(p.type)) {
768
+ const bindingKeys=['effectId','invocationId','registeredDigest','startedDigest','resultDigest'];
769
+ shape(p,[...common,...bindingKeys,...(p.type==='review-invocation-receipt'?['receipt']:['receiptDigest','checkpoint'])]);
770
+ need((config.externalModels||config.executionPolicy)&&r.kind==='result'&&pending===null&&lastReview!==null
771
+ &&(state.state==='unknown'&&lastReview.invocation.result.reconciliationRequired===true
772
+ ||state.state==='pending_review'&&reviewTransportTimeout(lastReview.invocation.result))
773
+ &&lastReview.invocation.result.inspection!==null&&lastReview.invocation.started!==null,
774
+ 'review_reconciliation_unavailable');
775
+ same(Object.fromEntries(bindingKeys.map(key=>[key,p[key]])),reconciliationBinding());
776
+ if(p.type==='review-invocation-receipt'){
777
+ need(!lastReview.reconciliation,'review_reconciliation_duplicate');
778
+ const receipt=readReconciliationReceipt(p.receipt);
779
+ prefix(lastReview.invocation.result.observation.events,receipt.events);
780
+ const observation={version:1,kind:'cm-provider-review-observation',requestDigest:lastReview.request.requestDigest,
781
+ events:receipt.events,result:receipt.result};
782
+ const inspection=inspectProviderReviewReconciliation(JSON.stringify(observation),JSON.stringify({request:lastReview.request,
783
+ developerThreadId:config.reviewInvocation.developerThreadId,
784
+ excludedThreadIds:reviewConfig(lastReview.before.calls).reviewInvocation.excludedThreadIds}));
785
+ need(inspection.providerThreadId===lastReview.invocation.started,'review_reconciliation_binding');
786
+ const result={dispatchAt:lastReview.invocation.result.dispatchAt,
787
+ outcome:inspection.observationStatus==='completed'?'observed':'failed',observation,inspection,reconciliationRequired:false};
788
+ lastReview.reconciliation={receiptDigest:r.digest,result};
789
+ }else{
790
+ need(lastReview.reconciliation?.receiptDigest===p.receiptDigest,'review_reconciliation_evidence_required');
791
+ state=checkpoint(lastReview.before,p.checkpoint,lastReview.effect,config,original,session,lastReview.controls,version,
792
+ state.taskCommit??null,{...lastReview.invocation,result:lastReview.reconciliation.result},supersession?.carriedReview??null);
793
+ lastReview=null;
794
+ }
697
795
  } else if(version===3&&p.type==='develop-retry-limit') {
698
796
  // Terminal: written instead of a develop intent when no delivery can still
699
797
  // be reviewed. Every field is recomputed from the replayed state.
@@ -711,6 +809,7 @@ export function readRunnerHistory(raw,config,version=1) {
711
809
  &&p.completionBlocks===completionBlockCount(state.cache),'runner_retry_limit');
712
810
  state.state='blocked';state.code='completion_retry_limit';state.reason=completionRetryLimitReason(p);lastReview=null;
713
811
  } else if(version===3&&p.type==='review-invocation-abandoned'&&Object.hasOwn(p,'resultDigest')) {
812
+ need(!(config.externalModels||config.executionPolicy),'external_review_reconciliation_required');
714
813
  // Abandoning a checkpointed review whose journaled result was never accepted.
715
814
  shape(p,[...common,'effectId','invocationId','registeredDigest','startedDigest','resultDigest','reason','at']);
716
815
  need(r.kind==='result'&&pending===null&&lastReview!==null
@@ -731,6 +830,7 @@ export function readRunnerHistory(raw,config,version=1) {
731
830
  result:{outcome:'abandoned',reason:p.reason,at:p.at,recordDigest:r.digest}};
732
831
  lastReview=null;
733
832
  } else if(version===3&&p.type==='review-invocation-abandoned') {
833
+ need(!(config.externalModels||config.executionPolicy),'external_review_reconciliation_required');
734
834
  shape(p,[...common,'effectId','invocationId','registeredDigest','startedDigest','reason','at']);
735
835
  need(r.kind==='result'&&pending?.kind==='review'&&invocation.registration&&!invocation.result
736
836
  &&!controls.cancelled&&!controls.workflowError&&state.state==='awaiting_review','runner_abandon');
@@ -754,6 +854,7 @@ export function readRunnerHistory(raw,config,version=1) {
754
854
  result:{outcome:'abandoned',reason:p.reason,at:p.at,recordDigest:r.digest}};
755
855
  pending=null;beforeIntent=null;invocation={registration:null,started:null,result:null};
756
856
  } else if(version===3&&p.type==='effect-abandoned') {
857
+ need(!(config.externalModels||config.executionPolicy),'external_review_reconciliation_required');
757
858
  shape(p,[...common,'effectId','effectKind','intentDigest','reason','at',
758
859
  ...(Object.hasOwn(p,'lastRecordDigest')?['lastRecordDigest']:[])]);
759
860
  let intentIndex=index-1;
@@ -777,7 +878,7 @@ export function readRunnerHistory(raw,config,version=1) {
777
878
  state=checkpoint(beforeIntent,p.checkpoint,pending,config,original,session,controls,version,state.taskCommit??null,invocation,
778
879
  supersession?.carriedReview??null);
779
880
  lastReview=version===3&&pending.kind==='review'&&invocation.result?{effect:pending,request:invocation.registration.request,
780
- registrationRecord,startedRecord,resultRecord}:null;
881
+ registrationRecord,startedRecord,resultRecord,before:beforeIntent,controls,invocation}:null;
781
882
  pending=null;beforeIntent=null;invocation={registration:null,started:null,result:null};
782
883
  } else if(version>=2 && ['task-commit-intent','task-commit-result'].includes(p.type)){
783
884
  shape(p,[...common,'effectId','completeIntentDigest','commit']);
@@ -838,19 +939,21 @@ export function readRunnerHistory(raw,config,version=1) {
838
939
  if(pending){state.state='unknown';state.code='reconciliation_required';
839
940
  if(version===3&&invocation.registration)state.reviewInvocation={registration:invocation.registration.record,
840
941
  started:invocation.started,result:invocation.result};}
841
- const pendingAbandonable=version===3&&pending!==null
942
+ const pendingAbandonable=!(config.externalModels||config.executionPolicy)&&version===3&&pending!==null
842
943
  &&['develop','complete','review'].includes(pending.kind)
843
944
  &&!transaction&&state.taskCommit?.intentDigest==null
844
945
  &&(pending.kind!=='review'||!invocation.registration&&!joinedForInvocation)
845
946
  &&records.slice(records.findLastIndex(row=>row.payload.type==='effect-intent')+1)
846
947
  .every(row=>row.payload.type==='control');
847
- const reviewResultAbandon=version===3&&pending===null&&lastReview!==null
948
+ const reviewResultAbandon=!(config.externalModels||config.executionPolicy)&&version===3&&pending===null&&lastReview!==null
848
949
  &&abandonableReviewResult(state,config.reviewers[0].contexts[state.attempt-1])
849
950
  ?{effectId:lastReview.effect.id,invocationId:lastReview.request.invocationId,
850
951
  registeredDigest:lastReview.registrationRecord.digest,startedDigest:lastReview.startedRecord?.digest??null,
851
952
  resultDigest:lastReview.resultRecord.digest}:null;
852
953
  return {original,session,state,pending,acceptedFixes,qaAttachment,
853
954
  ...(version===3?{joinedHosts,reviewerThreads,supersession,pendingAbandonable,reviewResultAbandon,
955
+ reviewReconciliation:lastReview?.reconciliation&&['unknown','pending_review'].includes(state.state)?{...reconciliationBinding(),
956
+ ...lastReview.reconciliation,request:lastReview.request,effect:lastReview.effect,before:lastReview.before}:null,
854
957
  pendingObservedReview:pending?.kind==='review'&&invocation.result?.outcome==='observed'
855
958
  ?{request:invocation.registration.request,registration:invocation.registration.record,
856
959
  started:invocation.started,result:invocation.result}:null}:{}),
@@ -51,7 +51,7 @@ const failureCodes=new Set(['invalid_input','limit_exceeded','call_timeout','can
51
51
  'unregistered_receipt','invalid_receipt','receipt_identity','receipt_package_mismatch','review_not_approved',
52
52
  'checks_not_passed','async_commit','commit_unknown','unsupported_path','unsupported_file','read_failed',
53
53
  'snapshot_changed','spec_drift','invalid_baseline','out_of_scope','empty_changes','invalid_package','package_mismatch',
54
- 'handoff_exists','verification_precheck_failed','completion_checks_changed']);
54
+ 'handoff_exists','verification_precheck_failed','completion_checks_changed','bootstrap_review_mismatch']);
55
55
  // An unlisted code becomes execution_error, which on its own is not actionable.
56
56
  // The EEXIST that blocked every retry of a task in #81 stayed invisible in the
57
57
  // log, the state and stderr until a temporary print was added by hand. Emit one
@@ -0,0 +1,58 @@
1
+ // Explicit, versioned policy for NEW executions. No defaults, migration or budgets.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {digest,json,need,id,shape} from './effect-contract.mjs';
5
+ import {isSupportedExecutionPlatform} from './execution-platform.mjs';
6
+ import {fixArchiveRoot} from '../cm-fix/layout.mjs';
7
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
8
+ import {scanRows} from './log-rows.mjs';
9
+ export const EXECUTION_POLICY_V1=Object.freeze({version:1,responseRecovery:'mechanical-v1',
10
+ checkReuse:'declared-adjacent-v1',reviewPresentation:'utf8-v1',usage:'provider-terminal-v1'});
11
+ export function readExecutionPolicy(raw){
12
+ const value=json(raw);need(digest(value)===digest(EXECUTION_POLICY_V1),'execution_policy_invalid');return value;
13
+ }
14
+ export function readLaunchExecutionPolicy({definition,mode,enabled=false}){
15
+ need(['create','resume'].includes(mode),'invalid_mode');
16
+ if(mode==='create')return enabled?readExecutionPolicy(EXECUTION_POLICY_V1):null;
17
+ let snapshot;
18
+ try{snapshot=readExecutionSnapshot({specsRoot:definition.specsDir,identity:{repositoryId:definition.identity.repositoryId,runId:definition.identity.runId}});}
19
+ catch(error){if(error.code!=='ENOENT')throw error;need(!enabled,'execution_policy_legacy_run');return null;}
20
+ const saved=snapshot.records.find(row=>row.payload.type==='init')?.payload.config.executionPolicy??null;
21
+ need(!enabled||saved!==null,'execution_policy_legacy_run');return saved===null?null:readExecutionPolicy(saved);
22
+ }
23
+ const batchRoot=batch=>path.join(batch.specsDir,'.cm-execution-policy-v1');
24
+ const batchIdentity=batch=>{id(batch.batchId);return {repositoryId:batch.repositoryId,runId:'batch-policy-'+digest(batch.batchId).slice(0,32)};};
25
+ export function readBatchExecutionPolicy({batch,started,enabled=false}){
26
+ const identity=batchIdentity(batch),root=batchRoot(batch),file=path.join(root,'.reviews','.execution',identity.runId,'state.json');
27
+ if(fs.existsSync(file)){
28
+ const snapshot=readExecutionSnapshot({specsRoot:root,identity});
29
+ need(snapshot.records.length===1&&snapshot.records[0].id==='batch-policy'&&snapshot.records[0].kind==='result','execution_policy_batch_binding');
30
+ const record=snapshot.records[0].payload;shape(record,['kind','batchId','planDigest','executionPolicy']);
31
+ need(record.kind==='cm-execution-policy-v1'&&record.batchId===batch.batchId&&record.planDigest===digest(batch),'execution_policy_batch_binding');
32
+ return readExecutionPolicy(record.executionPolicy);
33
+ }
34
+ const log=path.join(batch.specsDir,'运行日志.jsonl');
35
+ if(fs.existsSync(log))scanRows(log,row=>{if(row.workflow==='cm-ai'&&row.run_id===batch.batchId&&row.event==='decision'&&row.phase==='batch_start')started=true;});
36
+ need(!started||!enabled,'execution_policy_legacy_run');return enabled&&!started?readExecutionPolicy(EXECUTION_POLICY_V1):null;
37
+ }
38
+ export async function freezeBatchExecutionPolicy(batch,executionPolicy){
39
+ if(executionPolicy===null)return;
40
+ const root=batchRoot(batch),identity=batchIdentity(batch);
41
+ if(fs.existsSync(path.join(root,'.reviews','.execution',identity.runId,'state.json'))){
42
+ need(digest(readBatchExecutionPolicy({batch,started:true}))===digest(executionPolicy),'execution_policy_batch_binding');return;
43
+ }
44
+ need(isSupportedExecutionPlatform(),'unsupported_platform');
45
+ const {openExecutionStore}=await import('./execution-store.mjs');
46
+ try{fs.mkdirSync(root,{mode:0o700});}catch(error){if(error.code!=='EEXIST')throw error;}
47
+ need(fs.realpathSync(root)===root,'execution_policy_batch_binding');
48
+ const payload={kind:'cm-execution-policy-v1',batchId:batch.batchId,planDigest:digest(batch),executionPolicy:readExecutionPolicy(executionPolicy)};
49
+ const store=openExecutionStore({specsRoot:root,identity,create:true,fingerprints:{workflow:digest(payload.kind),config:digest(batch),inputs:digest(payload)}});
50
+ try{store.append({id:'batch-policy',kind:'result',payload,expectedRevision:store.snapshot().revision});}finally{store.close();}
51
+ }
52
+ export function readFixExecutionPolicy({config,mode,enabled=false}){
53
+ if(mode==='create')return enabled?readExecutionPolicy(EXECUTION_POLICY_V1):null;
54
+ need(mode==='resume','invalid_mode');
55
+ const snapshot=readExecutionSnapshot({specsRoot:fixArchiveRoot(config.specsRoot,config.reproduction.cwd),identity:{repositoryId:config.identity.repositoryId,runId:config.identity.runId}});
56
+ const saved=snapshot.records[0]?.payload.configuration?.executionPolicy??null;
57
+ need(!enabled||saved!==null,'execution_policy_legacy_run');return saved===null?null:readExecutionPolicy(saved);
58
+ }
@@ -0,0 +1,53 @@
1
+ // Existing batch/fix owners keep the same provider parser and immutable selection.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {digest,need,id,shape} from './effect-contract.mjs';
5
+ import {loadExternalModels,readExternalModels,selectExternalModels} from './external-models.mjs';
6
+ import {openExecutionStore} from './execution-store.mjs';
7
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
8
+ import {fixArchiveRoot} from '../cm-fix/layout.mjs';
9
+
10
+ export function batchModelsFile(batch){
11
+ id(batch.batchId);return path.join(batch.specsDir,'.cm-external-models-v1','.reviews','.execution','batch-models-'+digest(batch.batchId).slice(0,32),'state.json');
12
+ }
13
+ export function readBatchExternalModels({batch,started,enabled=false,inputFile,providers}){
14
+ const file=batchModelsFile(batch);
15
+ if(fs.existsSync(file)){
16
+ need(inputFile===undefined,'external_model_resume_selection_forbidden');
17
+ const snapshot=readExecutionSnapshot({specsRoot:path.join(batch.specsDir,'.cm-external-models-v1'),identity:{repositoryId:batch.repositoryId,runId:path.basename(path.dirname(file))}});
18
+ need(snapshot.records.length===1&&snapshot.records[0].id==='batch-models'&&snapshot.records[0].kind==='result','external_model_batch_binding');
19
+ const record=snapshot.records[0].payload;
20
+ shape(record,['kind','batchId','planDigest','externalModels']);
21
+ need(record.kind==='cm-external-batch-models-v1'&&record.batchId===batch.batchId
22
+ &&record.planDigest===digest(batch),'external_model_batch_binding');
23
+ return readExternalModels(record.externalModels);
24
+ }
25
+ need(!started||!enabled,'external_model_resume_selection_forbidden');
26
+ need(inputFile===undefined||enabled&&!started,'external_model_feature_required');
27
+ return enabled&&!started?selectExternalModels(loadExternalModels(inputFile),providers):null;
28
+ }
29
+ export function freezeBatchExternalModels(batch,externalModels){
30
+ if(!externalModels)return;
31
+ const value={kind:'cm-external-batch-models-v1',batchId:batch.batchId,planDigest:digest(batch),externalModels:readExternalModels(externalModels)};
32
+ const file=batchModelsFile(batch);
33
+ if(fs.existsSync(file)){need(digest(readBatchExternalModels({batch,started:true,providers:Object.keys(externalModels.providers)}))===digest(externalModels),'external_model_batch_binding');return;}
34
+ const specsRoot=path.join(batch.specsDir,'.cm-external-models-v1');
35
+ try{fs.mkdirSync(specsRoot,{mode:0o700});}catch(error){if(error.code!=='EEXIST')throw error;}
36
+ need(fs.realpathSync(specsRoot)===specsRoot,'external_model_batch_binding');
37
+ const fingerprint=digest('cm-external-batch-models-v1');
38
+ const store=openExecutionStore({specsRoot,identity:{repositoryId:batch.repositoryId,runId:path.basename(path.dirname(file))},create:true,
39
+ fingerprints:{workflow:fingerprint,config:digest(batch),inputs:digest(value)}});
40
+ try{store.append({id:'batch-models',kind:'result',payload:value,expectedRevision:store.snapshot().revision});}finally{store.close();}
41
+ }
42
+ export function readFixExternalModels({config,mode,enabled=false,inputFile,runtime='codex'}){
43
+ if(mode==='resume'){
44
+ need(inputFile===undefined,'external_model_resume_selection_forbidden');
45
+ const specsRoot=fixArchiveRoot(config.specsRoot,config.reproduction.cwd);
46
+ const saved=readExecutionSnapshot({specsRoot,identity:{repositoryId:config.identity.repositoryId,runId:config.identity.runId}})
47
+ .records[0]?.payload.configuration?.externalModels??null;
48
+ need(!enabled||saved!==null,'external_model_resume_selection_forbidden');
49
+ return saved===null?null:readExternalModels(saved);
50
+ }
51
+ need(inputFile===undefined||enabled,'external_model_feature_required');
52
+ return enabled?selectExternalModels(loadExternalModels(inputFile),[runtime]):null;
53
+ }
@@ -0,0 +1,23 @@
1
+ import {readExecutionSnapshot} from './execution-snapshot.mjs';
2
+ import {loadExternalModels,readExternalModels,selectExternalModels} from './external-models.mjs';
3
+ import {need} from './effect-contract.mjs';
4
+ export function readLaunchExternalModels({definition,mode,enabled=false,inputFile,providers}){
5
+ need(['create','resume'].includes(mode),'invalid_mode');
6
+ if(mode==='resume'){
7
+ need(inputFile===undefined,'external_model_resume_selection_forbidden');
8
+ let snapshot;
9
+ try{snapshot=readExecutionSnapshot({specsRoot:definition.specsDir,
10
+ identity:{repositoryId:definition.identity.repositoryId,runId:definition.identity.runId}});}
11
+ catch(error){
12
+ if(error.code!=='ENOENT')throw error;
13
+ need(!enabled,'external_model_resume_selection_forbidden');
14
+ // Let the original owner report store_missing, without changing legacy resume diagnostics.
15
+ return null;
16
+ }
17
+ const saved=snapshot.records.find(row=>row.payload.type==='init')?.payload.config.externalModels??null;
18
+ need(!enabled||saved!==null,'external_model_resume_selection_forbidden');
19
+ return saved===null?null:readExternalModels(saved);
20
+ }
21
+ need(inputFile===undefined||enabled,'external_model_feature_required');
22
+ return enabled?selectExternalModels(loadExternalModels(inputFile),providers):null;
23
+ }
@@ -0,0 +1,52 @@
1
+ // One explicit request per external provider; the host session is client-owned.
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import {json,need,shape} from './effect-contract.mjs';
5
+ import {readModelJsonRecord,writeModelJson} from './model-configuration-file.mjs';
6
+
7
+ export const EXTERNAL_MODEL_SCHEMA=1;
8
+ export const EXTERNAL_EFFORTS=Object.freeze({
9
+ codex:Object.freeze(['none','minimal','low','medium','high','xhigh']),
10
+ claude:Object.freeze(['low','medium','high','xhigh','max']),
11
+ });
12
+ export function externalEffort(provider,effort=undefined){
13
+ need(Object.hasOwn(EXTERNAL_EFFORTS,provider),'invalid_external_provider');
14
+ const value=effort===undefined?(provider==='codex'?'high':null):effort;
15
+ need(provider==='claude'&&value===null||EXTERNAL_EFFORTS[provider].includes(value),'unsupported_external_effort');
16
+ return value;
17
+ }
18
+ export function externalPair(provider,raw){
19
+ const value=json(raw);shape(value,['model',...(Object.hasOwn(value,'effort')?['effort']:[])]);
20
+ need(typeof value.model==='string'&&value.model.length<=128&&/^[a-zA-Z0-9._-]+$/.test(value.model)
21
+ &&value.model!=='current-session','external_model_required');
22
+ return {model:value.model,effort:externalEffort(provider,value.effort)};
23
+ }
24
+ export function readExternalModels(raw){
25
+ const value=json(raw,64*1024);shape(value,['schemaVersion','providers']);
26
+ need(value.schemaVersion===EXTERNAL_MODEL_SCHEMA,'external_schema_unsupported');
27
+ shape(value.providers,Object.keys(value.providers));
28
+ return {schemaVersion:EXTERNAL_MODEL_SCHEMA,providers:Object.fromEntries(Object.entries(value.providers)
29
+ .map(([provider,pair])=>[provider,externalPair(provider,pair)]))};
30
+ }
31
+ export const externalModelsPath=()=>path.join(path.resolve(process.env.CM_WORKFLOW_HOME||path.join(os.homedir(),'.cm-workflow')),'external-models-v1.json');
32
+ export function loadExternalModels(file=externalModelsPath()){
33
+ try{return readExternalModels(readModelJsonRecord(file).value);}
34
+ catch(error){if(error.code==='ENOENT')throw Object.assign(new Error('external_model_setup_required'),{code:'external_model_setup_required'});throw error;}
35
+ }
36
+ export function selectExternalModels(raw,providers){
37
+ const value=readExternalModels(raw);
38
+ return {schemaVersion:EXTERNAL_MODEL_SCHEMA,providers:Object.fromEntries([...new Set(providers)].map(provider=>{
39
+ need(Object.hasOwn(value.providers,provider),'external_model_setup_required');return [provider,value.providers[provider]];
40
+ }))};
41
+ }
42
+ export function externalSettingsRecord(file=externalModelsPath()){
43
+ try{return readModelJsonRecord(file);}catch(error){if(error.code==='ENOENT')return null;throw error;}
44
+ }
45
+ export function saveExternalModels(value,{file=externalModelsPath(),expectedSha256,sourceGuard=null}={}){
46
+ writeModelJson(file,readExternalModels(value),{expectedSha256,sourceGuard,createParents:true});
47
+ }
48
+ // This is a requested tuple and adapter capability, never provider confirmation.
49
+ export function describeExternalModels(raw){
50
+ return {host:'current-session (controlled by client)',external:readExternalModels(raw),
51
+ capabilityEvidence:'adapter argument contract',effectiveModel:'unknown',providerConfirmed:false};
52
+ }