@aibyzero/cm-workflow 0.16.7 → 0.16.9

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 (182) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +39 -3
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/compat/claude-commands/cm-notify.md +3 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +61 -4
  10. package/docs/next-steps.md +8 -2
  11. package/docs/user-guide.md +204 -0
  12. package/package.json +2 -1
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
  17. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  18. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  19. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  20. package/runtime/js/cm-ai/drive-core.mjs +26 -4
  21. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  22. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  23. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  24. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  25. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  26. package/runtime/js/cm-ai/host-check.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  28. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  29. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  30. package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
  31. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  32. package/runtime/js/cm-ai/host-session.mjs +47 -7
  33. package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
  34. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  35. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  36. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  37. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  38. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  39. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  40. package/runtime/js/cm-ai/review-package.mjs +10 -1
  41. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  42. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  43. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  44. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  45. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  46. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  47. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  48. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  49. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  50. package/runtime/js/cm-fix/execution.mjs +356 -187
  51. package/runtime/js/cm-fix/host.mjs +2 -1
  52. package/runtime/js/cm-fix/investigation.mjs +25 -9
  53. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  54. package/runtime/js/cm-fix/progress.mjs +15 -3
  55. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  56. package/runtime/js/cm-fix/repair.mjs +11 -3
  57. package/runtime/js/cm-fix/test-author.mjs +10 -3
  58. package/runtime/js/cm-idea/session.mjs +67 -4
  59. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  60. package/runtime/js/cm-prd/session.mjs +43 -0
  61. package/runtime/js/cm-refactor/records.mjs +98 -8
  62. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  63. package/runtime/js/cm-test/host.mjs +10 -3
  64. package/runtime/js/cm-test/session.mjs +45 -6
  65. package/runtime/js/notify-run.mjs +26 -0
  66. package/runtime/js/notify-safe-read.mjs +49 -0
  67. package/runtime/js/notify-send.mjs +312 -0
  68. package/runtime/js/notify.mjs +492 -0
  69. package/runtime/js/policy-binding-compat.mjs +54 -0
  70. package/runtime/model-efficiency.md +17 -0
  71. package/scripts/ci-test-shards.mjs +67 -0
  72. package/scripts/ci-test-shards.test.mjs +64 -0
  73. package/scripts/ci-test-weights.json +222 -0
  74. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  75. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  76. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  77. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  78. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  79. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  80. package/scripts/cm-ai-batch-drive.mjs +55 -10
  81. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  82. package/scripts/cm-ai-batch-host.mjs +132 -13
  83. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  84. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  85. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  86. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  87. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  88. package/scripts/cm-ai-batch-run.mjs +189 -22
  89. package/scripts/cm-ai-batch-run.test.mjs +22 -334
  90. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  91. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  92. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  93. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  94. package/scripts/cm-ai-drive.mjs +68 -23
  95. package/scripts/cm-ai-drive.test.mjs +37 -2
  96. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  97. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  98. package/scripts/cm-ai-host-fixture.mjs +268 -0
  99. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  100. package/scripts/cm-ai-host.mjs +28 -16
  101. package/scripts/cm-ai-host.test.mjs +17 -759
  102. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  103. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  104. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  105. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  106. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  107. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  108. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
  109. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  110. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  111. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  112. package/scripts/cm-ai-run.mjs +15 -6
  113. package/scripts/cm-ai-supersede.test.mjs +486 -41
  114. package/scripts/cm-check-drive-files.mjs +8 -0
  115. package/scripts/cm-check-drive.test.mjs +2 -5
  116. package/scripts/cm-check-runtime.sh +4 -2
  117. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  118. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  119. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  120. package/scripts/cm-claude-worker.test.mjs +18 -2
  121. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  122. package/scripts/cm-fix-abandon.test.mjs +249 -10
  123. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  124. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  125. package/scripts/cm-fix-drive.mjs +34 -8
  126. package/scripts/cm-fix-host.mjs +8 -7
  127. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  128. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  129. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  130. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  131. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  132. package/scripts/cm-host-documentation.test.mjs +49 -0
  133. package/scripts/cm-host-qa-executor.test.mjs +143 -10
  134. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  135. package/scripts/cm-idea-drive.mjs +49 -11
  136. package/scripts/cm-idea-drive.test.mjs +66 -0
  137. package/scripts/cm-idea-host.mjs +106 -16
  138. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  139. package/scripts/cm-init-drive.mjs +41 -7
  140. package/scripts/cm-init-host.mjs +61 -12
  141. package/scripts/cm-log-event.mjs +49 -12
  142. package/scripts/cm-notify-command.test.mjs +900 -0
  143. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  144. package/scripts/cm-notify.mjs +469 -0
  145. package/scripts/cm-notify.test.mjs +685 -0
  146. package/scripts/cm-patrol.mjs +83 -0
  147. package/scripts/cm-patrol.test.mjs +161 -0
  148. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  149. package/scripts/cm-prd-drive.mjs +18 -5
  150. package/scripts/cm-prd-drive.test.mjs +15 -0
  151. package/scripts/cm-prd-host.mjs +37 -4
  152. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  153. package/scripts/cm-prd-review-gate.mjs +56 -0
  154. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  155. package/scripts/cm-refactor-drive.mjs +52 -8
  156. package/scripts/cm-refactor-drive.test.mjs +44 -0
  157. package/scripts/cm-refactor-host.test.mjs +10 -6
  158. package/scripts/cm-release-smoke.sh +2 -0
  159. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  160. package/scripts/cm-test-drive.mjs +21 -5
  161. package/scripts/cm-token-report.mjs +497 -0
  162. package/scripts/cm-token-report.test.mjs +346 -0
  163. package/scripts/fixtures/claude-review-process.mjs +1 -1
  164. package/scripts/policy-binding-compat.test.mjs +99 -0
  165. package/scripts/scan-public-safety.py +4 -0
  166. package/scripts/validate-public-repo.py +4 -0
  167. package/skills/cm-ai/SKILL.md +7 -3
  168. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  169. package/skills/cm-ai/references/js-host-modes.md +90 -0
  170. package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
  171. package/skills/cm-ai/references/js-host-recovery.md +311 -0
  172. package/skills/cm-ai/references/js-host.md +76 -331
  173. package/skills/cm-check/SKILL.md +3 -3
  174. package/skills/cm-fix/SKILL.md +2 -0
  175. package/skills/cm-fix/references/js-host.md +56 -10
  176. package/skills/cm-idea/references/js-host.md +27 -2
  177. package/skills/cm-init/references/js-host.md +16 -3
  178. package/skills/cm-notify/SKILL.md +34 -0
  179. package/skills/cm-prd/SKILL.md +2 -0
  180. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  181. package/skills/cm-refactor/references/js-host.md +17 -0
  182. package/skills/cm-test/references/js-host.md +14 -1
