@aibyzero/cm-workflow 0.16.4 → 0.16.5

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 (167) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +50 -0
  4. package/README.md +12 -1
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/runtime-failover.md +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  11. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  12. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  14. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  16. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  17. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  19. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  20. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  21. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  22. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  24. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  26. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  27. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  28. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  29. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  30. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  31. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  32. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  33. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  34. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  35. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  36. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  37. package/runtime/js/cm-ai/host-session.mjs +12 -4
  38. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  39. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  40. package/runtime/js/cm-ai/host.mjs +1 -1
  41. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  42. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  43. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  44. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  45. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  46. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  47. package/runtime/js/cm-ai/review-package.mjs +427 -31
  48. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  49. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  50. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  51. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  52. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  53. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  54. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  55. package/runtime/js/cm-fix/execution.mjs +109 -25
  56. package/runtime/js/cm-fix/host-review.mjs +7 -3
  57. package/runtime/js/cm-fix/host.mjs +3 -1
  58. package/runtime/js/cm-fix/progress.mjs +1 -0
  59. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  60. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  61. package/runtime/js/cm-prd/analysis.mjs +2 -1
  62. package/runtime/js/cm-prd/change.mjs +28 -10
  63. package/runtime/js/cm-prd/draft.mjs +5 -2
  64. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  65. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  66. package/runtime/js/cm-prd/self-check.mjs +6 -3
  67. package/runtime/js/cm-prd/summary.mjs +3 -1
  68. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  69. package/runtime/js/spec-task-line.mjs +117 -0
  70. package/runtime/js/specs-status.mjs +10 -3
  71. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  72. package/scripts/cm-ai-admission.mjs +18 -11
  73. package/scripts/cm-ai-admission.test.mjs +65 -1
  74. package/scripts/cm-ai-batch-drive.mjs +92 -20
  75. package/scripts/cm-ai-batch-drive.test.mjs +164 -3
  76. package/scripts/cm-ai-batch-host.mjs +27 -11
  77. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  78. package/scripts/cm-ai-batch-run.mjs +33 -10
  79. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  80. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  81. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  82. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  84. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  85. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  86. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  87. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  88. package/scripts/cm-ai-drive.mjs +479 -47
  89. package/scripts/cm-ai-drive.test.mjs +240 -10
  90. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  91. package/scripts/cm-ai-host.mjs +84 -25
  92. package/scripts/cm-ai-host.test.mjs +232 -12
  93. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  94. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  95. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  96. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  97. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  98. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  99. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  100. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  101. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  102. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  103. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  104. package/scripts/cm-ai-run.mjs +160 -60
  105. package/scripts/cm-ai-run.test.mjs +4 -3
  106. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  107. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  108. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  109. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  110. package/scripts/cm-ai-supersede.test.mjs +571 -17
  111. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  112. package/scripts/cm-capability-gate.test.mjs +21 -2
  113. package/scripts/cm-check-drive.test.mjs +1 -1
  114. package/scripts/cm-check-host.test.mjs +1 -1
  115. package/scripts/cm-check-runtime.sh +1 -1
  116. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  117. package/scripts/cm-claude-probe.test.mjs +9 -1
  118. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  119. package/scripts/cm-claude-worker.test.mjs +11 -4
  120. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  121. package/scripts/cm-failover.mjs +8 -8
  122. package/scripts/cm-fix-abandon.test.mjs +123 -5
  123. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  124. package/scripts/cm-fix-drive.mjs +45 -13
  125. package/scripts/cm-fix-drive.test.mjs +36 -1
  126. package/scripts/cm-fix-host.mjs +9 -6
  127. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  128. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  129. package/scripts/cm-host-check.test.mjs +6 -3
  130. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  131. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  132. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  133. package/scripts/cm-log-event.mjs +17 -0
  134. package/scripts/cm-log-event.test.mjs +31 -0
  135. package/scripts/cm-prd-completion.test.mjs +75 -0
  136. package/scripts/cm-prd-draft.test.mjs +14 -0
  137. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  138. package/scripts/cm-prd-review-gate.mjs +126 -81
  139. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  140. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  141. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  142. package/scripts/cm-prd-self-check.test.mjs +6 -0
  143. package/scripts/cm-prd-summary.test.mjs +9 -0
  144. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  145. package/scripts/cm-review-inventory.test.mjs +253 -1
  146. package/scripts/cm-spec-manifest.mjs +28 -10
  147. package/scripts/cm-spec-manifest.test.mjs +8 -4
  148. package/scripts/cm-spec-task-line.test.mjs +138 -0
  149. package/scripts/cm-specs-status.test.mjs +12 -1
  150. package/scripts/cm-task-gate.mjs +18 -10
  151. package/scripts/cm-task-gate.py +1 -1
  152. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  153. package/scripts/fixtures/claude-review-process.mjs +1 -0
  154. package/scripts/fixtures/process-cleanup.mjs +99 -0
  155. package/scripts/test-cm-log-event.py +2 -0
  156. package/scripts/test-cm-prd-review-gate.py +2 -1
  157. package/scripts/test-npm-install.py +1 -1
  158. package/scripts/test-scan-public-safety.py +1 -1
  159. package/scripts/test-spec-manifest.py +16 -8
  160. package/scripts/test-task-gate.py +2 -2
  161. package/scripts/test-workflow-config.py +1 -0
  162. package/scripts/validate-public-repo.py +1 -0
  163. package/skills/cm-ai/references/N1-init.md +1 -1
  164. package/skills/cm-ai/references/js-host.md +261 -42
  165. package/skills/cm-fix/references/js-host.md +22 -1
  166. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  167. package/skills/cm-prd/references/js-host.md +6 -0
@@ -8,7 +8,7 @@ import {implementationSha256,loadHandoff} from '../../../scripts/cm-task-gate.mj
8
8
  import {digest,json,shape,text,need} from './effect-contract.mjs';
9
9
 
