@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
@@ -1,25 +1,29 @@
1
+ import {createProviderUsageCapture} from './provider-usage.mjs';
2
+ import {externalEffort} from './external-models.mjs';
1
3
  import {spawn} from 'node:child_process';
2
4
  import {createHash} from 'node:crypto';
3
5
  import {readFileSync} from 'node:fs';
4
6
  import {createClaudeReviewStream} from './claude-review-stream.mjs';
7
+ import {ownedProcessCleanup} from './owned-process-cleanup.mjs';
5
8
 
6
- export function claudeBaseArgs(model) {
9
+ export function claudeBaseArgs(model,effort=null) {
7
10
  if (typeof model !== 'string' || !/^[a-zA-Z0-9._-]+$/.test(model)) throw new Error('invalid_model');
8
- return ['--print','--input-format','text','--output-format','stream-json','--verbose',
11
+ effort=externalEffort('claude',effort);
12
+ return [...(effort===null?[]:['--effort',effort]),'--print','--input-format','text','--output-format','stream-json','--verbose',
9
13
  '--model',model,'--safe-mode','--setting-sources','','--tools','',
10
14
  '--disable-slash-commands','--strict-mcp-config','--mcp-config','{"mcpServers":{}}',
11
15
  '--permission-mode','dontAsk','--no-chrome','--no-session-persistence',
12
16
  '--prompt-suggestions','false'];
13
17
  }
14
- export function claudeReviewArgs(model) {
15
- const args=claudeBaseArgs(model);
18
+ export function claudeReviewArgs(model,effort=null) {
19
+ const args=claudeBaseArgs(model,effort);
16
20
  const schema=JSON.parse(readFileSync(new URL('./review-result.schema.json',import.meta.url),'utf8'));
17
21
  // Claude's schema engine does not accept the draft-2020-12 metadata.
18
22
  delete schema.$schema;delete schema.$id;
19
23
  return [...args,'--json-schema',JSON.stringify(schema)];
20
24
  }
21
- export function claudeReviewFingerprint({cwd,model,cli='claude'}) {
22
- return createHash('sha256').update(JSON.stringify({cwd,cli,args:claudeReviewArgs(model),
25
+ export function claudeReviewFingerprint({cwd,model,cli='claude',effort=null}) {
26
+ return createHash('sha256').update(JSON.stringify({cwd,cli,args:claudeReviewArgs(model,effort),
23
27
  environmentPolicy:1,promptTransport:'stdin'})).digest('hex');
24
28
  }
25
29
  export function claudeEnvironment() {
@@ -34,28 +38,42 @@ export function claudePreflightMatches(receipt,options) {
34
38
 
35
39
  // Diagnostic receipt is NOT authorization. Only the original V3 owner may dispatch this worker.
36
40
  // A matching diagnostic receipt remains required separately from the V3 grant.
37
- export function claudeWorker({cwd,model,preflight,cli='claude',timeoutMs=60000,spawnProcess=spawn,
38
- killProcess=(pid,signal)=>process.kill(pid,signal),onNotice=null}) {
39
- const args=claudeReviewArgs(model);
41
+ export function claudeWorker({cwd,model,preflight,cli='claude',timeoutMs=60000,spawnProcess=spawn,effort=null,
42
+ killProcess=(pid,signal)=>process.kill(pid,signal),onNotice=null,onUsage=null,onUsageClaim=null}) {
43
+ const args=claudeReviewArgs(model,effort);
40
44
  if (!Number.isSafeInteger(timeoutMs)||timeoutMs<1) throw new Error('invalid_timeout');
41
45
  let used=false;
42
- return async (request,{signal,onEvent})=>{
46
+ return async (request,{signal,onEvent,onTerminal})=>{
43
47
  if (process.platform==='win32') return {status:'blocked',code:'unsupported_process_cleanup'};
44
48
  if (used) return {status:'blocked',code:'worker_dispatch_limit'};
45
- if (!claudePreflightMatches(preflight,{cwd,model,cli})) {
49
+ if (!claudePreflightMatches(preflight,{cwd,model,cli,effort})) {
46
50
  return {status:'blocked',code:'tool_preflight_missing'};
47
51
  }
48
52
  if (signal.aborted) return {status:'cancelled',code:'cancelled_before_dispatch'};
49
53
  if (typeof request?.prompt!=='string') return {status:'failed',code:'invalid_prompt'};
50
54
  used=true;
55
+ const usage=createProviderUsageCapture('claude',onUsage);
56
+ try{onUsageClaim?.();}catch{}
51
57
  return new Promise(resolve=>{
52
58
  let child;
53
59
  try { child=spawnProcess(cli,args,{cwd,env:claudeEnvironment(),stdio:['pipe','pipe','pipe'],detached:true}); }
54
- catch { resolve({status:'failed',code:'spawn_failed'});return; }
60
+ catch { usage.complete();resolve({status:'failed',code:'spawn_failed'});return; }
55
61
  let buffer='', bytes=0, failure=null, settled=false, timedOut=false, killTimer, pendingClose;
56
- const stream=createClaudeReviewStream(onEvent,onNotice);
62
+ let providerThread=null,providerTerminal=false,failedTerminal=false,receiptInvalid=false;
63
+ const cleanupGroup=ownedProcessCleanup(child,{killProcess});
64
+ const providerFailure=()=>['provider_failed','reviewer_auth_failed','reviewer_billing_error',
65
+ 'reviewer_rate_limited','reviewer_server_error','reviewer_model_not_found','reviewer_api_error'].includes(failure);
66
+ const mayRead=()=>failure===null||['cancelled','timeout'].includes(failure)
67
+ ||typeof onTerminal==='function'&&providerFailure();
68
+ const stream=createClaudeReviewStream(event=>{
69
+ if(event.event==='thread.started')providerThread=event.provider_thread;
70
+ if(event.event==='turn.completed')providerTerminal=true;
71
+ onEvent(event);
72
+ },onNotice);
57
73
  const stop=code=>{
58
- failure??=code;
74
+ if(!['cancelled','timeout','provider_failed','reviewer_auth_failed','reviewer_billing_error',
75
+ 'reviewer_rate_limited','reviewer_server_error','reviewer_model_not_found','reviewer_api_error'].includes(code))receiptInvalid=true;
76
+ if(failure===null||['cancelled','timeout'].includes(failure))failure=code;
59
77
  if (code==='unexpected_tool_or_content') {
60
78
  // A successful non-StructuredOutput tool breaks the review boundary: kill now.
61
79
  try {killProcess(-child.pid,'SIGKILL');} catch {}
@@ -71,8 +89,27 @@ export function claudeWorker({cwd,model,preflight,cli='claude',timeoutMs=60000,s
71
89
  const timer=setTimeout(()=>{timedOut=true;stop('timeout');},timeoutMs);
72
90
  const clean=()=>{clearTimeout(timer);clearTimeout(killTimer);signal.removeEventListener('abort',abort);};
73
91
  const accept=line=>{
74
- if (failure || !line.trim()) return;
75
- try { stream.accept(JSON.parse(line)); }
92
+ if (!mayRead() || !line.trim()) return;
93
+ try {
94
+ const message=JSON.parse(line);
95
+ if(failedTerminal){stop('unexpected_event');return;}
96
+ // A synthetic assistant error is not a provider terminal. Only the
97
+ // original session's actual CLI result can attest a failed turn.
98
+ if((typeof onTerminal==='function'||typeof onUsage==='function')&&!providerTerminal&&!failedTerminal&&providerThread!==null
99
+ &&message?.type==='result'&&message.session_id===providerThread&&message.is_error===true
100
+ &&['success','error_during_execution','error_max_turns','error_max_budget_usd','error_max_structured_output_retries'].includes(message.subtype)
101
+ &&Number.isInteger(message.num_turns)&&message.num_turns>=0&&message.num_turns<=20){
102
+ failedTerminal=true;usage.terminal(message.usage);
103
+ // This branch is enabled only for receipt collection. The actual
104
+ // session result attests failure both before and after transport abort.
105
+ onEvent({event:'turn.failed',item_type:null});
106
+ stop('provider_failed');return;
107
+ }
108
+ if(providerFailure()){receiptInvalid=true;return;} // only the original session's terminal may follow an API failure
109
+ if(message.type==='result'&&message.session_id===providerThread&&message.subtype==='success'&&message.is_error===false
110
+ &&Number.isInteger(message.num_turns)&&message.num_turns>=1&&message.num_turns<=20)usage.terminal(message.usage);
111
+ stream.accept(message);
112
+ }
76
113
  catch (error) {stop(error instanceof SyntaxError?'invalid_event':error.code??'invalid_event');}
77
114
  };
78
115
  signal.addEventListener('abort',abort,{once:true});
@@ -80,7 +117,7 @@ export function claudeWorker({cwd,model,preflight,cli='claude',timeoutMs=60000,s
80
117
  child.stderr.resume(); // Do not persist provider diagnostics or authentication material.
81
118
  child.stdout.setEncoding('utf8');
82
119
  child.stdout.on('data',chunk=>{
83
- if (settled || failure) return;
120
+ if (settled || !mayRead()) return;
84
121
  bytes+=Buffer.byteLength(chunk,'utf8');
85
122
  if (bytes>1_000_000) {stop('output_limit');return;}
86
123
  buffer+=chunk;
@@ -89,13 +126,20 @@ export function claudeWorker({cwd,model,preflight,cli='claude',timeoutMs=60000,s
89
126
  accept(buffer.slice(0,index));buffer=buffer.slice(index+1);
90
127
  }
91
128
  });
92
- child.once('error',()=>{if(!settled){settled=true;clean();resolve({status:'failed',code:'spawn_failed'});}});
129
+ child.once('error',()=>{if(!settled){settled=true;clean();usage.complete();resolve({status:'failed',code:'spawn_failed'});}});
93
130
  child.once('close',(code,exitSignal)=>{
94
131
  if (settled) return;
95
132
  if (buffer.trim()) accept(buffer);
96
- pendingClose=()=>{
133
+ pendingClose=async()=>{
97
134
  settled=true;clean();
135
+ if(typeof onTerminal==='function')try{await cleanupGroup();}catch{failure='process_cleanup_unknown';}
136
+ usage.complete();
98
137
  onEvent({event:'process_closed',exit_code:code,signal:exitSignal,timed_out:timedOut});
138
+ if(failure==='process_cleanup_unknown'){resolve({status:'failed',code:failure});return;}
139
+ if(!receiptInvalid&&typeof onTerminal==='function'&&(failure===null||['cancelled','timeout'].includes(failure))){
140
+ try{onTerminal(stream.finish());}catch{}
141
+ }
142
+ else if(!receiptInvalid&&typeof onTerminal==='function'&&failedTerminal&&providerFailure())onTerminal({status:'failed',code:'provider_failed'});
99
143
  if (signal.aborted) {resolve({status:'cancelled',code:'cancelled'});return;}
100
144
  if (failure || code!==0 || exitSignal!==null) {
101
145
  resolve({status:'failed',code:failure??'incomplete_result'});return;
@@ -1,3 +1,4 @@
1
+ import {createProviderUsageCapture} from './provider-usage.mjs';
1
2
  // Coding subprocess only. The host must authorize the task and select an isolated
2
3
  // code workspace; workspace-write is not a per-file scope enforcement mechanism.
3
4
  import {spawn} from 'node:child_process';
@@ -5,9 +6,9 @@ import {fileURLToPath} from 'node:url';
5
6
  import {commonArgs,cleanEnvironment,specsPermissionArgs} from './codex-config.mjs';
6
7
  import {need,text,validCallTimeout,json} from './effect-contract.mjs';
7
8
 
8
- export function developerArgs({cwd,model,schemaPath,disabledSkills=[],specsRoot=null}) {
9
+ export function developerArgs({cwd,model,effort,schemaPath,disabledSkills=[],specsRoot=null}) {
9
10
  text(cwd);text(schemaPath);
10
- const args=commonArgs({cwd,model,disabledSkills}),coding=new Set(['shell_tool','unified_exec']);
11
+ const args=commonArgs({cwd,model,effort,disabledSkills}),coding=new Set(['shell_tool','unified_exec']);
11
12
  const result=[];
12
13
  for(let i=0;i<args.length;i++){
13
14
  if(specsRoot!==null&&args[i]==='--sandbox'){i++;continue;}
@@ -21,12 +22,12 @@ export function developerArgs({cwd,model,schemaPath,disabledSkills=[],specsRoot=
21
22
  '--output-schema',schemaPath,'-'];
22
23
  }
23
24
 
24
- export function codexDeveloperWorker({cwd,model,learning=true,specsRoot=null,
25
+ export function codexDeveloperWorker({cwd,model,effort,learning=true,specsRoot=null,
25
26
  schemaPath=fileURLToPath(new URL(learning?'./codex-developer-output.schema.json':'./codex-developer-basic-output.schema.json',import.meta.url)),
26
27
  disabledSkills=[],cli='codex',
27
- timeoutMs=1800000,spawnProcess=spawn,onNotice=null}) {
28
+ timeoutMs=1800000,spawnProcess=spawn,onNotice=null,onUsage=null,onUsageClaim=null}) {
28
29
  validCallTimeout(timeoutMs);
29
- const args=developerArgs({cwd,model,schemaPath,disabledSkills,specsRoot});
30
+ const args=developerArgs({cwd,model,effort,schemaPath,disabledSkills,specsRoot});
30
31
  let used=false;
31
32
  return async (request,{signal})=>{
32
33
  text(request.prompt);need(Buffer.byteLength(request.prompt)<=11*1024*1024,'limit_exceeded');
@@ -41,10 +42,12 @@ export function codexDeveloperWorker({cwd,model,learning=true,specsRoot=null,
41
42
  catch{return {status:'unavailable',code:'specs_protection_invalid'};}
42
43
  }
43
44
  used=true;
45
+ const usage=createProviderUsageCapture('codex',onUsage);
46
+ try{onUsageClaim?.();}catch{}
44
47
  return new Promise(resolve=>{
45
48
  let child;
46
49
  try{child=spawnProcess(cli,args,{cwd,env:cleanEnvironment(),stdio:['pipe','pipe','pipe'],shell:false,detached:true});}
47
- catch{resolve({status:'unavailable',code:'spawn_failed'});return;}
50
+ catch{usage.complete();resolve({status:'unavailable',code:'spawn_failed'});return;}
48
51
  let buffer='',bytes=0,thread=null,turnStarted=false,completed=false,lastMessage=null;
49
52
  let failure=null,closed=false,timer,cleanup,noticeCount=0;
50
53
  const signalGroup=signalName=>{
@@ -69,9 +72,11 @@ export function codexDeveloperWorker({cwd,model,learning=true,specsRoot=null,
69
72
  timer=setTimeout(()=>stop('timeout'),timeoutMs);
70
73
  if(signal.aborted)abort();
71
74
  const accept=line=>{
72
- if(!line.trim()||failure)return;
75
+ if(!line.trim()||failure&&failure!=='provider_failed')return;
73
76
  let event;try{event=JSON.parse(line);}catch{stop('invalid_event');return;}
74
77
  if(!event||Array.isArray(event)||typeof event.type!=='string'){stop('invalid_event');return;}
78
+ if(event.type==='turn.failed'&&thread&&turnStarted&&!completed)usage.terminal(event.usage);
79
+ if(failure==='provider_failed')return;
75
80
  if(event.type==='error'||event.type==='turn.failed'){stop('provider_failed');return;}
76
81
  if(completed){
77
82
  stop(event.type==='item.completed'&&event.item?.type==='error'?'invalid_event':'event_after_terminal');return;
@@ -92,7 +97,7 @@ export function codexDeveloperWorker({cwd,model,learning=true,specsRoot=null,
92
97
  if(turnStarted){stop('duplicate_turn');return;}turnStarted=true;return;
93
98
  }
94
99
  if(!turnStarted){stop('turn_missing');return;}
95
- if(event.type==='turn.completed'){completed=true;return;}
100
+ if(event.type==='turn.completed'){completed=true;usage.terminal(event.usage);return;}
96
101
  if(!['item.started','item.updated','item.completed'].includes(event.type)
97
102
  ||!event.item||typeof event.item.type!=='string'){stop('invalid_event');return;}
98
103
  // Tool output stays private. Failed test commands can be a legitimate red
@@ -108,7 +113,7 @@ export function codexDeveloperWorker({cwd,model,learning=true,specsRoot=null,
108
113
  child.stderr.resume();
109
114
  child.stdout.setEncoding('utf8');
110
115
  child.stdout.on('data',chunk=>{
111
- if(failure||closed)return;
116
+ if(failure&&failure!=='provider_failed'||closed)return;
112
117
  bytes+=Buffer.byteLength(chunk);if(bytes>4*1024*1024){stop('output_limit');return;}
113
118
  buffer+=chunk;let index;
114
119
  while((index=buffer.indexOf('\n'))!==-1){accept(buffer.slice(0,index));buffer=buffer.slice(index+1);}
@@ -123,6 +128,7 @@ export function codexDeveloperWorker({cwd,model,learning=true,specsRoot=null,
123
128
  closed=true;clearTimeout(timer);signal.removeEventListener('abort',abort);
124
129
  await cleanGroup();
125
130
  if(buffer.trim())accept(buffer);
131
+ usage.complete();
126
132
  if(failure||code!==0||exitSignal||!completed||lastMessage===null){
127
133
  resolve({status:failure==='spawn_failed'?'unavailable':'unknown',code:failure??'incomplete_result'});return;
128
134
  }
@@ -1,5 +1,7 @@
1
+ import {createProviderUsageCapture} from './provider-usage.mjs';
1
2
  import { spawn } from 'node:child_process';
2
3
  import { commonArgs, cleanEnvironment, configFingerprint } from './codex-config.mjs';
4
+ import {ownedProcessCleanup} from './owned-process-cleanup.mjs';
3
5
 
4
6
  // A preflight receipt is diagnostic evidence, not a human approval token.
5
7
  export function preflightMatches(receipt, options) {
@@ -26,28 +28,38 @@ function validEventShape(message) {
26
28
  return true;
27
29
  }
28
30
 
29
- export function codexWorker({ cwd, model, schemaPath, preflight,
31
+ export function codexWorker({ cwd, model, schemaPath, preflight, effort='high',
30
32
  disabledSkills = [], cli = 'codex', timeoutMs = 60000,
31
- promptTransport = 'argument', spawnProcess = spawn, onNotice = null }) {
33
+ promptTransport = 'argument', spawnProcess = spawn, onNotice = null,onUsage=null,onUsageClaim=null }) {
32
34
  if (!['argument','stdin'].includes(promptTransport)) throw new Error('invalid prompt transport');
33
35
  let used = false;
34
- return async (request, { signal, onEvent }) => {
36
+ return async (request, { signal, onEvent, onTerminal }) => {
35
37
  if (used) return { status: 'blocked', code: 'worker_dispatch_limit' };
36
- if (!preflightMatches(preflight, { cwd, model, disabledSkills, promptTransport })) return { status: 'blocked', code: 'tool_preflight_missing' };
38
+ if (!preflightMatches(preflight, { cwd, model, disabledSkills, promptTransport, effort })) return { status: 'blocked', code: 'tool_preflight_missing' };
37
39
  if (signal.aborted) return { status: 'cancelled', code: 'cancelled_before_dispatch' };
38
40
  used = true;
41
+ const usage=createProviderUsageCapture('codex',onUsage);
42
+ try{onUsageClaim?.();}catch{}
39
43
  return new Promise(resolve => {
40
- const child = spawnProcess(cli, [...commonArgs({ cwd, model, disabledSkills }), '--output-schema', schemaPath,
44
+ const child = spawnProcess(cli, [...commonArgs({ cwd, model, disabledSkills, effort }), '--output-schema', schemaPath,
41
45
  promptTransport==='stdin'?'-':request.prompt], {
42
- cwd, env: cleanEnvironment(), stdio: [promptTransport==='stdin'?'pipe':'ignore', 'pipe', 'pipe'],
46
+ cwd, env: cleanEnvironment(), stdio: [promptTransport==='stdin'?'pipe':'ignore', 'pipe', 'pipe'],shell:false,detached:process.platform!=='win32',
43
47
  });
48
+ const cleanupGroup=ownedProcessCleanup(child);
44
49
  let buffer = '', outputBytes = 0, value, completion = false, failure, settled = false;
45
- let failureTerminal = false, noticeCount = 0;
46
- let providerThread, turnStarted = false, timedOut = false, killTimer;
50
+ let failureTerminal = false, noticeCount = 0, receiptInvalid=false;
51
+ let providerThread, turnStarted = false, usageContextInvalid=false, timedOut = false, closeTimer, closing=false, terminationRequested=false;
52
+ const cleanup=()=>process.platform==='win32'&&!terminationRequested?Promise.resolve():
53
+ cleanupGroup().catch(()=>{failure='process_cleanup_unknown';});
47
54
  const stop = code => {
55
+ if(!['cancelled','timeout','provider_failed'].includes(code))receiptInvalid=true;
56
+ terminationRequested=true;
48
57
  failure ??= code;
49
- if (!child.killed) child.kill('SIGTERM');
50
- killTimer ??= setTimeout(() => child.kill('SIGKILL'), 1000);
58
+ cleanup();
59
+ if(!closing)closeTimer??=setTimeout(()=>{
60
+ if(settled)return;settled=true;clean();child.stdin?.destroy();child.stdout.destroy();child.stderr.destroy();child.unref?.();
61
+ usage.complete();resolve({status:'failed',code:'process_cleanup_unknown'});
62
+ },1500);
51
63
  };
52
64
  const onAbort = () => stop('cancelled');
53
65
  const timer = setTimeout(() => { timedOut = true; stop('timeout'); }, timeoutMs);
@@ -79,12 +91,15 @@ export function codexWorker({ cwd, model, schemaPath, preflight,
79
91
  stop('invalid_event');
80
92
  return;
81
93
  }
82
- if (message.type === 'turn.started') turnStarted = true;
94
+ if (message.type === 'turn.started') {if(!providerThread)usageContextInvalid=true;turnStarted = true;}
83
95
  const isFailureTerminal = message.type === 'turn.failed' || message.type === 'error';
96
+ // The generic error notice can precede the official turn.failed event.
97
+ // Preserve one normalized failure, while accounting only native terminals.
98
+ if(message.type==='turn.failed'&&providerThread&&turnStarted&&!completion&&!usageContextInvalid)usage.terminal(message.usage);
84
99
  if (failureTerminal && isFailureTerminal) { stop('provider_failed'); return; }
85
100
  if (isFailureTerminal) failureTerminal = true;
86
101
  if (message.type === 'thread.started') {
87
- if (providerThread && providerThread !== message.thread_id) { stop('thread_mismatch'); return; }
102
+ if (providerThread && providerThread !== message.thread_id) {usageContextInvalid=true;stop('thread_mismatch'); return; }
88
103
  providerThread = message.thread_id;
89
104
  onEvent({ event: message.type, provider_thread: providerThread });
90
105
  } else onEvent({ event: message.type ?? 'unknown', item_type: message.item?.type ?? null });
@@ -97,7 +112,7 @@ export function codexWorker({ cwd, model, schemaPath, preflight,
97
112
  if (message.type === 'item.completed' && message.item?.type === 'agent_message') {
98
113
  try { value = JSON.parse(message.item.text); } catch { stop('invalid_output_json'); }
99
114
  }
100
- if (message.type === 'turn.completed') completion = true;
115
+ if (message.type === 'turn.completed') {completion = true;if(providerThread&&turnStarted&&!failureTerminal&&!usageContextInvalid)usage.terminal(message.usage);}
101
116
  if (isFailureTerminal) stop('provider_failed');
102
117
  }
103
118
  child.stdout.on('data', chunk => {
@@ -111,18 +126,29 @@ export function codexWorker({ cwd, model, schemaPath, preflight,
111
126
  }
112
127
  });
113
128
  const clean = () => {
114
- clearTimeout(timer); clearTimeout(killTimer); signal.removeEventListener('abort', onAbort);
129
+ clearTimeout(timer); clearTimeout(closeTimer); signal.removeEventListener('abort', onAbort);
115
130
  };
116
- child.once('error', () => { settled = true; clean(); resolve({ status: 'failed', code: 'spawn_failed' }); });
117
- child.once('close', (code, exitSignal) => {
131
+ child.once('error', async () => {
132
+ if(settled)return;settled=true;closing=true;clean();await cleanup();
133
+ usage.complete();resolve({status:'failed',code:failure==='process_cleanup_unknown'?failure:'spawn_failed'});
134
+ });
135
+ child.once('close', async (code, exitSignal) => {
118
136
  if (settled) return;
119
- clean();
137
+ closing=true;clean();
120
138
  if (buffer.trim()) accept(buffer);
121
- clearTimeout(killTimer);
122
139
  settled = true;
140
+ await cleanup();
141
+ usage.complete();
123
142
  onEvent({ event: 'process_closed', exit_code: code, signal: exitSignal,
124
143
  timed_out: timedOut });
125
- if (signal.aborted) resolve({ status: 'cancelled', code: 'cancelled' });
144
+ // A local abort must not erase an already received provider terminal.
145
+ // Windows/direct-child exit and uncertain cleanup cannot issue this receipt.
146
+ if(process.platform!=='win32'&&failure!=='process_cleanup_unknown'&&!receiptInvalid&&typeof onTerminal==='function'){
147
+ if(completion&&providerThread&&value!==undefined)onTerminal({status:'succeeded',value});
148
+ else if(failureTerminal&&providerThread)onTerminal({status:'failed',code:'provider_failed'});
149
+ }
150
+ if(failure==='process_cleanup_unknown')resolve({status:'failed',code:failure});
151
+ else if (signal.aborted) resolve({ status: 'cancelled', code: 'cancelled' });
126
152
  else if (failure || code !== 0 || !completion || !providerThread || value === undefined) {
127
153
  resolve({ status: 'failed', code: failure ?? 'incomplete_result' });
128
154
  } else resolve({ status: 'succeeded', value });
@@ -4,21 +4,23 @@ import {digest,need} from '../cm-ai/effect-contract.mjs';
4
4
  import {writeReviewEvidence} from '../cm-ai/review-evidence-file.mjs';
5
5
  import {inspectCauseRegistration,inspectCauseResult} from './cause-invocation.mjs';
6
6
 
7
- export function publishCauseEvidence({specsRoot,configuration,registration,started,result,inspectOnly=false}){
7
+ export function publishCauseEvidence({specsRoot,configuration,registration,started,result,inspectOnly=false,round=1}){
8
+ need([1,2].includes(round),'cause_evidence_unavailable');
8
9
  const bound=inspectCauseRegistration(registration,configuration);
9
10
  const checked=inspectCauseResult(result,bound,configuration,started);
10
11
  need(checked.observationStatus==='completed','cause_evidence_unavailable');
11
12
  const pkg=bound.request.payload.reviewPackage;
13
+ need((round===2)===Boolean(pkg.rediagnosis),'cause_evidence_unavailable');
12
14
  const slug=/^T-FIX-([a-z0-9]+(?:-[a-z0-9]+)*)$/.exec(pkg.identity.taskId)?.[1];
13
15
  need(slug,'invalid_fix_slug');
14
16
  const bytes=Buffer.from(['---',`at: ${new Date(bound.registeredAt).toISOString()}`,
15
17
  `reviewer: ${checked.provider}-cli`,'independent: true',`task: ${pkg.identity.taskId}`,
16
- 'phase: cause','round: 1',`verdict: ${checked.review.verdict}`,`package_sha256: ${pkg.packageDigest}`,
18
+ 'phase: cause',`round: ${round}`,`verdict: ${checked.review.verdict}`,`package_sha256: ${pkg.packageDigest}`,
17
19
  `request_sha256: ${bound.request.requestDigest}`,'scope:',...pkg.files.map(file=>` - ${JSON.stringify(file.path)}`),
18
20
  '---','','Root-cause review only. This is not N4 implementation approval.',
19
21
  ...(pkg.correction?['Late observation cause review (data; not evidence of an earlier review):',JSON.stringify(pkg.correction)]:[]),
20
22
  `Registered invocation: ${bound.request.invocationId}`,`Registration digest: ${digest(bound)}`,
21
23
  `Observation digest: ${checked.observationDigest}`,`Provider thread: ${checked.providerThreadId}`,
22
24
  'Reviewer result (JSON data):',JSON.stringify(checked.review),''].join('\n'));
23
- return writeReviewEvidence({reviewsDir:path.join(specsRoot,'.reviews'),name:`fix-${slug}-cause-r1.md`,bytes,inspectOnly});
25
+ return writeReviewEvidence({reviewsDir:path.join(specsRoot,'.reviews'),name:`fix-${slug}-cause-r${round}.md`,bytes,inspectOnly});
24
26
  }
@@ -1,3 +1,4 @@
1
+ import {inspectFixReconciledResult} from './review-reconciliation.mjs';
1
2
  // Shared V3 grant and normalized observation contracts; no completion receipt issuer.
2
3
  import {validateReviewDispatchGrant} from '../cm-ai/durable-runner-state.mjs';
3
4
  import {inspectProviderCauseReview} from '../cm-ai/provider-review-observation.mjs';
@@ -20,7 +21,7 @@ export function fixHostContexts(configuration){
20
21
  export function validateCauseReviewer(raw,hostContextId,maxExclusions=32){
21
22
  const hosts=Array.isArray(hostContextId)?hostContextId:[hostContextId];
22
23
  need(hosts.length>=1&&hosts.length<=MAX_FIX_JOINED_HOSTS+2,'invalid_cause_reviewer');hosts.forEach(id);
23
- need([32,33,34].includes(maxExclusions),'invalid_cause_reviewer');
24
+ need([32,33,34,35].includes(maxExclusions),'invalid_cause_reviewer');
24
25
  const value=json(raw);shape(value,['reviewerId','adapterId','provider','requestedModel','contextId','excludedThreadIds',
25
26
  ...(Object.hasOwn(value,'workerConfigurationDigest')?['workerConfigurationDigest']:[])]);
26
27
  if(Object.hasOwn(value,'workerConfigurationDigest'))hex(value.workerConfigurationDigest);
@@ -49,9 +50,11 @@ export function inspectCauseRegistration(raw,configuration){
49
50
  return value;
50
51
  }
51
52
  export function inspectCauseResult(raw,registration,configuration,started){
52
- const value=json(raw,1024*1024);shape(value,['dispatchAt','observation']);
53
+ const value=json(raw,1024*1024);shape(value,['dispatchAt','observation',...(Object.hasOwn(value,'reconciliationReceipt')?['reconciliationReceipt']:[])]);
53
54
  need(Number.isSafeInteger(value.dispatchAt)&&value.dispatchAt>=registration.registeredAt
54
55
  &&value.dispatchAt<registration.grant.expiresAt,'cause_registration_mismatch');
55
- const result=inspectProviderCauseReview(JSON.stringify(value.observation),JSON.stringify(causeExpectation(registration.request,configuration)));
56
+ need(!value.reconciliationReceipt||(configuration.externalModels||configuration.executionPolicy),'review_reconciliation_unavailable');
57
+ const expected=causeExpectation(registration.request,configuration);
58
+ const result=value.reconciliationReceipt?inspectFixReconciledResult(value,expected,true):inspectProviderCauseReview(JSON.stringify(value.observation),JSON.stringify(expected));
56
59
  need(result.providerThreadId===started,'cause_registration_mismatch');return result;
57
60
  }
@@ -8,12 +8,16 @@ import {inspectFixTestAuthor} from './test-author.mjs';
8
8
  import {inventory} from './test-extension.mjs';
9
9
  import {inspectVisualCarrier} from './visual.mjs';
10
10
 
11
+ export const rediagnosisPackage=value=>({historyDigest:value.historyDigest,priorPackageDigest:value.priorPackageDigest,
12
+ priorObservationDigest:value.priorObservationDigest,reason:value.reason,reviewFeedback:value.reviewFeedback});
13
+
11
14
  export function createFixCausePackage({codeProject,defect,status}){
12
15
  need((status.stage==='cause_review_required'||status.stage==='observation_cause_review_correction_required'&&status.causeReviewCorrection)
13
16
  &&status.reproduction?.status==='reproduced'
14
17
  &&status.diagnosis!==null,'fix_cause_review_unavailable');
15
18
  const value=json({version:1,kind:'cm-fix-cause-review-package',identity:status.identity,defect,
16
19
  reproduction:status.reproduction,diagnosis:status.diagnosis,learning:status.learning,
20
+ ...(status.rediagnosis?{rediagnosis:rediagnosisPackage(status.rediagnosis)}:{}),
17
21
  ...(status.causeReviewCorrection?{correction:status.causeReviewCorrection}:{}),
18
22
  files:readReviewSourceFiles(codeProject,status.diagnosis.affectedPaths)},4*1024*1024);
19
23
  return json({...value,packageDigest:digest(value)},4*1024*1024);
@@ -22,7 +26,12 @@ export function createFixCausePackage({codeProject,defect,status}){
22
26
  export function readFixCausePackage(raw){
23
27
  const value=json(raw,4*1024*1024);
24
28
  shape(value,['version','kind','identity','defect','reproduction','diagnosis','learning','files','packageDigest',
25
- ...(Object.hasOwn(value,'correction')?['correction']:[])]);
29
+ ...(Object.hasOwn(value,'correction')?['correction']:[]),...(Object.hasOwn(value,'rediagnosis')?['rediagnosis']:[])]);
30
+ if(value.rediagnosis){
31
+ shape(value.rediagnosis,['historyDigest','priorPackageDigest','priorObservationDigest','reason','reviewFeedback']);
32
+ need([value.rediagnosis.historyDigest,value.rediagnosis.priorPackageDigest,value.rediagnosis.priorObservationDigest].every(v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v)), 'invalid_package');
33
+ text(value.rediagnosis.reason);need(value.rediagnosis.reviewFeedback?.verdict==='changes_requested','invalid_package');
34
+ }
26
35
  if(value.correction){
27
36
  shape(value.correction,['reason','resumeDigest','historyDigest','resumeStage',
28
37
  ...(Object.hasOwn(value.correction,'repairPackage')?['repairPackage']:[]),