@aibyzero/cm-workflow 0.16.5 → 0.16.7

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 (202) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +14 -0
  3. package/CHANGELOG.md +19 -1
  4. package/README.md +17 -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 +96 -6
  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-admission.mjs +34 -10
  27. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
  28. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -34
  29. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +93 -31
  30. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
  31. package/runtime/js/cm-ai/codex-config.mjs +3 -2
  32. package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
  33. package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
  34. package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
  35. package/runtime/js/cm-ai/drive-bootstrap.mjs +22 -12
  36. package/runtime/js/cm-ai/drive-core.mjs +9 -3
  37. package/runtime/js/cm-ai/durable-runner-state.mjs +146 -14
  38. package/runtime/js/cm-ai/effect-contract.mjs +1 -1
  39. package/runtime/js/cm-ai/execution-policy.mjs +58 -0
  40. package/runtime/js/cm-ai/external-group-models.mjs +53 -0
  41. package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
  42. package/runtime/js/cm-ai/external-models.mjs +52 -0
  43. package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
  44. package/runtime/js/cm-ai/host-bootstrap.mjs +70 -20
  45. package/runtime/js/cm-ai/host-check.mjs +30 -4
  46. package/runtime/js/cm-ai/host-conversation-execution.mjs +59 -17
  47. package/runtime/js/cm-ai/host-documentation.mjs +2 -2
  48. package/runtime/js/cm-ai/host-progress.mjs +80 -0
  49. package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
  50. package/runtime/js/cm-ai/host-qa-executor.mjs +54 -8
  51. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
  52. package/runtime/js/cm-ai/host-session.mjs +1 -1
  53. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
  54. package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
  55. package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
  56. package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
  57. package/runtime/js/cm-ai/live-evidence.mjs +96 -0
  58. package/runtime/js/cm-ai/log-rows.mjs +36 -0
  59. package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
  60. package/runtime/js/cm-ai/model_configuration_write.py +214 -0
  61. package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
  62. package/runtime/js/cm-ai/operator-guidance.mjs +89 -0
  63. package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
  64. package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
  65. package/runtime/js/cm-ai/provider-usage.mjs +39 -0
  66. package/runtime/js/cm-ai/review-package.mjs +11 -0
  67. package/runtime/js/cm-ai/review-presentation.mjs +45 -0
  68. package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
  69. package/runtime/js/cm-ai/status-projection.mjs +93 -0
  70. package/runtime/js/cm-ai/task-runner.mjs +176 -25
  71. package/runtime/js/cm-ai/tool-preview.mjs +8 -4
  72. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  73. package/runtime/js/cm-ai/worker-claude.mjs +63 -19
  74. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
  75. package/runtime/js/cm-ai/worker-codex.mjs +45 -19
  76. package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
  77. package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
  78. package/runtime/js/cm-fix/cause-package.mjs +10 -1
  79. package/runtime/js/cm-fix/execution.mjs +183 -40
  80. package/runtime/js/cm-fix/final-review.mjs +18 -10
  81. package/runtime/js/cm-fix/finish.mjs +2 -19
  82. package/runtime/js/cm-fix/host-review.mjs +25 -6
  83. package/runtime/js/cm-fix/host.mjs +4 -1
  84. package/runtime/js/cm-fix/layout.mjs +1 -1
  85. package/runtime/js/cm-fix/log-events.mjs +29 -0
  86. package/runtime/js/cm-fix/metrics.mjs +3 -2
  87. package/runtime/js/cm-fix/progress.mjs +4 -0
  88. package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
  89. package/runtime/js/cm-prd/analysis.mjs +5 -2
  90. package/runtime/js/cm-prd/response-recovery.mjs +23 -0
  91. package/runtime/js/cm-prd/review-host.mjs +2 -1
  92. package/runtime/js/cm-prd/review-publication.mjs +23 -13
  93. package/runtime/js/cm-prd/review-time.mjs +29 -0
  94. package/runtime/js/cm-prd/session.mjs +53 -6
  95. package/runtime/js/cm-security/finalize.mjs +32 -0
  96. package/runtime/js/cm-test/recovery.mjs +4 -4
  97. package/runtime/review.md +5 -0
  98. package/runtime/task-gates.md +6 -0
  99. package/runtime/workflow-config.md +10 -1
  100. package/scripts/cm-ai-admission.mjs +14 -3
  101. package/scripts/cm-ai-batch-drive.mjs +52 -23
  102. package/scripts/cm-ai-batch-drive.test.mjs +47 -2
  103. package/scripts/cm-ai-batch-host.mjs +44 -16
  104. package/scripts/cm-ai-batch-run.mjs +77 -29
  105. package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
  106. package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
  107. package/scripts/cm-ai-bootstrap.test.mjs +80 -87
  108. package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
  109. package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
  110. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
  111. package/scripts/cm-ai-drive.mjs +73 -28
  112. package/scripts/cm-ai-drive.test.mjs +119 -1
  113. package/scripts/cm-ai-feature-selection.test.mjs +178 -0
  114. package/scripts/cm-ai-host.mjs +79 -27
  115. package/scripts/cm-ai-host.test.mjs +88 -0
  116. package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
  117. package/scripts/cm-ai-progress.test.mjs +521 -0
  118. package/scripts/cm-ai-protected-scope.test.mjs +194 -0
  119. package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
  120. package/scripts/cm-ai-review-failure.test.mjs +71 -11
  121. package/scripts/cm-ai-run.mjs +94 -19
  122. package/scripts/cm-ai-run.test.mjs +2 -1
  123. package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
  124. package/scripts/cm-check-drive.test.mjs +1 -0
  125. package/scripts/cm-check-runtime.sh +11 -0
  126. package/scripts/cm-claude-install-layout.test.mjs +26 -0
  127. package/scripts/cm-claude-probe.test.mjs +1 -1
  128. package/scripts/cm-codex-plugin-metadata.py +83 -0
  129. package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
  130. package/scripts/cm-efficiency-checks.test.mjs +37 -0
  131. package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
  132. package/scripts/cm-efficiency-offline.mjs +35 -0
  133. package/scripts/cm-efficiency-policy.test.mjs +48 -0
  134. package/scripts/cm-efficiency-presentation.test.mjs +35 -0
  135. package/scripts/cm-efficiency-response.test.mjs +117 -0
  136. package/scripts/cm-efficiency-usage.test.mjs +148 -0
  137. package/scripts/cm-external-batch-host.test.mjs +157 -0
  138. package/scripts/cm-external-fix-host.test.mjs +281 -0
  139. package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
  140. package/scripts/cm-external-group-models.test.mjs +60 -0
  141. package/scripts/cm-external-model-host.test.mjs +180 -0
  142. package/scripts/cm-external-model-recovery.test.mjs +108 -0
  143. package/scripts/cm-external-models.test.mjs +89 -0
  144. package/scripts/cm-external-process-cleanup.test.mjs +71 -0
  145. package/scripts/cm-external-qa-fix.test.mjs +170 -0
  146. package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
  147. package/scripts/cm-fix-drive.mjs +28 -13
  148. package/scripts/cm-fix-final-review.test.mjs +11 -6
  149. package/scripts/cm-fix-host.mjs +17 -10
  150. package/scripts/cm-fix-large-log.test.mjs +113 -0
  151. package/scripts/cm-fix-protected-edits.test.mjs +12 -0
  152. package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
  153. package/scripts/cm-fix-review-budget.test.mjs +7 -1
  154. package/scripts/cm-host-qa-executor.test.mjs +329 -3
  155. package/scripts/cm-knowledge-closeout.test.mjs +160 -0
  156. package/scripts/cm-live-evidence.test.mjs +64 -0
  157. package/scripts/cm-log-event.mjs +34 -7
  158. package/scripts/cm-log-event.py +15 -0
  159. package/scripts/cm-model-setup.mjs +79 -0
  160. package/scripts/cm-prd-drive.mjs +32 -11
  161. package/scripts/cm-prd-drive.test.mjs +15 -0
  162. package/scripts/cm-prd-host.mjs +26 -6
  163. package/scripts/cm-prd-host.test.mjs +4 -0
  164. package/scripts/cm-prd-review-host.test.mjs +17 -0
  165. package/scripts/cm-prd-session-recovery.test.mjs +44 -2
  166. package/scripts/cm-prd-task-grouping.test.mjs +206 -0
  167. package/scripts/cm-release-smoke.sh +5 -1
  168. package/scripts/cm-review-scope-recovery.test.mjs +5 -3
  169. package/scripts/cm-runtime-i18n.mjs +15 -4
  170. package/scripts/cm-runtime-install.mjs +8 -4
  171. package/scripts/cm-runtime.mjs +116 -23
  172. package/scripts/cm-runtime.test.mjs +121 -12
  173. package/scripts/cm-security.test.mjs +32 -0
  174. package/scripts/cm-task-gate-correction.test.mjs +117 -0
  175. package/scripts/cm-task-gate.mjs +146 -10
  176. package/scripts/cm-task-gate.py +1 -0
  177. package/scripts/cm-test-branch-impact.test.mjs +11 -0
  178. package/scripts/cm-test-drive.mjs +10 -4
  179. package/scripts/cm-test-drive.test.mjs +14 -1
  180. package/scripts/cm-tool-preview-context.test.mjs +12 -0
  181. package/scripts/cm-usage-report.py +22 -3
  182. package/scripts/cm-workflow-config.mjs +10 -1
  183. package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
  184. package/scripts/fixtures/live-evidence-driver.mjs +35 -0
  185. package/scripts/fixtures/process-cleanup.mjs +3 -1
  186. package/scripts/test-cm-native-usage.py +62 -0
  187. package/scripts/test-external-model-setup.py +91 -0
  188. package/scripts/test-model-configuration-write.py +201 -0
  189. package/scripts/test-npm-install.py +10 -1
  190. package/skills/cm-ai/SKILL.md +2 -2
  191. package/skills/cm-ai/references/N1-init.md +1 -1
  192. package/skills/cm-ai/references/N8-finish.md +5 -0
  193. package/skills/cm-ai/references/js-host.md +16 -7
  194. package/skills/cm-ai/references/knowledge-closeout.md +90 -0
  195. package/skills/cm-fix/SKILL.md +1 -1
  196. package/skills/cm-fix/references/js-host.md +30 -2
  197. package/skills/cm-prd/SKILL.md +5 -4
  198. package/skills/cm-prd/references/spec-self-check.md +3 -1
  199. package/skills/cm-runtime/SKILL.md +29 -6
  200. package/skills/cm-security/SKILL.md +4 -2
  201. package/skills/cm-security/references/scan-contract.md +1 -0
  202. package/templates/cm-workflow.yml +1 -1