10
10
  export const REVIEWED_HANDOFF_HINT='仅 QA 卡住时,配置错误用 --revise-qa-config PREVIOUS.json --qa-config-revision-reason … 恢复原运行,宿主或环境证据不足用 --rerun-blocked-qa。确需重跑任务时,用 --supersede-reviewed-evidence --supersede-reason … 新建运行。';
11
- function reviewedHandoffConflict(){
11
+ export function reviewedHandoffConflict(){
12
12
  const error=new Error('handoff_exists');error.code='handoff_exists';error.reason=REVIEWED_HANDOFF_HINT;throw error;
13
13
  }
14
14
 
@@ -24,11 +24,20 @@ function prepareHostHandoff(raw){
24
24
  const parent=path.dirname(handoffPath);
25
25
  need(fs.realpathSync(parent)===parent&&fs.lstatSync(parent).isDirectory(),'unsupported_path');
26
26
  const reviewPackage=createReviewPackage({root,baseline,checks});
27
+ const changedFiles=reviewPackage.changes.map(change=>change.path);
28
+ const {payload,bytes}=hostHandoffDocument({baseline,checks,reviewPackage,
29
+ implementationSha256:implementationSha256(root,changedFiles),evidence});
30
+ need(bytes.length<=256*1024,'limit_exceeded');
31
+ return {root,baseline,checks,handoffPath,parent,reviewPackage,changedFiles,payload,bytes};
32
+ }
33
+ // Pure: the handoff document for a package and its checks, byte for byte as it is
34
+ // published. The driver builds it for a projected package to size a delivery.
35
+ export function hostHandoffDocument({baseline,checks,reviewPackage,implementationSha256,evidence=[]}){
27
36
  const changedFiles=reviewPackage.changes.map(change=>change.path);
28
37
  const passed=checks.every(check=>check.outcome==='passed');
29
38
  const payload={schema_version:1,task_id:baseline.identity.taskId,attempt:baseline.identity.attempt,
30
39
  status:passed?'ready_for_review':'blocked',changed_files:changedFiles,
31
- implementation_sha256:implementationSha256(root,changedFiles),
40
+ implementation_sha256:implementationSha256,
32
41
  verification:checks.map(check=>({command:check.kind==='visual'
33
42
  ?`Visual inspection (not a shell command): ${check.before.kind} before/after comparison`
34
43
  :JSON.stringify(check.command),
@@ -36,9 +45,7 @@ function prepareHostHandoff(raw){
36
45
  evidence:[`host review package ${reviewPackage.packageDigest}`,...evidence],
37
46
  blockers:passed?[]:checks.filter(check=>check.outcome!=='passed').map(check=>`check ${check.id}: ${check.outcome}`),
38
47
  scope_deviation:[]};
39
- const bytes=Buffer.from(JSON.stringify(payload,null,2)+'\n');
40
- need(bytes.length<=256*1024,'limit_exceeded');
41
- return {root,baseline,checks,handoffPath,parent,reviewPackage,changedFiles,payload,bytes};
48
+ return {payload,bytes:Buffer.from(JSON.stringify(payload,null,2)+'\n')};
42
49
  }
43
50
 
44
51
  // Same serialization as publication, without creating files or registering work.
@@ -57,7 +64,7 @@ export function verifyHostHandoff(raw){
57
64
  // One left by a run that died before review is not: it must not block every retry
58
65
  // of the same task forever. The receipt names the handoff it reviewed, so the two
59
66
  // cases are distinguishable without guessing from timestamps or run identity.
60
- function reviewConsumedHandoff(parent,name,attempt){
67
+ export function reviewConsumedHandoff(parent,name,attempt){
61
68
  const suffix=`-a${attempt}-handoff.json`;
62
69
  if(!name.endsWith(suffix))return true;
63
70
  const receipt=path.join(parent,`${name.slice(0,-suffix.length)}-r${attempt}.md`);
@@ -6,7 +6,7 @@ import {spawnSync} from 'node:child_process';
6
6
  import {fileURLToPath} from 'node:url';
7
7
  import {loadConfig,resolveRole} from '../../../scripts/cm-workflow-config.mjs';
8
8
  import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
9
- import {inspectCmAiAdmission,inspectCmAiQaTaskContext} from './cm-ai-admission.mjs';
9
+ import {inspectCmAiAdmission,inspectCmAiQaTaskContext,identifyApprovedBootstrapFeature} from './cm-ai-admission.mjs';
10
10
  import {createHostCheck} from './host-check.mjs';
11
11
  import {specsPermissionArgs} from './codex-config.mjs';
12
12
  import {resolveCodeProjects,codeProjectPaths} from './code-projects.mjs';
@@ -108,7 +108,8 @@ export function createHostQaExecutor(options) {
108
108
  for(const name of ['specsDir','codeProject'])need(fs.realpathSync(configuration[name])===configuration[name],'unsupported_path');
109
109
  const roots=configuration.codeProjects?resolveCodeProjects(configuration.codeProject,configuration.codeProjects):null;
110
110
  if(configuration.bootstrap){
111
- shape(configuration.bootstrap,['requirements','scope']);need(configuration.feature==='0.bootstrap','bootstrap_task_required');
111
+ shape(configuration.bootstrap,['requirements','scope']);
112
+ need(configuration.feature===identifyApprovedBootstrapFeature(configuration.specsDir),'bootstrap_task_required');
112
113
  }
113
114
  if(Object.hasOwn(configuration,'specsRoot')){
114
115
  need(configuration.specsRoot===configuration.specsDir,'execution_specs_mismatch');
@@ -217,10 +218,10 @@ export function createHostQaExecutor(options) {
217
218
  ...(hostRequestTimeout?{hostRequestTimeout:true}:{})});
218
219
  }else{
219
220
  logStep(configuration,binding,'test_run','case_start',{case_id:item.id},'QA browser case started');
220
- let observed,hostRequestTimeout=false;
221
+ let observed,hostRequestTimeout=false,answered=false;
221
222
  if(browser===null||item.expected.some(value=>value.includes('[需确认]')))
222
223
  observed={verdict:'BLOCKED',evidence:[],environment,cleanup:'not_needed'};
223
- else try{observed=json(await browser(request,signal));}
224
+ else try{observed=json(await browser(request,signal));answered=true;}
224
225
  catch(error){
225
226
  if(error.code!=='host_request_timeout')throw error;
226
227
  hostRequestTimeout=true;
@@ -238,11 +239,18 @@ export function createHostQaExecutor(options) {
238
239
  }catch{evidenceProblem='qa_evidence_required';}
239
240
  const verdict=evidenceProblem!==null||digest(observed.environment)!==digest(environment)||observed.cleanup==='failed'
240
241
  ||(item.cleanup.length>0&&observed.cleanup!=='completed')?'BLOCKED':observed.verdict;
242
+ // The session itself answered BLOCKED (for example: simulator
243
+ // unreachable). Unlike [需确认] or a missing capability, a later
244
+ // explicit rerun on the same code can change this outcome.
241
245
  rows.push({id:item.id,kind:'browser',origin:item.origin,blocking:item.blocking,verdict,
242
246
  evidence:observed.evidence,evidenceProblem,environment:observed.environment,cleanup:observed.cleanup,
243
- ...(hostRequestTimeout?{hostRequestTimeout:true}:{})});
247
+ ...(hostRequestTimeout?{hostRequestTimeout:true}:{}),
248
+ ...(answered&&observed.verdict==='BLOCKED'?{hostDeclaredBlocked:true}:{})});
249
+ // The durable log row, appended now through the writer, is the record
250
+ // that the session itself answered BLOCKED; the report only mirrors it.
244
251
  logStep(configuration,binding,'test_run',verdict==='BLOCKED'?'case_blocked':'case_complete',
245
- {case_id:item.id,result:verdict},'QA browser case finished');
252
+ {case_id:item.id,result:verdict,...(answered&&observed.verdict==='BLOCKED'?{host_declared_blocked:true}:{})},
253
+ 'QA browser case finished');
246
254
  }
247
255
  }
248
256
  }
@@ -257,8 +265,14 @@ export function createHostQaExecutor(options) {
257
265
  observed.length>0&&observed.every(item=>item?.outcome==='passed')?'PASS':'BLOCKED';
258
266
  row.commandEvidence=mappings.map(item=>item.id);
259
267
  const item=plan.cases.find(item=>item.id===row.id);
260
- if(item.expected.some(value=>value.includes('[需确认]')))row.verdict='BLOCKED';
268
+ // Record why a logic case is BLOCKED: an unresolved [需确认] expectation
269
+ // stays BLOCKED on every round, while a mapped command that produced no
270
+ // exit code is an environment outcome that an explicit rerun can change.
271
+ const needsConfirmation=item.expected.some(value=>value.includes('[需确认]'));
272
+ if(needsConfirmation){row.verdict='BLOCKED';row.needsConfirmation=true;}
261
273
  if(row.hostRequestTimeout)row.verdict='BLOCKED';
274
+ if(row.verdict==='BLOCKED'&&row.staticVerdict==='SUPPORTED'&&!needsConfirmation
275
+ &&observed.some(result=>result?.outcome==='unavailable'))row.commandUnavailable=true;
262
276
  }
263
277
  if(rows.length===0)rows.push({id:'qa-unavailable',kind:'commands',verdict:'BLOCKED',evidence:['No executable QA contract']});
264
278
  const drift=digest(before.files)!==digest(snapshot().files);
@@ -43,7 +43,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
43
43
  busy=true;try{return await current.host.handle(request);}finally{busy=false;}
44
44
  }
45
45
  const value=json(request);shape(value,['version','requestId','operation','identity','packageDigest','testRunId',
46
- ...(request.operation==='fix_action'?['fixOperation',...(request.fixOperation==='abandon_step'&&Object.hasOwn(request,'reason')?['reason']:[])]:[])]);
46
+ ...(request.operation==='fix_action'?['fixOperation',...(['abandon_step','abandon_review'].includes(request.fixOperation)&&Object.hasOwn(request,'reason')?['reason']:[])]:[])]);
47
47
  need(value.version===1,'invalid_input');id(value.requestId);validIdentity(value.identity);hex(value.packageDigest);id(value.testRunId);
48
48
  if(fixedTemplate)definition=bindQaFixDefinition({template:fixedTemplate,identity:value.identity,
49
49
  packageDigest:value.packageDigest,testRunId:value.testRunId});
@@ -55,7 +55,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
55
55
  const acting=value.operation==='fix_action';
56
56
  if(acting)need(['red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback',
57
57
  'handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression',
58
- 'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review','abandon_step'].includes(value.fixOperation),'fix_operation_unavailable');
58
+ 'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review','abandon_step','abandon_review'].includes(value.fixOperation),'fix_operation_unavailable');
59
59
  need(!(advancing||acting)||allowStart,'qa_fix_start_authorization_required');