@@ -95,6 +95,15 @@ function createClaudeDeveloperStream(onNotice=null,onUsageTerminal=null){
95
95
  if(substantive)assistant=true;return;
96
96
  }
97
97
  if(event.type==='user'){
98
+ // CLI-authored reminder (see claude-review-stream.mjs): a notice, never content.
99
+ if(event.isSynthetic===true){
100
+ const c=event.message?.content;
101
+ need(event.parent_tool_use_id===null&&event.message?.role==='user'&&Array.isArray(c)&&c.length===1
102
+ &&c[0]?.type==='text'&&typeof c[0].text==='string'&&Buffer.byteLength(c[0].text,'utf8')<=1024&&tools.size===0,'unexpected_tool_or_content');
103
+ need(noticeCount<32,'unexpected_event');noticeCount++;
104
+ try{onNotice?.({kind:'claude_system_notice',subtype:'synthetic_user'});}catch{}
105
+ return;
106
+ }
98
107
  need(event.message?.role==='user'&&Array.isArray(event.message.content),'invalid_event');
99
108
  for(const block of event.message.content){need(block.type==='tool_result'&&tools.has(block.tool_use_id),'unexpected_tool_or_content');tools.delete(block.tool_use_id);}
100
109
  return;
@@ -59,7 +59,11 @@ export function claudeWorker({cwd,model,preflight,cli='claude',timeoutMs=60000,s
59
59
  try { child=spawnProcess(cli,args,{cwd,env:claudeEnvironment(),stdio:['pipe','pipe','pipe'],detached:true}); }
60
60
  catch { usage.complete();resolve({status:'failed',code:'spawn_failed'});return; }
61
61
  let buffer='', bytes=0, failure=null, settled=false, timedOut=false, killTimer, pendingClose;
62
- let providerThread=null,providerTerminal=false,failedTerminal=false,receiptInvalid=false;
62
+ let providerThread=null,providerTerminal=false,failedTerminal=false,receiptInvalid=false,failureDetail=null;
63
+ // The boundary code carries the stream's body-free summary so the record
64
+ // shows what was rejected; stop() and callers keep matching the base code.
65
+ const withDetail=code=>code==='unexpected_tool_or_content'&&failureDetail!==null
66
+ ?`${code}:${JSON.stringify(failureDetail)}`:code;
63
67
  const cleanupGroup=ownedProcessCleanup(child,{killProcess});
64
68
  const providerFailure=()=>['provider_failed','reviewer_auth_failed','reviewer_billing_error',
65
69
  'reviewer_rate_limited','reviewer_server_error','reviewer_model_not_found','reviewer_api_error'].includes(failure);
@@ -110,7 +114,10 @@ export function claudeWorker({cwd,model,preflight,cli='claude',timeoutMs=60000,s
110
114
  &&Number.isInteger(message.num_turns)&&message.num_turns>=1&&message.num_turns<=20)usage.terminal(message.usage);
111
115
  stream.accept(message);
112
116
  }
113
- catch (error) {stop(error instanceof SyntaxError?'invalid_event':error.code??'invalid_event');}
117
+ catch (error) {
118
+ if(failure===null&&error?.code==='unexpected_tool_or_content'&&error.detail)failureDetail=error.detail;
119
+ stop(error instanceof SyntaxError?'invalid_event':error.code??'invalid_event');
120
+ }
114
121
  };
115
122
  signal.addEventListener('abort',abort,{once:true});
116
123
  if (signal.aborted) abort();
@@ -142,7 +149,7 @@ export function claudeWorker({cwd,model,preflight,cli='claude',timeoutMs=60000,s
142
149
  else if(!receiptInvalid&&typeof onTerminal==='function'&&failedTerminal&&providerFailure())onTerminal({status:'failed',code:'provider_failed'});
143
150
  if (signal.aborted) {resolve({status:'cancelled',code:'cancelled'});return;}
144
151
  if (failure || code!==0 || exitSignal!==null) {
145
- resolve({status:'failed',code:failure??'incomplete_result'});return;
152
+ resolve({status:'failed',code:withDetail(failure??'incomplete_result')});return;
146
153
  }
147
154
  try {resolve(stream.finish());}
148
155
  catch(error){resolve({status:'failed',code:error.code??'incomplete_result'});}
@@ -0,0 +1,43 @@
1
+ // Process identity of a detached provider worker (its pid is also its process
2
+ // group id) and the host's later check that the whole group is gone. Only a
3
+ // definite ESRCH, or a pid that now belongs to a process started at another
4
+ // time, proves "gone"; Windows, permission errors and unreadable start times
5
+ // stay "unknown" and never grant a redo.
6
+ import {spawnSync} from 'node:child_process';
7
+
8
+ export const MAX_START_TIME_LENGTH=64;
9
+ export const validWorkerPid=pid=>Number.isSafeInteger(pid)&&pid>1&&pid<=0x7fffffff;
10
+ export const validStartTime=value=>value===null||typeof value==='string'&&value.length>0
11
+ &&value.length<=MAX_START_TIME_LENGTH&&/^[\x20-\x7e]+$/.test(value);
12
+
13
+ // `ps -o lstart=` in the C locale: a stable, second-resolution start time.
14
+ export function readProcessStartTime(pid,{platform=process.platform,run=spawnSync}={}){
15
+ if(platform==='win32'||!validWorkerPid(pid))return null;
16
+ try{
17
+ const result=run('ps',['-o','lstart=','-p',String(pid)],{encoding:'utf8',timeout:5000,
18
+ env:{...process.env,LC_ALL:'C',LANG:'C'},maxBuffer:4096});
19
+ if(result.error||result.status!==0)return null;
20
+ const value=String(result.stdout).trim().replace(/\s+/g,' ');
21
+ return validStartTime(value)?value:null;
22
+ }catch{return null;}
23
+ }
24
+
25
+ // 'gone' | 'alive' | 'unknown'
26
+ export function inspectWorkerGroup({pid,startTime},{platform=process.platform,kill=process.kill.bind(process),
27
+ startTimeOf=value=>readProcessStartTime(value,{platform})}={}){
28
+ if(platform==='win32'||!validWorkerPid(pid)||!validStartTime(startTime))return 'unknown';
29
+ const probe=target=>{try{kill(target,0);return 'present';}catch(error){return error?.code==='ESRCH'?'absent':'unknown';}};
30
+ const group=probe(-pid);
31
+ if(group==='absent')return 'gone';
32
+ if(group==='unknown')return 'unknown';
33
+ // A process group exists under this id. POSIX never reuses a pid while a
34
+ // group with that id still exists, so a leader started at another time
35
+ // means the recorded worker group ended before the pid was reused.
36
+ const leader=probe(pid);
37
+ if(leader==='unknown')return 'unknown';
38
+ if(leader==='absent')return 'alive';
39
+ if(startTime===null)return 'unknown';
40
+ const current=startTimeOf(pid);
41
+ if(current===null)return 'unknown';
42
+ return current===startTime?'alive':'gone';
43
+ }
@@ -11,22 +11,38 @@ import {inspectVisualCarrier} from './visual.mjs';
11
11
  export const rediagnosisPackage=value=>({historyDigest:value.historyDigest,priorPackageDigest:value.priorPackageDigest,
12
12
  priorObservationDigest:value.priorObservationDigest,reason:value.reason,reviewFeedback:value.reviewFeedback});
13
13
 
14
- export function createFixCausePackage({codeProject,defect,status}){
14
+ // Round 2 shows the reviewer the round-1 review; every file that review examined
15
+ // or cited (outside the revised affectedPaths) is supplied as read-only context so
16
+ // the reviewer can examine and cite it. Old round-2 packages have no contextFiles.
17
+ const priorReviewPaths=feedback=>[...new Set([...(feedback?.examinedPaths??[]),...(feedback?.findings??[]).map(f=>f?.path)]
18
+ .filter(p=>typeof p==='string'&&!p.startsWith('specs:')))].sort();
19
+ function readContextFiles(codeProject,feedback,affectedPaths){
20
+ const files=[];
21
+ for(const p of priorReviewPaths(feedback).filter(p=>!affectedPaths.includes(p))){
22
+ // Only existing, ordinary source files inside the code root; anything else is omitted, never forged.
23
+ try{files.push(...readReviewSourceFiles(codeProject,[p]));}catch{}
24
+ }
25
+ return files;
26
+ }
27
+
28
+ export function createFixCausePackage({codeProject,defect,status,context=true}){
15
29
  need((status.stage==='cause_review_required'||status.stage==='observation_cause_review_correction_required'&&status.causeReviewCorrection)
16
30
  &&status.reproduction?.status==='reproduced'
17
31
  &&status.diagnosis!==null,'fix_cause_review_unavailable');
32
+ const contextFiles=context&&status.rediagnosis?readContextFiles(codeProject,status.rediagnosis.reviewFeedback,status.diagnosis.affectedPaths):[];
18
33
  const value=json({version:1,kind:'cm-fix-cause-review-package',identity:status.identity,defect,
19
34
  reproduction:status.reproduction,diagnosis:status.diagnosis,learning:status.learning,
20
35
  ...(status.rediagnosis?{rediagnosis:rediagnosisPackage(status.rediagnosis)}:{}),
21
36
  ...(status.causeReviewCorrection?{correction:status.causeReviewCorrection}:{}),
22
- files:readReviewSourceFiles(codeProject,status.diagnosis.affectedPaths)},4*1024*1024);
37
+ files:readReviewSourceFiles(codeProject,status.diagnosis.affectedPaths),...(contextFiles.length?{contextFiles}:{})},4*1024*1024);
23
38
  return json({...value,packageDigest:digest(value)},4*1024*1024);
24
39
  }
25
40
 
26
41
  export function readFixCausePackage(raw){
27
42
  const value=json(raw,4*1024*1024);
28
43
  shape(value,['version','kind','identity','defect','reproduction','diagnosis','learning','files','packageDigest',
29
- ...(Object.hasOwn(value,'correction')?['correction']:[]),...(Object.hasOwn(value,'rediagnosis')?['rediagnosis']:[])]);
44
+ ...(Object.hasOwn(value,'correction')?['correction']:[]),...(Object.hasOwn(value,'rediagnosis')?['rediagnosis']:[]),
45
+ ...(Object.hasOwn(value,'contextFiles')?['contextFiles']:[])]);
30
46
  if(value.rediagnosis){
31
47
  shape(value.rediagnosis,['historyDigest','priorPackageDigest','priorObservationDigest','reason','reviewFeedback']);
32
48
  need([value.rediagnosis.historyDigest,value.rediagnosis.priorPackageDigest,value.rediagnosis.priorObservationDigest].every(v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v)), 'invalid_package');
@@ -62,6 +78,12 @@ export function readFixCausePackage(raw){
62
78
  text(d.rootCause);text(d.plan);need(Array.isArray(d.affectedModules)&&d.affectedModules.length>0,'invalid_package');
63
79
  d.affectedModules.forEach(text);
64
80
  need(Array.isArray(d.affectedPaths)&&digest([...d.affectedPaths].sort())===digest(files.map(file=>file.path)),'invalid_package');
81
+ if(Object.hasOwn(value,'contextFiles')){
82
+ need(value.rediagnosis&&Array.isArray(value.contextFiles)&&value.contextFiles.length>0,'invalid_package');
83
+ const context=readReviewSourceRecords(value.contextFiles).map(file=>file.path),allowed=priorReviewPaths(value.rediagnosis.reviewFeedback);
84
+ need(digest(context)===digest([...context].sort())&&new Set(context).size===context.length
85
+ &&context.every(p=>allowed.includes(p)&&!d.affectedPaths.includes(p)),'invalid_package');
86
+ }
65
87
  shape(r,['status','next','observation',...(Object.hasOwn(r,'attempts')?['attempts']:[])]);
66
88
  need(r.status==='reproduced'&&r.next==='diagnose','invalid_package');inspectFixReproductionAttempts(r);
67
89
  const o=r.observation;
@@ -78,23 +100,30 @@ export function readFixCausePackage(raw){
78
100
  return value;
79
101
  }
80
102
 
81
- export const causeReviewPaths=pkg=>pkg.files.map(file=>file.path);
103
+ export const causeReviewPaths=pkg=>[...pkg.files,...(pkg.contextFiles??[])].map(file=>file.path);
82
104
 
83
105
  // Validate the original package, then admit only the exact registered test transition.
84
106
  export function verifyFixCauseTransition(original,current,authorBaseline,authorResult){
85
107
  const reviewed=readFixCausePackage(original),now=readFixCausePackage(current);
86
108
  const expected=new Map(reviewed.files.map(file=>[file.path,file]));
109
+ // Round-2 context files (e.g. an existing regression test the narrowed
110
+ // diagnosis no longer covers) admit the same registered test transition;
111
+ // any other change to them is drift.
112
+ const expectedContext=new Map((reviewed.contextFiles??[]).map(file=>[file.path,file]));
87
113
  if(authorBaseline&&authorResult){
88
114
  const authored=inspectFixTestAuthor(authorResult,authorBaseline);
89
115
  need(authored.outcome==='authored','cause_review_drift');
90
116
  const before=new Map(authorBaseline.files.map(file=>[file.path,file]));
91
117
  for(const file of authored.testFiles){
92
- if(!expected.has(file.path))continue;
93
- need(digest(inventory([before.get(file.path)]))===digest(inventory([expected.get(file.path)])),'cause_review_drift');
94
- expected.set(file.path,file);
118
+ const target=expected.has(file.path)?expected:expectedContext.has(file.path)?expectedContext:null;
119
+ if(!target)continue;
120
+ need(digest(inventory([before.get(file.path)]))===digest(inventory([target.get(file.path)])),'cause_review_drift');
121
+ target.set(file.path,file);
95
122
  }
96
123
  }
97
124
  need(digest(inventory(now.files))===digest(inventory([...expected.values()])),'cause_review_drift');
125
+ need(Object.hasOwn(now,'contextFiles')===Object.hasOwn(reviewed,'contextFiles')
126
+ &&digest(inventory(now.contextFiles??[]))===digest(inventory([...expectedContext.values()])),'cause_review_drift');
98
127
  const {packageDigest,...body}=now;
99
- need(digest({...body,files:reviewed.files})===reviewed.packageDigest,'cause_review_drift');
128
+ need(digest({...body,files:reviewed.files,...(reviewed.contextFiles?{contextFiles:reviewed.contextFiles}:{})})===reviewed.packageDigest,'cause_review_drift');
100
129
  }
@@ -0,0 +1,43 @@
1
+ // One fix_diagnose validator for journal replay, live answers and the driver
2
+ // preflight. Replay keeps its historical error codes; a live answer that fails
3
+ // becomes invalid_diagnosis with the failing field, so the caller can resubmit.
4
+ import path from 'node:path';
5
+ import {json,need,shape,text} from '../cm-ai/effect-contract.mjs';
6
+ import {tagDiagnosticReason} from '../cm-ai/diagnostic-reason.mjs';
7
+ import {atField,inspectFixInvestigation} from './investigation.mjs';
8
+
9
+ export function inspectFixDiagnosis(raw){
10
+ const value=atField('(answer)',()=>json(raw,32*1024));
11
+ atField('(answer)',()=>shape(value,['status','rootCause','affectedPaths','plan','crossLayer','affectedModules',...(Object.hasOwn(value,'investigation')?['investigation']:[])]));
12
+ atField('status',()=>need(['diagnosed','needs_evidence','design_change'].includes(value.status),'invalid_diagnosis'));
13
+ for(const key of ['rootCause','plan'])atField(key,()=>text(value[key]));
14
+ atField('crossLayer',()=>need(typeof value.crossLayer==='boolean','invalid_diagnosis'));
15
+ if(Object.hasOwn(value,'investigation'))inspectFixInvestigation(value.investigation,value.crossLayer);
16
+ for(const key of ['affectedPaths','affectedModules']){
17
+ atField(key,()=>need(Array.isArray(value[key])&&value[key].length>0&&value[key].length<=32,'invalid_diagnosis'),32,
18
+ Array.isArray(value[key])?value[key].length:null);
19
+ value[key].forEach((item,index)=>atField(`${key}[${index}]`,()=>{
20
+ text(item);need(!path.isAbsolute(item)&&item===path.posix.normalize(item)
21
+ &&item!=='.'&&!item.startsWith('../')&&!/[\\\0]/.test(item),'invalid_diagnosis');
22
+ }));
23
+ atField(key,()=>need(new Set(value[key]).size===value[key].length,'invalid_diagnosis'));
24
+ }
25
+ return value;
26
+ }
27
+
28
+ export function describeFixDiagnosisError(error){
29
+ const field=typeof error?.field==='string'?error.field:'(answer)';
30
+ const limit=Number.isSafeInteger(error?.limit)?`:最多 ${error.limit} 项${Number.isSafeInteger(error.actual)?`,实际 ${error.actual} 项`:''}`:'';
31
+ return `诊断答案字段 ${field} 不合法${limit}(${error?.code??'invalid_input'})`;
32
+ }
33
+
34
+ // Live answer: never an interruption. The step stays pending and the same
35
+ // request may be answered again; nothing about the rejected answer is recorded.
36
+ export function fixDiagnosisAnswer(raw){
37
+ try{return inspectFixDiagnosis(raw);}
38
+ catch(error){
39
+ const failure=Object.assign(new Error('invalid_diagnosis'),{code:'invalid_diagnosis'});
40
+ throw tagDiagnosticReason(failure,describeFixDiagnosisError(error));
41
+ }
42
+ }
43
+ export const isInvalidFixDiagnosis=error=>error?.code==='invalid_diagnosis'&&typeof error.reason==='string';