@@ -1,4 +1,7 @@
1
+ import {readExecutionPolicy} from './execution-policy.mjs';
2
+ import {readExternalModels} from './external-models.mjs';
1
3
  import {beforeFirstQaRound,readQaConfigRevision} from './qa-config-revision.mjs';
4
+ import {readCloseoutPolicy} from './knowledge-closeout.mjs';
2
5
  import {readQaAttachment} from './qa-attachment.mjs';
3
6
  // Trusted synthetic fixture host; explicit V2 supports isolated task-file writes.
4
7
  import { randomUUID } from 'node:crypto';
@@ -16,13 +19,14 @@ import { checkCompletion } from './gate-bridge.mjs';
16
19
  import { runnerPayload,runnerPayloadV3,readRunnerHistory,attemptBaseline,boundRunnerRecord,
17
20
  MAX_AI_JOINED_HOSTS,controlledState,stageAllowed,effectSlotFree,reviewTimeoutTransition,validateReviewDispatchGrant,validateTaskLearningReviewPackage,
18
21
  reviewRetrySpent,abandonableReviewResult,developBudget,developBudgetExhausted,
19
- completionBlockCount,completionRetriesExhausted,supersededReviewPayload } from './durable-runner-state.mjs';
22
+ completionBlockCount,completionRetriesExhausted,supersededReviewPayload,bootstrapReviewRecoverable,protectedDevelopScope,protectedScopeBlockReason } from './durable-runner-state.mjs';
20
23
  import {commitRunnerFixture} from './task-commit.mjs';
21
24
  import {inspectProviderReview,hasProviderReviewResult,inspectProviderReviewFailure} from './provider-review-observation.mjs';
22
25
  import {attachCmAiTaskLearningApplicationEvidence,attachCmAiTaskLearningEvidence,
23
26
  readCmAiTaskLearningApplication} from './cm-ai-context-refresh.mjs';
24
27
  import {readCmAiProjectLearningWriteback,writeCmAiProjectLearning} from './cm-ai-learning-writer.mjs';
25
28
  import {verifyCmAiTaskLearningHandoff,writeCmAiTaskLearningHandoff} from './cm-ai-learning-handoff-writer.mjs';
29
+ import {implementationSha256,loadHandoff} from '../../../scripts/cm-task-gate.mjs';
26
30
  import {createHostHandoff} from './host-handoff.mjs';
27
31
  import {inspectFixCodeAssociation,explainCompletedDelivery} from './fix-code-association.mjs';
28
32
  import {approvedReviewAt,completedReviewedDeliveries,fixReviewedAt,resolveDeliverySteps} from './reviewed-deliveries.mjs';
@@ -35,6 +39,7 @@ import {reviewExclusions} from './effect-contract.mjs';
35
39
  import {bootstrapConfiguration,readBootstrapEvidence} from './host-bootstrap.mjs';
36
40
  import {validateCodeProjectPaths,assertCodeProjectSelections} from './code-projects.mjs';
37
41
  import {readEvidenceSupersession} from './reviewed-evidence-supersession-record.mjs';
