@aibyzero/cm-workflow 0.16.8 → 0.17.0

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 (226) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +22 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/cm-control-policy-v2.md +331 -0
  7. package/docs/execution-optimizations.md +1 -1
  8. package/docs/external-models.md +3 -3
  9. package/docs/human-correction.md +5 -5
  10. package/docs/installation.md +1 -1
  11. package/docs/js-workflow-control.md +119 -78
  12. package/docs/next-steps.md +19 -2
  13. package/docs/untested-branches.md +2 -3
  14. package/docs/user-guide.md +105 -5
  15. package/package.json +2 -1
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  17. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +103 -68
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +79 -27
  19. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  20. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  21. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  22. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  23. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +883 -69
  25. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  26. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  27. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  28. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  29. package/runtime/js/cm-ai/host-check.mjs +4 -1
  30. package/runtime/js/cm-ai/host-conversation-execution.mjs +33 -24
  31. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  32. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  33. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  34. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +53 -9
  35. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  36. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  37. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +43 -3
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  41. package/runtime/js/cm-ai/host.mjs +1 -2
  42. package/runtime/js/cm-ai/operator-guidance.mjs +89 -3
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  44. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  45. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  46. package/runtime/js/cm-ai/review-package.mjs +26 -5
  47. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  48. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  49. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  50. package/runtime/js/cm-ai/task-runner.mjs +629 -121
  51. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  52. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  53. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  54. package/runtime/js/cm-fix/execution.mjs +176 -48
  55. package/runtime/js/cm-fix/host.mjs +2 -1
  56. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  57. package/runtime/js/cm-fix/progress.mjs +13 -3
  58. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  59. package/runtime/js/cm-fix/repair.mjs +11 -3
  60. package/runtime/js/cm-fix/test-author.mjs +10 -3
  61. package/runtime/js/cm-idea/session.mjs +67 -4
  62. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  63. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  64. package/runtime/js/cm-prd/review-host.mjs +1 -1
  65. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  66. package/runtime/js/cm-prd/session.mjs +43 -0
  67. package/runtime/js/cm-refactor/records.mjs +98 -8
  68. package/runtime/js/cm-refactor/workflow.mjs +80 -10
  69. package/runtime/js/cm-test/host.mjs +10 -3
  70. package/runtime/js/cm-test/session.mjs +45 -6
  71. package/runtime/js/notify-safe-read.mjs +49 -0
  72. package/runtime/js/notify-send.mjs +313 -0
  73. package/runtime/js/notify.mjs +164 -37
  74. package/runtime/js/policy-binding-compat.mjs +55 -0
  75. package/runtime/review.md +52 -7
  76. package/runtime/task-gates.md +107 -9
  77. package/scripts/ci-test-shards.mjs +67 -0
  78. package/scripts/ci-test-shards.test.mjs +64 -0
  79. package/scripts/ci-test-weights.json +222 -0
  80. package/scripts/cm-ai-abandon-effect-position.test.mjs +71 -10
  81. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  82. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  83. package/scripts/cm-ai-answer-gap-fixture.mjs +89 -0
  84. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  85. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  86. package/scripts/cm-ai-batch-drive.mjs +98 -34
  87. package/scripts/cm-ai-batch-drive.test.mjs +124 -16
  88. package/scripts/cm-ai-batch-host.mjs +167 -29
  89. package/scripts/cm-ai-batch-host.test.mjs +303 -31
  90. package/scripts/cm-ai-batch-run-fixture.mjs +452 -0
  91. package/scripts/cm-ai-batch-run-member-stops.test.mjs +26 -0
  92. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  93. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  94. package/scripts/cm-ai-batch-run.mjs +213 -25
  95. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  96. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  97. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  98. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  99. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  100. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  101. package/scripts/cm-ai-develop-answer-invalid.test.mjs +97 -0
  102. package/scripts/cm-ai-develop-call-timeout.test.mjs +146 -0
  103. package/scripts/cm-ai-develop-driver-gaps.test.mjs +37 -23
  104. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  105. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  106. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  107. package/scripts/cm-ai-drive.mjs +142 -58
  108. package/scripts/cm-ai-drive.test.mjs +70 -84
  109. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  110. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  111. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +267 -0
  113. package/scripts/cm-ai-host-fixture.mjs +296 -0
  114. package/scripts/cm-ai-host-protected.test.mjs +253 -0
  115. package/scripts/cm-ai-host.mjs +122 -100
  116. package/scripts/cm-ai-host.test.mjs +35 -776
  117. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  118. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  119. package/scripts/cm-ai-light-modules.test.mjs +54 -0
  120. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  121. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  122. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  123. package/scripts/cm-ai-progress.test.mjs +10 -8
  124. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  125. package/scripts/cm-ai-protected-scope.test.mjs +8 -5
  126. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  127. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  128. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  129. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +95 -13
  130. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  131. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  132. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +59 -14
  133. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  134. package/scripts/cm-ai-review-failure.test.mjs +137 -32
  135. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  136. package/scripts/cm-ai-review-timeout.test.mjs +132 -67
  137. package/scripts/cm-ai-run.mjs +91 -28
  138. package/scripts/cm-ai-run.test.mjs +11 -38
  139. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  140. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  141. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  142. package/scripts/cm-ai-supersede.test.mjs +489 -51
  143. package/scripts/cm-blocked-reason.test.mjs +2 -3
  144. package/scripts/cm-capability-gate.test.mjs +33 -1
  145. package/scripts/cm-check-drive-files.mjs +8 -0
  146. package/scripts/cm-check-drive.test.mjs +2 -5
  147. package/scripts/cm-check-runtime.sh +4 -2
  148. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  149. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  150. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  151. package/scripts/cm-claude-worker.test.mjs +23 -5
  152. package/scripts/cm-controlled-correction.test.mjs +469 -0
  153. package/scripts/cm-external-batch-host.test.mjs +30 -11
  154. package/scripts/cm-external-model-host.test.mjs +1 -1
  155. package/scripts/cm-external-model-recovery.test.mjs +32 -12
  156. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  157. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  158. package/scripts/cm-fix-abandon.test.mjs +163 -10
  159. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  160. package/scripts/cm-fix-drive.mjs +25 -7
  161. package/scripts/cm-fix-host.mjs +8 -7
  162. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  163. package/scripts/cm-fix-review-recovery.test.mjs +36 -1
  164. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  165. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  166. package/scripts/cm-host-documentation.test.mjs +49 -0
  167. package/scripts/cm-host-qa-executor.test.mjs +23 -12
  168. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  169. package/scripts/cm-host-review-authority.test.mjs +0 -31
  170. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  171. package/scripts/cm-idea-drive.mjs +49 -11
  172. package/scripts/cm-idea-drive.test.mjs +66 -0
  173. package/scripts/cm-idea-host.mjs +106 -16
  174. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  175. package/scripts/cm-init-drive.mjs +41 -7
  176. package/scripts/cm-init-host.mjs +61 -12
  177. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  178. package/scripts/cm-log-event.mjs +21 -10
  179. package/scripts/cm-notify-command.test.mjs +936 -0
  180. package/scripts/cm-notify-read-drift.test.mjs +270 -0
  181. package/scripts/cm-notify.mjs +481 -0
  182. package/scripts/cm-notify.test.mjs +312 -23
  183. package/scripts/cm-patrol.test.mjs +3 -2
  184. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  185. package/scripts/cm-prd-drive.mjs +18 -5
  186. package/scripts/cm-prd-drive.test.mjs +15 -0
  187. package/scripts/cm-prd-host.mjs +37 -4
  188. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  189. package/scripts/cm-prd-review-gate.mjs +56 -0
  190. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  191. package/scripts/cm-refactor-drive.mjs +52 -8
  192. package/scripts/cm-refactor-drive.test.mjs +44 -0
  193. package/scripts/cm-refactor-host.test.mjs +10 -6
  194. package/scripts/cm-release-smoke.sh +2 -0
  195. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  196. package/scripts/cm-task-gate.mjs +368 -34
  197. package/scripts/cm-task-gate.py +2 -0
  198. package/scripts/cm-task-gate.test.mjs +252 -4
  199. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  200. package/scripts/cm-test-drive.mjs +21 -5
  201. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  202. package/scripts/fixtures/claude-review-process.mjs +1 -1
  203. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  204. package/scripts/policy-binding-compat.test.mjs +103 -0
  205. package/scripts/scan-public-safety.py +4 -0
  206. package/scripts/validate-public-repo.py +4 -0
  207. package/skills/cm-ai/SKILL.md +8 -6
  208. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  209. package/skills/cm-ai/references/N4-review.md +11 -21
  210. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  211. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  212. package/skills/cm-ai/references/js-host-modes.md +35 -14
  213. package/skills/cm-ai/references/js-host-qa-recovery.md +85 -11
  214. package/skills/cm-ai/references/js-host-recovery.md +181 -21
  215. package/skills/cm-ai/references/js-host.md +76 -32
  216. package/skills/cm-check/SKILL.md +3 -3
  217. package/skills/cm-fix/SKILL.md +12 -0
  218. package/skills/cm-fix/references/js-host.md +44 -5
  219. package/skills/cm-idea/references/js-host.md +27 -2
  220. package/skills/cm-init/references/js-host.md +17 -4
  221. package/skills/cm-notify/SKILL.md +34 -0
  222. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  223. package/skills/cm-prd/references/js-host.md +1 -1
  224. package/skills/cm-refactor/SKILL.md +12 -0
  225. package/skills/cm-refactor/references/js-host.md +17 -0
  226. package/skills/cm-test/references/js-host.md +14 -1