60
60
  busy=true;let child=null,released=false,result;
61
61
  try{
@@ -75,7 +75,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
75
75
  runtime:definition.configuration.runtime??'codex',permissions:[...permissions,'--allow-reproduction'],...fixAuthorities});
76
76
  actionResult=running?await host.run(value.requestId)
77
77
  :await host.handle({requestId:value.requestId,operation:advancing?'advance':value.fixOperation,
78
- ...(value.fixOperation==='abandon_step'?{reason:value.reason}:{})});
78
+ ...(['abandon_step','abandon_review'].includes(value.fixOperation)?{reason:value.reason}:{})});
79
79
  }
80
80
  // Original observation/escalation finish intentionally closes its owner. Preserve
81
81
  // that successful incomplete exit without reading a closed store.
@@ -95,7 +95,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
95
95
  // completion evidence uses the existing parent journal contract.
96
96
  if(result.code==='qa_fix_completed'&&typeof current.inspectFixAssociation==='function'){
97
97
  try{
98
- const association=current.inspectFixAssociation(result.evidence.reviewPackage);
98
+ const association=current.inspectFixAssociation(result.evidence.reviewPackage,result.evidence);
99
99
  const accepted=(running||(acting&&value.fixOperation==='finish'))&&typeof current.acceptCompletedFix==='function'
100
100
  ?current.acceptCompletedFix(result.evidence):null;
101
101
  return json({...result,association,...(accepted?{accepted}: {})},12*1024*1024);
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {inspectCmAiQaTaskContext} from './cm-ai-admission.mjs';
5
5
  import {scanRows,readDecision} from './cm-ai-qa-log.mjs';
6
- import {digest,freeze,hex,json,need,shape,validIdentity} from './effect-contract.mjs';
6
+ import {digest,freeze,hex,id,json,need,shape,validIdentity} from './effect-contract.mjs';
7
7
 
8
8
  const key=(feature,task)=>`${feature}/${task}`;
9
9
 
@@ -53,23 +53,32 @@ export function decideHostQaPolicy({assessment,pending,mergeEligible,unassessedT
53
53
  export function createHostQaDecisionProvider({assess,timeoutMs}) {
54
54
  need(typeof assess==='function'&&Number.isSafeInteger(timeoutMs)&&timeoutMs>0&&timeoutMs<=60000,'qa_assessment_invalid');
55
55
  return Object.freeze({timeoutMs,async decide(raw,signal){
56
- const binding=json(raw);shape(binding,['specsDir','codeProject','feature','identity','packageDigest']);
56
+ const input=json(raw);
57
+ shape(input,['specsDir','codeProject','feature','identity','packageDigest',...(Object.hasOwn(input,'previousDecisionId')?['previousDecisionId']:[])]);
58
+ // previousDecisionId names an older recorded decision that an explicit
59
+ // recovery supersedes; it only derives a distinct id, never the assessment.
60
+ const {previousDecisionId=null,...binding}=input;if(previousDecisionId!==null)id(previousDecisionId);
57
61
  validIdentity(binding.identity);hex(binding.packageDigest);
58
62
  const context=inspectCmAiQaTaskContext({...binding,taskId:binding.identity.taskId});
59
63
  const unassessedTasks=history(binding,context);
60
64
  need(!signal.aborted,'cancelled');
61
- let assessment,timedOut=false;
65
+ let assessment;
62
66
  try{assessment=await assess(freeze({...binding,pending:context.pending,mergeEligible:context.mergeEligible,
63
67
  unassessedTasks}),signal);}
64
- catch(error){if(error.code!=='host_request_timeout')throw error;timedOut=true;}
68
+ catch(error){
69
+ // A missed answer window is a transport outcome, not a QA decision. It is
70
+ // reported like the outer decision timer: retryable, and nothing durable.
71
+ if(error?.code==='host_request_timeout')throw Object.assign(new Error('QA assessment timed out'),{code:'qa_decision_timeout'});
72
+ throw error;
73
+ }
65
74
  need(!signal.aborted,'cancelled');
66
75
  // Assessment is read-only. A task/log change while it was pending requires
67
76
  // another decision; do not bind an answer to different policy inputs.
68
77
  const current=inspectCmAiQaTaskContext({...binding,taskId:binding.identity.taskId});
69
78
  need(digest(current)===digest(context)&&history(binding,current)===unassessedTasks,'stale_qa');
70
- const result=timedOut?{status:'blocked',score:null,reason:'host_request_timeout'}:
71
- decideHostQaPolicy({assessment,pending:context.pending,mergeEligible:context.mergeEligible,unassessedTasks});
72
- return freeze({...result,decisionId:`qa-${digest({identity:binding.identity,packageDigest:binding.packageDigest}).slice(0,48)}`,
79
+ const result=decideHostQaPolicy({assessment,pending:context.pending,mergeEligible:context.mergeEligible,unassessedTasks});
80
+ const bound={identity:binding.identity,packageDigest:binding.packageDigest,...(previousDecisionId===null?{}:{previousDecisionId})};
81
+ return freeze({...result,decisionId:`qa-${digest(bound).slice(0,48)}`,
73
82
  identity:binding.identity,packageDigest:binding.packageDigest,at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')});
74
83
  }});
75
84
  }
@@ -1,7 +1,11 @@
1
1
  // JSONL transport only. The existing host/runner owns decisions and durable state.
2
2
  import {executionDiagnostic,need} from './effect-contract.mjs';
3
+ import {diagnosticReason} from './diagnostic-reason.mjs';
3
4
 
4
5
  const LIMIT=64*1024;
6
+ // One wording for every host that stops on an over-limit line.
7
+ export const inputLimitReason=limit=>`an input line exceeded --input-limit ${Number.isSafeInteger(limit)?limit:LIMIT} bytes `
8
+ +`(default ${LIMIT}, maximum ${4*1024*1024}); restart the same run with --mode resume and a larger --input-limit`;
5
9
  export function parseHostInputLimit(raw){
6
10
  if(raw===undefined)return LIMIT;
7
11
  const value=Number(raw);
@@ -9,7 +13,7 @@ export function parseHostInputLimit(raw){
9
13
  &&value>=LIMIT&&value<=4*1024*1024,'invalid_arguments');
10
14
  return value;
11
15
  }
12
- const operationNames=new Set(['replace_inputs','read_batch','recover_final_review','abandon_step','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
16
+ const operationNames=new Set(['replace_inputs','read_batch','recover_final_review','abandon_step','abandon_review','abandon_effect','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
13
17
  'context_refresh','finish','completion_evidence','run_finalize','review_findings','review_disposition','save_draft','save_design','correct_findings','prepare_summary','publish_summary','inspect_correction','resume_correction','cancel','resume','prepare_judge_revision','cause_review_package','cause_review','red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression','publish_dossier','walkthrough']);
14
18
 
15
19
  // Which contract codes may reach the peer is a deliberate boundary: the host
@@ -22,11 +26,15 @@ const operationNames=new Set(['replace_inputs','read_batch','recover_final_revie
22
26
  function reportRequestFailure(errorOutput,operation,error){
23
27
  try{
24
28
  const detail=executionDiagnostic(error);
29
+ const reason=diagnosticReason(error);
25
30
  errorOutput.write(JSON.stringify({diagnostic:'host_request_failed',operation,
26
- ...(detail??{detail:'unavailable'})})+'\n');
31
+ ...(detail??{detail:'unavailable'}),...(reason?{reason}:{})})+'\n');
27
32
  }catch{/* diagnostics never change the reply */}
28
33
  }
29
34
 
35
+ // A line above the transport limit ends the session. Carry a code and the
36
+ // limit so every host can name it instead of a generic launch failure.
37
+ const tooLarge=limit=>Object.assign(new Error('request_too_large'),{code:'request_too_large',limit});
30
38
  export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimit=LIMIT,errorOutput=process.stderr}){
31
39
  if(!Number.isSafeInteger(inputLimit)||inputLimit<LIMIT||inputLimit>4*1024*1024)throw Error('input_limit_invalid');
32
40
  let pending=null,buffer=Buffer.alloc(0),failure=null,closeRequested=false;
@@ -93,13 +101,13 @@ export async function serveCmAiHost({host,input,output,toolBridge=null,inputLimi
93
101
  let start=0;
94
102
  for(let end=0;end<bytes.length;end++){
95
103
  if(bytes[end]!==10)continue;
96
- if(buffer.length+end-start>inputLimit)throw Error('request_too_large');
104
+ if(buffer.length+end-start>inputLimit)throw tooLarge(inputLimit);
97
105
  const line=Buffer.concat([buffer,bytes.subarray(start,end)]);
98
106
  buffer=Buffer.alloc(0);start=end+1;
99
107
  if(line.length)await dispatch(line);
100
108
  if(closeRequested)break reading;
101
109
  }
102
- if(buffer.length+bytes.length-start>inputLimit)throw Error('request_too_large');
110
+ if(buffer.length+bytes.length-start>inputLimit)throw tooLarge(inputLimit);
103
111
  buffer=Buffer.concat([buffer,bytes.subarray(start)]);
104
112
  }
105
113
  if(buffer.length&&!closeRequested)await dispatch(buffer);
@@ -47,7 +47,7 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
47
47
  reply=json(raw,responseLimit);shape(reply,['type','sessionId','callId','requestDigest','result']);
48
48
  need(reply.type==='host_result'&&pending!==null&&!closed,'host_response_mismatch');
49
49
  for(const key of ['sessionId','callId','requestDigest'])need(reply[key]===pending.request[key],'host_response_mismatch');
50
- }catch{return {accepted:false,code:'host_response_mismatch'};}
50
+ }catch(error){return {accepted:false,code:error?.code==='limit_exceeded'?'host_response_too_large':'host_response_mismatch'};}
51
51
  const call=pending;pending=null;clearTimeout(call.timer);call.signal.removeEventListener('abort',call.abort);
52
52
  call.resolve(reply.result);return {accepted:true,callId:reply.callId};
53
53
  },
@@ -6,6 +6,7 @@ import {createHostQaDecisionProvider} from './host-qa-policy.mjs';
6
6
  import {createHostQaExecutor} from './host-qa-executor.mjs';
7
7
  import {loadConfig} from '../../../scripts/cm-workflow-config.mjs';
8
8
  import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
9
+ import {QA_ENVIRONMENT_CARRIERS} from './qa-environment.mjs';
9
10
 
10
11
  // Browser capability is a property of the launching session, not of the project.
11
12
  // The host cannot probe whether this session can drive a browser; it can only
@@ -26,10 +27,18 @@ export function featureHasBrowserCases(specsDir,feature,codeProject){
26
27
  }
27
28
 
28
29
  export function readBrowserCapability(value,applicable){
29
- if(!applicable){need(value===undefined,'invalid_arguments');return null;}
30
- need(value!==undefined,'browser_capability_required');
31
- need(['available','unavailable'].includes(value),'invalid_arguments');
32
- need(value==='available','browser_capability_unavailable');
30
+ const carriers=Array.isArray(applicable)?[...new Set(applicable)].sort():applicable?['browser']:[];
31
+ const invalid=reason=>{throw Object.assign(new Error('invalid_arguments'),{code:'invalid_arguments',reason});};
32
+ if(!carriers.every(carrier=>Object.values(QA_ENVIRONMENT_CARRIERS).some(values=>values.includes(carrier))))
33
+ invalid(`QA environment carrier is not supported: ${carriers.join(', ')}`);
34
+ if(carriers.length===0){
35
+ if(value!==undefined)invalid('--browser-qa 只在启用 QA(--workflow-config 的 qa 不为 null)且本 feature 有 blocking 或策略启用的交互式用例时使用;本次没有适用的交互式 QA,去掉 --browser-qa');
36
+ return null;
37
+ }
38
+ const reason=`--browser-qa available|unavailable declares whether this session can run interactive QA for carrier(s): ${carriers.join(', ')}.`;
39
+ if(value===undefined)throw Object.assign(new Error('browser_capability_required'),{code:'browser_capability_required',reason});
40
+ if(!['available','unavailable'].includes(value))invalid('--browser-qa 只接受 available 或 unavailable');
41
+ if(value!=='available')throw Object.assign(new Error('browser_capability_unavailable'),{code:'browser_capability_unavailable',reason});
33
42
  return 'available';
34
43
  }
35
44
 
@@ -16,5 +16,5 @@ export function createCmAiHost(options) {
16
16
  ...(qaExecutor===undefined?{}:{qaExecutor}),
17
17
  ...(documentationProvider===undefined?{}:{documentationProvider}),
18
18
  ...(qaDecisionProvider===undefined?{}:{qaDecisionProvider})});
19
- return Object.freeze({handle:entry.handle,inspectFixAssociation:runner.inspectFixAssociation,acceptCompletedFix:runner.acceptCompletedFix,attachQa:runner.attachQa,reviseQa:runner.reviseQa,supersedeEvidence:runner.supersedeEvidence});
19
+ return Object.freeze({handle:entry.handle,inspectFixAssociation:runner.inspectFixAssociation,acceptCompletedFix:runner.acceptCompletedFix,attachQa:runner.attachQa,reviseQa:runner.reviseQa,supersedeEvidence:runner.supersedeEvidence,rebindSpecification:runner.rebindSpecification});
20
20
  }
@@ -0,0 +1,42 @@
1
+ // Diagnostic only. A resume whose launch inputs differ from creation is still
2
+ // refused with fingerprint_mismatch; this names the differing input so the
3
+ // operator can find the exit. The comparison reads the journal's own init
4
+ // record (the runner configuration it bound) and never widens what opens.
5
+ import {digest} from './effect-contract.mjs';
6
+
7
+ const UNLISTED='其余启动配置与创建时不同:--workflow-config、--protected-conversation-config、--bootstrap-config、'
8
+ +'QA/文档设置或创建时的任务选择(journal 只保存它们的指纹)。请用创建时的同一组文件与参数恢复。';
9
+
10
+ export function explainFingerprintMismatch({snapshot,definition,execution,fingerprints}){
11
+ try{
12
+ if(snapshot.fingerprints.workflow!==fingerprints.workflow)
13
+ return execution===null?'该运行由 cm-ai-host.mjs 创建,不能用无执行适配的 cm-ai-run.mjs 恢复'
14
+ :'该运行由无执行适配的控制入口 cm-ai-run.mjs 创建,不能用 cm-ai-host.mjs 恢复';
15
+ if(snapshot.fingerprints.inputs!==fingerprints.inputs)return `运行定义的 feature/task 与创建时不同(本次 ${definition.feature}/${definition.identity.taskId})`;
16
+ const bound=snapshot.records[0]?.payload?.config;
17
+ if(!bound)return UNLISTED;
18
+ const found=[];
19
+ const changed=[['scope','scope'],['requirements','requirements'],['identity','identity'],['root','codeProject']]
20
+ .filter(([key,field])=>digest(bound[key])!==digest(key==='root'?definition.codeProject:definition[field]))
21
+ .map(([,field])=>field);
22
+ if(changed.length)found.push(`运行定义字段 ${changed.join('、')} 与创建时不同`);
23
+ if(execution!==null){
24
+ const developer=execution.developer??{},reviewer=execution.reviewers?.[0]??{},was=bound.reviewers?.[0]??{};
25
+ if(bound.developer?.provider!==developer.provider)
26
+ found.push(`--runtime:创建时为 ${bound.developer?.provider},本次为 ${developer.provider}(驱动 PLAN 未写 runtime 时默认 codex)`);
27
+ else if(bound.developer?.requestedModel!==developer.requestedModel)
28
+ found.push(`开发模式不同:创建时开发者为 ${bound.developer?.requestedModel},本次为 ${developer.requestedModel}(--protected-config 是否使用须与创建时一致)`);
29
+ if(was.requestedModel==='unconfigured'&&reviewer.requestedModel!=='unconfigured')
30
+ found.push('--review-config:创建时没有审查配置,运行已绑定为“未配置审查”,resume 不能补加;'
31
+ +'本运行只能 status/cancel。要审查这次开发:cancel 后以带 --review-config 的新运行重做(--supersede-reviewed-evidence)');
32
+ else if(was.requestedModel!=='unconfigured'&&reviewer.requestedModel==='unconfigured')
33
+ found.push(`--review-config:创建时用了审查模型 ${was.requestedModel},本次没有提供;请带上创建时的 review.json`);
34
+ else if(was.requestedModel!==reviewer.requestedModel||was.provider!==reviewer.provider)
35
+ found.push(`审查配置:创建时为 ${was.provider}/${was.requestedModel},本次为 ${reviewer.provider}/${reviewer.requestedModel}`);
36
+ const host=bound.excludedContexts?.[0],current=execution.excludedContexts?.[0];
37
+ if(host!==current)found.push(`--host-context:创建会话为 ${host},本次按 ${current} 恢复;换会话恢复请加 --original-host-context ${host}`);
38
+ if(bound.timeoutMs!==execution.timeoutMs&&!found.length)found.push('开发模式或受保护配置与创建时不同');
39
+ }
40
+ return found.length?found.join(';'):UNLISTED;
41
+ }catch{return UNLISTED;}
42
+ }
@@ -0,0 +1,21 @@
1
+ // Bounded, no-follow reader for the specs-local JSONL log. Leaf module: it has
2
+ // no workflow imports, so read-only inspectors (admission included) can share it.
3
+ import fs from 'node:fs';
4
+ import {json,need} from './effect-contract.mjs';
5
+
6
+ const MiB=1024*1024;
7
+ export function scanRows(log,visit) {
8
+ let descriptor;
9
+ try {
10
+ const stat=fs.lstatSync(log);need(stat.isFile()&&!stat.isSymbolicLink(),'qa_log_failed');
11
+ descriptor=fs.openSync(log,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
12
+ const chunk=Buffer.alloc(64*1024);let pending=Buffer.alloc(0);
13
+ const consume=line=>{if(line.length){need(line.length<=MiB,'qa_log_failed');
14
+ visit(json(JSON.parse(new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(line)),MiB));}};
15
+ while(true){const size=fs.readSync(descriptor,chunk,0,chunk.length,null);if(size===0)break;
16
+ pending=Buffer.concat([pending,chunk.subarray(0,size)]);let newline;
17
+ while((newline=pending.indexOf(10))!==-1){consume(pending.subarray(0,newline));pending=pending.subarray(newline+1);}
18
+ need(pending.length<=MiB,'qa_log_failed');}
19
+ consume(pending);
20
+ } finally {if(descriptor!==undefined)fs.closeSync(descriptor);}
21
+ }
@@ -0,0 +1,84 @@
1
+ // Project-level view of every approved feature's latest N6 QA, read from the
2
+ // authoritative specs log. Read-only: it names what has not passed; it never
3
+ // reruns, repairs, supersedes or reinterprets a QA result.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import {scanRows} from './log-rows.mjs';
7
+
8
+ const LABELS={qa_failed:'最新一轮 FAIL',qa_blocked:'最新一轮 BLOCKED',qa_decision_blocked:'QA 决策阻塞',
9
+ qa_not_run:'已触发但未执行',qa_execution_unknown:'执行结果未知',qa_pending:'旧结果已作废,待下一轮',
10
+ qa_missing:'任务已全部完成,但没有 QA 记录',qa_skipped:'任务已全部完成,但最新 QA 决策为跳过'};
11
+ const cache=new Map();
12
+
13
+ // One pass: the latest decision per feature, and the test_run rows bound to it.
14
+ function readFeatureQa(specsDir){
15
+ const log=path.join(path.resolve(specsDir),'运行日志.jsonl');
16
+ let stat;
17
+ try{stat=fs.lstatSync(log);}catch(error){if(error.code==='ENOENT')return new Map();throw error;}
18
+ const key=[log,stat.dev,stat.ino,stat.size,stat.mtimeMs,stat.ctimeMs].join(':');
19
+ if(cache.has(key))return cache.get(key);
20
+ const decisions=new Map(),runs=[];
21
+ scanRows(log,row=>{
22
+ if(row?.schema_version!==1||row.workflow!=='cm-ai'||row.node!=='N6'||typeof row.feature!=='string')return;
23
+ if(row.event==='qa')decisions.set(row.feature,row);
24
+ else if(row.event==='test_run')runs.push(row);
25
+ });
26
+ const result=new Map([...decisions].map(([feature,decision])=>[feature,{decision,
27
+ runs:runs.filter(row=>row.feature===feature&&row.run_id===decision.run_id&&row.repository_id===decision.repository_id
28
+ &&row.task===decision.task&&row.package_digest===decision.package_digest&&row.qa_decision_id===decision.decision_id)}]));
29
+ cache.clear();cache.set(key,result);
30
+ return result;
31
+ }
32
+
33
+ // Row-level reading for warnings. The strict owner validator replaces it via
34
+ // `inspect` wherever a result gates run_done.
35
+ function latestRound(runs){
36
+ const start=runs.filter(row=>row.phase==='start').at(-1);
37
+ if(!start)return 'qa_not_run';
38
+ const rows=runs.filter(row=>row.operation_id===start.operation_id);
39
+ if(rows.some(row=>['superseded','abandoned'].includes(row.phase)))return 'qa_pending';
40
+ const complete=rows.find(row=>row.phase==='complete');
41
+ if(!complete)return 'qa_execution_unknown';
42
+ const result=String(complete.result).toUpperCase();
43
+ return ['PASS','PASSED'].includes(result)?null:['FAIL','FAILED'].includes(result)?'qa_failed':'qa_blocked';
44
+ }
45
+
46
+ // features: admission summaries {name,pending}. The latest QA decision of each
47
+ // feature (from any run but the caller's own) must not have failed. A skip is
48
+ // fine while tasks remain; a terminal feature (pending 0) must end in its
49
+ // feature-completion QA with a completed PASS. N6 cannot be switched off in the
50
+ // JS flow, so a terminal feature with no QA rows, or whose latest decision is a
51
+ // skip, was finished outside it and is reported rather than trusted.
52
+ export function outstandingFeatureQa({specsDir,features,currentRunId=null,inspect=null}){
53
+ const outstanding=[],qa=readFeatureQa(specsDir);
54
+ for(const {name:feature,pending} of features){
55
+ const terminal=pending===0,entry=qa.get(feature);
56
+ if(!entry){
57
+ if(terminal)outstanding.push({feature,runId:null,taskId:null,attempt:null,status:'qa_missing'});
58
+ continue;
59
+ }
60
+ const {decision,runs}=entry;
61
+ if(decision.run_id===currentRunId)continue;
62
+ let status;
63
+ if(decision.status==='skipped')status=terminal?'qa_skipped':null;
64
+ else if(decision.status!=='triggered')status='qa_decision_blocked';
65
+ else if(inspect===null)status=latestRound(runs);
66
+ else{
67
+ try{
68
+ const latest=inspect({specsDir,feature,packageDigest:decision.package_digest,identity:{repositoryId:decision.repository_id,
69
+ runId:decision.run_id,taskId:decision.task,attempt:decision.attempt}});
70
+ status=latest===null?'qa_not_run':latest.status==='passed'?null:latest.status==='failed'?'qa_failed':'qa_blocked';
71
+ }catch(error){
72
+ status=error?.code==='qa_result_incomplete'?'qa_execution_unknown':error?.code==='qa_result_superseded'?'qa_pending'
73
+ :typeof error?.code==='string'&&/^[a-z][a-z0-9_]{0,63}$/.test(error.code)?error.code:'qa_result_invalid';
74
+ }
75
+ }
76
+ if(status!==null)outstanding.push({feature,runId:decision.run_id,taskId:decision.task,attempt:decision.attempt,status});
77
+ }
78
+ return outstanding;
79
+ }
80
+
81
+ export function describeOutstandingQa(item){
82
+ const label=LABELS[item.status]??item.status;
83
+ return item.runId===null?`${item.feature}(${label})`:`${item.feature}(${item.taskId} / run ${item.runId}:${label})`;
84
+ }
@@ -18,9 +18,10 @@ function expectation(v,cause=false) {
18
18
  need(r.version===1&&r.role==='reviewer'&&['codex','claude'].includes(r.provider));
19
19
  id(r.invocationId);id(r.contextId);validIdentity(r.identity);text(r.requestedModel);hex(r.requestDigest);
20
20
  const {requestDigest,...body}=r;need(digest(body)===requestDigest,'observation_binding');
21
- shape(r.payload,['reviewPackage','priorReview']);
21
+ const carried=Object.hasOwn(r.payload,'supersededReview');
22
+ shape(r.payload,['reviewPackage','priorReview',...(carried?['supersededReview']:[])]);
22
23
  const pkg=(cause?readFixCausePackage:readReviewPackage)(r.payload.reviewPackage);
23
- if(cause)need(r.payload.priorReview===null,'observation_binding');
24
+ if(cause)need(r.payload.priorReview===null&&!carried,'observation_binding');
24
25
  need(digest(pkg.identity)===digest(r.identity),'observation_binding');
25
26
  return {request:r,pkg,excluded:new Set([v.developerThreadId,...v.excludedThreadIds])};
26
27
  }
@@ -60,15 +61,19 @@ export function inspectProviderCauseReview(observationText,expectationText){
60
61
  need(arguments.length===2);
61
62
  return inspect(observationText,expectationText,true);
62
63
  }
64
+ function readObservation(observationText,expectationText,cause) {
65
+ const observation=decode(observationText,1024*1024),expected=expectation(decode(expectationText,10*1024*1024),cause);
66
+ shape(observation,['version','kind','requestDigest','events','result']);
67
+ need(observation.version===1&&observation.kind==='cm-provider-review-observation');
68
+ hex(observation.requestDigest);need(observation.requestDigest===expected.request.requestDigest,'observation_binding');
69
+ const stream=eventStream(observation.events,expected.excluded),r=observation.result;
70
+ if(r?.status==='succeeded')shape(r,['status','value']);
71
+ else {shape(r,['status','code']);need(['failed','cancelled'].includes(r.status));text(r.code);need(r.code.length<=256);}
72
+ return {observation,expected,...stream,r};
73
+ }
63
74
  function inspect(observationText,expectationText,cause) {
64
75
  try {
65
- const observation=decode(observationText,1024*1024),expected=expectation(decode(expectationText,10*1024*1024),cause);
66
- shape(observation,['version','kind','requestDigest','events','result']);
67
- need(observation.version===1&&observation.kind==='cm-provider-review-observation');
68
- hex(observation.requestDigest);need(observation.requestDigest===expected.request.requestDigest,'observation_binding');
69
- const {thread,terminal,close}=eventStream(observation.events,expected.excluded),r=observation.result;
70
- if(r?.status==='succeeded')shape(r,['status','value']);
71
- else {shape(r,['status','code']);need(['failed','cancelled'].includes(r.status));text(r.code);need(r.code.length<=256);}
76
+ const {observation,expected,thread,terminal,close,r}=readObservation(observationText,expectationText,cause);
72
77
  let observationStatus='unknown',code='transport_incomplete',review=null;
73
78
  if(close?.timed_out===true||r.code==='timeout')code='transport_timeout';
74
79
  else if(r.status==='cancelled'||r.code==='cancelled'){observationStatus='cancelled';code='transport_cancelled';}
@@ -88,3 +93,42 @@ function inspect(observationText,expectationText,cause) {
88
93
  throw Object.assign(new Error(code),{code});
89
94
  }
90
95
  }
96
+
97
+ // A reviewer that ended without a usable verdict and broke no boundary may be
98
+ // dispatched once more; the class tells the user whether to log in or wait.
99
+ // Only these fixed worker codes qualify, and only with no final message and an
100
+ // observed process exit. Tool/context breaks, output limits, spawn or prompt
101
+ // failures and any other code stay unknown, as before.
102
+ export const REVIEWER_PROVIDER_FAILURES=Object.freeze({
103
+ reviewer_auth_failed:'reviewer_auth_failed',reviewer_billing_error:'reviewer_billing_error',
104
+ reviewer_rate_limited:'reviewer_rate_limited',reviewer_server_error:'reviewer_server_error',
105
+ reviewer_model_not_found:'reviewer_model_not_found',reviewer_api_error:'reviewer_api_error',
106
+ provider_failed:'reviewer_provider_failed',incomplete_result:'reviewer_exited',
107
+ missing_init:'reviewer_stream_unrecognized',unexpected_event:'reviewer_stream_unrecognized',
108
+ invalid_event:'reviewer_stream_unrecognized'});
109
+ // A complete answer that breaks the written verdict contract can never become a
110
+ // receipt. It is retried under the same budget and its exact code is kept.
111
+ export const REVIEWER_VERDICT_FAILURES=Object.freeze(['contradictory_verdict','invalid_finding_path',
112
+ 'invalid_finding_severity','invalid_finding_id','invalid_finding_shape','missing_material','review_package_mismatch']);
113
+ // Pure and deterministic: live classification and journal replay call it with
114
+ // the same bytes. Returns null for everything that is not such a failure.
115
+ export function inspectProviderReviewFailure(observationText,expectationText){
116
+ need(arguments.length===2);
117
+ let read;
118
+ try{read=readObservation(observationText,expectationText,false);}catch{return null;}
119
+ const {observation,expected,thread,terminal,close,hasResult,r}=read;
120
+ if(close===null||close.timed_out||r.status==='cancelled'||['timeout','cancelled'].includes(r.code))return null;
121
+ let category,failure;
122
+ if(!hasResult){
123
+ if(r.status!=='failed'||!Object.hasOwn(REVIEWER_PROVIDER_FAILURES,r.code))return null;
124
+ category='provider';failure=REVIEWER_PROVIDER_FAILURES[r.code];
125
+ }else{
126
+ if(!(close.exit_code===0&&close.signal===null&&terminal==='turn.completed'&&r.status==='succeeded'))return null;
127
+ try{reviewResult(r.value,expected.pkg);return null;}
128
+ catch(error){if(!REVIEWER_VERDICT_FAILURES.includes(error?.code))return null;category='verdict';failure=error.code;}
129
+ }
130
+ return json({version:1,kind:'cm-provider-review-failure',requestDigest:expected.request.requestDigest,
131
+ observationDigest:digest(observation),identity:expected.request.identity,logicalContextId:expected.request.contextId,
132
+ provider:expected.request.provider,requestedModel:expected.request.requestedModel,providerThreadId:thread,
133
+ category,failure,completionEligible:false});
134
+ }