42
+ import {readReconciliationReceipt} from './review-reconciliation.mjs';
38
43
 
39
44
  // Keep default V1 imports free of SQLite initialization/warnings. Native ownership
40
45
  // is loaded synchronously only at the explicit V2 boundary (Node24.14+).
@@ -134,6 +139,9 @@ export function createTaskRunner(options) {
134
139
  if(options && Object.hasOwn(options,'codeProjectPaths'))optionKeys.push('codeProjectPaths');
135
140
  if(options && Object.hasOwn(options,'verificationGate'))optionKeys.push('verificationGate');
136
141
  if(options && Object.hasOwn(options,'providerDevelopment'))optionKeys.push('providerDevelopment');
142
+ if(options && Object.hasOwn(options,'knowledgeCloseout'))optionKeys.push('knowledgeCloseout');
143
+ if(options && Object.hasOwn(options,'executionPolicy'))optionKeys.push('executionPolicy');
144
+ if(options && Object.hasOwn(options,'externalModels'))optionKeys.push('externalModels');
137
145
  if(invocationMode)optionKeys.push('reviewInvocation');
138
146
  shape(options,optionKeys);
139
147
  need(options.providerDevelopment===undefined||typeof options.providerDevelopment==='boolean','invalid_input');
@@ -190,7 +198,10 @@ export function createTaskRunner(options) {
190
198
  }
191
199
  let metadata=json({...config,developer:{provider:developer.provider,requestedModel:developer.requestedModel,contextId:developer.contextId},
192
200
  reviewers:reviewers.map(({run,...r})=>r),...(invocationMode?{reviewInvocation:invocationConfig}:{}),
193
- ...(Object.hasOwn(options,'taskLearning')?{taskLearning:json(options.taskLearning)}:{})});
201
+ ...(Object.hasOwn(options,'taskLearning')?{taskLearning:json(options.taskLearning)}:{}),
202
+ ...(Object.hasOwn(options,'knowledgeCloseout')?{knowledgeCloseout:readCloseoutPolicy(options.knowledgeCloseout)}:{}),
203
+ ...(Object.hasOwn(options,'executionPolicy')?{executionPolicy:readExecutionPolicy(options.executionPolicy)}:{}),
204
+ ...(Object.hasOwn(options,'externalModels')?{externalModels:readExternalModels(options.externalModels)}:{})});
194
205
  const taskLearning=metadata.taskLearning??null;