@@ -1,4 +1,4 @@
1
- // N6 policy over host semantic assessment; no provider, QA execution or new state.
1
+ // N6 fixed checkpoints over registered paths and runner-proven changes.
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {inspectCmAiQaTaskContext} from './cm-ai-admission.mjs';
@@ -28,43 +28,85 @@ function history(binding,context) {
28
28
  return new Set([...unseen,...since,key(binding.feature,binding.identity.taskId)]).size;
29
29
  }
30
30
 
31
- export function decideHostQaPolicy({assessment,pending,mergeEligible,unassessedTasks}) {
32
- const value=json(assessment);shape(value,['scores','changes']);
33
- shape(value.scores,['scope','risk','accumulation','boundary']);
34
- shape(value.changes,['api','migration','authentication','authorization','payment']);
35
- for(const score of Object.values(value.scores))need(Number.isInteger(score)&&score>=1&&score<=5,'qa_assessment_invalid');
36
- for(const flag of Object.values(value.changes))need(typeof flag==='boolean','qa_assessment_invalid');
31
+ const categories=['migration','authentication','authorization','payment','api'];
32
+
33
+ // Deliberately bounded POSIX glob grammar: literals, *, ?, and whole-segment **.
34
+ // A registry never imports executable patterns, absolute roots or parent traversal.
35
+ function relativePath(value,pattern=false){
36
+ need(typeof value==='string'&&value.length>0&&value.length<=1024&&!/[\\\r\n\0]/.test(value)
37
+ &&!value.startsWith('/')&&!/^[A-Za-z]:/.test(value),'qa_assessment_invalid');
38
+ const parts=value.split('/');
39
+ need(parts.every(part=>part.length>0&&part!=='.'&&part!=='..'),'qa_assessment_invalid');
40
+ if(pattern)need(!/[\[\]{}()!+@]/.test(value)&&parts.every(part=>!part.includes('**')||part==='**'),'qa_assessment_invalid');
41
+ return value;
42
+ }
43
+ export function readQaCriticalPaths(raw={}){
44
+ const registry=json(raw);need(registry&&typeof registry==='object'&&!Array.isArray(registry),'qa_assessment_invalid');
45
+ need(Object.keys(registry).every(name=>categories.includes(name)),'qa_assessment_invalid');
46
+ for(const patterns of Object.values(registry)){
47
+ need(Array.isArray(patterns)&&patterns.length<=256&&new Set(patterns).size===patterns.length,'qa_assessment_invalid');
48
+ patterns.forEach(pattern=>relativePath(pattern,true));
49
+ }
50
+ return registry;
51
+ }
52
+ function matchesPath(file,pattern){
53
+ const segments=pattern.split('/');
54
+ const source=segments.map((part,index)=>part==='**'
55
+ ?index===segments.length-1?'.*':'(?:[^/]+/)*'
56
+ :part.replace(/[.*+?^${}()|[\]\\]/g,char=>char==='*'?'[^/]*':char==='?'?'[^/]':`\\${char}`)
57
+ +(index===segments.length-1?'':'/')).join('');
58
+ return new RegExp(`^${source}$`).test(file);
59
+ }
60
+ export function readQaAssessment(raw){
61
+ const value=json(raw);shape(value,['confirmed']);need(value.confirmed===true,'qa_assessment_invalid');
62
+ return value;
63
+ }
64
+ export function readQaChangedFiles(raw){
65
+ const value=json(raw);shape(value,['paths','source']);
66
+ need(['review_package','handoff_only','unavailable'].includes(value.source),'qa_policy_unavailable');
67
+ need(Array.isArray(value.paths)&&value.paths.length<=10000&&new Set(value.paths).size===value.paths.length,'qa_policy_unavailable');
68
+ value.paths.forEach(file=>relativePath(file));
69
+ need(value.source!=='unavailable'||value.paths.length===0,'qa_policy_unavailable');
70
+ return value;
71
+ }
72
+ export function decideHostQaPolicy({changedFiles,criticalPaths={},pending,mergeEligible,unassessedTasks}) {
73
+ const registry=readQaCriticalPaths(criticalPaths);
74
+ need(Array.isArray(changedFiles)&&new Set(changedFiles).size===changedFiles.length,'qa_policy_unavailable');
75
+ changedFiles.forEach(file=>relativePath(file));
37
76
  need(Number.isSafeInteger(pending)&&pending>=0&&typeof mergeEligible==='boolean'
38
77
  &&Number.isSafeInteger(unassessedTasks)&&unassessedTasks>=1,'qa_policy_unavailable');
39
78
  need(!mergeEligible||pending===1,'qa_policy_unavailable');
40
- const score=Object.values(value.scores).reduce((sum,item)=>sum+item,0);
79
+ const hits=new Set(categories.filter(name=>(registry[name]??[]).some(pattern=>changedFiles.some(file=>matchesPath(file,pattern)))));
41
80
  const reasons=[];
42
81
  if(pending===0)reasons.push('feature_complete');
43
- for(const name of ['migration','authentication','authorization','payment'])if(value.changes[name])reasons.push(name);
82
+ for(const name of categories.slice(0,-1))if(hits.has(name))reasons.push(name);
44
83
  if(unassessedTasks>=5)reasons.push('five_tasks_without_qa');
45
- if(value.changes.api&&!mergeEligible)reasons.push('api_change');
84
+ if(hits.has('api')&&!mergeEligible)reasons.push('api');
46
85
  if(reasons.length)return {status:'triggered',score:null,reason:reasons.join(',')};
47
- if(score>=8)return {status:'triggered',score,reason:'risk_score'};
48
- return {status:'skipped',score,reason:value.changes.api&&mergeEligible?'merged_to_feature_qa':'risk_score_below_threshold'};
86
+ return {status:'skipped',score:null,reason:hits.has('api')&&mergeEligible?'merged_to_feature_qa':'no_fixed_trigger'};
49
87
  }
50
88
 
51
89
  // Plug directly into the existing trusted qaDecisionProvider seam. The host
52
- // classifies meaning; this function owns the mechanical decision and binding.
53
- export function createHostQaDecisionProvider({assess,timeoutMs}) {
90
+ // confirms the supplied inventory source; JS owns the decision and binding.
91
+ export function createHostQaDecisionProvider({assess,timeoutMs,criticalPaths={}}) {
92
+ const registry=readQaCriticalPaths(criticalPaths);
54
93
  need(typeof assess==='function'&&Number.isSafeInteger(timeoutMs)&&timeoutMs>0&&timeoutMs<=60000,'qa_assessment_invalid');
55
94
  return Object.freeze({timeoutMs,async decide(raw,signal){
56
95
  const input=json(raw);
57
- shape(input,['specsDir','codeProject','feature','identity','packageDigest',...(Object.hasOwn(input,'previousDecisionId')?['previousDecisionId']:[])]);
96
+ shape(input,['specsDir','codeProject','feature','identity','packageDigest',...(Object.hasOwn(input,'previousDecisionId')?['previousDecisionId']:[]),
97
+ ...(Object.hasOwn(input,'changedFiles')?['changedFiles']:[])]);
58
98
  // previousDecisionId names an older recorded decision that an explicit
59
99
  // recovery supersedes; it only derives a distinct id, never the assessment.
60
- const {previousDecisionId=null,...binding}=input;if(previousDecisionId!==null)id(previousDecisionId);
100
+ const {previousDecisionId=null,changedFiles:rawFiles={paths:[],source:'unavailable'},...binding}=input;
101
+ const changedFiles=readQaChangedFiles(rawFiles);
102
+ need(changedFiles.source!=='unavailable'||!Object.values(registry).some(patterns=>patterns.length),'qa_policy_unavailable');
103
+ if(previousDecisionId!==null)id(previousDecisionId);
61
104
  validIdentity(binding.identity);hex(binding.packageDigest);
62
105
  const context=inspectCmAiQaTaskContext({...binding,taskId:binding.identity.taskId});
63
106
  const unassessedTasks=history(binding,context);
64
107
  need(!signal.aborted,'cancelled');
65
- let assessment;
66
- try{assessment=await assess(freeze({...binding,pending:context.pending,mergeEligible:context.mergeEligible,
67
- unassessedTasks}),signal);}
108
+ try{readQaAssessment(await assess(freeze({...binding,pending:context.pending,mergeEligible:context.mergeEligible,
109
+ unassessedTasks,changedFiles,criticalPaths:registry}),signal));}
68
110
  catch(error){
69
111
  // A missed answer window is a transport outcome, not a QA decision. It is
70
112
  // reported like the outer decision timer: retryable, and nothing durable.
@@ -76,9 +118,9 @@ export function createHostQaDecisionProvider({assess,timeoutMs}) {
76
118
  // another decision; do not bind an answer to different policy inputs.
77
119
  const current=inspectCmAiQaTaskContext({...binding,taskId:binding.identity.taskId});
78
120
  need(digest(current)===digest(context)&&history(binding,current)===unassessedTasks,'stale_qa');
79
- const result=decideHostQaPolicy({assessment,pending:context.pending,mergeEligible:context.mergeEligible,unassessedTasks});
121
+ const result=decideHostQaPolicy({changedFiles:changedFiles.paths,criticalPaths:registry,pending:context.pending,mergeEligible:context.mergeEligible,unassessedTasks});
80
122
  const bound={identity:binding.identity,packageDigest:binding.packageDigest,...(previousDecisionId===null?{}:{previousDecisionId})};
81
123
  return freeze({...result,decisionId:`qa-${digest(bound).slice(0,48)}`,
82
- identity:binding.identity,packageDigest:binding.packageDigest,at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')});
124
+ identity:binding.identity,packageDigest:binding.packageDigest,changedFilesSource:changedFiles.source,at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')});
83
125
  }});
84
126
  }
@@ -1,5 +1,5 @@
1
- // Trusted host decision -> existing V3 synchronous grant. No dispatch or durable
2
- // authority database. The runner alone registers, consumes and replays grants.
1
+ // CMFIX legacy decision-to-grant consistency adapter. It does not verify a person
2
+ // or an independent identity. cm-ai no longer calls this adapter.
3
3
  import {randomUUID} from 'node:crypto';
4
4
  import {digest,id,json,need,shape,validIdentity} from './effect-contract.mjs';
5
5
 
@@ -15,7 +15,7 @@ export function publishHostReview({reviewsDir,feature,handoffPath,reviewPackage,
15
15
  const {receiptDigest,...body}=r;
16
16
  need(receiptDigest===digest(body)&&r.packageDigest===pkg.packageDigest
17
17
  &&digest(r.identity)===digest(pkg.identity),'review_package_mismatch');
18
- need(r.execution.channel==='host-authorized'&&r.execution.started===true
18
+ need(['host-review','host-authorized'].includes(r.execution.channel)&&r.execution.started===true
19
19
  &&r.execution.terminal==='succeeded'&&['codex','claude'].includes(r.execution.provider),'execution_mismatch');
20
20
  id(r.execution.providerThreadId);
21
21
  const result=reviewResult(r.result,pkg);
@@ -15,7 +15,7 @@ export function parseHostInputLimit(raw){
15
15
  &&value>=LIMIT&&value<=4*1024*1024,'invalid_arguments');
16
16
  return value;
17
17
  }
18
- const operationNames=new Set(['repair_review_response','reconcile_review','rediagnose','replace_inputs','read_batch','recover_final_review','abandon_step','abandon_review','abandon_effect','bootstrap_review_recover','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',
18
+ const operationNames=new Set(['repair_review_response','reconcile_review','rediagnose','replace_inputs','read_batch','recover_final_review','abandon_step','abandon_review','rerun_blocked_step','abandon_effect','bootstrap_review_recover','develop_redo','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',
19
19
  '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']);
20
20
 
21
21
  // Which contract codes may reach the peer is a deliberate boundary: the host
@@ -15,12 +15,46 @@ function waitNotice(kind,callId){
15
15
  return ()=>{cancelled=true;cancel?.();};
16
16
  }
17
17
 
18
- export function createHostToolBridge({responseLimit=64*1024}={}){
18
+ // Every call has a deadline (R0). A call without its own timeoutMs waits at most
19
+ // the host answer limit: CM_HOST_ANSWER_TIMEOUT_MINUTES (integer 1-60, default 30).
20
+ // It is read when the host starts and is never journaled, so it changes no run
21
+ // fingerprint and a resumed run may use another value. Hosts whose calls already
22
+ // run under their own budget (cm-ai, cm-ai batch, cm-fix: at most 60 minutes)
23
+ // pass HOST_ANSWER_BACKSTOP_MS, which never fires before that budget.
24
+ export const HOST_ANSWER_TIMEOUT_DEFAULT_MS=30*60000;
25
+ export const HOST_ANSWER_TIMEOUT_MAX_MS=60*60000;
26
+ export const HOST_ANSWER_BACKSTOP_MS=HOST_ANSWER_TIMEOUT_MAX_MS+60000;
27
+ export function hostAnswerTimeoutMs(env=process.env){
28
+ const raw=env.CM_HOST_ANSWER_TIMEOUT_MINUTES;
29
+ if(raw===undefined||raw==='')return HOST_ANSWER_TIMEOUT_DEFAULT_MS;
30
+ need(/^[1-9][0-9]?$/.test(raw)&&Number(raw)<=60,'host_answer_timeout_invalid');
31
+ return Number(raw)*60000;
32
+ }
33
+ // qa_assess carries runner-proven changedFiles and project criticalPaths. Its
34
+ // consumer validates only {confirmed:true}; scores/semantic risk flags are not
35
+ // part of this kind's business contract. The bridge remains transport-only.
36
+ // Every kind a workflow host may ask the session. A kind missing here makes
37
+ // that step throw host_operation_invalid on every attempt (O20: the second-round
38
+ // refactor judge revision, refactor_revise_tests, was missing).
39
+ export const HOST_CALL_KINDS=Object.freeze(['develop','check','verification_precheck','check_runtime','check_semantic','qa_assess','qa_logic','qa_browser','change_impact','test_cases','refactor_analyze','refactor_confirm','refactor_apply','refactor_review','refactor_batch','refactor_prepare_tests','refactor_revise_tests','refactor_retrospective','refactor_recover','documentation_sync','documentation_inspect','fix_diagnose','fix_learning','fix_test_author','fix_repair','fix_retrospective','init_analyze','init_generate','init_verify','init_confirm','init_review','init_write','idea_interview','idea_confirm_save','prd_analyze','prd_materials','prd_generate','prd_self_check','prd_review','prd_correct','prd_summary']);
40
+ // Answers that first run the project's own commands (test suites, builds,
41
+ // devices) normally take tens of minutes; they always get the 60-minute maximum.
42
+ const COMMAND_KINDS=new Set(['check','verification_precheck','init_verify','check_runtime','qa_logic','qa_browser']);
43
+ // A late answer (its call already stopped by the deadline or a cancel) is refused
44
+ // with one diagnostic line; it never reaches the step that stopped waiting.
45
+ const LATE_CALLS=32;
46
+ const lateDiagnostic=fields=>{try{process.stderr.write(JSON.stringify({diagnostic:'host_response_late',...fields})+'\n');}catch{}};
47
+
48
+ export function createHostToolBridge({responseLimit=64*1024,answerTimeoutMs=hostAnswerTimeoutMs()}={}){
19
49
  need(Number.isSafeInteger(responseLimit)&&responseLimit>=64*1024&&responseLimit<=4*1024*1024,'host_response_limit_invalid');
50
+ need(Number.isSafeInteger(answerTimeoutMs)&&answerTimeoutMs>=1000&&answerTimeoutMs<=HOST_ANSWER_BACKSTOP_MS,'host_answer_timeout_invalid');
20
51
  const sessionId=randomUUID();let send=null,pending=null,closed=false;
52
+ const stopped=new Map();
21
53
  const stop=(code,call=pending)=>{
22
54
  if(!call||pending!==call)return;pending=null;clearTimeout(call.timer);call.notice?.();
23
55
  call.signal.removeEventListener('abort',call.abort);
56
+ if(code!=='host_disconnected'){stopped.set(call.request.callId,{kind:call.request.kind,stoppedBy:code});
57
+ if(stopped.size>LATE_CALLS)stopped.delete(stopped.keys().next().value);}
24
58
  call.reject(Object.assign(new Error(code),{code}));
25
59
  };
26
60
  return Object.freeze({
@@ -30,8 +64,7 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
30
64
  },
31
65
  call(kind,payload,signal,{timeoutMs=null}={}){
32
66
  need(send!==null&&!closed,'host_bridge_unavailable');need(pending===null,'host_bridge_busy');
33
- need(['develop','check','verification_precheck','check_runtime','check_semantic','qa_assess','qa_logic','qa_browser','change_impact','test_cases','refactor_analyze','refactor_confirm','refactor_apply','refactor_review','refactor_batch','refactor_prepare_tests','refactor_retrospective','refactor_recover','documentation_sync','documentation_inspect','fix_diagnose','fix_learning','fix_test_author','fix_repair','fix_retrospective','init_analyze','init_generate','init_verify','init_confirm','init_review','init_write','idea_interview','idea_confirm_save','prd_analyze','prd_materials','prd_generate','prd_self_check','prd_review','prd_correct','prd_summary']
34
- .includes(kind),'host_operation_invalid');need(!signal.aborted,'cancelled');
67
+ need(HOST_CALL_KINDS.includes(kind),'host_operation_invalid');need(!signal.aborted,'cancelled');
35
68
  const data=json({kind,payload},12*1024*1024);
36
69
  const request={type:'host_request',sessionId,callId:randomUUID(),requestDigest:digest(data),...data};
37
70
  need(timeoutMs===null||Number.isSafeInteger(timeoutMs)&&timeoutMs>0&&timeoutMs<=3600000,'host_request_timeout_invalid');
@@ -42,6 +75,9 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
42
75
  };
43
76
  const call={request,signal,abort,resolve,reject,timer:null,notice:waitNotice(kind,request.callId)};pending=call;
44
77
  if(timeoutMs!==null)call.timer=setTimeout(()=>stop('host_request_timeout',call),timeoutMs);
78
+ // The default deadline never keeps an otherwise finished process alive.
79
+ else {call.timer=setTimeout(()=>stop('host_request_timeout',call),
80
+ COMMAND_KINDS.has(kind)?Math.max(answerTimeoutMs,HOST_ANSWER_TIMEOUT_MAX_MS):answerTimeoutMs);call.timer.unref?.();}
45
81
  signal.addEventListener('abort',abort,{once:true});
46
82
  if(signal.aborted){abort();return;}
47
83
  Promise.resolve().then(()=>{
@@ -57,6 +93,10 @@ export function createHostToolBridge({responseLimit=64*1024}={}){
57
93
  closed=true;stop('host_disconnected');return {accepted:true,closing:true};
58
94
  }
59
95
  reply=json(raw,responseLimit);shape(reply,['type','sessionId','callId','requestDigest','result']);
96
+ const late=reply.type==='host_result'&&reply.sessionId===sessionId&&pending?.request.callId!==reply.callId
97
+ ?stopped.get(reply.callId):undefined;
98
+ if(late){lateDiagnostic({kind:late.kind,callId:reply.callId,stoppedBy:late.stoppedBy});
99
+ return {accepted:false,code:'host_response_late'};}
60
100
  need(reply.type==='host_result'&&pending!==null&&!closed,'host_response_mismatch');
61
101
  for(const key of ['sessionId','callId','requestDigest'])need(reply[key]===pending.request[key],'host_response_mismatch');
62
102
  }catch(error){return {accepted:false,code:error?.code==='limit_exceeded'?'host_response_too_large':'host_response_mismatch'};}
@@ -2,7 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {digest,json,need,shape,validIdentity,hex} from './effect-contract.mjs';
5
- import {createHostQaDecisionProvider} from './host-qa-policy.mjs';
5
+ import {createHostQaDecisionProvider,readQaCriticalPaths} 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';
@@ -56,7 +56,9 @@ export function validateHostWorkflowConfiguration(raw){
56
56
  for(const key of ['documentationPaths','applicableAgentFiles'])
57
57
  need(Array.isArray(config[key])&&config[key].length<=256&&config[key].every(item=>typeof item==='string'),'invalid_workflow_config');
58
58
  if(config.qa!==null){
59
- shape(config.qa,['commands','environment',...(Object.hasOwn(config.qa,'timeoutMs')?['timeoutMs']:[])]);
59
+ shape(config.qa,['commands','environment',...(Object.hasOwn(config.qa,'timeoutMs')?['timeoutMs']:[]),
60
+ ...(Object.hasOwn(config.qa,'criticalPaths')?['criticalPaths']:[])]);
61
+ if(Object.hasOwn(config.qa,'criticalPaths'))readQaCriticalPaths(config.qa.criticalPaths);
60
62
  // A real browser walkthrough of one blocking case runs for minutes, so this
61
63
  // follows the shared call-timeout range rather than a fixed minute. The
62
64
  // default below is unchanged; only an explicit configuration may raise it.
@@ -66,7 +68,7 @@ export function validateHostWorkflowConfiguration(raw){
66
68
  return config;
67
69
  }
68
70
 
69
- export function createHostWorkflowCapabilities({definition,configuration,bridge,allowQa,runtime='codex',protectedExecution=false,bootstrap=null,parallelMember=false}){
71
+ export function createHostWorkflowCapabilities({definition,configuration,bridge,allowQa,runtime='codex',protectedExecution=false,bootstrap=null,parallelMember=false,controlPolicy=null}){
70
72
  need(['codex','claude'].includes(runtime),'invalid_runtime');
71
73
  const {specsDir,codeProject,feature,requirements}=definition;
72
74
  const logHome=path.join(specsDir,'.reviews','host-log-mirror');
@@ -74,18 +76,25 @@ export function createHostWorkflowCapabilities({definition,configuration,bridge,
74
76
  documentationProvider:{timeoutMs:60000,inspect:(request,signal)=>bridge.call('documentation_inspect',request,signal)}};
75
77
  if(!protectedExecution&&configuration.documentationPaths.length)result.documentationSync={paths:configuration.documentationPaths,
76
78
  run:(request,signal)=>bridge.call('documentation_sync',request,signal)};
77
- if(configuration.qa!==null){
78
- need(allowQa===true,'qa_authorization_required');
79
+ // The N6 disposition is required even when execution is disabled. Its
80
+ // fixed checkpoints and registered path matches may require QA;
81
+ // only a configured executor can then supply actual execution evidence.
82
+ // Legacy qa:null keeps its historical caller-supplied disposition contract.
83
+ if(configuration.qa!==null||controlPolicy!==null){
79
84
  result.qaLogHome=logHome;
80
- const requestTimeout={timeoutMs:configuration.qa.timeoutMs??60000};
81
- result.qaDecisionProvider=parallelMember?createParallelMemberQaDecisionProvider():createHostQaDecisionProvider({timeoutMs:60000,
85
+ const requestTimeout={timeoutMs:configuration.qa?.timeoutMs??60000};
86
+ result.qaDecisionProvider=parallelMember?createParallelMemberQaDecisionProvider():createHostQaDecisionProvider({timeoutMs:60000,criticalPaths:configuration.qa?.criticalPaths??{},
82
87
  assess:(request,signal)=>bridge.call('qa_assess',request,signal,requestTimeout)});
88
+ }
89
+ if(configuration.qa!==null&&(controlPolicy===null||controlPolicy.qa==='run')){
90
+ need(allowQa===true,'qa_authorization_required');
91
+ const requestTimeout={timeoutMs:configuration.qa.timeoutMs??60000};
83
92
  // requestTimeoutMs stays outside the fingerprinted executor configuration;
84
93
  // timed-out QA recovery reads older case_blocked rows against it.
85
94
  result.qaExecutor=Object.freeze({...createHostQaExecutor({specsDir,codeProject,feature,requirements,runtime,
86
95
  ...(definition.codeProjects?{codeProjects:definition.codeProjects}:{}),
87
96
  ...(bootstrap?{bootstrap:{requirements:bootstrap.configuration.bootstrapRequirements,scope:definition.scope}}:{}),
88
- ...configuration.qa,timeoutMs:1800000,logHome,
97
+ commands:configuration.qa.commands,environment:configuration.qa.environment,timeoutMs:1800000,logHome,
89
98
  ...(protectedExecution?{specsRoot:specsDir}:{}),
90
99
  logic:(request,signal)=>bridge.call('qa_logic',request,signal,requestTimeout),
91
100
  browser:(request,signal)=>bridge.call('qa_browser',request,signal,requestTimeout)}),requestTimeoutMs:requestTimeout.timeoutMs});
@@ -95,10 +104,12 @@ export function createHostWorkflowCapabilities({definition,configuration,bridge,
95
104
 
96
105
  export function createParallelMemberQaDecisionProvider(){
97
106
  return Object.freeze({timeoutMs:60000,async decide(raw,signal){
98
- const binding=json(raw);shape(binding,['specsDir','codeProject','feature','identity','packageDigest']);
107
+ const binding=json(raw);shape(binding,['specsDir','codeProject','feature','identity','packageDigest',
108
+ ...(Object.hasOwn(binding,'changedFiles')?['changedFiles']:[])]);
99
109
  validIdentity(binding.identity);hex(binding.packageDigest);need(!signal.aborted,'cancelled');
100
110
  return {decisionId:`qa-${digest({identity:binding.identity,packageDigest:binding.packageDigest}).slice(0,48)}`,
101
111
  identity:binding.identity,packageDigest:binding.packageDigest,status:'skipped',
102
- reason:'parallel_member_deferred',score:4,at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')};
112
+ reason:'parallel_member_deferred',score:null,
113
+ ...(binding.changedFiles?{changedFilesSource:binding.changedFiles.source}:{}),at:new Date().toISOString().replace(/\.\d{3}Z$/,'Z')};
103
114
  }});
104
115
  }
@@ -7,12 +7,11 @@ export function createCmAiHost(options) {
7
7
  need(arguments.length===1,'invalid_input');
8
8
  shape(options,['runner','entry']);
9
9
  const keys=Object.keys(options.entry);shape(options.entry,keys);
10
- const {hostDecisionProvider,qaDecisionProvider,qaExecutor,documentationProvider,...data}=options.entry;
10
+ const {qaDecisionProvider,qaExecutor,documentationProvider,...data}=options.entry;
11
11
  const entryOptions=json(data);
12
12
  need(!Object.hasOwn(entryOptions,'runner'),'invalid_input');
13
13
  const runner=createTaskRunner(options.runner);
14
14
  const entry=createCmAiConversationEntry({...entryOptions,runner,
15
- ...(hostDecisionProvider===undefined?{}:{hostDecisionProvider}),
16
15
  ...(qaExecutor===undefined?{}:{qaExecutor}),
17
16
  ...(documentationProvider===undefined?{}:{documentationProvider}),
18
17
  ...(qaDecisionProvider===undefined?{}:{qaDecisionProvider})});
@@ -10,6 +10,18 @@ const deliveryMessages={
10
10
  develop_unchanged_after_review:['交付没有处理上一轮审查要求。','处理原审查 findings 后提供本轮修改'],
11
11
  develop_requirement_missing:['交付后缺少要求保留的文件。','恢复 reason 指出的必要文件'],
12
12
  bootstrap_verification_failed:['项目规则验证未通过。','根据规则验证证据修正草稿或检查环境'],
13
+ develop_answer_invalid:['开发应答未通过交付合同校验(如 application.note 过长),代码已保留、尚未进入审查。','按 reason 中的字段上限重新应答'],
14
+ develop_dispatch_failed:['开发请求在派发给会话之前失败(宿主自己的运行日志或角色配置出错),代码未改动。','修好 reason 指出的宿主环境'],
15
+ develop_interrupted:['宿主在本轮开发中途退出,中断已登记,盘上改动保留、尚未进入审查。','确认会话或 provider 进程已停止修改代码'],
16
+ develop_call_timeout:['开发应答超时、代码未改动。','先确认会话已不再修改代码;重发的请求须在宿主请求上限(默认 30 分钟)内应答,迟到应答仍被拒绝'],
17
+ };
18
+ // Q16/Q17: documentation_sync of the final task, after develop already answered.
19
+ const documentationMessages={
20
+ documentation_sync_answer_missing:['文档同步没有拿到应答(超时、断开或迟到)。开发应答已记录,不需要重新开发。','重发的文档同步须在宿主请求上限内应答,迟到应答仍被拒绝;'],
21
+ documentation_sync_answer_invalid:['文档同步的应答格式不合格。开发应答已记录,不需要重新开发。','只按合同应答 {"status":"completed"} 或 {"status":"blocked"};'],
22
+ documentation_sync_answer_blocked:['文档同步答复 blocked,文档没有同步完。开发应答已记录,不需要重新开发。','先按会话说明补齐或修正文档、解决阻碍;'],
23
+ documentation_sync_out_of_scope:['文档同步改了文档路径以外的文件(reason 列出路径),尚未进入审查。','先把这些文件还原到文档同步开始时的内容(宿主按存档摘要核对,没还原就拒绝;确需修改先走规格变更);'],
24
+ documentation_sync_interrupted:['宿主在文档同步中途退出,中断已登记。开发应答已记录,不需要重新开发。',''],
13
25
  };
14
26
  const explain=(summary,nextStep,operation=null,prerequisites=[])=>Object.freeze({
15
27
  summary,nextStep,recoveryOperation:operation,prerequisites:Object.freeze(prerequisites),authorizationGranted:false,
@@ -29,15 +41,59 @@ export function operatorGuidance(result,{executionActive=false}={}){
29
41
  if(state==='unknown'){
30
42
  if(action==='abandon_effect'||action==='abandon_review'){
31
43
  const review=action==='abandon_review';
32
- return explain(review?'独立审查结果尚未确认。':'开发或完成操作的结果尚未确认。',
33
- '先核对原操作与磁盘结果,确认旧宿主及相关子进程已退出;符合原宿主条件时,再审计放弃这次操作。放弃不代表成功。',
44
+ return explain(review?'独立审查结果尚未确认。':'宿主在开发、审查或完成中途退出,这一步只登记了意图、没有结果。',
45
+ review?'先核对原操作与磁盘结果,确认旧宿主及相关子进程已退出;符合原宿主条件时,再审计放弃这次操作。放弃不代表成功。'
46
+ :result.documentationSyncPending===true
47
+ ?'先确认旧宿主及相关子进程已退出、会话已停止修改文档(宿主按存档核对文档路径以外的文件与此刻的文档);再发送 abandon_effect 登记中断,运行转为 documentation_sync_interrupted,之后只重发文档同步、不重新开发,计入文档同步重发的 2 次上限。盘上改动保留并经检查与独立审查;登记中断不代表成功。'
48
+ :'先确认旧宿主及相关子进程已退出、会话已停止写入(provider 开发由宿主按存档记下的进程身份核对);再发送 abandon_effect 登记中断,运行从这一步的可重试阻断继续:开发重发本轮、未登记的审查重新派发、未写提交意图的完成重新复查。盘上改动保留并经检查与独立审查;登记中断不代表成功。',
34
49
  action,['保留原配置、runId 和失败历史,以 --mode resume 启动',
35
50
  review?'显式 --allow-abandon-review,并提供单行 reason':'显式 --allow-abandon-effect,并提供单行 reason',
36
51
  '由原宿主核对可放弃条件;不得直接重跑或改写完成记录']);
37
52
  }
53
+ // V5 (A33/A36): a no-verdict review end the host cannot prove safe to redispatch.
54
+ if(['review_process_unverified','review_observation_invalid','review_boundary_unverified','review_abandon_budget_exhausted'].includes(result.reviewAbandonRefusal))
55
+ return explain('独立审查没有结论,且宿主不能证明再派一次是安全的(reason 写明原因)。',
56
+ '按 reason 手工核对旧审查进程与原审查证据;本运行不再重派审查,确认后用 --supersede-reviewed-evidence 新建运行重做。',
57
+ null,['原运行记录保留,不改写','本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift']);
38
58
  return explain('执行结果尚未确认,不能判断这一步成功或失败。',
39
59
  '只读核对原运行记录、进程及实际文件;当前没有已确认的直接重试入口,不新建运行绕过历史。');
40
60
  }
61
+ if(state==='blocked'&&action==='abandon_review')return explain('本轮独立审查第二次没有结论,本轮还剩 1 次无结论重派,但宿主不能证明原审查进程已停止。',
62
+ '先确认原审查进程(含子进程)已退出;再恢复原运行并发送 abandon_review 登记确认,之后 advance 重派。不算审查轮次。',
63
+ 'abandon_review',['保留原配置、runId 与历史,以 --mode resume 启动','显式 --allow-abandon-review,并提供单行 reason','用满 2 次后为 review_redispatch_limit']);
64
+ // Q16/Q17: the final task's documentation_sync failed after develop answered.
65
+ // R3: whatever the failure, the host cannot see whether the session still writes.
66
+ if(action==='develop_redo'&&Object.hasOwn(documentationMessages,code))return explain(`${documentationMessages[code][0]}宿主无法证明会话已停止修改文档。`,
67
+ `先确认会话已停止修改文档,${documentationMessages[code][1]}再恢复原运行并发送 develop_redo 写入确认,之后 advance 只重发文档同步。盘上的开发与文档改动保留,经检查和独立审查。`,
68
+ 'develop_redo',['保留原配置、runId 与历史,以 --mode resume 启动','显式 --allow-develop-redo,并提供单行 reason','只重发文档同步,不重发开发;每运行最多 2 次']);
69
+ if(state==='blocked'&&action==='resume'&&Object.hasOwn(documentationMessages,code)){
70
+ const [summary,repair]=documentationMessages[code];
71
+ return explain(summary,`${repair}然后恢复原运行并发送 advance,只重发文档同步,复用已记录的开发应答,不重新开发。`,
72
+ 'advance',['保留原配置、runId 与历史,以 --mode resume 启动','文档路径以外的文件须与文档同步开始时一致、文档须与确认停写时一致,否则拒绝','不占调用与 effect 名额;每运行最多 2 次,用满为 documentation_sync_retry_limit']);
73
+ }
74
+ if(code==='documentation_sync_retry_limit')return explain('文档同步重发已在本运行用满 2 次,不再重发。',
75
+ '先查清会话为何一直不应答、答复 blocked 或越界写文件;修好后按 reason 用 --supersede-reviewed-evidence 新建运行重做。',
76
+ null,['原运行记录保留,不改写','本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift']);
77
+ if(action==='develop_redo')return explain('开发应答没有拿到(超时后代码已改动、会话断开或只回了 failed),会话可能仍在写文件。',
78
+ '先确认会话已停止修改代码;再恢复原运行并发送 develop_redo 写入确认,之后 advance 重发本轮开发。盘上改动保留,经检查和独立审查。',
79
+ 'develop_redo',['保留原配置、runId 与历史,以 --mode resume 启动','显式 --allow-develop-redo,并提供单行 reason','不占调用与 effect 名额;每运行最多 2 次']);
80
+ if(state==='blocked'&&action==='resume'&&code==='develop_answer_missing')return explain('已确认会话停写,本轮开发等待重发。',
81
+ '恢复原运行并发送 advance,用新 effect id 重发本轮开发;盘上改动保留,经检查和独立审查。',
82
+ 'advance',['保留原配置、runId 与历史,以 --mode resume 启动','确认原宿主已关闭,且本轮开发有原合同要求的授权']);
83
+ if(state==='blocked'&&action==='resume'&&code==='develop_out_of_scope')return explain('开发交付已落盘,但改动超出了任务 scope(reason 列出路径),尚未进入审查。',
84
+ '核对这些路径:会话越界写的就还原,你自己的改动就移出代码根,确需改动先走规格变更扩大 scope;然后恢复原运行并发送 advance,只重跑检查、验证预检与审查包,不重新开发。',
85
+ 'advance',['保留原配置、runId 与历史,以 --mode resume 启动','不占开发调用与 effect 名额;每运行最多 2 次','不擅自删除用户改动']);
86
+ if(state==='blocked'&&action==='resume'&&['check_answer_missing','check_answer_invalid'].includes(code))
87
+ return explain(code==='check_answer_invalid'?'开发交付已落盘,但之后的检查或验证预检答复格式不合格。'
88
+ :'开发交付已落盘,但之后的检查或验证预检没有拿到应答(超时、断开或迟到)。',
89
+ '先确认上一次检查命令已停止;然后恢复原运行并发送 advance,只重跑检查、验证预检与审查包,不重新开发。',
90
+ 'advance',['保留原配置、runId 与历史,以 --mode resume 启动','不占开发调用与 effect 名额;每运行最多 2 次','不会自动完成任务或消耗新的独立审查轮次']);
91
+ if(state==='blocked'&&action==='complete'&&code==='complete_commit_interrupted')return explain('宿主在写入任务完成提交意图后退出,tasks.md 可能已勾选也可能未勾选。',
92
+ '恢复原运行并发送 complete;宿主只按存档里的提交计划核对并收尾,不重新复查、不重新开发。tasks.md 或证据被改动时会拒绝并保留现场。',
93
+ 'complete',['保留原配置、runId 与历史,以 --mode resume 启动','不能 abandon_effect,也不能新建运行替代']);
94
+ if(state==='blocked'&&action==='complete'&&code==='complete_recheck_failed')return explain('完成前复查没有正常结束(应答缺失或宿主在提交前出错),任务尚未勾选。',
95
+ '恢复原运行并发送 complete,重新复查并完成;不重新开发或审查。',
96
+ 'complete',['原 run 与已审交接、范围和包绑定不变','task-commit-intent 尚未写入;每运行最多 2 次']);
41
97
  if(state==='blocked'&&action==='resume'&&Object.hasOwn(deliveryMessages,code)){
42
98
  const [summary,repair]=deliveryMessages[code];
43
99
  return explain(summary,`${repair};然后恢复原运行并发送 advance,重做本轮交付和检查。`,
@@ -49,6 +105,21 @@ export function operatorGuidance(result,{executionActive=false}={}){
49
105
  if(state==='blocked'&&action==='complete')return explain('完成前复核受阻,已有审查结论不能直接当作任务完成。',
50
106
  '核对 reason 中的检查或文件变化;满足原完成条件后,在原运行发送 complete,不重新开发。',
51
107
  'complete',['原 run 与已审交接、范围和包绑定不变','使用当前 packageDigest;由宿主重新核对完成条件']);
108
+ if(code==='review_redispatch_limit')return explain('本轮独立审查已无结论重派 2 次,不再重派;这不计为审查轮次。',
109
+ '先查清审查进程为何一直没有结论(登录、额度、网络或审查答复格式);修好后按 reason 用 --supersede-reviewed-evidence 新建运行重做。',
110
+ null,['原运行记录保留,不改写','本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift']);
111
+ if(['check_answer_retry_limit','complete_recheck_limit','develop_redo_limit'].includes(code))
112
+ return explain('这一步的自动恢复已在本运行用满 2 次,不再重做。',
113
+ '先查清会话为何一直不应答或答复不合格(或宿主环境为何失败);修好后按 reason 用 --supersede-reviewed-evidence 新建运行重做。',
114
+ null,['原运行记录保留,不改写','本运行留在盘上的改动需还原,或加 --accept-superseded-code-drift']);
115
+ // Q06/Q07/Q11: a QA call that stopped as a whole.
116
+ if(state==='fixture_completed'&&code==='qa_execution_unknown')return explain('本轮 QA 没有正常结束(整轮超时、宿主中途退出、答复格式不合格,或浏览器请求超时后设备可能仍被会话占用)。',
117
+ '先确认上一轮的会话、浏览器或模拟器已停止、设备已空闲;再用原配置 --mode resume 加 --rerun-unknown-qa 重跑本轮。宿主拒绝时按拒绝码处理:含原始 FAIL、未解决的 [需确认] 或无法归因的旧记录的轮次不能替代,改用 --supersede-reviewed-evidence 新建运行。',
118
+ null,['保留原运行与 QA 日志,只追加不改写','因宿主或应答原因替代的轮次不占三轮预算']);
119
+ // Q15: the read-only documentation check answered blocked.
120
+ if(state==='fixture_completed'&&code==='documentation_sync_blocked')return explain('文档核对判定文档尚未同步(reason 写明缺什么)。',
121
+ '按 reason 补齐 README 或功能文档;文档核对只读、可重复,用原配置 --mode resume 重启宿主后再发 finish 重新核对(同一宿主进程内结论已缓存)。',
122
+ null,['不改写运行记录','补文档不需要重新开发或审查']);
52
123
  if(code==='protected_scope')return explain('任务 scope 含项目规则或工作流文件,开发在派发前被拒绝,未写入任何文件。',
53
124
  '本运行到此结束,原记录保留。从 scope 移除 reason 列出的路径,按原门禁用新 runId 新建运行;规则文件改动走 docs/js-workflow-control.md「项目规则文件的修改通道」。',
54
125
  null,['不放宽受保护路径,开发者不能写这些文件','不改写原运行记录']);
@@ -70,14 +141,29 @@ export function guidanceText(result){
70
141
  return `${guidance.summary} ${guidance.nextStep} ${guidance.prerequisites.join(';')}`.trim();
71
142
  }
72
143
 
144
+ // Q24: in-run recovery operations the batch entry forwards to the stopped member
145
+ // (scripts/cm-ai-batch-run.mjs BATCH_MEMBER_ACTIONS), with what to confirm first.
146
+ const BATCH_RECOVERY={
147
+ develop_redo:['--allow-develop-redo','先确认会话已停止修改代码'],
148
+ abandon_effect:['--allow-abandon-effect','先确认旧宿主及相关子进程已退出、会话已停止写入'],
149
+ abandon_review:['--allow-abandon-review','先确认旧宿主与审查进程已退出'],
150
+ bootstrap_review_recover:['--allow-bootstrap-review-recovery','先核对当前规则文件、handoff 和原证据'],
151
+ };
73
152
  // A member result is not a batch control surface. Keep unsupported single-run
74
153
  // recovery operations out of batch instructions without changing pendingAction.
75
- export function batchOperatorGuidance(result){
154
+ export function batchOperatorGuidance(result,{taskKey=null}={}){
76
155
  const g=result?.guidance;if(!g)return null;
156
+ if(Object.hasOwn(BATCH_RECOVERY,g.recoveryOperation)){
157
+ const [flag,confirm]=BATCH_RECOVERY[g.recoveryOperation],target=taskKey??'FEATURE/TASK';
158
+ return explain(g.summary,`${confirm};关闭批次宿主,带 ${flag} ${target} 用同一批次配置重新启动,发送批次操作 ${g.recoveryOperation}(taskKey ${target}、单行 reason),之后 advance 继续本批次。`,
159
+ g.recoveryOperation,['保持原批次配置;批次只用这一项权限打开该成员运行,不跨成员','授权用一次即失效;批次 cancel 后不能再恢复']);
160
+ }
77
161
  if(result.code==='spec_drift')return explain(g.summary,
78
162
  '批次成员不能换绑规格;先按 reason 核对原批次可用出口,不直接重派。');
79
163
  if(g.recoveryOperation==='advance')return explain(g.summary,
80
164
  g.nextStep.replace('然后恢复原运行并发送 advance,重做本轮交付和检查。','然后从原批次入口发送 advance,重做本轮交付和检查。')
165
+ .replace('然后恢复原运行并发送 advance,只重跑','然后从原批次入口发送 advance,只重跑')
166
+ .replace('恢复原运行并发送 advance,用新 effect id','从原批次入口发送 advance,用新 effect id')
81
167
  .replace('恢复原运行后,取得本轮绑定的独立审查授权,再发送 advance。','沿原批次续接,取得本轮绑定的独立审查授权,再发送 advance。'),
82
168
  'advance',['保持原批次配置、身份和 PLAN;成员运行由批次宿主选择恢复','先确认原批次宿主已关闭;开发与审查仍需原合同授权']);
83
169
  if(g.recoveryOperation==='complete')return explain(g.summary,
@@ -106,6 +106,56 @@ export const REVIEWER_PROVIDER_FAILURES=Object.freeze({
106
106
  provider_failed:'reviewer_provider_failed',incomplete_result:'reviewer_exited',
107
107
  missing_init:'reviewer_stream_unrecognized',unexpected_event:'reviewer_stream_unrecognized',
108
108
  invalid_event:'reviewer_stream_unrecognized'});
109
+ // Reviewer boundary exits (unexpected_tool_or_content). The Claude worker appends
110
+ // a fixed, body-free summary of the rejected message to the base code; readers
111
+ // that predate it see one opaque failed code and keep the result unknown.
112
+ export const REVIEWER_REJECTION_CHECKS=Object.freeze(['empty_content','block_type','tool_attempt_limit',
113
+ 'duplicate_tool_id','user_content','unknown_tool_result','tool_result_not_error']);
114
+ export function reviewerBoundaryExit(code){
115
+ if(typeof code!=='string'||code.length>256)return null;
116
+ if(code==='unexpected_tool_or_content')return {check:null,message:null,block:null,tool:null,isError:null};
117
+ if(!code.startsWith('unexpected_tool_or_content:'))return null;
118
+ let d;try{d=JSON.parse(code.slice('unexpected_tool_or_content:'.length));}catch{return null;}
119
+ if(!d||typeof d!=='object'||Array.isArray(d)||Object.keys(d).sort().join(',')!=='b,e,k,m,t')return null;
120
+ if(!REVIEWER_REJECTION_CHECKS.includes(d.k)||!['assistant','user'].includes(d.m))return null;
121
+ if(d.b!==null&&!(typeof d.b==='string'&&/^[A-Za-z_]{1,32}$/.test(d.b)))return null;
122
+ if(d.t!==null&&!(typeof d.t==='string'&&/^[A-Za-z0-9_.:-]{1,64}$/.test(d.t)))return null;
123
+ if(d.e!==null&&typeof d.e!=='boolean')return null;
124
+ return {check:d.k,message:d.m,block:d.b,tool:d.t,isError:d.e};
125
+ }
126
+ // Such an exit may be abandoned by the operator (never retried automatically)
127
+ // only when nothing was ever received from it: the process was observed closed,
128
+ // not by timeout, with no final message and no terminal, and the rejection is
129
+ // one that cannot have run a tool successfully (a user-role message that was
130
+ // not a tool result, empty content, or the attempt limit). A legacy code with
131
+ // no summary cannot tell these apart from a successful tool; it qualifies by
132
+ // compatibility decision only (nothing was ever accepted from it, and the
133
+ // operator abandons explicitly, once). A new record of a successful or
134
+ // unmatched tool result stays unknown, as before.
135
+ const ABANDONABLE_CHECKS=new Set(['user_content','empty_content','tool_attempt_limit']);
136
+ export function abandonableReviewerExit(observation){
137
+ const exit=reviewerBoundaryExit(observation?.result?.code);
138
+ if(exit===null||observation.result.status!=='failed')return false;
139
+ if(exit.check!==null&&!ABANDONABLE_CHECKS.has(exit.check))return false;
140
+ let stream;try{stream=eventStream(observation.events,new Set());}catch{return false;}
141
+ return stream.close!==null&&stream.close.timed_out===false&&!stream.hasResult&&stream.terminal===null;
142
+ }
143
+ // V5 (A33): other worker failures after which the reviewer process is proven
144
+ // gone and nothing usable was lost. The worker only reports these codes after it
145
+ // awaited its process-group cleanup (process_cleanup_unknown otherwise), so:
146
+ // spawn_failed with no event at all (nothing ever started), or an observed close
147
+ // that was not a timeout with no final message. An unparseable final message
148
+ // (invalid_output_json) has no conclusion to reconcile either. Tool or item
149
+ // boundary exits stay with abandonableReviewerExit; process_cleanup_unknown and
150
+ // any other code stay unknown.
151
+ const GONE_FAILURES=new Set(['spawn_failed','prompt_write_failed','output_limit','invalid_output_json','thread_mismatch','cli_diagnostic']);
152
+ export function reviewerGoneWithoutResult(observation){
153
+ const r=observation?.result;
154
+ if(r?.status!=='failed'||!GONE_FAILURES.has(r.code))return false;
155
+ let stream;try{stream=eventStream(observation.events,new Set());}catch{return false;}
156
+ if(r.code==='spawn_failed')return observation.events.length===0;
157
+ return stream.close!==null&&stream.close.timed_out===false&&(r.code==='invalid_output_json'||!stream.hasResult);
158
+ }
109
159
  // A complete answer that breaks the written verdict contract can never become a
110
160
  // receipt. It is retried under the same budget and its exact code is kept.
111
161
  export const REVIEWER_VERDICT_FAILURES=Object.freeze(['contradictory_verdict','invalid_finding_path',
@@ -0,0 +1,46 @@
1
+ // Q13/Q26: a QA command resource recorded cleanup_failed (whole-round timeout,
2
+ // cancel, or a cleanup the checker could not confirm) keeps the run open: the
3
+ // log writer refuses abandonment, timed-out supersession, run_done and the
4
+ // batch handoff while it is unclosed. The host may close it only with proof:
5
+ // the cleanup_failed row names the command's process group (pid and start
6
+ // time, written by current executors) and that group is gone now. The released
7
+ // row carries the proof; rows without a recorded pid, or a group that is alive
8
+ // or cannot be checked (Windows, permission, unreadable start time), stay open.
9
+ // QA browser cases hold no resource rows: their device or browser state is the
10
+ // session's own report (cleanup), so there is no device lock to release here.
11
+ import path from 'node:path';
12
+ import {spawnSync} from 'node:child_process';
13
+ import {fileURLToPath} from 'node:url';
14
+ import {scanRows} from './log-rows.mjs';
15
+ import {inspectWorkerGroup,validWorkerPid,validStartTime} from './worker-process-identity.mjs';
16
+ import {need} from './effect-contract.mjs';
17
+
18
+ const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
19
+
20
+ export function inspectOpenQaResources({specsDir,runId}){
21
+ const last=new Map();
22
+ scanRows(path.join(specsDir,'运行日志.jsonl'),row=>{
23
+ if(row?.workflow==='cm-ai'&&row.event==='resource'&&row.run_id===runId&&typeof row.resource_id==='string')
24
+ last.set(row.resource_id,row);
25
+ });
26
+ return [...last.values()].filter(row=>['acquired','cleanup_failed'].includes(row.phase));
27
+ }
28
+
29
+ export function releaseVerifiedQaResources({specsDir,codeProject,runId,runtime='codex',logHome=null,inspect=inspectWorkerGroup}){
30
+ const released=[],open=[];
31
+ for(const row of inspectOpenQaResources({specsDir,runId})){
32
+ const proof=row.phase==='cleanup_failed'&&row.resource_kind==='qa_command'&&validWorkerPid(row.pid)
33
+ &&validStartTime(row.process_start_time??null)?inspect({pid:row.pid,startTime:row.process_start_time??null}):null;
34
+ if(proof!=='gone'){open.push({resourceId:row.resource_id,phase:row.phase,verdict:proof??'unrecorded'});continue;}
35
+ const data={...(row.node?{node:row.node}:{}),...(row.feature?{feature:row.feature}:{}),...(row.task?{task:row.task}:{}),
36
+ resource_id:row.resource_id,resource_kind:row.resource_kind,released_by:'host_verified',
37
+ verification:'process_group_gone',pid:row.pid,process_start_time:row.process_start_time??null};
38
+ const result=spawnSync('python3',[writer,'--workflow','cm-ai','--event','resource','--phase','released',
39
+ '--runtime',runtime,'--project-root',codeProject,'--specs-dir',specsDir,'--run-id',runId,
40
+ '--detail','宿主核对 QA 命令进程组已退出,补记资源释放','--data-json',JSON.stringify(data)],
41
+ {timeout:10000,maxBuffer:1024*1024,...(logHome?{env:{...process.env,CM_WORKFLOW_LOG_HOME:logHome}}:{})});
42
+ need(!result.error&&result.status===0,'qa_resource_release_failed');
43
+ released.push(row.resource_id);
44
+ }
45
+ return {released,open};
46
+ }
@@ -0,0 +1,13 @@
1
+ // Q14: the N6 QA budget is three rounds of product evidence. A round that ended
2
+ // because of the host or the session's answer (no answer before the deadline or
3
+ // a host death, a host-judged evidence or environment gap, a session-declared
4
+ // BLOCKED) and was superseded for exactly that reason does not count; at most
5
+ // two such rounds are given back per run. Operator decisions (a declared
6
+ // environment failure, a configuration revision) and product FAILs still count.
7
+ export const QA_BASE_ROUNDS=3;
8
+ export const QA_EXTRA_ROUNDS=2;
9
+ export const QA_MAX_ROUNDS=QA_BASE_ROUNDS+QA_EXTRA_ROUNDS;
10
+ export const NON_PRODUCT_SUPERSESSIONS=Object.freeze(['host_request_timeout','host_evidence_problem']);
11
+ export const nonProductSupersession=reason=>NON_PRODUCT_SUPERSESSIONS.includes(reason);
12
+ // The highest round that may start once `freed` such supersessions are recorded.
13
+ export const qaRoundLimit=freed=>QA_BASE_ROUNDS+Math.min(QA_EXTRA_ROUNDS,freed);