195
206
  if(taskLearning!==null){need(taskMode,'runner_learning');
196
207
  shape(taskLearning,['feature',...(Object.hasOwn(taskLearning,'hostHandoff')?['hostHandoff']:[])]);
@@ -276,13 +287,13 @@ export function createTaskRunner(options) {
276
287
  // derivation in one place, next to the cache it is derived from.
277
288
  const verificationBlocks=()=>[...cache.values()].filter(entry=>entry.effect.kind==='develop'
278
289
  &&entry.result?.state==='blocked'
279
- &&['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(entry.result?.code)).length;
290
+ &&['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(entry.result?.code)).length;
280
291
  const completionBlocks=()=>[...cache.values()].filter(entry=>entry.effect.kind==='complete'
281
292
  &&entry.result?.state==='blocked'&&['completion_checks_changed','completion_package_changed'].includes(entry.result?.code)).length;
282
293
  const privateStatus=()=>json({state,code,...(reason?{reason}:{}),
283
- ...(state==='unknown'&&restored?.pendingAbandonable
294
+ ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pendingAbandonable
284
295
  ?{pendingEffectKind:restored.pending.kind}:{}),
285
- ...(state==='unknown'&&restored?.pending?.kind==='review'
296
+ ...(!(metadata.externalModels||metadata.executionPolicy)&&state==='unknown'&&restored?.pending?.kind==='review'
286
297
  &&restored.state.reviewInvocation?.registration&&restored.state.reviewInvocation.result===null
287
298
  ?{pendingReviewInvocation:true}:{}),
288
299
  identity:{...config.identity,attempt},packageDigest:reviewPackage?.packageDigest??null,
@@ -304,15 +315,28 @@ export function createTaskRunner(options) {
304
315
  };
305
316
  const laterOptions=(evidence=null)=>({deliveries:laterDeliveries,after:reviewedAt(),fixTime:fixTime(evidence)});
306
317
  let publication;
318
+ let pendingReconciliation=null;
307
319
  // Replay decides; this only reports an exit abandonReview would accept.
308
320
  function reviewResultAbandonable(){
309
- return invocationMode&&store&&!busy&&!poisoned&&state==='unknown'&&!restored?.pending
321
+ return !(metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned&&state==='unknown'&&!restored?.pending
310
322
  &&abandonableReviewResult({state,attempt,cache:[...cache.values()],calls,reviewInvocation},reviewers[0].contexts[attempt-1]);
311
323
  }
312
324
  const status=()=>{
313
325
  let current=store?publication:privateStatus();
326
+ if(!busy&&!poisoned&&bootstrapReviewRecoverable(frame(),restored?.pending??null,metadata.bootstrap))
327
+ current=freeze({...current,bootstrapReviewRecovery:true});
314
328
  // Status only; never part of a cached result or checkpoint.
315
329
  if(current.state==='unknown'&&reviewResultAbandonable())current=freeze({...current,abandonableReviewResult:true});
330
+ const available=Boolean((metadata.externalModels||metadata.executionPolicy))&&!busy&&!poisoned&&invocationMode&&store&&['unknown','pending_review'].includes(current.state)
331
+ &&readRunnerHistory(journal,metadata,3).reviewReconciliation!==null;
332
+ if((metadata.externalModels||metadata.executionPolicy)&&!busy&&!poisoned&&invocationMode&&store&&reviewInvocation?.registration
333
+ &&(available||current.state==='unknown'&&reviewInvocation.result?.reconciliationRequired!==false)){
334
+ const grant=reviewInvocation.registration.grant;
335
+ current=freeze({...current,reviewReconciliation:{invocationId:grant.invocationId,requestDigest:grant.requestDigest,
336
+ provider:reviewers[0].provider,providerThreadId:reviewInvocation.started,available},
337
+ reason:available?'原调用的终态与本地清理收据已保存;使用 reconcile_review 接纳证据,此操作不派发模型。'
338
+ :'缺少原调用的可信终态或本地清理证据。保留本 run、attempt、journal 和快照;按 invocationId / providerThreadId 向原宿主或 provider 核对结果及终止状态,并确认本地后代已退出。当前适配器没有远端状态查询入口,人工说明、PID 消失或重启均不能解锁;不要删 journal、换 runId 或重派。'});
339
+ }
316
340
  if(!busy&&!poisoned)try{publishRegisteredReview(true);}
317
341
  catch{return freeze({...current,code:'review_publication_required'});}
318
342
  // Every next effect re-verifies the bound specification. When it no longer
@@ -399,9 +423,10 @@ export function createTaskRunner(options) {
399
423
  kind:{init:'result','effect-intent':'intent','effect-checkpoint':'result',control:'cancel',
400
424
  'task-commit-intent':'commit-intent','task-commit-result':'commit-result',
401
425
  'review-invocation-registered':'intent','review-invocation-started':'result','review-invocation-result':'result',
402
- 'review-invocation-abandoned':'result','effect-abandoned':'result',
426
+ 'review-invocation-abandoned':'result','review-invocation-receipt':'result','review-invocation-reconciled':'result','effect-abandoned':'result',
403
427
  'host-joined':'result','qa-fix-accepted':'result','qa-attached':'result','qa-config-revised':'result',
404
- 'evidence-superseded':'result','develop-retry-limit':'result','completion-retry-limit':'result','specification-rebound':'result'}[type],
428
+ 'evidence-superseded':'result','develop-retry-limit':'result','completion-retry-limit':'result','specification-rebound':'result',
429
+ 'bootstrap-review-recovered':'result'}[type],
405
430
  payload:version===3?runnerPayloadV3(type,fields):runnerPayload(type,fields,version)};
406
431
  const body={version:1,seq:journal.length+1,...basic,previousDigest:journal.at(-1)?.digest??null};
407
432
  const record={...body,digest:digest(body)};boundRunnerRecord(record,body.seq);
@@ -646,6 +671,21 @@ export function createTaskRunner(options) {
646
671
  const expectation={request,developerThreadId:invocationConfig.developerThreadId,
647
672
  excludedThreadIds:reviewExclusions(liveInvocation(),calls,developer.contextId)};
648
673
  const events=[];let started=null,sealed=false,invalid=false,invalidReject;
674
+ let capturedReceipt=null,receiptConflict=false,captureOpen=true,adapterDone;
675
+ const adapterFinished=new Promise(resolve=>{adapterDone=resolve;});
676
+ const onReconciliation=raw=>{
677
+ if(!captureOpen||invalid)return false;
678
+ try{
679
+ let value=readReconciliationReceipt(raw);
680
+ if(value.result?.status==='succeeded'){
681
+ const bounded=boundReviewText(value.result.value);need(bounded!==null,'observation_invalid');
682
+ value={...value,result:{status:'succeeded',value:bounded}};
683
+ }
684
+ if(capturedReceipt&&digest(value)!==digest(capturedReceipt))receiptConflict=true;
685
+ else capturedReceipt=value;
686
+ return !receiptConflict;
687
+ }catch{receiptConflict=true;return false;}
688
+ };
649
689
  const localController=new AbortController();
650
690
  const abort=()=>localController.abort();controller.signal.addEventListener('abort',abort,{once:true});
651
691
  const observation=result=>json({version:1,kind:'cm-provider-review-observation',requestDigest:request.requestDigest,
@@ -684,13 +724,14 @@ export function createTaskRunner(options) {
684
724
  new Promise((resolve,reject)=>queueMicrotask(()=>{
685
725
  try{
686
726
  need(!localController.signal.aborted,'cancelled');
687
- const returned=adapter.run(request,{signal:localController.signal,onEvent});
727
+ const returned=adapter.run(request,{signal:localController.signal,onEvent,...((metadata.externalModels||metadata.executionPolicy)?{onReconciliation}:{})});
688
728
  if(types.isPromise(returned)){
689
729
  const supported=Object.getPrototypeOf(returned)===promisePrototype&&!Object.hasOwn(returned,'constructor');
690
- const observed=observePromise(returned,supported?resolve:ignorePromiseResult,supported?reject:ignorePromiseResult);
730
+ const observed=observePromise(returned,supported?value=>{adapterDone();resolve(value);}:ignorePromiseResult,
731
+ supported?error=>{adapterDone();reject(error);}:ignorePromiseResult);
691
732
  need(supported&&observed);
692
- }else resolve(returned);
693
- }catch(error){reject(error);}
733
+ }else {adapterDone();resolve(returned);}
734
+ }catch(error){adapterDone();reject(error);}
694
735
  })),
695
736
  invalidPromise,
696
737
  new Promise((_,reject)=>{timer=setTimeout(()=>{timedOut=true;localController.abort();
@@ -706,7 +747,7 @@ export function createTaskRunner(options) {
706
747
  const recorded=observation({status:'failed',code:'timeout'});
707
748
  fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'timed_out',
708
749
  observation:recorded,inspection:inspectProviderReview(JSON.stringify(recorded),JSON.stringify(expectation)),
709
- reconciliationRequired:hasProviderReviewResult(recorded.events)};
750
+ reconciliationRequired:Boolean((metadata.externalModels||metadata.executionPolicy))||hasProviderReviewResult(recorded.events)};
710
751
  }
711
752
  else if(state==='cancelled'){fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'cancelled',
712
753
  observation:observation({status:'cancelled',code:'cancelled'}),inspection:null,reconciliationRequired:true};}
@@ -720,7 +761,12 @@ export function createTaskRunner(options) {
720
761
  reviewInvocation=json({registration,started,result});
721
762
  if(fields.outcome==='cancelled')halt('cancelled','cancelled');
722
763
  else if(retry)halt(retry.state,retry.code);
723
- else halt('unknown',fields.reason??fields.inspection?.code??'reconciliation_required');return;
764
+ else halt('unknown',fields.reason??fields.inspection?.code??'reconciliation_required');
765
+ // Bound cleanup draining; never wait indefinitely or dispatch again.
766
+ // The original unknown is already journaled and remains unchanged.
767
+ if((metadata.externalModels||metadata.executionPolicy)&&timedOut&&!invalid){let drainTimer;await Promise.race([adapterFinished,
768
+ new Promise(resolve=>{drainTimer=setTimeout(resolve,2500);})]);clearTimeout(drainTimer);}
769
+ return;
724
770
  }
725
771
  sealed=true;
726
772
  let providerResult;
@@ -740,11 +786,11 @@ export function createTaskRunner(options) {
740
786
  // the verdict contract, ends in a new explicit retryable result.
741
787
  const reviewerFailed=(recorded,failure)=>{
742
788
  const fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:'failed',observation:recorded,
743
- inspection:failure,reconciliationRequired:false};
789
+ inspection:failure,reconciliationRequired:Boolean((metadata.externalModels||metadata.executionPolicy))};
744
790
  persist('review-invocation-result',fields);const result=resultView(fields);
745
791
  const retry=reviewTimeoutTransition(result,[...cache.values()],attempt,calls.slice(0,-1),contextId);
746
- Object.assign(call,{terminal:'failed',resultDigest:digest(result)});reviewInvocation=json({registration,started,result});
747
- halt(retry.state,retry.code,reviewFailureReason(failure.failure));
792
+ Object.assign(call,{terminal:retry?'failed':'unknown',resultDigest:digest(result)});reviewInvocation=json({registration,started,result});
793
+ halt(retry?.state??'unknown',retry?.code??failure.code??'reconciliation_required',reviewFailureReason(failure.failure));
748
794
  };
749
795
  // Bound the reviewer text before it is observed, inspected or journaled.
750
796
  if(providerResult.status==='succeeded'){
@@ -771,7 +817,7 @@ export function createTaskRunner(options) {
771
817
  if(failure){reviewerFailed(recorded,failure);return;}
772
818
  const fields={effectId,invocationId:request.invocationId,dispatchAt,outcome:observed?'observed':inspection.code==='transport_timeout'?'timed_out':'unknown',
773
819
  observation:recorded,inspection,reconciliationRequired:!observed
774
- &&(inspection.code!=='transport_timeout'||hasProviderReviewResult(recorded.events))};
820
+ &&(Boolean((metadata.externalModels||metadata.executionPolicy))||inspection.code!=='transport_timeout'||hasProviderReviewResult(recorded.events))};
775
821
  persist('review-invocation-result',fields);const result=resultView(fields);
776
822
  const retry=reviewTimeoutTransition(result,[...cache.values()],attempt,calls.slice(0,-1),contextId);
777
823
  Object.assign(call,{terminal:observed?'succeeded':retry?'failed':'unknown',resultDigest:digest(observed?inspection.review:result)});
@@ -779,7 +825,12 @@ export function createTaskRunner(options) {
779
825
  if(observed)acceptReview(request,call,inspection.review);
780
826
  else if(retry)halt(retry.state,retry.code);
781
827
  else halt('unknown',inspection.code??'reconciliation_required');
782
- }finally{sealed=true;clearTimeout(timer);controller.signal.removeEventListener('abort',abort);
828
+ }finally{
829
+ captureOpen=false;
830
+ if((metadata.externalModels||metadata.executionPolicy)&&(state==='unknown'||state==='pending_review'&&code==='review_transport_timeout')
831
+ &&started!==null&&!invalid&&!receiptConflict&&capturedReceipt)
832
+ pendingReconciliation={effectId,invocationId:request.invocationId,receipt:capturedReceipt};
833
+ sealed=true;clearTimeout(timer);controller.signal.removeEventListener('abort',abort);
783
834
  if(cancelReject)controller.signal.removeEventListener('abort',cancelReject);}
784
835
  }
785
836
  async function collectChecks(){
@@ -843,6 +894,15 @@ export function createTaskRunner(options) {
843
894
  });
844
895
  const emptyDelivery=error=>{
845
896
  if(error?.code==='empty_changes'){halt('blocked','develop_empty_changes',EMPTY_DELIVERY);return;}
897
+ // Instruction bootstrap has its own no-redispatch recovery contract once
898
+ // rule evidence starts being written. Keep its size failures on that
899
+ // conservative path instead of granting a fresh developer effect.
900
+ if(error?.code==='limit_exceeded'&&metadata.bootstrap?.mode!=='instructions'){
901
+ halt('blocked','develop_package_too_large',boundedReason('develop_package_too_large: ',
902
+ [safeReason(error)??'review material exceeds its bounded size'],
903
+ '; shrink the changed files or move generated artifacts out of scope, then resume to redo this attempt'));
904
+ return;
905
+ }
846
906
  const missing=error?.code==='read_failed'?missingScopeRequirements():[];
847
907
  if(!missing.length)throw error;
848
908
  halt('blocked','develop_requirement_missing',boundedReason('develop_requirement_missing: ',missing,
@@ -851,9 +911,23 @@ export function createTaskRunner(options) {
851
911
  async function perform(v) {
852
912
  if(v.kind==='develop') {
853
913
  need(stageAllowed('develop',state,code,priorReview?.verdict),'stage_mismatch');state='developing';code=null;reason=null;checkNewPaths=null;receipt=null;
914
+ // The adapter would refuse this scope before any provider runs. Block it
915
+ // here instead: no call starts, nothing is written, and the outcome is
916
+ // definite rather than unknown (create refuses such runs already).
917
+ const refusedScope=protectedDevelopScope(metadata);
918
+ if(refusedScope.length){halt('blocked','protected_scope',protectedScopeBlockReason(refusedScope));return;}
854
919
  const previousLearning=learningResult;
855
920
  const previousBootstrap=learningResult?.bootstrap??null;
856
921
  const previousWriteback=learningResult?.writeback??null;
922
+ if(bootstrap!==null&&metadata.bootstrap?.mode==='instructions'){
923
+ try{bootstrap.assertInstructionBaseline({identity:v.identity,previous:previousBootstrap,
924
+ previousWriteback});}
925
+ catch(error){if(error.code!=='bootstrap_instruction_conflict')throw error;
926
+ halt('blocked','bootstrap_instruction_conflict',boundedReason(
927
+ 'bootstrap_instruction_conflict: 规则文件与本运行绑定的基准不一致:',error.paths??[],
928
+ '。本轮未派发或写入。请还原这些文件后在原 run resume;若要采用新的提交,使用新 runId 重建。'));
929
+ return;}
930
+ }
857
931
  if(taskLearning!==null)learningResult=null;
858
932
  let verificationReason=null;
859
933
  const adapter=bootstrap===null?developer:{...developer,run:(request,control)=>
@@ -1063,10 +1137,12 @@ export function createTaskRunner(options) {
1063
1137
  const failure=failureCode(error);
1064
1138
  const checkOnly=failure==='out_of_scope'&&Array.isArray(error.violations)&&error.violations.length>0
1065
1139
  &&error.violations.every(item=>item.newFile&&checkNewPaths?.has(item.path));
1066
- halt(checkOnly||failure==='spec_drift'?'blocked':'unknown',
1140
+ halt(checkOnly||failure==='spec_drift'||failure==='bootstrap_review_mismatch'?'blocked':'unknown',
1067
1141
  checkOnly?'check_output_out_of_scope':failure,
1068
- ['out_of_scope','unsupported_file','limit_exceeded','package_mismatch','snapshot_changed'].includes(failure)
1069
- ?safeReason(error):null);
1142
+ failure==='bootstrap_review_mismatch'
1143
+ ?'规则审查包与六项目标证据不符;核对当前文件及 handoff 后,在原 run 使用 bootstrap_review_recover 恢复审查包。'
1144
+ :['out_of_scope','unsupported_file','limit_exceeded','package_mismatch','snapshot_changed'].includes(failure)
1145
+ ?safeReason(error):null);
1070
1146
  }}
1071
1147
  if(poisoned)return status();
1072
1148
  let result=privateStatus();cache.set(v.id,{effect:v,digest:digest(v),result});
@@ -1091,6 +1167,16 @@ export function createTaskRunner(options) {
1091
1167
  }
1092
1168
  try{persist('effect-checkpoint',{effectId:v.id,checkpoint:frame()});publication=result;}
1093
1169
  catch{return poison();}
1170
+ if(pendingReconciliation){
1171
+ const saved=pendingReconciliation;pendingReconciliation=null;
1172
+ const registration=journal.findLast(row=>row.payload.type==='review-invocation-registered'&&row.payload.effectId===saved.effectId);
1173
+ const startedRecord=journal.findLast(row=>row.payload.type==='review-invocation-started'&&row.payload.effectId===saved.effectId);
1174
+ const resultRecord=journal.findLast(row=>row.payload.type==='review-invocation-result'&&row.payload.effectId===saved.effectId);
1175
+ const fields={...saved,registeredDigest:registration.digest,startedDigest:startedRecord?.digest??null,resultDigest:resultRecord.digest};
1176
+ // Invalid/unusable evidence never mutates the journal or poisons a run.
1177
+ let usable=false;try{assertJournalFits('review-invocation-receipt',fields,'review_reconciliation_limit');usable=true;}catch{}
1178
+ if(usable)try{persist('review-invocation-receipt',fields);}catch{return poison();}
1179
+ }
1094
1180
  // A block or verdict that leaves no reviewable delivery ends the run now,
1095
1181
  // so status never invites a resume that could not finish.
1096
1182
  try{const record=limitDue();return record?record():result;}catch{return poison();}
@@ -1098,7 +1184,7 @@ export function createTaskRunner(options) {
1098
1184
  if(poisoned)return result;
1099
1185
  try{publishRegisteredReview();}
1100
1186
  catch{return freeze({...result,code:'review_publication_required'});}
1101
- return result.state==='unknown'&&reviewResultAbandonable()?freeze({...result,abandonableReviewResult:true}):result;
1187
+ return ['unknown','pending_review'].includes(result.state)?status():result;
1102
1188
  });
1103
1189
  return pending;
1104
1190
  }
@@ -1114,8 +1200,11 @@ export function createTaskRunner(options) {
1114
1200
  }
1115
1201
  function currentLearningInput() {
1116
1202
  const currentIdentity={...config.identity,attempt};
1203
+ const recovered=journal?.some(row=>row.payload.type==='bootstrap-review-recovered'
1204
+ &&row.payload.reviewPackage.packageDigest===reviewPackage?.packageDigest)??false;
1117
1205
  const develop=[...cache.values()].filter(entry=>entry.effect.kind==='develop'
1118
- &&digest(entry.effect.identity)===digest(currentIdentity)&&entry.result.state==='awaiting_review');
1206
+ &&digest(entry.effect.identity)===digest(currentIdentity)
1207
+ &&(entry.result.state==='awaiting_review'||recovered&&['unknown','blocked'].includes(entry.result.state)));
1119
1208
  need(develop.length===1&&Object.hasOwn(develop[0].effect,'learningInput'),'runner_learning');
1120
1209
  return develop[0].effect.learningInput;
1121
1210
  }
@@ -1223,6 +1312,7 @@ export function createTaskRunner(options) {
1223
1312
  };
1224
1313
  const abandonReview=raw=>{
1225
1314
  try{
1315
+ need(!(metadata.externalModels||metadata.executionPolicy),'external_review_reconciliation_required');
1226
1316
  need(invocationMode&&store&&!busy&&!poisoned&&state==='unknown'
1227
1317
  &&(restored?.pending?.kind==='review'||reviewResultAbandonable()),'review_abandon_unavailable');
1228
1318
  const value=json(raw);shape(value,['allowed','reason']);
@@ -1261,8 +1351,36 @@ export function createTaskRunner(options) {
1261
1351
  publication=privateStatus();return status();
1262
1352
  }catch(error){return freeze({outcome:'rejected',code:error.code??'review_abandon_unavailable'});}
1263
1353
  };
1354
+ const reconcileReview=raw=>{
1355
+ try{
1356
+ need((metadata.externalModels||metadata.executionPolicy)&&invocationMode&&store&&!busy&&!poisoned,'review_reconciliation_unavailable');
1357
+ const value=json(raw);shape(value,['invocationId']);id(value.invocationId);
1358
+ const prior=journal.findLast(row=>row.payload.type==='review-invocation-reconciled');
1359
+ if(prior?.payload.invocationId===value.invocationId&&state!=='unknown')return status();
1360
+ const history=readRunnerHistory(journal,metadata,3),proof=history.reviewReconciliation;
1361
+ need(['unknown','pending_review'].includes(state)&&!history.pending&&proof!==null,'review_reconciliation_evidence_required');
1362
+ need(proof.invocationId===value.invocationId,'review_reconciliation_binding');
1363
+ const {request,effect,before,result,...binding}=proof;
1364
+ const call=calls.find(item=>item.invocationId===value.invocationId);
1365
+ need(['unknown','failed'].includes(call?.terminal),'review_reconciliation_unavailable');
1366
+ // Same call, same grant and same effect. The journal retains the original
1367
+ // unknown and receipt; one atomic record contains the validated transition.
1368
+ Object.assign(call,{terminal:result.outcome==='observed'?'succeeded':'failed',
1369
+ resultDigest:digest(result.outcome==='observed'?result.inspection.review:result)});
1370
+ reviewInvocation=json({...reviewInvocation,result});reason=null;
1371
+ if(result.outcome==='observed')acceptReview(request,call,result.inspection.review);
1372
+ else {const retry=reviewTimeoutTransition(result,before.cache,before.attempt,before.calls,call.contextId);
1373
+ halt(retry.state,retry.code,reviewFailureReason(result.inspection.failure));}
1374
+ const response=privateStatus();cache.set(effect.id,{effect,digest:digest(effect),result:response});
1375
+ try{persist('review-invocation-reconciled',{...binding,checkpoint:frame()});publication=response;}
1376
+ catch{return poison();}
1377
+ try{limitDue()?.();}catch{return poison();}
1378
+ return status();
1379
+ }catch(error){return freeze({outcome:'rejected',code:error.code??'review_reconciliation_unavailable'});}
1380
+ };
1264
1381
  const abandonEffect=raw=>{
1265
1382
  try{
1383
+ need(!(metadata.externalModels||metadata.executionPolicy),'external_review_reconciliation_required');
1266
1384
  need(invocationMode&&store&&!busy&&!poisoned&&options.persistence.mode==='resume','effect_abandon_unavailable');
1267
1385
  const value=json(raw);shape(value,['allowed','reason']);
1268
1386
  need(value.allowed===true,'effect_abandon_authorization_required');
@@ -1285,7 +1403,40 @@ export function createTaskRunner(options) {
1285
1403
  }catch(error){return freeze({outcome:'rejected',code:error.code??'effect_abandon_unavailable',
1286
1404
  ...(error.code==='effect_abandon_commit_pending'?{reason:'task-commit-intent 已写入,tasks.md 可能已改名或勾选;请核对 tasks.md、提交回执和旧进程后按原提交恢复路径处理。'}:{})});}
1287
1405
  };
1288
- const api={reviseQa,supersedeEvidence,rebindSpecification,abandonReview,abandonEffect,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks,completionBlocks};
1406
+ const recoverBootstrapReview=raw=>{
1407
+ try{
1408
+ need(invocationMode&&store&&!busy&&!poisoned&&options.persistence.mode==='resume',
1409
+ 'bootstrap_review_recovery_unavailable');
1410
+ const value=json(raw);shape(value,['allowed','reason']);
1411
+ need(value.allowed===true,'bootstrap_review_recovery_authorization_required');
1412
+ need(typeof value.reason==='string'&&value.reason.trim().length>0&&Buffer.byteLength(value.reason,'utf8')<=500
1413
+ &&!/[\r\n\0]/.test(value.reason),'bootstrap_review_recovery_reason_required');
1414
+ const history=readRunnerHistory(journal,metadata,3);
1415
+ need(bootstrapReviewRecoverable(history.state,history.pending,metadata.bootstrap),
1416
+ 'bootstrap_review_recovery_unavailable');
1417
+ const input=history.state.cache.at(-1).effect.learningInput;
1418
+ const handoffPath=completion.handoffs[attempt-1];
1419
+ verifyCmAiTaskLearningHandoff({handoffPath,feature:taskLearning.feature,
1420
+ identity:{...config.identity,attempt},learningInput:input,
1421
+ ...(Object.hasOwn(learningResult,'application')?{application:learningResult.application}:{}),
1422
+ retrospective:learningResult.retrospective,writeback:learningResult.writeback});
1423
+ const pkg=createReviewPackage({root:config.root,baseline:base,checks:currentChecks,handoffPath});
1424
+ validateTaskLearningReviewPackage(pkg,learningResult.writeback,input,learningResult.bootstrap,metadata.bootstrap);
1425
+ const handoff=loadHandoff(handoffPath,{task:config.identity.taskId,attempt});
1426
+ const paths=pkg.changes.map(item=>item.path);
1427
+ need(digest([...handoff.changed_files].sort())===digest([...paths].sort())
1428
+ &&handoff.implementation_sha256===implementationSha256(config.root,handoff.changed_files),
1429
+ 'bootstrap_review_recovery_mismatch');
1430
+ verifyReviewPackage({root:config.root,baseline:base,checks:currentChecks,
1431
+ reviewPackage:pkg,expectedDigest:pkg.packageDigest,handoffPath});
1432
+ persist('bootstrap-review-recovered',{fromDigest:journal.at(-1).digest,reviewPackage:pkg,
1433
+ reason:value.reason,at:new Date().toISOString()});
1434
+ reviewPackage=pkg;state='awaiting_review';code=null;reason=null;
1435
+ publication=privateStatus();return status();
1436
+ }catch(error){return freeze({outcome:'rejected',code:error.code??'bootstrap_review_recovery_mismatch',
1437
+ reason:'原运行的文件、handoff 或证据无法精确核对;请保留现场并检查差异,不要重新派发开发。'});}
1438
+ };
1439
+ const api={reviseQa,supersedeEvidence,rebindSpecification,abandonReview,reconcileReview,abandonEffect,recoverBootstrapReview,executeEffect,status,cancel,run,inspectFixAssociation,acceptCompletedFix,attachQa,verificationBlocks,completionBlocks};
1289
1440
  if(bootstrap!==null)api.inspectBootstrapAdmission=()=>bootstrap.inspectAdmission(original);
1290
1441
  if(taskLearning!==null)api.attachLearningEvidence=attachLearningEvidence;
1291
1442
  // A terminal reviewer observation is durable even if the host died before
@@ -58,14 +58,18 @@ export function skillContext(parsed) {
58
58
  // Unknown prose and unresolved entries still count as a catalog.
59
59
  const introduction = 'Each entry includes a name, description, and location for its `SKILL.md`. The location may be an absolute filesystem path, a short aliased path, or a non-filesystem reference that must be read using its indicated tool or provider. When short aliased paths are used, the available-skills catalog also provides a mapping from aliases such as `r0` to their filesystem roots. Expand the alias before accessing the skill.';
60
60
  const usagePreamble = introduction + "\n\nThe user's instructions take precedence over guidelines provided in a skill. If explicit user instructions conflict with a skill's instructions, prioritize the user's instructions. \n\nThe first time in a conversation that you decide to apply a skill, inform the user in the commentary channel.\n\nIf a skill causes you to ask for permission or confirmation, pause, or leave requested work unfinished, name and link to the exact SKILL.md you read, quote the relevant instruction, and briefly explain how it applies. Distinguish explicit skill requirements from your interpretation. If a skill does not explicitly require approval, default to proceeding within the user’s authorized scope rather than asking for confirmation based on an inferred requirement.";
61
+ // Codex 0.159.2 retains this exact empty-catalog prose too. Only known
62
+ // preambles are exempt; any extra prose or unresolved entry stays blocked.
63
+ const currentUsagePreamble = introduction + "\n\nThe user's instructions take precedence over guidelines provided in a skill. If explicit user instructions conflict with a skill's instructions, prioritize the user's instructions.\n\nThe first time in a conversation that you decide to apply a skill, inform the user in the commentary channel.\n\nIf a skill causes you to ask for permission or confirmation, pause, or leave requested work unfinished, name the skill and summarize the specific instruction in the skill that led to your decision. Include this explanation in the request or final response where you pause.";
64
+ const emptyPreambles = new Set([introduction, usagePreamble, currentUsagePreamble]);
61
65
  const sections = texts.flatMap(text => [...text.matchAll(/### Available skills[^\n]*\n([\s\S]*?)(?=\n#{1,3} |\n<\/skills_instructions>|$)/g)]
62
- .map(m => m[1].trim()).map(section => section === introduction || section === usagePreamble ? '' : section));
66
+ .map(m => m[1].trim()).map(section => emptyPreambles.has(section) ? '' : section));
63
67
  const hasMarker = texts.some(text => /### Available skills|<skills_instructions>/.test(text));
64
68
  return { present: folders.size > 0 || (hasMarker && (!sections.length || sections.some(section => section.length > 0))),
65
69
  section_lengths: sections.map(s => s.length), folders: [...folders].sort() };
66
70
  }
67
71
 
68
- export async function previewTools({ cwd, model, fixtureResponse = false, disabledSkills = [],
72
+ export async function previewTools({ cwd, model, effort, fixtureResponse = false, disabledSkills = [],
69
73
  promptTransport = 'argument', cli = 'codex', allowCodeProject = false }) {
70
74
  cwd = fs.realpathSync(cwd);
71
75
  if (typeof allowCodeProject !== 'boolean' || !fs.statSync(cwd).isDirectory()) throw new Error('invalid code project');
@@ -126,7 +130,7 @@ export async function previewTools({ cwd, model, fixtureResponse = false, disabl
126
130
  const loopbackBase = `http://${server.address().address}:${port}`;
127
131
  const previewPrompt = 'Return a greeting for synthetic task A-DEMO-001.';
128
132
  const transport = previewPromptTransport(promptTransport, previewPrompt);
129
- const args = [...commonArgs({ cwd, model, disabledSkills }),
133
+ const args = [...commonArgs({ cwd, model, effort, disabledSkills }),
130
134
  '-c', 'model_provider="cm_local_tool_preview"',
131
135
  '-c', `model_providers.cm_local_tool_preview={name="CM local tool preview",base_url="${loopbackBase}/v1",wire_api="responses",env_key="CM_JS_PROBE_AUTH",requires_openai_auth=false,request_max_retries=0,stream_max_retries=0}`,
132
136
  transport.argument];
@@ -172,7 +176,7 @@ export async function previewTools({ cwd, model, fixtureResponse = false, disabl
172
176
  && posts[0].tools?.length === 0 && posts[0].auth_is_synthetic
173
177
  && posts[0].skill_catalog_present === false
174
178
  && result.code === (fixtureResponse ? 0 : 1) && !result.timedOut && !result.promptWriteFailed;
175
- const receipt = { cli_model: model, config_fingerprint: configFingerprint({ cwd, model, disabledSkills }),
179
+ const receipt = { cli_model: model, config_fingerprint: configFingerprint({ cwd, model, effort, disabledSkills }),
176
180
  passed, fixture_response: fixtureResponse, prompt_transport: promptTransport,
177
181
  real_model_requests: 0, local_requests: seen,
178
182
  disabled_skill_count: disabledSkills.length, process: result, listener_closed: true };
@@ -1,3 +1,4 @@
1
+ import {createProviderUsageCapture} from './provider-usage.mjs';
1
2
  // Read-only Claude process: edits are text proposals consumed by the protected host.
2
3
  import {spawn} from 'node:child_process';
3
4
  import {readFileSync} from 'node:fs';
@@ -5,8 +6,8 @@ import {claudeBaseArgs,claudeEnvironment} from './worker-claude.mjs';
5
6
  import {reportClaudeDevIntentNotice,reportClaudeRateLimitNotice} from './claude-review-stream.mjs';
6
7
  import {need,text,validCallTimeout,json,shape} from './effect-contract.mjs';
7
8
 
8
- export function claudeDeveloperArgs(model){
9
- const args=claudeBaseArgs(model),index=args.indexOf('--tools');
9
+ export function claudeDeveloperArgs(model,effort){
10
+ const args=claudeBaseArgs(model,effort),index=args.indexOf('--tools');
10
11
  args[index+1]='Read,Grep,Glob';
11
12
  const schema=JSON.parse(readFileSync(new URL('./claude-developer-proposal.schema.json',import.meta.url),'utf8'));
12
13
  delete schema.$schema;delete schema.$id;
@@ -53,7 +54,7 @@ export function validateClaudeProposal(raw){
53
54
  return result;
54
55
  }
55
56
 
56
- function createClaudeDeveloperStream(onNotice=null){
57
+ function createClaudeDeveloperStream(onNotice=null,onUsageTerminal=null){
57
58
  let session=null,initialized=false,done=false,value,assistant=false,noticeCount=0,thinkingCount=0;
58
59
  const tools=new Set();
59
60
  return {
@@ -99,8 +100,13 @@ function createClaudeDeveloperStream(onNotice=null){
99
100
  return;
100
101
  }
101
102
  need(event.type==='result','unexpected_event');
103
+ if(event.is_error===true&&['error_during_execution','error_max_turns','error_max_budget_usd','error_max_structured_output_retries'].includes(event.subtype)){
104
+ if(Number.isInteger(event.num_turns)&&event.num_turns>=0&&event.num_turns<=20)onUsageTerminal?.(event.usage);
105
+ need(false,'provider_failed');
106
+ }
102
107
  need(event.subtype==='success'&&event.is_error===false,'provider_failed');
103
108
  need(assistant&&tools.size===0&&Number.isInteger(event.num_turns)&&event.num_turns>=1,'unexpected_result');
109
+ onUsageTerminal?.(event.usage);
104
110
  let proposal=event.structured_output;
105
111
  if(!Object.hasOwn(event,'structured_output')){
106
112
  try{proposal=JSON.parse(event.result);}catch{need(false,'invalid_output_json');}
@@ -111,9 +117,9 @@ function createClaudeDeveloperStream(onNotice=null){
111
117
  };
112
118
  }
113
119
 
114
- export function claudeDeveloperWorker({cwd,model,cli='claude',timeoutMs=1800000,spawnProcess=spawn,onNotice=null}) {
120
+ export function claudeDeveloperWorker({cwd,model,effort,cli='claude',timeoutMs=1800000,spawnProcess=spawn,onNotice=null,onUsage=null,onUsageClaim=null}) {
115
121
  validCallTimeout(timeoutMs);
116
- const args=claudeDeveloperArgs(model);
122
+ const args=claudeDeveloperArgs(model,effort);
117
123
  let used=false;
118
124
  return async (request,{signal})=>{
119
125
  text(request.prompt);need(Buffer.byteLength(request.prompt)<=11*1024*1024,'limit_exceeded');
@@ -122,12 +128,14 @@ export function claudeDeveloperWorker({cwd,model,cli='claude',timeoutMs=1800000,
122
128
  if(process.platform==='win32')return {status:'unavailable',code:'process_tree_unsupported'};
123
129
  if(used)return {status:'unavailable',code:'worker_dispatch_limit'};
124
130
  used=true;
131
+ const usage=createProviderUsageCapture('claude',onUsage);
132
+ try{onUsageClaim?.();}catch{}
125
133
  return new Promise(resolve=>{
126
134
  let child;
127
135
  try{child=spawnProcess(cli,args,{cwd,env:claudeEnvironment(),stdio:['pipe','pipe','pipe'],shell:false,detached:true});}
128
- catch{resolve({status:'unavailable',code:'spawn_failed'});return;}
136
+ catch{usage.complete();resolve({status:'unavailable',code:'spawn_failed'});return;}
129
137
  let buffer='',bytes=0;
130
- const stream=createClaudeDeveloperStream(onNotice);
138
+ const stream=createClaudeDeveloperStream(onNotice,value=>usage.terminal(value));
131
139
  let failure=null,closed=false,timer,cleanup;
132
140
  const signalGroup=signalName=>{
133
141
  if(!Number.isInteger(child.pid)||child.pid<=0)return false;
@@ -172,6 +180,7 @@ export function claudeDeveloperWorker({cwd,model,cli='claude',timeoutMs=1800000,
172
180
  closed=true;clearTimeout(timer);signal.removeEventListener('abort',abort);
173
181
  await cleanGroup();
174
182
  if(buffer.trim())accept(buffer);
183
+ usage.complete();
175
184
  if(failure||code!==0||exitSignal){
176
185
  resolve({status:['spawn_failed','provider_failed'].includes(failure)?'unavailable':'unknown',code:failure??'incomplete_result'});return;
177
186
  }